698 lines
26 KiB
Rust
698 lines
26 KiB
Rust
//! High-level async client API for Meow v2.
|
|||
|
|
//!
|
||
|
|
//! [`MeowClient`] owns one identity (profile) and exposes servers, contacts,
|
||
|
|
//! invitations, messaging and synchronisation. It is the API mirrored by the CLI
|
||
|
|
//! and, later, by the Flutter FFI layer (`meow-ffi`).
|
||
|
|
//!
|
||
|
|
//! Invariant: any ratchet/contact state change is **persisted before** the
|
||
|
|
//! resulting bytes leave the device, so a crash can never make us reuse a key.
|
||
|
|
|
||
|
|
#![forbid(unsafe_code)]
|
||
|
|
#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))]
|
||
|
|
|
||
|
|
pub mod profile;
|
||
|
|
pub mod transport;
|
||
|
|
|
||
|
|
use std::collections::BTreeMap;
|
||
|
|
use std::path::{Path, PathBuf};
|
||
|
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||
|
|
|
||
|
|
use futures_util::future::join_all;
|
||
|
|
use meow_core::contact::{Contact, ContactState};
|
||
|
|
use meow_core::invitation::{self, OfferInfo};
|
||
|
|
use meow_core::server::{canonical_url, ServerInfo};
|
||
|
|
use meow_core::{messaging, rpc};
|
||
|
|
use meow_crypto::password::KdfParams;
|
||
|
|
use meow_crypto::{SignPublic, SigningKeyPair};
|
||
|
|
use meow_proto::v2::{self, request::Body as Req, response::Body as Resp};
|
||
|
|
use meow_proto::Message;
|
||
|
|
|
||
|
|
pub use meow_core::contact::ContactState as State;
|
||
|
|
pub use profile::{Content, HistoryEntry};
|
||
|
|
|
||
|
|
/// Maximum file size sent in a single message (chunking: roadmap 5.7).
|
||
|
|
pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
|
||
|
|
/// Default invitation lifetime.
|
||
|
|
pub const DEFAULT_INVITATION_TTL: u64 = 7 * 86_400;
|
||
|
|
|
||
|
|
#[derive(Debug, thiserror::Error)]
|
||
|
|
pub enum Error {
|
||
|
|
#[error("wrong password or corrupted identity file")]
|
||
|
|
BadPassword,
|
||
|
|
#[error("corrupted identity file: {0}")]
|
||
|
|
Corrupted(String),
|
||
|
|
#[error("i/o: {0}")]
|
||
|
|
Io(#[from] std::io::Error),
|
||
|
|
#[error("network: {0}")]
|
||
|
|
Network(String),
|
||
|
|
#[error(transparent)]
|
||
|
|
Protocol(#[from] meow_core::Error),
|
||
|
|
#[error("crypto: {0}")]
|
||
|
|
Crypto(#[from] meow_crypto::CryptoError),
|
||
|
|
#[error("unknown server: {0}")]
|
||
|
|
UnknownServer(String),
|
||
|
|
#[error("server {0} changed its keys: refusing (remove and re-add it if this is expected)")]
|
||
|
|
ServerKeyChanged(String),
|
||
|
|
#[error("unknown contact: {0}")]
|
||
|
|
UnknownContact(String),
|
||
|
|
#[error("a contact named {0:?} already exists")]
|
||
|
|
NameTaken(String),
|
||
|
|
#[error("{0}")]
|
||
|
|
Invalid(String),
|
||
|
|
#[error("identity {0} is in use by another process")]
|
||
|
|
Locked(String),
|
||
|
|
}
|
||
|
|
|
||
|
|
pub type Result<T> = std::result::Result<T, Error>;
|
||
|
|
|
||
|
|
pub(crate) fn now() -> u64 {
|
||
|
|
SystemTime::now()
|
||
|
|
.duration_since(UNIX_EPOCH)
|
||
|
|
.map(|d| d.as_secs())
|
||
|
|
.unwrap_or(0)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn now_ms() -> u64 {
|
||
|
|
SystemTime::now()
|
||
|
|
.duration_since(UNIX_EPOCH)
|
||
|
|
.map(|d| d.as_millis() as u64)
|
||
|
|
.unwrap_or(0)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Something that happened during [`MeowClient::sync`].
|
||
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
|
|
pub enum Event {
|
||
|
|
/// Initiator side: the invitee answered a server-published invitation; the
|
||
|
|
/// confirmation has been sent automatically.
|
||
|
|
InvitationAccepted { contact: String },
|
||
|
|
/// The handshake is complete on this side.
|
||
|
|
ContactActivated { contact: String },
|
||
|
|
Message {
|
||
|
|
contact: String,
|
||
|
|
id: Vec<u8>,
|
||
|
|
text: String,
|
||
|
|
sent_at_ms: u64,
|
||
|
|
},
|
||
|
|
File {
|
||
|
|
contact: String,
|
||
|
|
name: String,
|
||
|
|
data: Vec<u8>,
|
||
|
|
},
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Outcome of a send.
|
||
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
|
|
pub struct SendReport {
|
||
|
|
pub message_id: Vec<u8>,
|
||
|
|
/// Number of servers that accepted the deposit.
|
||
|
|
pub delivered_to: usize,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One identity, with its servers, contacts and history.
|
||
|
|
pub struct MeowClient {
|
||
|
|
path: PathBuf,
|
||
|
|
password: String,
|
||
|
|
kdf: KdfParams,
|
||
|
|
profile: profile::Profile,
|
||
|
|
transport: transport::Transport,
|
||
|
|
/// Exclusive OS lock on `<identity>.lock`, held for the client's lifetime:
|
||
|
|
/// two processes saving the same ratchet state would roll sessions back.
|
||
|
|
_lock: std::fs::File,
|
||
|
|
}
|
||
|
|
|
||
|
|
fn lock_identity(path: &Path) -> Result<std::fs::File> {
|
||
|
|
let mut lock_path = path.as_os_str().to_owned();
|
||
|
|
lock_path.push(".lock");
|
||
|
|
let f = std::fs::OpenOptions::new()
|
||
|
|
.create(true)
|
||
|
|
.truncate(false)
|
||
|
|
.write(true)
|
||
|
|
.open(PathBuf::from(lock_path))?;
|
||
|
|
match f.try_lock() {
|
||
|
|
Ok(()) => Ok(f),
|
||
|
|
Err(std::fs::TryLockError::WouldBlock) => Err(Error::Locked(path.display().to_string())),
|
||
|
|
Err(std::fs::TryLockError::Error(e)) => Err(Error::Io(e)),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
impl MeowClient {
|
||
|
|
// ───────────────────────── lifecycle ─────────────────────────
|
||
|
|
|
||
|
|
/// Create a new identity file. Fails if it exists, unless `overwrite`.
|
||
|
|
pub async fn create(path: &Path, nickname: &str, password: &str, kdf: KdfParams, overwrite: bool) -> Result<Self> {
|
||
|
|
if !overwrite && path.exists() {
|
||
|
|
return Err(Error::Invalid(format!(
|
||
|
|
"{} already exists (use --force)",
|
||
|
|
path.display()
|
||
|
|
)));
|
||
|
|
}
|
||
|
|
let c = Self {
|
||
|
|
path: path.to_path_buf(),
|
||
|
|
password: password.to_string(),
|
||
|
|
kdf,
|
||
|
|
profile: profile::Profile::new(nickname),
|
||
|
|
transport: transport::Transport::new()?,
|
||
|
|
_lock: lock_identity(path)?,
|
||
|
|
};
|
||
|
|
c.save().await?;
|
||
|
|
Ok(c)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Open an existing identity file. `kdf` is used for subsequent saves.
|
||
|
|
pub async fn open(path: &Path, password: &str, kdf: KdfParams) -> Result<Self> {
|
||
|
|
Ok(Self {
|
||
|
|
path: path.to_path_buf(),
|
||
|
|
password: password.to_string(),
|
||
|
|
kdf,
|
||
|
|
_lock: lock_identity(path)?,
|
||
|
|
profile: profile::Profile::load(path, password).await?,
|
||
|
|
transport: transport::Transport::new()?,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn save(&self) -> Result<()> {
|
||
|
|
self.profile.save(&self.path, &self.password, self.kdf).await
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn nickname(&self) -> &str {
|
||
|
|
&self.profile.nickname
|
||
|
|
}
|
||
|
|
|
||
|
|
// ───────────────────────── servers ─────────────────────────
|
||
|
|
|
||
|
|
/// Add a server: fetch its card, verify it and pin its keys (TOFU).
|
||
|
|
pub async fn add_server(&mut self, url: &str) -> Result<ServerInfo> {
|
||
|
|
let info = self.transport.fetch_card(url).await?;
|
||
|
|
if canonical_url(url) != info.url {
|
||
|
|
tracing::warn!("server announces {} (contacted as {url})", info.url);
|
||
|
|
}
|
||
|
|
if let Some(known) = self
|
||
|
|
.profile
|
||
|
|
.servers
|
||
|
|
.iter()
|
||
|
|
.find(|s| s.url == info.url || s.sign_key == info.sign_key)
|
||
|
|
{
|
||
|
|
if !known.same_keys(&info) {
|
||
|
|
return Err(Error::ServerKeyChanged(info.url));
|
||
|
|
}
|
||
|
|
return Ok(known.clone());
|
||
|
|
}
|
||
|
|
self.profile.servers.push(info.clone());
|
||
|
|
self.save().await?;
|
||
|
|
Ok(info)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn servers(&self) -> &[ServerInfo] {
|
||
|
|
&self.profile.servers
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn remove_server(&mut self, url_or_name: &str) -> Result<()> {
|
||
|
|
let u = canonical_url(url_or_name);
|
||
|
|
let before = self.profile.servers.len();
|
||
|
|
self.profile.servers.retain(|s| s.url != u && s.name != url_or_name);
|
||
|
|
if self.profile.servers.len() == before {
|
||
|
|
return Err(Error::UnknownServer(url_or_name.to_string()));
|
||
|
|
}
|
||
|
|
self.save().await
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Resolve URLs to known servers; an empty list means "all my servers".
|
||
|
|
fn resolve_servers(&self, urls: &[String]) -> Result<Vec<ServerInfo>> {
|
||
|
|
if urls.is_empty() {
|
||
|
|
if self.profile.servers.is_empty() {
|
||
|
|
return Err(Error::Invalid("no server configured: add one first".into()));
|
||
|
|
}
|
||
|
|
return Ok(self.profile.servers.clone());
|
||
|
|
}
|
||
|
|
urls.iter()
|
||
|
|
.map(|u| {
|
||
|
|
let cu = canonical_url(u);
|
||
|
|
self.profile
|
||
|
|
.servers
|
||
|
|
.iter()
|
||
|
|
.find(|s| s.url == cu || s.name == *u)
|
||
|
|
.cloned()
|
||
|
|
.ok_or_else(|| Error::UnknownServer(u.clone()))
|
||
|
|
})
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
// ───────────────────────── contacts ─────────────────────────
|
||
|
|
|
||
|
|
pub fn contacts(&self) -> &[Contact] {
|
||
|
|
&self.profile.contacts
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn contact(&self, name: &str) -> Result<&Contact> {
|
||
|
|
self.profile
|
||
|
|
.contacts
|
||
|
|
.iter()
|
||
|
|
.find(|c| c.name == name)
|
||
|
|
.ok_or_else(|| Error::UnknownContact(name.to_string()))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn contact_index(&self, name: &str) -> Result<usize> {
|
||
|
|
self.profile
|
||
|
|
.contacts
|
||
|
|
.iter()
|
||
|
|
.position(|c| c.name == name)
|
||
|
|
.ok_or_else(|| Error::UnknownContact(name.to_string()))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ensure_free_name(&self, name: &str) -> Result<()> {
|
||
|
|
if self.profile.contacts.iter().any(|c| c.name == name) {
|
||
|
|
return Err(Error::NameTaken(name.to_string()));
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn remove_contact(&mut self, name: &str) -> Result<()> {
|
||
|
|
let i = self.contact_index(name)?;
|
||
|
|
let c = self.profile.contacts.remove(i);
|
||
|
|
self.profile.history.retain(|h| h.contact != c.id);
|
||
|
|
self.save().await
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn history(&self, name: &str) -> Result<Vec<&HistoryEntry>> {
|
||
|
|
let id = &self.contact(name)?.id;
|
||
|
|
Ok(self.profile.history.iter().filter(|h| &h.contact == id).collect())
|
||
|
|
}
|
||
|
|
|
||
|
|
// ───────────────────────── invitations ─────────────────────────
|
||
|
|
|
||
|
|
/// Step 1: create an invitation for `contact_name`. Returns the encoded offer.
|
||
|
|
pub async fn create_invitation(
|
||
|
|
&mut self,
|
||
|
|
contact_name: &str,
|
||
|
|
server_urls: &[String],
|
||
|
|
message: &str,
|
||
|
|
ttl: u64,
|
||
|
|
) -> Result<Vec<u8>> {
|
||
|
|
self.ensure_free_name(contact_name)?;
|
||
|
|
let servers = self.resolve_servers(server_urls)?;
|
||
|
|
let offer = invitation::create_offer(contact_name, &self.profile.nickname, servers, message, now(), ttl)?;
|
||
|
|
self.profile.contacts.push(offer.contact);
|
||
|
|
self.save().await?;
|
||
|
|
Ok(offer.offer_bytes)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn inspect_invitation(&self, offer_bytes: &[u8]) -> Result<OfferInfo> {
|
||
|
|
Ok(invitation::inspect_offer(offer_bytes, now())?)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Step 2: answer an offer. Returns the encoded answer (file flow).
|
||
|
|
pub async fn answer_invitation(
|
||
|
|
&mut self,
|
||
|
|
offer_bytes: &[u8],
|
||
|
|
contact_name: Option<&str>,
|
||
|
|
server_urls: &[String],
|
||
|
|
) -> Result<Vec<u8>> {
|
||
|
|
let info = self.inspect_invitation(offer_bytes)?;
|
||
|
|
let name = contact_name.unwrap_or(&info.initiator_name).to_string();
|
||
|
|
self.ensure_free_name(&name)?;
|
||
|
|
if self
|
||
|
|
.profile
|
||
|
|
.contacts
|
||
|
|
.iter()
|
||
|
|
.any(|c| c.invitation_id == info.invitation_id)
|
||
|
|
{
|
||
|
|
return Err(Error::Invalid("this invitation was already answered".into()));
|
||
|
|
}
|
||
|
|
let servers = self.resolve_servers(server_urls)?;
|
||
|
|
let (contact, answer) = invitation::answer(offer_bytes, &name, &self.profile.nickname, servers, now())?;
|
||
|
|
self.profile.contacts.push(contact);
|
||
|
|
self.save().await?;
|
||
|
|
Ok(answer.encode_to_vec())
|
||
|
|
}
|
||
|
|
|
||
|
|
fn by_invitation(&mut self, id: &[u8]) -> Result<&mut Contact> {
|
||
|
|
self.profile
|
||
|
|
.contacts
|
||
|
|
.iter_mut()
|
||
|
|
.find(|c| c.invitation_id.as_slice() == id)
|
||
|
|
.ok_or_else(|| Error::Invalid("no pending invitation matches".into()))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Step 3 (file flow): process an answer, returns the encoded confirmation.
|
||
|
|
pub async fn accept_answer(&mut self, answer_bytes: &[u8]) -> Result<Vec<u8>> {
|
||
|
|
let msg = v2::InvitationMessage::decode(answer_bytes).map_err(meow_core::Error::from)?;
|
||
|
|
let contact = self.by_invitation(&msg.invitation_id)?;
|
||
|
|
let confirm = invitation::accept(contact, &msg, now())?;
|
||
|
|
self.save().await?;
|
||
|
|
Ok(confirm.encode_to_vec())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Step 4 (file flow): process a confirmation and send the ack through the network.
|
||
|
|
pub async fn finalize_invitation(&mut self, confirm_bytes: &[u8]) -> Result<String> {
|
||
|
|
let msg = v2::InvitationMessage::decode(confirm_bytes).map_err(meow_core::Error::from)?;
|
||
|
|
let contact = self.by_invitation(&msg.invitation_id)?;
|
||
|
|
let ack = invitation::finalize(contact, &msg)?;
|
||
|
|
let deposit = messaging::deposit_for(contact, &ack)?;
|
||
|
|
let servers = contact
|
||
|
|
.peer
|
||
|
|
.as_ref()
|
||
|
|
.map(|p| p.pull_servers.clone())
|
||
|
|
.unwrap_or_default();
|
||
|
|
let name = contact.name.clone();
|
||
|
|
self.save().await?;
|
||
|
|
self.deliver(&servers, vec![deposit]).await?;
|
||
|
|
Ok(name)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Step 1 through a server: publish the offer and return its URL
|
||
|
|
/// (`<server>/inv/<shortcode>`).
|
||
|
|
pub async fn publish_invitation(
|
||
|
|
&mut self,
|
||
|
|
contact_name: &str,
|
||
|
|
server_urls: &[String],
|
||
|
|
message: &str,
|
||
|
|
password: &str,
|
||
|
|
ttl: u64,
|
||
|
|
) -> Result<String> {
|
||
|
|
let offer = self.create_invitation(contact_name, server_urls, message, ttl).await?;
|
||
|
|
let server = self.resolve_servers(server_urls)?.remove(0);
|
||
|
|
let resp = self
|
||
|
|
.transport
|
||
|
|
.call(
|
||
|
|
&server,
|
||
|
|
Req::InvPublish(v2::InvitationPublish {
|
||
|
|
payload: offer,
|
||
|
|
ttl_seconds: ttl.min(u32::MAX as u64) as u32,
|
||
|
|
shortcode_len: 10,
|
||
|
|
password: password.to_string(),
|
||
|
|
}),
|
||
|
|
Duration::ZERO,
|
||
|
|
)
|
||
|
|
.await?;
|
||
|
|
match resp {
|
||
|
|
Resp::InvPublished(p) => Ok(format!("{}/inv/{}", server.url, p.shortcode)),
|
||
|
|
_ => Err(Error::Network("unexpected response".into())),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Step 2 through a server: fetch an offer by URL, answer it and post the answer
|
||
|
|
/// in the initiator's answer mailbox. Returns the initiator's name.
|
||
|
|
pub async fn accept_published_invitation(
|
||
|
|
&mut self,
|
||
|
|
url: &str,
|
||
|
|
password: &str,
|
||
|
|
contact_name: Option<&str>,
|
||
|
|
server_urls: &[String],
|
||
|
|
) -> Result<String> {
|
||
|
|
let (base, code) = url
|
||
|
|
.rsplit_once("/inv/")
|
||
|
|
.ok_or_else(|| Error::Invalid("invitation URL must look like <server>/inv/<code>".into()))?;
|
||
|
|
let server = self.transport.fetch_card(base).await?;
|
||
|
|
let resp = self
|
||
|
|
.transport
|
||
|
|
.call(
|
||
|
|
&server,
|
||
|
|
Req::InvFetch(v2::InvitationFetch {
|
||
|
|
shortcode: code.to_string(),
|
||
|
|
password: password.to_string(),
|
||
|
|
}),
|
||
|
|
Duration::ZERO,
|
||
|
|
)
|
||
|
|
.await?;
|
||
|
|
let Resp::InvFetched(f) = resp else {
|
||
|
|
return Err(Error::Network("unexpected response".into()));
|
||
|
|
};
|
||
|
|
let info = self.inspect_invitation(&f.payload)?;
|
||
|
|
let answer_bytes = self.answer_invitation(&f.payload, contact_name, server_urls).await?;
|
||
|
|
let answer = v2::InvitationMessage::decode(answer_bytes.as_slice()).map_err(meow_core::Error::from)?;
|
||
|
|
self.deliver(&info.answer_servers, vec![invitation::answer_deposit(&info, &answer)])
|
||
|
|
.await?;
|
||
|
|
Ok(info.initiator_name)
|
||
|
|
}
|
||
|
|
|
||
|
|
// ───────────────────────── messaging ─────────────────────────
|
||
|
|
|
||
|
|
pub async fn send_text(&mut self, contact_name: &str, text: &str) -> Result<SendReport> {
|
||
|
|
let msg = messaging::text(text, now_ms());
|
||
|
|
self.send(contact_name, msg, Content::Text(text.to_string())).await
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn send_file(&mut self, contact_name: &str, path: &Path) -> Result<SendReport> {
|
||
|
|
let data = tokio::fs::read(path).await?;
|
||
|
|
if data.len() > MAX_FILE_BYTES {
|
||
|
|
return Err(Error::Invalid(format!("file larger than {MAX_FILE_BYTES} bytes")));
|
||
|
|
}
|
||
|
|
let name = path
|
||
|
|
.file_name()
|
||
|
|
.map(|n| n.to_string_lossy().to_string())
|
||
|
|
.ok_or_else(|| Error::Invalid("bad file name".into()))?;
|
||
|
|
let size = data.len() as u64;
|
||
|
|
let body = v2::user_message::Body::File(v2::FileBody {
|
||
|
|
filename: name.clone(),
|
||
|
|
size,
|
||
|
|
chunk: 0,
|
||
|
|
chunks: 1,
|
||
|
|
data,
|
||
|
|
mime: String::new(),
|
||
|
|
});
|
||
|
|
self.send(
|
||
|
|
contact_name,
|
||
|
|
messaging::new_message(body, now_ms()),
|
||
|
|
Content::File { name, size },
|
||
|
|
)
|
||
|
|
.await
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn send(&mut self, contact_name: &str, msg: v2::UserMessage, content: Content) -> Result<SendReport> {
|
||
|
|
let i = self.contact_index(contact_name)?;
|
||
|
|
let contact = &mut self.profile.contacts[i];
|
||
|
|
let env = messaging::encrypt(contact, &msg)?;
|
||
|
|
let deposit = messaging::deposit_for(contact, &env)?;
|
||
|
|
let servers = contact
|
||
|
|
.peer
|
||
|
|
.as_ref()
|
||
|
|
.map(|p| p.pull_servers.clone())
|
||
|
|
.unwrap_or_default();
|
||
|
|
self.profile.history.push(HistoryEntry {
|
||
|
|
id: msg.id.clone(),
|
||
|
|
contact: contact.id.clone(),
|
||
|
|
outbound: true,
|
||
|
|
sent_at_ms: msg.sent_at_ms,
|
||
|
|
received_at: now(),
|
||
|
|
content,
|
||
|
|
});
|
||
|
|
self.save().await?;
|
||
|
|
let delivered_to = self.deliver(&servers, vec![deposit]).await?;
|
||
|
|
Ok(SendReport {
|
||
|
|
message_id: msg.id,
|
||
|
|
delivered_to,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Post deposits to every server; succeeds if at least one accepted them.
|
||
|
|
async fn deliver(&self, servers: &[ServerInfo], deposits: Vec<v2::Deposit>) -> Result<usize> {
|
||
|
|
if servers.is_empty() {
|
||
|
|
return Err(Error::Invalid("contact has no server".into()));
|
||
|
|
}
|
||
|
|
let calls = servers.iter().map(|s| {
|
||
|
|
self.transport.call(
|
||
|
|
s,
|
||
|
|
Req::Post(v2::Post {
|
||
|
|
deposits: deposits.clone(),
|
||
|
|
}),
|
||
|
|
Duration::ZERO,
|
||
|
|
)
|
||
|
|
});
|
||
|
|
let mut ok = 0;
|
||
|
|
let mut last_err = None;
|
||
|
|
for (s, r) in servers.iter().zip(join_all(calls).await) {
|
||
|
|
match r {
|
||
|
|
Ok(Resp::PostAck(_)) => ok += 1,
|
||
|
|
Ok(_) => last_err = Some(Error::Network(format!("{}: unexpected response", s.url))),
|
||
|
|
Err(e) => {
|
||
|
|
tracing::warn!("deposit on {} failed: {e}", s.url);
|
||
|
|
last_err = Some(e);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
match (ok, last_err) {
|
||
|
|
(0, Some(e)) => Err(e),
|
||
|
|
(n, _) => Ok(n),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// ───────────────────────── sync ─────────────────────────
|
||
|
|
|
||
|
|
/// Pull every mailbox on every server (one request per server), process what
|
||
|
|
/// arrived and return the resulting events. With `wait > 0` the servers hold the
|
||
|
|
/// request until something arrives or the delay expires (long-poll).
|
||
|
|
pub async fn sync(&mut self, wait: Duration) -> Result<Vec<Event>> {
|
||
|
|
// server (by signing key) → (server, mailbox keys)
|
||
|
|
let mut jobs: BTreeMap<SignPublic, (ServerInfo, Vec<SigningKeyPair>)> = BTreeMap::new();
|
||
|
|
for c in &self.profile.contacts {
|
||
|
|
for (kp, servers) in c.mailboxes() {
|
||
|
|
for s in servers {
|
||
|
|
jobs.entry(s.sign_key)
|
||
|
|
.or_insert_with(|| (s.clone(), Vec::new()))
|
||
|
|
.1
|
||
|
|
.push(kp.clone());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if jobs.is_empty() {
|
||
|
|
return Ok(Vec::new());
|
||
|
|
}
|
||
|
|
let wait_s = wait.as_secs().min(u32::MAX as u64) as u32;
|
||
|
|
let calls = jobs.values().map(|(server, kps)| {
|
||
|
|
let rid = meow_crypto::random_bytes::<16>().to_vec();
|
||
|
|
let ts = now();
|
||
|
|
let auths = kps.iter().map(|kp| rpc::mailbox_auth(kp, server, &rid, ts)).collect();
|
||
|
|
let req = v2::Request {
|
||
|
|
request_id: rid,
|
||
|
|
timestamp: ts,
|
||
|
|
body: Some(Req::Pull(v2::Pull {
|
||
|
|
auths,
|
||
|
|
wait_seconds: wait_s,
|
||
|
|
})),
|
||
|
|
};
|
||
|
|
self.transport.call_request(server, req, wait)
|
||
|
|
});
|
||
|
|
let results = join_all(calls).await;
|
||
|
|
|
||
|
|
let mut stored = Vec::new();
|
||
|
|
let mut failures = 0;
|
||
|
|
let mut last_err = None;
|
||
|
|
for ((server, _), r) in jobs.values().zip(results) {
|
||
|
|
match r {
|
||
|
|
Ok(Resp::PullResult(p)) => stored.extend(p.messages),
|
||
|
|
Ok(_) => failures += 1,
|
||
|
|
Err(e) => {
|
||
|
|
tracing::warn!("pull on {} failed: {e}", server.url);
|
||
|
|
failures += 1;
|
||
|
|
last_err = Some(e);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if failures == jobs.len() {
|
||
|
|
return Err(last_err.unwrap_or_else(|| Error::Network("all servers failed".into())));
|
||
|
|
}
|
||
|
|
self.process(stored).await
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn process(&mut self, stored: Vec<v2::StoredMessage>) -> Result<Vec<Event>> {
|
||
|
|
// Handshake messages first (step 2 before step 3), then ratchet messages by arrival.
|
||
|
|
let mut envs: Vec<(u32, u64, Vec<u8>, v2::PeerEnvelope)> = stored
|
||
|
|
.into_iter()
|
||
|
|
.filter_map(|m| {
|
||
|
|
let env = v2::PeerEnvelope::decode(m.payload.as_slice()).ok()?;
|
||
|
|
let rank = match &env.body {
|
||
|
|
Some(v2::peer_envelope::Body::Invitation(i)) => i.step,
|
||
|
|
_ => 10,
|
||
|
|
};
|
||
|
|
Some((rank, m.received_at, m.mailbox, env))
|
||
|
|
})
|
||
|
|
.collect();
|
||
|
|
envs.sort_by_key(|(rank, at, _, _)| (*rank, *at));
|
||
|
|
|
||
|
|
let mut events = Vec::new();
|
||
|
|
let mut outgoing: Vec<(Vec<ServerInfo>, v2::Deposit)> = Vec::new();
|
||
|
|
for (_, received_at, mailbox, env) in envs {
|
||
|
|
let Some(i) = self.profile.contacts.iter().position(|c| {
|
||
|
|
c.mailboxes()
|
||
|
|
.iter()
|
||
|
|
.any(|(kp, _)| kp.public().as_bytes().as_slice() == mailbox.as_slice())
|
||
|
|
}) else {
|
||
|
|
tracing::debug!("message for an unknown mailbox");
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
let contact = &mut self.profile.contacts[i];
|
||
|
|
match env.body {
|
||
|
|
Some(v2::peer_envelope::Body::Invitation(inv)) if inv.step == 2 => {
|
||
|
|
match invitation::accept(contact, &inv, now()) {
|
||
|
|
Ok(confirm) => {
|
||
|
|
let servers = contact
|
||
|
|
.peer
|
||
|
|
.as_ref()
|
||
|
|
.map(|p| p.pull_servers.clone())
|
||
|
|
.unwrap_or_default();
|
||
|
|
outgoing.push((servers, invitation::confirm_deposit(contact, &confirm)?));
|
||
|
|
events.push(Event::InvitationAccepted {
|
||
|
|
contact: contact.name.clone(),
|
||
|
|
});
|
||
|
|
}
|
||
|
|
Err(e) => tracing::debug!("ignoring answer: {e}"),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Some(v2::peer_envelope::Body::Invitation(inv)) if inv.step == 3 => {
|
||
|
|
match invitation::finalize(contact, &inv) {
|
||
|
|
Ok(ack) => {
|
||
|
|
let servers = contact
|
||
|
|
.peer
|
||
|
|
.as_ref()
|
||
|
|
.map(|p| p.pull_servers.clone())
|
||
|
|
.unwrap_or_default();
|
||
|
|
outgoing.push((servers, messaging::deposit_for(contact, &ack)?));
|
||
|
|
events.push(Event::ContactActivated {
|
||
|
|
contact: contact.name.clone(),
|
||
|
|
});
|
||
|
|
}
|
||
|
|
Err(e) => tracing::debug!("ignoring confirmation: {e}"),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Some(v2::peer_envelope::Body::Ratchet(rm)) => {
|
||
|
|
let was = contact.state;
|
||
|
|
let msg = match messaging::decrypt(contact, &rm) {
|
||
|
|
Ok(m) => m,
|
||
|
|
// Typically the same deposit received from a second server.
|
||
|
|
Err(e) => {
|
||
|
|
tracing::debug!("dropping undecryptable message: {e}");
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
let name = contact.name.clone();
|
||
|
|
let cid = contact.id.clone();
|
||
|
|
if was != ContactState::Active && contact.state == ContactState::Active {
|
||
|
|
events.push(Event::ContactActivated { contact: name.clone() });
|
||
|
|
}
|
||
|
|
let mut record = |content| {
|
||
|
|
self.profile.history.push(HistoryEntry {
|
||
|
|
id: msg.id.clone(),
|
||
|
|
contact: cid.clone(),
|
||
|
|
outbound: false,
|
||
|
|
sent_at_ms: msg.sent_at_ms,
|
||
|
|
received_at,
|
||
|
|
content,
|
||
|
|
})
|
||
|
|
};
|
||
|
|
match &msg.body {
|
||
|
|
Some(v2::user_message::Body::Text(t)) => {
|
||
|
|
record(Content::Text(t.text.clone()));
|
||
|
|
events.push(Event::Message {
|
||
|
|
contact: name,
|
||
|
|
id: msg.id.clone(),
|
||
|
|
text: t.text.clone(),
|
||
|
|
sent_at_ms: msg.sent_at_ms,
|
||
|
|
});
|
||
|
|
}
|
||
|
|
Some(v2::user_message::Body::File(f)) => {
|
||
|
|
record(Content::File {
|
||
|
|
name: f.filename.clone(),
|
||
|
|
size: f.size,
|
||
|
|
});
|
||
|
|
events.push(Event::File {
|
||
|
|
contact: name,
|
||
|
|
name: f.filename.clone(),
|
||
|
|
data: f.data.clone(),
|
||
|
|
});
|
||
|
|
}
|
||
|
|
_ => {}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
_ => tracing::debug!("ignoring unsupported envelope"),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
// Persist before anything leaves the device.
|
||
|
|
self.save().await?;
|
||
|
|
for (servers, deposit) in outgoing {
|
||
|
|
if let Err(e) = self.deliver(&servers, vec![deposit]).await {
|
||
|
|
tracing::warn!("could not deliver handshake message: {e}");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(events)
|
||
|
|
}
|
||
|
|
}
|