use std::time::Duration;
use bytes::Bytes;
use futures::channel::mpsc;
use futures::future::Either;
use futures::FutureExt;
use futures::SinkExt;
use futures::StreamExt;
use rings_core::utils::get_epoch_ms;
use rings_runtime::sleep;
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::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;
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) async fn next_is_fin(&mut self) -> Option<bool> {
self.commands
.next()
.await
.map(|command| matches!(command, OnionStreamCommand::Fin))
}
}
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))
}
}
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 target = Bytes::from(request.target.authority().into_bytes());
let arguments = OnionSessionArguments {
session: OnionSessionId::random(),
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 driver = OnionSessionDriver {
loops,
scope,
application: OnionApplication {
symbol: request.symbol,
arguments: arguments.encode(),
},
route: request.route,
class: request.class,
window: request.window,
machine: OnionClientSession::new(target, get_epoch_ms()),
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 = 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,
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>>;
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(sleep(self.tick_after(get_epoch_ms())).fuse());
loop {
let (step, control) = futures::select! {
command = commands.next() => match command {
Some(OnionStreamCommand::Data(bytes)) => {
(self.upload(bytes, &sink).await, None)
}
Some(OnionStreamCommand::Fin) => (self.finish(&sink).await, None),
None => {
if !(self.fin_sent && self.world_ended) {
self.abort(&sink);
}
return Ok(());
}
},
reply = replies.next() => match reply {
Some(reply) => match self.on_reply(reply, &mut events, opened).await {
OnionReplyFlow::Continue => (Ok(()), Some(OnionControlStep::Refill)),
OnionReplyFlow::Stop => return Ok(()),
OnionReplyFlow::Fail => (
Err(Error::OnionRouteError(OnionRouteError::SessionFailed)),
None,
),
},
None => (
Err(Error::OnionRouteError(OnionRouteError::SessionFailed)),
None,
),
},
_ = tick => {
tick = Box::pin(sleep(self.tick_after(get_epoch_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.abort(&sink);
self.witness_failure();
let _ = events.send(OnionStreamEvent::Failed).await;
return Err(error);
}
}
}
async fn on_reply(
&mut self,
reply: OnionReply,
events: &mut mpsc::Sender<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 {
let forwarded = match event {
OnionClientEvent::Opened => {
if let Some(opened) = opened.take() {
let _ = opened.send(Ok(true));
}
Ok(())
}
OnionClientEvent::Refused => {
if let Some(opened) = opened.take() {
let _ = opened.send(Ok(false));
}
return OnionReplyFlow::Stop;
}
OnionClientEvent::Data(bytes) => events.send(OnionStreamEvent::Data(bytes)).await,
OnionClientEvent::Fin => {
self.world_ended = true;
events.send(OnionStreamEvent::Fin).await
}
OnionClientEvent::Aborted => {
self.given_up = true;
self.witness_failure();
let _ = events.send(OnionStreamEvent::Failed).await;
return OnionReplyFlow::Stop;
}
};
if forwarded.is_err() {
return OnionReplyFlow::Stop;
}
}
OnionReplyFlow::Continue
}
fn witness_failure(&self) {
if !self.world_ended {
self.witness.record_failed();
}
}
async fn upload(&mut self, bytes: Bytes, sink: &OnionReplySink) -> Result<()> {
let mut rest = bytes;
while !rest.is_empty() {
let capacity = self.machine.data_capacity(self.class).max(1);
let chunk = rest.split_to(capacity.min(rest.len()));
let frame = self.machine.data(chunk).map_err(|_| Error::InvalidData)?;
self.send(&frame, sink).await?;
}
Ok(())
}
async fn finish(&mut self, sink: &OnionReplySink) -> Result<()> {
if self.fin_sent {
return Ok(());
}
self.fin_sent = true;
let frame = self.machine.fin().map_err(|_| Error::InvalidData)?;
self.send(&frame, 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(get_epoch_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 = get_epoch_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 = OnionFrame::credit_capacity(self.class);
let (surbs, expiry) = self.loops.surbs(&self.route, self.class, blocks, sink)?;
let frame = self.machine.credit(surbs).map_err(|_| Error::InvalidData)?;
self.enqueue(&frame, sink)?;
self.credit.sent(get_epoch_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 = get_epoch_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())
}