Merge branch 'main' into feat/zeroize-secrets
All checks were successful
ci / test (pull_request) Successful in 6m33s

This commit is contained in:
sirius 2026-09-12 19:06:50 +00:00
commit 8eb0820df0
27 changed files with 2863 additions and 139 deletions

View file

@ -15,6 +15,7 @@ use crate::file;
use crate::frame;
use crate::hs::{self, Client, HS_PORT};
use crate::loc;
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
use crate::pay;
use crate::profile;
use crate::qr;
@ -40,9 +41,18 @@ impl Drop for HsHandle {
}
}
/// Abort the outbox worker when the node goes away.
struct WorkerHandle(tokio::task::JoinHandle<()>);
impl Drop for WorkerHandle {
fn drop(&mut self) {
self.0.abort();
}
}
pub struct Node {
home: PathBuf,
store: Mutex<Store>,
store: Arc<Mutex<Store>>,
client: Client,
hs: Mutex<Option<HsHandle>>,
onion: Mutex<String>,
@ -50,6 +60,8 @@ pub struct Node {
wallet: Wallet,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
_outbox_worker: WorkerHandle,
}
impl Node {
@ -82,9 +94,17 @@ impl Node {
let (svc, rend) = launched;
let onion = hs::onion_string(&svc)?;
let inbox = file::Inbox::new(home.join("inbox"));
let store = Arc::new(Mutex::new(store));
let outbox = Arc::new(Outbox::new(
Arc::clone(&store),
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
));
if let Err(e) = outbox.reset_stale() {
eprintln!("outbox: {e}");
}
let node = Arc::new(Self {
home,
store: Mutex::new(store),
store,
client,
hs: Mutex::new(None),
onion: Mutex::new(onion.clone()),
@ -92,7 +112,12 @@ impl Node {
wallet: Wallet::from_env(),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
_outbox_worker: WorkerHandle(outbox.spawn_worker()),
});
// Unlock trigger: flush anything queued by a previous run now, in the
// background, rather than waiting out its backoff.
spawn_flush_all(Arc::clone(&node.outbox));
// Accept rens before waiting so a reachability probe can succeed
// while combined status is still Bootstrapping.
let rend = spawn_rend(Arc::clone(&node), rend);
@ -419,6 +444,8 @@ impl Node {
self.try_send(&onion, friend_pk, &prekey, plaintext).await
}
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
/// the outbox retry triggers.
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
tokio::time::timeout(
Duration::from_secs(20),
@ -427,6 +454,14 @@ impl Node {
.await
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
if let Ok(Some(friend)) = self
.store
.lock()
.map_err(|e| e.to_string())
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
{
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
}
Ok(())
}
@ -509,36 +544,30 @@ impl Node {
Ok(name)
}
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
let (onion, prekey) = {
let store = self.store.lock().map_err(|e| e.to_string())?;
let f = store
.get_friend(friend_pk)
.map_err(|e| e.to_string())?
.ok_or_else(|| "unknown friend".to_string())?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
(f.onion, f.prekey)
};
let deadline = Instant::now() + Duration::from_secs(180);
let mut last = None::<String>;
while Instant::now() < deadline {
match self.try_send(&onion, friend_pk, &prekey, plaintext).await {
Ok(()) => {
self.store
.lock()
.map_err(|e| e.to_string())?
.append_message(friend_pk, "out", plaintext)
.map_err(|e| e.to_string())?;
return Ok(());
}
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
Err(e) => last = Some(e),
}
tokio::time::sleep(Duration::from_secs(3)).await;
}
Err(last.unwrap_or_else(|| "send timed out".into()))
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
/// when the peer's onion is unreachable — the outbox worker then retries with
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
/// frame) still fails immediately and is never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
self.outbox.send(friend_pk, plaintext).await
}
/// Pending and failed outbox rows for a friend, for UI surfacing.
/// Delivered rows are dropped, so a message absent here was sent.
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
self.outbox.pending(friend_pk)
}
pub fn outbox_status_of_message(
&self,
message_id: i64,
) -> Result<Option<OutboxStatus>, String> {
self.outbox.status_of_message(message_id)
}
/// Foreground/unlock trigger: try every outstanding queued send now.
pub fn flush_outbox(&self) {
spawn_flush_all(Arc::clone(&self.outbox));
}
async fn push_loc(
@ -571,20 +600,10 @@ impl Node {
remote_prekey: &[u8],
plaintext: &[u8],
) -> Result<(), String> {
let mut stream = self
.client
.connect((onion, HS_PORT))
self.outbox
.deliverer()
.deliver(onion, pinned_id, remote_prekey, plaintext)
.await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let keys = self.keys()?;
let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey)
.await
.map_err(session_err)?;
let ct = sess.encrypt(plaintext).map_err(session_err)?;
frame::write_frame(&mut stream, &ct)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
@ -601,6 +620,9 @@ impl Node {
})
.await
.map_err(session_err)?;
// Trigger (c): the peer just proved they are online. Try their queued
// sends now instead of waiting out the backoff, off this stream's path.
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
let pt = sess.decrypt(&ct).map_err(session_err)?;
match dispatch::classify(&pt) {
@ -817,6 +839,24 @@ fn spawn_rend(
})
}
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
fn spawn_flush_all(outbox: Arc<Outbox>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_all(unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
/// We just saw this peer (handshake or successful dial): try their queue now.
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
fn next_hs_nickname(cur: &str) -> String {
let n = cur
.strip_prefix("ow")