use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::task::Poll;
use std::time::Duration;
use bytes::Bytes;
use futures::channel::mpsc;
use futures::future::Either;
use futures::future::Fuse;
use futures::future::FusedFuture;
use futures::FutureExt;
use futures::SinkExt;
use futures::StreamExt;
use rings_core::utils::SharedClock;
use rings_core::utils::SharedRng;
use zeroize::Zeroizing;
use super::client::keep_alive_at;
use super::client::OnionClientCredit;
use super::client::OnionClientEvent;
use super::client::OnionClientSession;
use super::client::OnionControlStep;
use super::client::OnionCreditWindow;
use super::frame::OnionFrame;
use super::pool::ONION_SURB_POOL_CAPACITY;
use super::session_sleep;
use super::witness::OnionSessionWitness;
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::OnionExpiry;
use crate::onion::circuit::OnionLoopClient;
use crate::onion::circuit::OnionReply;
use crate::onion::circuit::OnionReplySink;
use crate::onion::sphinx::class::OnionLoopClass;
use crate::onion::sphinx::layer::OnionApplication;
use crate::onion::OnionProxyTarget;
use crate::onion::OnionRoute;
use crate::onion::OnionRouteError;
use crate::onion::OnionServiceName;
#[cfg(rings_native)]
use crate::tasks::NodeTasks;
pub(crate) const ONION_SESSION_OPEN_TIMEOUT: Duration = Duration::from_secs(45);
const ONION_SESSION_TICK_MS: u128 = 10_000;
pub(crate) const ONION_SESSION_QUEUE: usize = 32;
pub(crate) struct OnionSessionRequest {
pub(crate) route: OnionRoute,
pub(crate) symbol: OnionServiceName,
pub(crate) target: OnionProxyTarget,
pub(crate) class: OnionLoopClass,
pub(crate) window: OnionCreditWindow,
}
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum OnionStreamEvent {
Data(Bytes),
Fin,
Failed,
}
enum OnionStreamCommand {
Data(Bytes),
Fin,
}
pub(crate) struct OnionClientStream {
commands: mpsc::Sender<OnionStreamCommand>,
events: mpsc::Receiver<OnionStreamEvent>,
#[cfg(rings_native)]
witness: OnionSessionWitness,
#[cfg(rings_native)]
tasks: NodeTasks,
}
impl OnionClientStream {
#[cfg(rings_native)]
pub(crate) fn witness(&self) -> OnionSessionWitness {
self.witness.clone()
}
#[cfg(rings_native)]
pub(crate) fn tasks(&self) -> &NodeTasks {
&self.tasks
}
pub(crate) fn split(self) -> (OnionStreamSender, OnionStreamReceiver) {
(
OnionStreamSender {
commands: self.commands,
},
OnionStreamReceiver {
events: self.events,
},
)
}
}
#[cfg(all(test, rings_native))]
pub(crate) struct OnionTestDriver {
events: mpsc::Sender<OnionStreamEvent>,
commands: mpsc::Receiver<OnionStreamCommand>,
}
#[cfg(all(test, rings_native))]
impl OnionClientStream {
pub(crate) fn driven_by_test() -> (Self, OnionTestDriver) {
let (commands, received) = mpsc::channel(ONION_SESSION_QUEUE);
let (events, delivered) = mpsc::channel(ONION_SESSION_QUEUE);
(
Self {
commands,
events: delivered,
witness: OnionSessionWitness::default(),
tasks: NodeTasks::new(),
},
OnionTestDriver {
events,
commands: received,
},
)
}
}
#[cfg(all(test, rings_native))]
impl OnionTestDriver {
pub(crate) async fn emit(&mut self, event: OnionStreamEvent) {
self.events
.send(event)
.await
.expect("the user holds the stream");
}
pub(crate) fn try_emit(&mut self, event: OnionStreamEvent) -> bool {
self.events.try_send(event).is_ok()
}
pub(crate) async fn next_is_fin(&mut self) -> Option<bool> {
self.commands
.next()
.await
.map(|command| matches!(command, OnionStreamCommand::Fin))
}
pub(crate) async fn next_data(&mut self) -> Option<Bytes> {
match self.commands.next().await {
Some(OnionStreamCommand::Data(bytes)) => Some(bytes),
Some(OnionStreamCommand::Fin) | None => None,
}
}
}
pub(crate) struct OnionStreamSender {
commands: mpsc::Sender<OnionStreamCommand>,
}
impl OnionStreamSender {
pub(crate) async fn send(&mut self, bytes: Bytes) -> Result<()> {
self.commands
.send(OnionStreamCommand::Data(bytes))
.await
.map_err(|_| Error::OnionRouteError(OnionRouteError::TcpStreamClosed))
}
pub(crate) async fn fin(&mut self) -> Result<()> {
self.commands
.send(OnionStreamCommand::Fin)
.await
.map_err(|_| Error::OnionRouteError(OnionRouteError::TcpStreamClosed))
}
#[cfg(rings_native)]
pub(crate) async fn ready(&mut self) -> Result<()> {
std::future::poll_fn(|cx| self.commands.poll_ready(cx))
.await
.map_err(|_| Error::OnionRouteError(OnionRouteError::TcpStreamClosed))
}
#[cfg(rings_native)]
pub(crate) fn start_send(&mut self, bytes: Bytes) -> Result<()> {
self.commands
.start_send(OnionStreamCommand::Data(bytes))
.map_err(|_| Error::OnionRouteError(OnionRouteError::TcpStreamClosed))
}
#[cfg(rings_native)]
pub(crate) fn start_fin(&mut self) -> Result<()> {
self.commands
.start_send(OnionStreamCommand::Fin)
.map_err(|_| Error::OnionRouteError(OnionRouteError::TcpStreamClosed))
}
}
pub(crate) struct OnionStreamReceiver {
events: mpsc::Receiver<OnionStreamEvent>,
}
impl OnionStreamReceiver {
pub(crate) async fn next(&mut self) -> Option<OnionStreamEvent> {
self.events.next().await
}
}
pub(crate) async fn open(
loops: OnionLoopClient,
scope: Scope,
request: OnionSessionRequest,
) -> Result<OnionClientStream> {
let clock = loops.clock().clone();
let rng = loops.rng().clone();
open_with_capabilities(loops, scope, request, clock, &rng).await
}
pub(crate) async fn open_with_capabilities(
loops: OnionLoopClient,
scope: Scope,
request: OnionSessionRequest,
clock: SharedClock,
rng: &SharedRng,
) -> Result<OnionClientStream> {
let target = Bytes::from(request.target.authority().into_bytes());
let arguments = OnionSessionArguments {
session: OnionSessionId::from_rng(&mut rng.lock_rng()),
digest: OnionTargetDigest::of(&target),
};
let (commands, received) = mpsc::channel(ONION_SESSION_QUEUE);
let (opened, mut open_result) = futures::channel::oneshot::channel();
let (events, delivered) = mpsc::channel(ONION_SESSION_QUEUE);
let machine = OnionClientSession::with_clock(target, clock.as_ref());
let driver = OnionSessionDriver {
loops,
scope,
clock,
application: OnionApplication {
symbol: request.symbol.into(),
arguments: arguments.encode(),
},
route: request.route,
class: request.class,
window: request.window,
machine,
credit: OnionClientCredit::default(),
last_forward_ms: 0,
fin_sent: false,
given_up: false,
world_ended: false,
witness: OnionSessionWitness::default(),
};
#[cfg(rings_native)]
let witness = driver.witness.clone();
let tasks = driver.scope.tasks().clone();
tasks.spawn(driver.run(received, events, opened))?;
let timeout = session_sleep(ONION_SESSION_OPEN_TIMEOUT).fuse();
futures::pin_mut!(timeout);
match futures::future::select(&mut open_result, timeout).await {
Either::Left((Ok(Ok(true)), _)) => Ok(OnionClientStream {
commands,
events: delivered,
#[cfg(rings_native)]
witness,
#[cfg(rings_native)]
tasks,
}),
Either::Left((Ok(Ok(false)), _)) => {
Err(Error::OnionRouteError(OnionRouteError::ExitRefused))
}
Either::Left((Ok(Err(ended)), _)) => Err(ended),
Either::Left((Err(_), _)) => Err(Error::OnionRouteError(OnionRouteError::SessionFailed)),
Either::Right(_) => Err(Error::OnionProxyRequestTimedOut),
}
}
struct OnionSessionDriver {
loops: OnionLoopClient,
scope: Scope,
clock: SharedClock,
application: OnionApplication,
route: OnionRoute,
class: OnionLoopClass,
window: OnionCreditWindow,
machine: OnionClientSession,
credit: OnionClientCredit,
last_forward_ms: u128,
fin_sent: bool,
given_up: bool,
world_ended: bool,
witness: OnionSessionWitness,
}
type OnionOpenAnswer = futures::channel::oneshot::Sender<Result<bool>>;
type LoopSend = Pin<Box<rings_runtime::maybe_send!(dyn Future<Output = Result<OnionExpiry>>)>>;
enum OnionReplyFlow {
Continue,
Stop,
Fail,
}
impl OnionSessionDriver {
async fn run(
mut self,
commands: mpsc::Receiver<OnionStreamCommand>,
events: mpsc::Sender<OnionStreamEvent>,
opened: OnionOpenAnswer,
) {
let mut opened = Some(opened);
let ended = self.drive(commands, events, &mut opened).await;
if let Some(opened) = opened {
let why = ended
.err()
.unwrap_or(Error::OnionRouteError(OnionRouteError::SessionFailed));
let _ = opened.send(Err(why));
}
}
async fn drive(
&mut self,
mut commands: mpsc::Receiver<OnionStreamCommand>,
mut events: mpsc::Sender<OnionStreamEvent>,
opened: &mut Option<OnionOpenAnswer>,
) -> Result<()> {
let (sink, mut replies) = mpsc::channel::<OnionReply>(ONION_SURB_POOL_CAPACITY);
let frame = self
.machine
.data(Bytes::new())
.map_err(|_| Error::InvalidData)?;
self.send(&frame, &sink).await?;
self.control(OnionControlStep::Refill, &sink)?;
let mut tick = Box::pin(session_sleep(self.tick_after(self.clock.now_ms())).fuse());
let mut sending: Fuse<LoopSend> = Fuse::terminated();
let mut upload_rest = Bytes::new();
let mut fin_requested = false;
let mut pending_events = VecDeque::new();
let mut refill_pending = false;
loop {
if sending.is_terminated() {
if let Err(error) =
self.start_next_send(&mut sending, &mut upload_rest, &mut fin_requested, &sink)
{
self.fail_closed(&sink, &mut events);
return Err(error);
}
}
let can_send_command = sending.is_terminated();
let (step, control) = futures::select! {
sent = sending => match sent {
Ok(expiry) => {
self.departed(expiry);
(Ok(()), None)
}
Err(error) => (Err(error), None),
},
command = next_command(&mut commands, can_send_command).fuse() => match command {
Some(OnionStreamCommand::Data(bytes)) => {
upload_rest = bytes;
(Ok(()), None)
}
Some(OnionStreamCommand::Fin) => {
fin_requested = true;
(Ok(()), None)
}
None => {
if !(self.fin_sent && self.world_ended) {
self.abort(&sink);
}
return Ok(());
}
},
reply_step = step_reply_or_flush(&mut replies, &mut events, &mut pending_events).fuse() => match reply_step {
ReplyOrFlush::Flushed(Ok(())) => {
let control = refill_pending.then_some(OnionControlStep::Refill);
refill_pending = false;
(Ok(()), control)
}
ReplyOrFlush::Flushed(Err(())) => {
if !(self.fin_sent && self.world_ended) {
self.abort(&sink);
}
return Ok(());
}
ReplyOrFlush::Reply(Some(reply)) => match self.on_reply(reply, &mut events, &mut pending_events, opened) {
OnionReplyFlow::Continue if pending_events.is_empty() => {
(Ok(()), Some(OnionControlStep::Refill))
}
OnionReplyFlow::Continue => {
refill_pending = true;
(Ok(()), None)
}
OnionReplyFlow::Stop => return Ok(()),
OnionReplyFlow::Fail => (
Err(Error::OnionRouteError(OnionRouteError::SessionFailed)),
None,
),
},
ReplyOrFlush::Reply(None) => (
Err(Error::OnionRouteError(OnionRouteError::SessionFailed)),
None,
),
},
_ = tick => {
tick = Box::pin(session_sleep(self.tick_after(self.clock.now_ms())).fuse());
(self.expire(), Some(OnionControlStep::Tick))
},
};
let controlled = step.and_then(|()| match control {
Some(control) => self.control(control, &sink),
None => Ok(()),
});
if let Err(error) = controlled {
self.fail_closed(&sink, &mut events);
return Err(error);
}
}
}
fn on_reply(
&mut self,
reply: OnionReply,
events: &mut mpsc::Sender<OnionStreamEvent>,
pending_events: &mut VecDeque<OnionStreamEvent>,
opened: &mut Option<OnionOpenAnswer>,
) -> OnionReplyFlow {
self.credit.replied(reply.received_at_ms);
let Ok(released) = self.machine.reply(reply.received_at_ms, reply.frame) else {
return OnionReplyFlow::Fail;
};
self.witness.record_stalled(self.machine.stalled());
for event in released {
match event {
OnionClientEvent::Opened => {
if let Some(opened) = opened.take() {
let _ = opened.send(Ok(true));
}
}
OnionClientEvent::Refused => {
if let Some(opened) = opened.take() {
let _ = opened.send(Ok(false));
}
return OnionReplyFlow::Stop;
}
OnionClientEvent::Data(bytes) => {
pending_events.push_back(OnionStreamEvent::Data(bytes));
}
OnionClientEvent::Fin => {
self.world_ended = true;
pending_events.push_back(OnionStreamEvent::Fin);
}
OnionClientEvent::Aborted => {
self.given_up = true;
self.witness_failure();
pending_events.clear();
let _ = events.try_send(OnionStreamEvent::Failed);
return OnionReplyFlow::Stop;
}
}
}
OnionReplyFlow::Continue
}
fn fail_closed(&mut self, sink: &OnionReplySink, events: &mut mpsc::Sender<OnionStreamEvent>) {
self.abort(sink);
self.witness_failure();
let _ = events.try_send(OnionStreamEvent::Failed);
}
fn witness_failure(&self) {
if !self.world_ended {
self.witness.record_failed();
}
}
fn start_next_send(
&mut self,
sending: &mut Fuse<LoopSend>,
upload_rest: &mut Bytes,
fin_requested: &mut bool,
sink: &OnionReplySink,
) -> Result<()> {
if !upload_rest.is_empty() {
let capacity = self.machine.data_capacity(self.class).max(1);
let chunk = upload_rest.split_to(capacity.min(upload_rest.len()));
let frame = self.machine.data(chunk).map_err(|_| Error::InvalidData)?;
*sending = self.send_loop(&frame, sink)?.fuse();
} else if *fin_requested {
*fin_requested = false;
if !self.fin_sent {
self.fin_sent = true;
let frame = self.machine.fin().map_err(|_| Error::InvalidData)?;
*sending = self.send_loop(&frame, sink)?.fuse();
}
}
Ok(())
}
fn send_loop(&self, frame: &OnionFrame, sink: &OnionReplySink) -> Result<LoopSend> {
let value = self.encode(frame)?;
let loops = self.loops.clone();
let scope = self.scope.clone();
let route = self.route.clone();
let application = self.application.clone();
let class = self.class;
let sink = sink.clone();
Ok(Box::pin(async move {
loops
.send(&scope, &route, &application, class, &value, &sink)
.await
}))
}
fn abort(&mut self, sink: &OnionReplySink) {
if self.given_up {
return;
}
self.given_up = true;
if let Ok(frame) = self.machine.abort() {
if let Err(error) = self.enqueue(&frame, sink) {
tracing::debug!(%error, "an onion session's abort did not leave");
}
}
}
fn tick_after(&self, now_ms: u128) -> Duration {
let keep_alive_ms = (!self.world_ended).then(|| keep_alive_at(self.last_forward_ms));
let wake_ms = [keep_alive_ms, self.machine.deadline_ms()]
.into_iter()
.flatten()
.filter(|at_ms| *at_ms > now_ms)
.fold(now_ms.saturating_add(ONION_SESSION_TICK_MS), u128::min);
Duration::from_millis(u64::try_from(wake_ms.saturating_sub(now_ms)).unwrap_or(u64::MAX))
}
fn expire(&mut self) -> Result<()> {
self.machine
.expire(self.clock.now_ms())
.map_err(|_| Error::OnionRouteError(OnionRouteError::SessionFailed))
}
fn control(&mut self, step: OnionControlStep, sink: &OnionReplySink) -> Result<()> {
if self.world_ended {
return Ok(());
}
let now_ms = self.clock.now_ms();
let loops = self.window.control_loops(
step,
self.credit.count(now_ms),
self.class,
now_ms,
self.last_forward_ms,
);
for _ in 0..loops {
match self.credit_loop(sink) {
Ok(()) => {}
Err(error) if is_lane_full(&error) => break,
Err(error) => return Err(error),
}
}
Ok(())
}
fn credit_loop(&mut self, sink: &OnionReplySink) -> Result<()> {
let blocks = self.window.credit_blocks(self.class);
let (surbs, tags, expiry) = self.loops.surbs(&self.route, self.class, blocks, sink)?;
let frame = match self.machine.credit(surbs) {
Ok(frame) => frame,
Err(_) => {
self.loops.unregister_tags(tags);
return Err(Error::InvalidData);
}
};
if let Err(error) = self.enqueue(&frame, sink) {
self.loops.unregister_tags(tags);
return Err(error);
}
self.credit.sent(self.clock.now_ms(), expiry, blocks);
Ok(())
}
async fn send(&mut self, frame: &OnionFrame, sink: &OnionReplySink) -> Result<()> {
let value = self.encode(frame)?;
let expiry = self
.loops
.send(
&self.scope,
&self.route,
&self.application,
self.class,
&value,
sink,
)
.await?;
self.departed(expiry);
Ok(())
}
fn enqueue(&mut self, frame: &OnionFrame, sink: &OnionReplySink) -> Result<()> {
let value = self.encode(frame)?;
let expiry = self.loops.enqueue(
&self.scope,
&self.route,
&self.application,
self.class,
&value,
sink,
)?;
self.departed(expiry);
Ok(())
}
fn encode(&self, frame: &OnionFrame) -> Result<Zeroizing<Vec<u8>>> {
frame
.encode(self.class)
.map_err(|error| Error::OnionRouteError(OnionRouteError::LoopBuild(error.to_string())))
}
fn departed(&mut self, expiry: OnionExpiry) {
let now_ms = self.clock.now_ms();
self.credit.sent(now_ms, expiry, 1);
self.last_forward_ms = now_ms;
}
}
fn is_lane_full(error: &Error) -> bool {
matches!(error, Error::OnionQueueAdmission { reason, .. } if reason.is_full())
}
async fn next_command(
commands: &mut mpsc::Receiver<OnionStreamCommand>,
idle: bool,
) -> Option<OnionStreamCommand> {
if !idle {
return futures::future::pending().await;
}
commands.next().await
}
enum ReplyOrFlush {
Flushed(std::result::Result<(), ()>),
Reply(Option<OnionReply>),
}
async fn step_reply_or_flush(
replies: &mut mpsc::Receiver<OnionReply>,
events: &mut mpsc::Sender<OnionStreamEvent>,
pending: &mut VecDeque<OnionStreamEvent>,
) -> ReplyOrFlush {
if pending.is_empty() {
return ReplyOrFlush::Reply(replies.next().await);
}
let flushed = std::future::poll_fn(|cx| {
while !pending.is_empty() {
match events.poll_ready(cx) {
Poll::Ready(Ok(())) => {
if let Some(event) = pending.pop_front() {
if events.start_send(event).is_err() {
return Poll::Ready(Err(()));
}
}
}
Poll::Ready(Err(_)) => return Poll::Ready(Err(())),
Poll::Pending => return Poll::Pending,
}
}
Poll::Ready(Ok(()))
})
.await;
ReplyOrFlush::Flushed(flushed)
}