Lines
72.09 %
Functions
6.4 %
Branches
100 %
//! Channel for sending messages to [`StreamReactor`].
// TODO(DEDUP): this will replace CircHopList when we rewrite the client reactor
// to use the new reactor architecture
mod circhop;
use crate::circuit::UniqId;
use crate::circuit::circhop::{CircHopOutbound, HopSettings};
use crate::circuit::metrics::CircuitMetrics;
use crate::circuit::reactor::stream::{CtrlMsg, ReadyStreamMsg, StreamHandler, StreamReactor};
use crate::congestion::{CongestionControl, CongestionSignals};
use crate::crypto::cell::RelayCellBody;
use crate::memquota::CircuitAccount;
use crate::util::err::ReactorError;
use crate::{Error, HopNum, Result};
use circhop::CircHopList;
#[cfg(any(feature = "hs-service", feature = "relay"))]
use {
crate::stream::CloseStreamBehavior, crate::stream::incoming::IncomingStreamRequestHandler,
tor_cell::relaycell::StreamId,
};
use tor_cell::chancell::CircId;
use tor_cell::relaycell::msg::{Sendme, SendmeTag};
use tor_cell::relaycell::{AnyRelayMsgOuter, RelayCellDecoderResult, RelayCellFormat};
use tor_error::internal;
use tor_rtcompat::{DynTimeProvider, Runtime};
use futures::SinkExt;
use futures::channel::mpsc;
use std::result::Result as StdResult;
use std::sync::{Arc, Mutex, RwLock};
/// The state of a circuit.
///
/// This contains the per-hop state (e.g. congestion control information),
/// and a handle to the stream reactor of the hop.
/// The stream reactor of the hop is launched lazily,
/// when the first [`CtrlMsg`] is sent via [`CircuitState::send`].
/// This is owned by the decrypting reactor.
pub(crate) struct CircuitState<R: Runtime> {
/// A handle to the runtime.
runtime: R,
/// Context used when spawning a stream reactor.
ctx: StreamReactorContext,
/// Sender for sending messages to the encrypting reactor.
/// The receiver is in encrypting reactor.
/// A clone of this is passed to each spawned StreamReactor
enc_tx: mpsc::Sender<ReadyStreamMsg>,
/// The shared parts of the circuit state.
/// The encrypting reactor has a clone of this.
shared: Arc<CircuitStateShared>,
/// Memory quota account
memquota: CircuitAccount,
}
/// The shared parts of a [`CircuitState`].
/// Currently, this is used by the encrypting reactor,
/// which needs access to the congestion control objects.
/// The encrypting reactor only ever *reads* from this
/// (it never mutates the circ hop list).
pub(crate) struct CircuitStateShared {
/// The underlying senders, indexed by [`HopNum`].
/// Relays have at most one stream reactor per circuit.
/// Clients have at most one stream reactor per circuit hop.
hops: RwLock<CircHopList>,
impl CircuitStateShared {
/// Return the RelayCellFormat and CC state of a given hop.
pub(crate) fn hop_info(
&self,
hopnum: Option<HopNum>,
) -> Result<(RelayCellFormat, Arc<Mutex<CongestionControl>>)> {
let hops = self.hops.read().expect("poisoned lock");
let hop = hops.get(hopnum)?;
let relay_cell_format = hop.settings.relay_crypt_protocol().relay_cell_format();
let ccontrol = Arc::clone(&hop.ccontrol);
Ok((relay_cell_format, ccontrol))
/// Update the congestion control state of the specified hop
/// that we received a SENDME along with possible congestion signals.
pub(crate) fn note_sendme_received(
runtime: &DynTimeProvider,
tag: SendmeTag,
signals: CongestionSignals,
) -> Result<()> {
// Update the CC object that we received a SENDME along
// with possible congestion signals.
hop.ccontrol
.lock()
.expect("poisoned lock")
.note_sendme_received(runtime, tag, signals)?;
Ok(())
/// Try to parse a RELAY or RELAY_EARLY cell body.
/// Relays pass `None` for the hopnum.
pub(crate) fn decode(
body: RelayCellBody,
) -> Result<RelayCellDecoderResult> {
hops.get(hopnum)?.inbound.decode(body.into())
/// Note that we have received a RELAY cell.
/// Returns whether we need to send back a SENDME.
/// Updates the padding and CC state.
pub(crate) fn note_relay_cell_received(
c_t_w: bool,
) -> Result<Option<AnyRelayMsgOuter>> {
let mut hops = self.hops.write().expect("poisoned lock");
let hop = hops.get_mut(hopnum)?;
// Check whether we are allowed to receive more data for this circuit hop.
hop.inbound.decrement_cell_limit()?;
// Decrement the circuit sendme windows, and see if we need to
// send a sendme cell.
let send_circ_sendme = if c_t_w {
.note_data_received()?
} else {
false
// If we do need to send a circuit-level SENDME cell, do so.
if send_circ_sendme {
// This always sends a V1 (tagged) sendme cell, and thereby assumes
// that SendmeEmitMinVersion is no more than 1. If the authorities
// every increase that parameter to a higher number, this will
// become incorrect. (Higher numbers are not currently defined.)
let sendme = Sendme::from(tag);
Ok(Some(AnyRelayMsgOuter::new(None, sendme.into())))
Ok(None)
/// State needed to build a stream reactor.
/// Used when spawning the stream reactor of a hop.
struct StreamReactorContext {
/// An identifier for logging about this reactor's circuit.
unique_id: UniqId,
/// The circuit identifier on the inbound Tor channel.
circ_id: CircId,
/// The incoming stream handler.
/// This is shared with every StreamReactor.
incoming: Arc<Mutex<Option<IncomingStreamRequestHandler>>>,
/// A handler for customizing the stream reactor behavior.
handler: Arc<dyn StreamHandler>,
/// The circuit metrics.
metrics: Arc<CircuitMetrics>,
impl<R: Runtime> CircuitState<R> {
/// Create a new [`CircuitState`] consisting of a single CircHop
/// (built using the specified `settings),
/// setting the incoming stream request handler to `incoming_handler`.
#[cfg(feature = "relay")]
#[allow(clippy::too_many_arguments)] // this is an internal function with 1 call site
pub(crate) fn new_relay<S: StreamHandler>(
settings: HopSettings,
handler: S,
incoming_handler: IncomingStreamRequestHandler,
) -> Self {
let hops = CircHopList::new_relay(settings);
Self::new_inner(
runtime,
hops,
unique_id,
circ_id,
handler,
enc_tx,
Some(incoming_handler),
memquota,
metrics,
)
/// Create a new [`CircuitState`] with an empty hop list.
/// Hops are added with [`CircuitState::add_hop`].
#[expect(unused)] // TODO(dedup): clients will use this
pub(crate) fn new_client<S: StreamHandler>(
let hops = CircHopList::new_client();
None,
/// Helper for the new*() functions.
#[allow(clippy::too_many_arguments)] // this is an internal function with 2 call sites
fn new_inner<S: StreamHandler>(
hops: CircHopList,
#[cfg(any(feature = "hs-service", feature = "relay"))] incoming_handler: Option<
IncomingStreamRequestHandler,
>,
let hops = RwLock::new(hops);
let ctx = StreamReactorContext {
incoming: Arc::new(Mutex::new(incoming_handler)),
handler: Arc::new(handler),
let shared = Arc::new(CircuitStateShared { hops });
Self {
shared,
ctx,
/// Return a reference to our shared state.
pub(crate) fn shared(&self) -> &Arc<CircuitStateShared> {
&self.shared
/// Set the incoming stream handler for this reactor.
/// There can only be one incoming stream handler per reactor,
/// and each stream handler only pertains to a single hop (see expected_hop())
//
// TODO: eventually, we might want a different design here,
// for example we might want to allow multiple stream handlers per reactor (one per hop).
// However, for now, the implementation is intentionally kept similar to that
// in the client reactor (to make it easier to migrate it to the new reactor design).
/// Returns an error if a stream handler was already installed.
/// Since the handler is shared with every hop's stream reactor,
/// this function will update the handler for all of them.
// TODO(DEDUP): almost identical to the client-side
// CellHandlers::set_incoming_stream_req_handler()
pub(crate) fn set_incoming_handler(&self, handler: IncomingStreamRequestHandler) -> Result<()> {
let mut lock = self.ctx.incoming.lock().expect("poisoned lock");
if lock.is_none() {
*lock = Some(handler);
Err(Error::from(internal!(
"Tried to install a BEGIN cell handler before the old one was gone."
)))
/// Push a new hop to our hop list.
/// Prepares a cc object for the hop, but does not spawn a stream reactor.
/// Will return an error if the circuit already has [`u8::MAX`] hops.
pub(crate) fn add_hop(&mut self, settings: HopSettings) -> Result<()> {
let mut hops = self.shared.hops.write().expect("poisoned lock");
hops.add_hop(settings)
/// Send a message to the stream reactor of the specified `hop`,
/// spawning it if necessary.
pub(crate) async fn send(
&mut self,
msg: CtrlMsg,
) -> StdResult<(), ReactorError> {
let mut tx = self.get_or_spawn_stream_reactor(hopnum)?;
tx.send(msg).await.map_err(|_| {
// The stream reactor has shut down
ReactorError::Shutdown
})
/// Tell the stream reactor of the specified `hop`
/// to close the stream with the specified `stream_id`.
pub(crate) async fn close_pending(
stream_id: StreamId,
behav: CloseStreamBehavior,
) -> StdResult<(), Error> {
let msg = CtrlMsg::ClosePendingStream { stream_id, behav };
Error::NotConnected
/// Get a handle to the stream reactor, spawning it if necessary
fn get_or_spawn_stream_reactor(
) -> StdResult<mpsc::Sender<CtrlMsg>, Error> {
let tx = match &hop.tx {
Some(tx) => tx.clone(),
None => {
// If we don't have a handle to the stream reactor,
// it means it hasn't been spawned yet, so we have to spawn it now.
let tx =
self.spawn_stream_reactor(hopnum, &hop.settings, Arc::clone(&hop.ccontrol))?;
hop.tx = Some(tx.clone());
// Return a copy of this sender (can't borrow because the hop
// is behind a Mutex, and we can't keep it locked across the send()
// await point)
tx
Ok(tx)
/// Spawn a [`StreamReactor`] for the specified hop.
fn spawn_stream_reactor(
settings: &HopSettings,
ccontrol: Arc<Mutex<CongestionControl>>,
use tor_rtcompat::SpawnExt as _;
// NOTE: not registering this channel with the memquota subsystem is okay,
// because it has no buffering (if ever decide to make the size of this buffer
// non-zero for whatever reason, we must remember to register it with memquota
// so that it counts towards the total memory usage for the circuit.
// NOTE: We should be careful about the effect of buffering on flow control.
// See comments on `StreamReactor::cell_rx` about XON/XOFF flow control.
// TODO(tuning): having zero buffering here is very likely suboptimal.
// We should do *some* buffering here, and then figure out if we should it
// up to memquota or not.
#[allow(clippy::disallowed_methods)]
let (dec_stream_tx, dec_stream_rx) = mpsc::channel(0);
let flow_ctrl_params = Arc::new(settings.flow_ctrl_params.clone());
let relay_format = settings.relay_crypt_protocol().relay_cell_format();
let outbound = CircHopOutbound::new(ccontrol, relay_format, flow_ctrl_params, settings);
let stream_reactor = StreamReactor::new(
self.runtime.clone(),
hopnum,
outbound,
self.ctx.unique_id,
self.ctx.circ_id,
dec_stream_rx,
self.enc_tx.clone(),
Arc::clone(&self.ctx.handler),
Arc::clone(&self.ctx.incoming),
self.memquota.clone(),
Arc::clone(&self.ctx.metrics),
);
self.runtime
.spawn(async {
let _ = stream_reactor.run().await;
.map_err(|e| Error::Spawn {
spawning: "stream reactor",
cause: e.into(),
})?;
Ok(dec_stream_tx)