use std::collections::HashMap;
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use bytes::Bytes;
use futures::channel::mpsc;
use futures::future::Fuse;
use futures::future::FusedFuture;
use futures::FutureExt;
use futures::StreamExt;
use rings_core::dht::Did;
use rings_core::utils::get_epoch_ms;
use rings_runtime::sleep;
use rings_runtime::MaybeSend;
use rings_runtime::MaybeSendSync;
use super::exit::reply_to_unheld;
use super::exit::seal;
use super::exit::OnionExitEffect;
use super::exit::OnionExitSession;
use super::exit::OnionWorldRead;
use super::frame::OnionFrame;
use super::OnionSessionArguments;
use super::OnionSessionId;
use super::OnionTargetDigest;
use crate::error::Error;
use crate::error::Result;
use crate::extension::ext::Scope;
use crate::onion::circuit::OnionApplicationInput;
use crate::onion::circuit::OnionInterpretation;
use crate::onion::circuit::OnionLink;
use crate::onion::circuit::OnionLinkSender;
use crate::onion::circuit::ONION_ADMISSION_WINDOW_MS;
use crate::onion::exit_accounting::OnionExitAccounting;
use crate::onion::exit_accounting::OnionExitLease;
use crate::onion::sphinx::cell::OnionSurb;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionProxyTarget;
use crate::sync_lock::lock;
const ONION_EXIT_MAX_SESSIONS: usize = 1_024;
const ONION_EXIT_SESSION_INBOUND: usize = 256;
const ONION_EXIT_SESSION_TICK: Duration = Duration::from_secs(10);
#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
#[cfg_attr(rings_native, async_trait::async_trait)]
pub(crate) trait OnionWorld: MaybeSendSync + 'static {
type Reader: OnionWorldReader;
type Writer: OnionWorldWriter;
async fn open(&self, target: &OnionProxyTarget) -> Result<(Self::Reader, Self::Writer)>;
}
#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
#[cfg_attr(rings_native, async_trait::async_trait)]
pub(crate) trait OnionWorldReader: MaybeSend + 'static {
async fn read(&mut self, max: usize) -> Result<Option<Bytes>>;
}
#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
#[cfg_attr(rings_native, async_trait::async_trait)]
pub(crate) trait OnionWorldWriter: MaybeSend + 'static {
async fn write(&mut self, bytes: Bytes) -> Result<()>;
async fn shutdown(&mut self) -> Result<()>;
}
struct OnionExitInput {
frame: OnionFrame,
surb: Box<OnionSurb>,
received_at_ms: u128,
}
struct OnionExitSessionHandle {
digest: OnionTargetDigest,
from: Did,
inbound: mpsc::Sender<OnionExitInput>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum OnionExitRoute {
Deliver,
Open,
Answer,
Drop,
}
#[derive(Default)]
struct OnionExitTable {
live: HashMap<OnionSessionId, OnionExitSessionHandle>,
closed: HashMap<OnionSessionId, u128>,
}
impl OnionExitTable {
fn bury(&mut self, session: OnionSessionId, now_ms: u128) {
self.live.remove(&session);
self.closed.retain(|_, lapse_ms| *lapse_ms > now_ms);
if self.closed.len() >= ONION_EXIT_MAX_SESSIONS {
let nearest = self
.closed
.iter()
.min_by_key(|(_, lapse_ms)| **lapse_ms)
.map(|(nearest, _)| *nearest);
if let Some(nearest) = nearest {
tracing::debug!("onion exit tombstones are full; evict the nearest to lapse");
self.closed.remove(&nearest);
}
}
self.closed
.insert(session, now_ms + ONION_ADMISSION_WINDOW_MS);
}
fn route(
&self,
arguments: &OnionSessionArguments,
carries_target: bool,
now_ms: u128,
) -> OnionExitRoute {
match self.live.get(&arguments.session) {
Some(handle) if handle.digest == arguments.digest => OnionExitRoute::Deliver,
Some(_) => OnionExitRoute::Drop,
None if self.is_buried(&arguments.session, now_ms) => OnionExitRoute::Answer,
None if !carries_target => OnionExitRoute::Drop,
None if self.live.len() >= ONION_EXIT_MAX_SESSIONS => OnionExitRoute::Answer,
None => OnionExitRoute::Open,
}
}
fn lose(&mut self, peer: Did, now_ms: u128) {
let riding = self
.live
.iter()
.filter(|(_, handle)| handle.from == peer)
.map(|(session, _)| *session)
.collect::<Vec<_>>();
for session in riding {
self.bury(session, now_ms);
}
}
fn is_buried(&self, session: &OnionSessionId, now_ms: u128) -> bool {
self.closed
.get(session)
.is_some_and(|lapse_ms| *lapse_ms > now_ms)
}
}
struct OnionExitShared<W> {
world: W,
policy: OnionExitPolicy,
accounting: OnionExitAccounting,
link_sender: OnionLinkSender,
sessions: Mutex<OnionExitTable>,
}
pub(crate) struct OnionExitSessions<W> {
shared: Arc<OnionExitShared<W>>,
}
impl<W: OnionWorld> OnionExitSessions<W> {
pub(crate) fn new(
world: W,
policy: OnionExitPolicy,
accounting: OnionExitAccounting,
link_sender: OnionLinkSender,
) -> Self {
Self {
shared: Arc::new(OnionExitShared {
world,
policy,
accounting,
link_sender,
sessions: Mutex::new(OnionExitTable::default()),
}),
}
}
}
#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
#[cfg_attr(rings_native, async_trait::async_trait)]
impl<W: OnionWorld> OnionInterpretation for OnionExitSessions<W> {
async fn evaluate(&self, scope: &Scope, input: OnionApplicationInput) -> Result<()> {
let OnionApplicationInput {
from,
arguments,
value,
surb,
received_at_ms,
} = input;
let arguments = OnionSessionArguments::decode(&arguments).ok_or(Error::InvalidData)?;
let frame =
OnionFrame::decode(surb.class(), value.as_slice()).map_err(|_| Error::InvalidData)?;
let loop_input = OnionExitInput {
frame,
surb,
received_at_ms,
};
let mut sessions = lock(&self.shared.sessions)?;
let route = sessions.route(
&arguments,
loop_input.frame.carries_target(),
received_at_ms,
);
match route {
OnionExitRoute::Drop => return Ok(()),
OnionExitRoute::Answer => {
drop(sessions);
self.answer_unheld(scope, loop_input);
return Ok(());
}
OnionExitRoute::Open => {
let Ok(lease) = self.shared.accounting.admit(&self.shared.policy, from) else {
drop(sessions);
tracing::debug!(%from, "onion exit session share is full; refuse an open");
self.answer_unheld(scope, loop_input);
return Ok(());
};
let (inbound, received) = mpsc::channel(ONION_EXIT_SESSION_INBOUND);
scope.tasks().spawn(drive(
Arc::clone(&self.shared),
scope.clone(),
arguments,
lease,
received,
received_at_ms,
))?;
sessions
.live
.insert(arguments.session, OnionExitSessionHandle {
digest: arguments.digest,
from,
inbound,
});
}
OnionExitRoute::Deliver => {}
}
let Some(handle) = sessions.live.get_mut(&arguments.session) else {
return Ok(());
};
match handle.inbound.try_send(loop_input) {
Ok(()) => Ok(()),
Err(refused) if refused.is_disconnected() => {
drop(sessions);
self.answer_unheld(scope, refused.into_inner());
Ok(())
}
Err(refused) => {
let input = refused.into_inner();
if input.frame.is_sequenced() {
tracing::debug!(%from, "onion exit session queue is full; abort the session");
sessions.bury(arguments.session, received_at_ms);
drop(sessions);
self.answer_unheld(scope, input);
} else {
tracing::debug!(%from, "onion exit session queue is full; drop credit");
}
Ok(())
}
}
}
fn lose(&self, peer: Did) {
match lock(&self.shared.sessions) {
Ok(mut sessions) => sessions.lose(peer, get_epoch_ms()),
Err(error) => tracing::debug!(%peer, %error, "onion exit sessions are unreadable"),
}
}
}
impl<W: OnionWorld> OnionExitSessions<W> {
fn answer_unheld(&self, scope: &Scope, input: OnionExitInput) {
let Some(frame) = reply_to_unheld(&input.frame) else {
return;
};
let Some((next, cell)) = seal(&frame, *input.surb) else {
return;
};
let queued =
self.shared
.link_sender
.enqueue_local(scope.clone(), OnionLink::new(next), cell);
if let Err(error) = queued {
tracing::debug!(
%next,
%error,
"an onion exit's answer to an unheld session was dropped"
);
}
}
}
type WorldRead<R> =
Pin<Box<rings_runtime::maybe_send!(dyn Future<Output = (R, Result<Option<Bytes>>)>)>>;
struct OnionOpenWorld<W: OnionWorld> {
reader: Option<W::Reader>,
writer: W::Writer,
}
async fn drive<W: OnionWorld>(
shared: Arc<OnionExitShared<W>>,
scope: Scope,
arguments: OnionSessionArguments,
lease: OnionExitLease,
mut inbound: mpsc::Receiver<OnionExitInput>,
created_at_ms: u128,
) {
let mut machine = OnionExitSession::new(arguments.digest, created_at_ms);
let mut world: Option<OnionOpenWorld<W>> = None;
let mut reading: Fuse<WorldRead<W::Reader>> = Fuse::terminated();
let mut tick = Box::pin(sleep(ONION_EXIT_SESSION_TICK).fuse());
loop {
let effects = futures::select! {
input = inbound.next() => match input {
Some(input) => machine.forward(input.received_at_ms, input.frame, *input.surb),
None => {
let effects = machine.fail(get_epoch_ms());
perform(&shared, &scope, &mut machine, &mut world, effects).await;
break;
}
},
(reader, read) = reading => {
if let Some(open) = world.as_mut() {
open.reader = Some(reader);
}
let now_ms = get_epoch_ms();
match read {
Ok(Some(bytes)) => machine.world(now_ms, OnionWorldRead::Bytes(bytes)),
Ok(None) => machine.world(now_ms, OnionWorldRead::Eof),
Err(_) => machine.fail(now_ms),
}
},
_ = tick => {
tick = Box::pin(sleep(ONION_EXIT_SESSION_TICK).fuse());
machine.tick(get_epoch_ms())
},
};
let open = perform(&shared, &scope, &mut machine, &mut world, effects).await;
if !open {
break;
}
if reading.is_terminated() {
let started = machine.reply_capacity(get_epoch_ms()).and_then(|max| {
world
.as_mut()
.and_then(|open| open.reader.take())
.map(|reader| read_world(reader, max))
});
if let Some(read) = started {
reading = read.fuse();
}
}
}
drop(lease);
if let Ok(mut sessions) = lock(&shared.sessions) {
sessions.bury(arguments.session, get_epoch_ms());
}
}
fn read_world<R: OnionWorldReader>(mut reader: R, max: usize) -> WorldRead<R> {
Box::pin(async move {
let read = reader.read(max).await;
(reader, read)
})
}
async fn perform<W: OnionWorld>(
shared: &OnionExitShared<W>,
scope: &Scope,
machine: &mut OnionExitSession,
world: &mut Option<OnionOpenWorld<W>>,
effects: Vec<OnionExitEffect>,
) -> bool {
let mut queue = VecDeque::from(effects);
while let Some(effect) = queue.pop_front() {
match effect {
OnionExitEffect::Open { target } => {
let opened = open(shared, &target).await;
let accepted = opened.is_some();
*world = opened;
queue.extend(machine.opened(get_epoch_ms(), accepted));
}
OnionExitEffect::Write(bytes) => {
let written = match world.as_mut() {
Some(open) if record(shared, bytes.len(), get_epoch_ms()) => {
open.writer.write(bytes).await.is_ok()
}
_ => false,
};
if !written {
fail(machine, &mut queue);
}
}
OnionExitEffect::ShutdownWrite => {
if let Some(open) = world.as_mut() {
let _ = open.writer.shutdown().await;
}
}
OnionExitEffect::Reply { frame, surb } => {
let Some((next, cell)) = seal(&frame, *surb) else {
tracing::debug!("an onion reply could not be sealed");
fail(machine, &mut queue);
continue;
};
let sent = shared
.link_sender
.send(scope.clone(), OnionLink::new(next), cell)
.await;
if let Err(error) = sent {
tracing::debug!(%next, %error, "an onion reply did not leave");
fail(machine, &mut queue);
}
}
OnionExitEffect::Close => return false,
}
}
true
}
fn fail(machine: &mut OnionExitSession, queue: &mut VecDeque<OnionExitEffect>) {
*queue = VecDeque::from(machine.fail(get_epoch_ms()));
}
async fn open<W: OnionWorld>(
shared: &OnionExitShared<W>,
target: &[u8],
) -> Option<OnionOpenWorld<W>> {
let target = std::str::from_utf8(target)
.ok()
.and_then(|authority| OnionProxyTarget::parse_authority(authority).ok())?;
if !shared.policy.allows_target(&target) {
tracing::debug!(target = %target.authority(), "onion exit policy refuses a target");
return None;
}
match shared.world.open(&target).await {
Ok((reader, writer)) => Some(OnionOpenWorld {
reader: Some(reader),
writer,
}),
Err(error) => {
tracing::debug!(target = %target.authority(), %error, "onion exit world refused");
None
}
}
}
fn record<W>(shared: &OnionExitShared<W>, bytes: usize, now_ms: u128) -> bool {
u64::try_from(bytes).ok().is_some_and(|bytes| {
shared
.accounting
.record_bytes(&shared.policy, bytes, now_ms)
.is_ok()
})
}
#[cfg(all(test, rings_native))]
mod tests {
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Mutex;
use bytes::Bytes;
use rings_core::dht::Did;
use super::fail;
use super::open;
use super::OnionExitRoute;
use super::OnionExitSessionHandle;
use super::OnionExitShared;
use super::OnionExitTable;
use super::OnionWorld;
use super::OnionWorldReader;
use super::OnionWorldWriter;
use super::ONION_EXIT_MAX_SESSIONS;
use crate::error::Result;
use crate::onion::circuit::OnionLinkSender;
use crate::onion::circuit::ONION_ADMISSION_WINDOW_MS;
use crate::onion::exit_accounting::OnionExitAccounting;
use crate::onion::session::exit::OnionExitEffect;
use crate::onion::session::exit::OnionExitSession;
use crate::onion::session::OnionSessionArguments;
use crate::onion::session::OnionSessionId;
use crate::onion::session::OnionTargetDigest;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionProxyTarget;
#[derive(Default)]
struct CountingWorld(AtomicUsize);
struct Empty;
#[async_trait::async_trait]
impl OnionWorld for CountingWorld {
type Reader = Empty;
type Writer = Empty;
async fn open(&self, _: &OnionProxyTarget) -> Result<(Empty, Empty)> {
self.0.fetch_add(1, Ordering::SeqCst);
Ok((Empty, Empty))
}
}
#[async_trait::async_trait]
impl OnionWorldReader for Empty {
async fn read(&mut self, _: usize) -> Result<Option<Bytes>> {
Ok(None)
}
}
#[async_trait::async_trait]
impl OnionWorldWriter for Empty {
async fn write(&mut self, _: Bytes) -> Result<()> {
Ok(())
}
async fn shutdown(&mut self) -> Result<()> {
Ok(())
}
}
fn shared(policy: OnionExitPolicy) -> OnionExitShared<CountingWorld> {
OnionExitShared {
world: CountingWorld::default(),
policy,
accounting: OnionExitAccounting::default(),
link_sender: OnionLinkSender::default(),
sessions: Mutex::new(OnionExitTable::default()),
}
}
#[tokio::test]
async fn test_open_refuses_what_the_policy_denies_before_the_world() -> Result<()> {
let policy = OnionExitPolicy::from_target_strings(vec!["*:443".to_string()], vec![
"blocked.example:443".to_string(),
])?;
let exit = shared(policy);
assert!(open(&exit, b"allowed.example:443").await.is_some());
assert!(open(&exit, b"blocked.example:443").await.is_none());
assert!(open(&exit, b"allowed.example:80").await.is_none());
assert!(open(&exit, b"not an authority").await.is_none());
assert!(open(&exit, &[0xff, 0xfe]).await.is_none());
assert_eq!(exit.world.0.load(Ordering::SeqCst), 1);
Ok(())
}
#[test]
fn test_a_loop_is_routed_by_its_session() {
let mut table = OnionExitTable::default();
let target = OnionTargetDigest::of(b"example.com:443");
let other = OnionTargetDigest::of(b"other.example:443");
let arguments = |byte: u8, digest: OnionTargetDigest| OnionSessionArguments {
session: OnionSessionId::new([byte; 16]),
digest,
};
let (inbound, _received) = futures::channel::mpsc::channel(1);
table
.live
.insert(arguments(1, target).session, OnionExitSessionHandle {
digest: target,
from: Did::from(1_u32),
inbound,
});
table.bury(arguments(2, target).session, 0);
assert_eq!(
table.route(&arguments(1, target), false, 0),
OnionExitRoute::Deliver
);
assert_eq!(
table.route(&arguments(1, other), true, 0),
OnionExitRoute::Drop
);
assert_eq!(
table.route(&arguments(2, target), false, 1),
OnionExitRoute::Answer
);
assert_eq!(
table.route(&arguments(2, target), true, 1),
OnionExitRoute::Answer
);
assert_eq!(
table.route(&arguments(3, target), false, 1),
OnionExitRoute::Drop
);
assert_eq!(
table.route(&arguments(3, target), true, 1),
OnionExitRoute::Open
);
for index in 0..ONION_EXIT_MAX_SESSIONS {
let (inbound, _) = futures::channel::mpsc::channel(1);
let session = u128::try_from(index + 16).expect("small").to_be_bytes();
table
.live
.insert(OnionSessionId::new(session), OnionExitSessionHandle {
digest: target,
from: Did::from(1_u32),
inbound,
});
}
assert_eq!(
table.route(&arguments(3, target), true, 1),
OnionExitRoute::Answer,
"a refused open is answered"
);
}
#[test]
fn test_a_closed_session_is_buried_for_v() {
let mut table = OnionExitTable::default();
let session = OnionSessionId::new([3; 16]);
table.bury(session, 1_000);
assert!(table.is_buried(&session, 1_000 + ONION_ADMISSION_WINDOW_MS - 1));
assert!(!table.is_buried(&session, 1_000 + ONION_ADMISSION_WINDOW_MS));
let mut full = OnionExitTable {
live: HashMap::new(),
closed: HashMap::new(),
};
for index in 0..=ONION_EXIT_MAX_SESSIONS {
let bytes = u128::try_from(index).expect("small").to_be_bytes();
full.bury(
OnionSessionId::new(bytes),
u128::try_from(index).expect("small"),
);
}
assert_eq!(full.closed.len(), ONION_EXIT_MAX_SESSIONS);
let newest = u128::try_from(ONION_EXIT_MAX_SESSIONS)
.expect("small")
.to_be_bytes();
assert!(full.is_buried(&OnionSessionId::new(newest), 0));
assert!(!full.is_buried(&OnionSessionId::new(0_u128.to_be_bytes()), 0));
}
#[test]
fn test_a_lost_link_buries_only_the_sessions_it_carries() {
let mut table = OnionExitTable::default();
let target = OnionTargetDigest::of(b"example.com:443");
let (lost, kept) = (Did::from(7_u32), Did::from(8_u32));
let mut queues = Vec::new();
for (byte, from) in [(1, lost), (2, kept), (3, lost)] {
let (inbound, received) = futures::channel::mpsc::channel(1);
queues.push(received);
table
.live
.insert(OnionSessionId::new([byte; 16]), OnionExitSessionHandle {
digest: target,
from,
inbound,
});
}
table.lose(lost, 0);
let arguments = |byte: u8| OnionSessionArguments {
session: OnionSessionId::new([byte; 16]),
digest: target,
};
assert_eq!(table.route(&arguments(1), false, 1), OnionExitRoute::Answer);
assert_eq!(table.route(&arguments(3), false, 1), OnionExitRoute::Answer);
assert_eq!(
table.route(&arguments(2), false, 1),
OnionExitRoute::Deliver
);
let closed = queues
.iter_mut()
.map(|queue| queue.try_recv().is_err_and(|error| error.is_closed()))
.collect::<Vec<_>>();
assert_eq!(closed, [true, false, true]);
}
#[test]
fn test_a_failure_replaces_the_queued_effects() {
let mut machine = OnionExitSession::new(OnionTargetDigest::of(b"example.com:443"), 0);
let mut queue = VecDeque::from([
OnionExitEffect::Write(Bytes::from_static(b"late")),
OnionExitEffect::ShutdownWrite,
]);
fail(&mut machine, &mut queue);
assert!(queue.iter().all(|effect| !matches!(
effect,
OnionExitEffect::Write(_) | OnionExitEffect::ShutdownWrite
)));
assert!(matches!(queue.back(), Some(OnionExitEffect::Close)));
}
}