git clone https://garage44.eu/jeroen/pinnacle.git.. /ui/src/p2p.rs
//! Talking to the p2p service: the requests an app sends it, what it sends
//! back, and the payloads contacts exchange (end-to-end encrypted by the
//! service; it reads only their first byte, to keep texts).
use alloc::vec::Vec;
pub use pinnacle_contacts::{self as contacts, Entry};
use pinnacle_rt::{Channel, Received};
/// App → service: send to a contact (to: 32 bytes, then the payload).
pub const SEND: u8 = 1;
/// App → service: this device's card (answered with its 160 bytes).
pub const CARD: u8 = 2;
/// App → service: the contacts (answered with their cards, 160 bytes each,
/// the name in each the one the address book gives it, [`name_slot`]: so
/// their signatures no longer hold, and a card to pass on is a [`CARD`]).
pub const CONTACTS: u8 = 3;
/// App → service: add a contact (then its card).
pub const ADD_CONTACT: u8 = 4;
/// App → service: this is the Calls app; send it a ring that is waiting.
pub const RING_PENDING: u8 = 5;
/// App → service: the conversation with a contact (then its key), answered
/// with its newest messages that fit one message, oldest first: each a byte
/// (1 sent, 0 received), the time (u64), the length (u16) and the text.
pub const HISTORY: u8 = 6;
/// The service a command on a contact's device is asked of: one request,
/// [`EXEC`]. Its name starts `system-`, so the kernel keeps installed apps
/// from reaching it; only system programs (the terminal) run commands on
/// other devices in the person's name.
pub const EXEC_SERVICE: &str = "system-p2p";
/// App → service: run a command on a contact's device (then its key and
/// the command line), with five channels as handles: the command's stdin,
/// stdout, stderr, exit code and a control channel (see [`crate::remote`]).
pub const EXEC: u8 = 7;
/// Which contacts may run commands on this device: their keys, 32 bytes
/// each. Settings writes it, the p2p service reads it at each request;
/// installed apps cannot reach `/settings`.
pub const ALLOWED: &str = "system:/settings/remote";
/// The contacts that may run commands on this device.
pub fn allowed() -> Vec<Key> {
pinnacle_rt::fs::read(ALLOWED)
.unwrap_or_default()
.as_chunks::<32>()
.0
.to_vec()
}
/// Whether `contact` may run commands on this device: kept at once.
pub fn allow(contact: &Key, allow: bool) -> bool {
let mut keys = allowed();
keys.retain(|k| k != contact);
if allow {
keys.push(*contact);
}
pinnacle_rt::fs::write(ALLOWED, &keys.concat())
}
/// Runs `line` on `contact`'s device, through [`EXEC_SERVICE`], its five
/// channels given as [`EXEC`] says. False when the service is not there.
pub fn exec(contact: &Key, line: &str, channels: Vec<pinnacle_rt::Handle>) -> bool {
let Some(service) = pinnacle_rt::connect(EXEC_SERVICE) else {
return false;
};
let mut m = alloc::vec![EXEC];
m.extend_from_slice(contact);
m.extend_from_slice(line.as_bytes());
service.send(&m, channels)
}
/// App → `system-p2p`: a channel to a service on a contact's device (then
/// its key and the service's name), the caller's end of a channel as the
/// handle. The p2p service carries every message between that channel and
/// a stream to the contact tagged [`verbs_tag`], where its p2p service
/// connects it to the service, if that device's person offers its
/// services to this one ([`OFFERED`]). Handles do not cross.
pub const REMOTE: u8 = 8;
/// App → service: the address book, from its entry `n` (then `n`, u32):
/// answered with how many entries there are (u32), the first not in this
/// answer (u32), and as many as fit one message, each its id
/// ([`ID_LEN`] bytes), its vCard's length (u16) and its vCard. Every
/// contact with a card has an entry, made when the card came.
pub const BOOK: u8 = 9;
/// App → service: keep an entry (then its id, zeros for a new one, and its
/// vCard, at most [`MAX_VCARD`] bytes): answered with the id it is kept
/// under, or with nothing when it is refused. An entry with no id that
/// names a key or a UID already in the book replaces that one (an import
/// of the same contact again); a card in it that holds is added as a
/// contact. With no id, as many vCards as fit, kept at once and answered
/// with the ids of those kept, one after another (an import).
pub const PUT_ENTRY: u8 = 10;
/// App → service: remove an entry (then its id), and the contact with it,
/// whose card goes: messages and calls no longer reach it.
pub const REMOVE_ENTRY: u8 = 11;
/// An entry's id: hex digits, the name of its file.
pub const ID_LEN: usize = 32;
/// The longest vCard an entry is kept as: a [`PUT_ENTRY`] and a
/// [`BOOK`] answer with one entry each fit one message.
pub const MAX_VCARD: usize = 4000;
/// A name as a card's 32 bytes hold it: cut where a character ends, the
/// rest zeros.
pub fn name_slot(name: &str) -> [u8; 32] {
let mut slot = [0u8; 32];
let mut end = name.len().min(32);
while !name.is_char_boundary(end) {
end -= 1;
}
slot[..end].copy_from_slice(&name.as_bytes()[..end]);
slot
}
/// One page of a [`BOOK`] answer: of `entries` (id and vCard, all of
/// them), those from `from` that fit.
pub fn book_page(entries: &[(alloc::string::String, alloc::string::String)], from: usize) -> Vec<u8> {
let mut page = Vec::with_capacity(pinnacle_rt::abi::MAX_MESSAGE);
page.extend_from_slice(&(entries.len() as u32).to_le_bytes());
page.extend_from_slice(&[0; 4]);
let mut next = from.min(entries.len());
for (id, vcard) in &entries[next..] {
let size = ID_LEN + 2 + vcard.len();
if id.len() != ID_LEN || vcard.len() > MAX_VCARD {
next += 1;
continue;
}
if page.len() + size > pinnacle_rt::abi::MAX_MESSAGE {
break;
}
page.extend_from_slice(id.as_bytes());
page.extend_from_slice(&(vcard.len() as u16).to_le_bytes());
page.extend_from_slice(vcard.as_bytes());
next += 1;
}
page[4..8].copy_from_slice(&(next as u32).to_le_bytes());
page
}
/// Which contacts may use this device's services (`crate::verbs::SERVICES`,
/// and any other that is not `system-…`): their keys, 32 bytes each.
pub const OFFERED: &str = "system:/settings/offered";
/// The tag of a stream to a contact's service `name`.
pub fn verbs_tag(name: &str) -> alloc::string::String {
alloc::format!("verbs:{name}")
}
/// The contacts this device offers its services to.
pub fn offered() -> Vec<Key> {
pinnacle_rt::fs::read(OFFERED)
.unwrap_or_default()
.as_chunks::<32>()
.0
.to_vec()
}
/// Whether `contact` may use this device's services: kept at once.
pub fn offer(contact: &Key, offer: bool) -> bool {
let mut keys = offered();
keys.retain(|k| k != contact);
if offer {
keys.push(*contact);
}
pinnacle_rt::fs::write(OFFERED, &keys.concat())
}
/// A channel to service `name` on `contact`'s device, through
/// [`EXEC_SERVICE`]; it closes when the contact cannot be reached or does
/// not offer it.
pub fn remote_service(contact: &Key, name: &str) -> Option<Channel> {
let service = pinnacle_rt::connect(EXEC_SERVICE)?;
let (ours, theirs) = Channel::pair();
let mut m = alloc::vec![REMOTE];
m.extend_from_slice(contact);
m.extend_from_slice(name.as_bytes());
service.send(&m, alloc::vec![theirs.0]).then_some(ours)
}
/// The person's own devices, linked to this one (`docs/backup-and-sync.md`):
/// their keys, 32 bytes each. Only they may open a sync stream. The p2p
/// service adds one when two devices link; Settings forgets one. In the
/// vault, and not kept in step: each device has its own list.
pub const OWN: &str = "data:/sync/devices";
pub fn own_devices() -> Vec<Key> {
pinnacle_rt::fs::read(OWN)
.unwrap_or_default()
.as_chunks::<32>()
.0
.to_vec()
}
/// Adds `device` to the person's own, or forgets it: kept at once.
pub fn set_own(device: &Key, own: bool) -> bool {
let mut keys = own_devices();
keys.retain(|k| k != device);
if own {
keys.push(*device);
}
pinnacle_rt::fs::create_dir("data:/sync");
pinnacle_rt::fs::write(OWN, &keys.concat())
}
/// The tag of a stream between two own devices' sync services.
pub const SYNC_TAG: &str = "sync";
/// The sync service. Its name starts `system-`: installed apps cannot
/// reach it.
pub const SYNC_SERVICE: &str = "system-sync";
/// App → `system-p2p`: a channel to the sync service of an own device
/// (then its key), the caller's end as the handle. The other device's p2p
/// service connects it to its sync service only if this device is its own
/// too, and sends that first the key of the device it came from.
pub const SYNC: u8 = 12;
/// App → `system-p2p`: show a code to link a device by, the caller's end
/// of a channel as the handle. It is sent [`LINK_CODE`] and the code,
/// then [`LINKED`] and the other's card when it linked, or is closed when
/// ten minutes passed.
pub const LINK_SHOW: u8 = 13;
/// App → `system-p2p`: link to the device showing a code (then the code as
/// typed), the caller's end of a channel as the handle: answered
/// [`LINKED`] and the other's card, or [`LINK_FAILED`].
pub const LINK_ENTER: u8 = 14;
/// App → `system-p2p`: read the contacts and the address book again: the
/// sync service changed them.
pub const RELOAD: u8 = 15;
/// App → service: forget the conversation with a contact on this device
/// (then its key), or one message of it (then also its direction byte
/// and its time, u64, as [`HISTORY`] gives them). Not answered; the
/// contact's own copy is theirs.
pub const FORGET: u8 = 16;
pub const LINK_CODE: u8 = 1;
pub const LINKED: u8 = 2;
pub const LINK_FAILED: u8 = 3;
/// The first message on a connection to [`SYNC_SERVICE`]: from the p2p
/// service, a sync with an own device (then its key); from Settings, a
/// backup or a restore (then the password that seals it).
pub const SYNC_FROM: u8 = 0;
pub const BACKUP: u8 = 1;
pub const RESTORE: u8 = 2;
/// The disk backups go to: its file system's label.
pub const BACKUP_DISK: &str = "backup";
/// When the last backup was made and what it held, as the sync service
/// keeps it: `<seconds since 1970> <files> <written>`.
pub const BACKUP_LAST: &str = "data:/sync/backed-up";
/// What a backup or a restore did: the files it holds or put back, and of
/// them those written now.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Copied {
pub files: u32,
pub written: u32,
}
/// Backs the vault up to the [`BACKUP_DISK`] (`restore` false), or puts
/// back what it holds, sealed under `password`; waits until it is done.
/// None when there is no disk, the password does not open the backup, or
/// the sync service is not there.
pub fn backup(restore: bool, password: &str) -> Option<Copied> {
let service = pinnacle_rt::connect(SYNC_SERVICE)?;
let kind = if restore { RESTORE } else { BACKUP };
service.send(&[&[kind][..], password.as_bytes()].concat(), Vec::new());
let mut buffer = [0u8; 16];
match service.receive(&mut buffer) {
Received::Message { len: 9, .. } if buffer[0] == 1 => Some(Copied {
files: u32::from_le_bytes(buffer[1..5].try_into().unwrap()),
written: u32::from_le_bytes(buffer[5..9].try_into().unwrap()),
}),
_ => None,
}
}
/// A request to `system-p2p` carrying the caller's end of a new channel:
/// ours back, or None when the service is not there.
fn with_channel(request: Vec<u8>) -> Option<Channel> {
let service = pinnacle_rt::connect(EXEC_SERVICE)?;
let (ours, theirs) = Channel::pair();
service.send(&request, alloc::vec![theirs.0]).then_some(ours)
}
/// A channel to the sync service of the own device `device`.
pub fn sync_with(device: &Key) -> Option<Channel> {
with_channel([&[SYNC][..], device].concat())
}
pub fn link_show() -> Option<Channel> {
with_channel(alloc::vec![LINK_SHOW])
}
pub fn link_enter(code: &str) -> Option<Channel> {
with_channel([&[LINK_ENTER][..], code.as_bytes()].concat())
}
pub fn reload() -> bool {
pinnacle_rt::connect(EXEC_SERVICE).is_some_and(|s| s.send(&[RELOAD], Vec::new()))
}
/// Service → app: a contact's payload (from: 32 bytes, then the payload).
pub const RECEIVED: u8 = 0x81;
/// Service → the Calls app (a client that sent [`RING_PENDING`]): a
/// contact could not be found through the DHT (then its key, 32 bytes).
/// Only to it, as an answer to a request can begin with any byte.
pub const UNREACHABLE: u8 = 0x82;
/// Payload: a text message (UTF-8 follows).
pub const TEXT: u8 = 1;
/// Payload: call signalling (one of `call::*` follows).
pub const CALL: u8 = 2;
/// Payload: a call's media (see the Call app).
pub const MEDIA: u8 = 3;
/// Payload: the receiver's p2p service, on a [`TEXT`]: it arrived. A text
/// that hears none in time is texted to the contact's phone number
/// instead (`pinnacle_p2p::delivery`).
pub const DELIVERED: u8 = 4;
pub mod call {
/// A ring; a byte may follow, [`VOICE`] for a call with no video (a
/// ring without it is a video call, as before there was a choice).
pub const RING: u8 = 1;
pub const ANSWER: u8 = 2;
pub const HANG_UP: u8 = 3;
/// The callee's p2p service, on a RING: it arrived. A caller that
/// hears none in time calls the contact's phone number instead.
pub const RINGING: u8 = 4;
/// The callee's Calls app, on a RING while it is in another call: the
/// ring is not shown, and the caller says the contact is busy.
pub const BUSY: u8 = 5;
/// After RING: the call is voice only.
pub const VOICE: u8 = 1;
}
pub type Key = [u8; 32];
pub const CARD_SIZE: usize = 160;
pub fn received(from: &Key, payload: &[u8]) -> Vec<u8> {
let mut m = Vec::with_capacity(33 + payload.len());
m.push(RECEIVED);
m.extend_from_slice(from);
m.extend_from_slice(payload);
m
}
/// A contact as an app sees it: key and name.
#[derive(Clone)]
pub struct Contact {
pub key: Key,
pub name: alloc::string::String,
}
/// An app's connection to the p2p service.
pub struct Client {
channel: Channel,
}
impl Client {
/// Connects, waiting up to `ms` for the service to be there.
pub fn connect(ms: u64) -> Option<Client> {
let until = pinnacle_rt::time() + ms;
loop {
if let Some(channel) = pinnacle_rt::connect("p2p") {
return Some(Client { channel });
}
if pinnacle_rt::time() >= until {
return None;
}
pinnacle_rt::sleep(50);
}
}
pub fn channel(&self) -> &Channel {
&self.channel
}
pub fn send(&self, to: &Key, payload: &[u8]) {
let mut m = alloc::vec![SEND];
m.extend_from_slice(to);
m.extend_from_slice(payload);
self.channel.send(&m, Vec::new());
}
pub fn send_text(&self, to: &Key, text: &str) {
let mut payload = alloc::vec![TEXT];
payload.extend_from_slice(text.as_bytes());
self.send(to, &payload);
}
/// Waits for the answer to a request, setting aside what arrives
/// meanwhile in `pending`.
fn ask(&self, request: &[u8], pending: &mut Vec<(Key, Vec<u8>)>) -> Vec<u8> {
self.channel.send(request, Vec::new());
let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
loop {
match self.channel.receive(&mut buffer) {
Received::Message { len, .. } if buffer.first() == Some(&RECEIVED) && len >= 33 => {
pending.push((buffer[1..33].try_into().unwrap(), buffer[33..len].to_vec()));
}
Received::Message { len, .. } => return buffer[..len].to_vec(),
_ => return Vec::new(),
}
}
}
pub fn card(&self, pending: &mut Vec<(Key, Vec<u8>)>) -> Vec<u8> {
self.ask(&[CARD], pending)
}
pub fn contacts(&self, pending: &mut Vec<(Key, Vec<u8>)>) -> Vec<Contact> {
self.ask(&[CONTACTS], pending)
.as_chunks::<CARD_SIZE>()
.0
.iter()
.map(|c| {
let name = &c[64..96];
let len = name.iter().position(|&b| b == 0).unwrap_or(32);
Contact {
key: c[..32].try_into().unwrap(),
name: alloc::string::String::from_utf8_lossy(&name[..len]).into_owned(),
}
})
.collect()
}
/// The conversation with `contact`, as [`HISTORY`] answers it.
pub fn history(&self, contact: &Key, pending: &mut Vec<(Key, Vec<u8>)>) -> Vec<u8> {
let mut request = alloc::vec![HISTORY];
request.extend_from_slice(contact);
self.ask(&request, pending)
}
/// Forgets the conversation with `contact` on this device, or, given
/// one (whether it was sent, and its time), only that message.
pub fn forget(&self, contact: &Key, message: Option<(bool, u64)>) {
let mut m = alloc::vec![FORGET];
m.extend_from_slice(contact);
if let Some((outgoing, at)) = message {
m.push(u8::from(outgoing));
m.extend_from_slice(&at.to_le_bytes());
}
self.channel.send(&m, Vec::new());
}
pub fn add_contact(&self, card: &[u8]) {
let mut m = alloc::vec![ADD_CONTACT];
m.extend_from_slice(card);
self.channel.send(&m, Vec::new());
}
/// The address book, every entry with its id, in the order kept.
pub fn book(&self, pending: &mut Vec<(Key, Vec<u8>)>) -> Vec<Entry> {
let mut entries = Vec::new();
let mut from = 0u32;
loop {
let mut request = alloc::vec![BOOK];
request.extend_from_slice(&from.to_le_bytes());
let page = self.ask(&request, pending);
if page.len() < 8 {
return entries;
}
let total = u32::from_le_bytes(page[..4].try_into().unwrap());
let next = u32::from_le_bytes(page[4..8].try_into().unwrap());
let mut at = 8;
while at + ID_LEN + 2 <= page.len() {
let id = &page[at..at + ID_LEN];
let len = usize::from(u16::from_le_bytes([page[at + ID_LEN], page[at + ID_LEN + 1]]));
let Some(vcard) = page.get(at + ID_LEN + 2..at + ID_LEN + 2 + len) else {
break;
};
if let Some(mut entry) = contacts::parse(&alloc::string::String::from_utf8_lossy(vcard))
.into_iter()
.next()
{
entry.id = alloc::string::String::from_utf8_lossy(id).into_owned();
entries.push(entry);
}
at += ID_LEN + 2 + len;
}
// A page that moved nothing on would ask the same forever.
if next >= total || next <= from {
return entries;
}
from = next;
}
}
/// Keeps `entry` (a new one when its id is empty): the id it is kept
/// under, or `None` when the service refused it (too long, or empty).
pub fn put_entry(
&self,
entry: &Entry,
pending: &mut Vec<(Key, Vec<u8>)>,
) -> Option<alloc::string::String> {
let vcard = entry.to_vcard();
if vcard.len() > MAX_VCARD {
return None;
}
let mut request = alloc::vec![PUT_ENTRY];
let mut id = [0u8; ID_LEN];
if entry.id.len() == ID_LEN {
id.copy_from_slice(entry.id.as_bytes());
}
request.extend_from_slice(&id);
request.extend_from_slice(vcard.as_bytes());
let answer = self.ask(&request, pending);
(answer.len() == ID_LEN).then(|| alloc::string::String::from_utf8_lossy(&answer).into_owned())
}
/// Keeps every one of `entries` as new ones, or in place of those
/// with their key or UID: as many to a request as fit. How many were
/// kept.
pub fn import(&self, entries: &[Entry], pending: &mut Vec<(Key, Vec<u8>)>) -> usize {
let room = pinnacle_rt::abi::MAX_MESSAGE - 1 - ID_LEN;
let mut kept = 0;
let mut batch = alloc::string::String::new();
let mut send = |batch: &mut alloc::string::String| {
if batch.is_empty() {
return;
}
let mut request = alloc::vec![PUT_ENTRY];
request.extend_from_slice(&[0; ID_LEN]);
request.extend_from_slice(batch.as_bytes());
kept += self.ask(&request, pending).len() / ID_LEN;
batch.clear();
};
for entry in entries {
let vcard = contacts::to_vcards(core::slice::from_ref(entry));
if vcard.len() > MAX_VCARD {
continue;
}
if batch.len() + vcard.len() > room {
send(&mut batch);
}
batch.push_str(&vcard);
}
send(&mut batch);
kept
}
/// Removes the entry `id`, and the contact's card with it.
pub fn remove_entry(&self, id: &str) {
if id.len() != ID_LEN {
return;
}
let mut m = alloc::vec![REMOVE_ENTRY];
m.extend_from_slice(id.as_bytes());
self.channel.send(&m, Vec::new());
}
}
/// A conversation's records (as [`HISTORY`] has them, and the phone
/// service its texts) without the first one sent (`outgoing`: direction 1,
/// or 2 for one gone as a text) or received
/// at `at`, ms since 1970; None when there is no such record.
pub fn without_record(log: &[u8], outgoing: bool, at: u64) -> Option<Vec<u8>> {
let mut i = 0;
while i + 11 <= log.len() {
let end = i + 11 + usize::from(u16::from_le_bytes([log[i + 9], log[i + 10]]));
if (log[i] != 0) == outgoing && log[i + 1..i + 9] == at.to_le_bytes() {
let mut rest = log[..i].to_vec();
rest.extend_from_slice(log.get(end..).unwrap_or(&[]));
return Some(rest);
}
i = end;
}
None
}
/// A message from a service's RECEIVED: who from, and the payload.
pub fn parse_received(message: &[u8]) -> Option<(Key, &[u8])> {
if message.first() != Some(&RECEIVED) || message.len() < 33 {
return None;
}
Some((message[1..33].try_into().ok()?, &message[33..]))
}