use crate::FlowCtrlParameters;
use crate::ccparams::{
Algorithm, AlgorithmDiscriminants, CongestionControlParams, CongestionWindowParams,
FixedWindowParams, RoundTripEstimatorParams, VegasParams,
};
use crate::channel::Channel;
use crate::circuit::CircuitRxSender;
use crate::circuit::UniqId;
use crate::circuit::celltypes::{CreateRequest, CreateResponse};
use crate::circuit::circhop::{HopNegotiationType, HopSettings};
use crate::client::circuit::CircParameters;
use crate::client::circuit::padding::PaddingController;
use crate::crypto::cell::CryptInit as _;
use crate::crypto::cell::RelayLayer as _;
use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer, tor1};
use crate::crypto::handshake::RelayHandshakeError;
use crate::crypto::handshake::ServerHandshake as _;
use crate::crypto::handshake::fast::CreateFastServer;
use crate::memquota::SpecificAccount as _;
use crate::memquota::{ChannelAccount, CircuitAccount};
use crate::relay::RelayCirc;
use crate::relay::channel_provider::ChannelProvider;
use crate::relay::reactor::Reactor;
use std::sync::{Arc, RwLock, Weak};
use tor_cell::chancell::ChanMsg as _;
use tor_cell::chancell::CircId;
use tor_cell::chancell::msg::{CreateFast, CreatedFast, Destroy, DestroyReason};
use tor_error::{Bug, ErrorKind, HasKind, debug_report, internal, into_internal};
use tor_linkspec::OwnedChanTarget;
use tor_llcrypto::cipher::aes::Aes128Ctr;
use tor_llcrypto::d::Sha1;
use tor_llcrypto::pk::ed25519::Ed25519Identity;
use tor_llcrypto::pk::rsa::RsaIdentity;
use tor_memquota::mq_queue::ChannelSpec as _;
use tor_memquota::mq_queue::MpscSpec;
use tor_relay_crypto::pk::RelayNtorKeys;
use tor_rtcompat::SpawnExt as _;
use tor_rtcompat::{DynTimeProvider, Runtime};
use tracing::warn;
#[derive(derive_more::Debug)]
pub struct CreateRequestHandler {
chan_provider: Weak<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
circ_net_params: RwLock<CircNetParameters>,
#[debug(skip)]
ntor_keys: RwLock<RelayNtorKeys>,
}
impl CreateRequestHandler {
pub fn new(
chan_provider: Weak<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
circ_net_params: CircNetParameters,
ntor_keys: RelayNtorKeys,
) -> Self {
Self {
chan_provider,
circ_net_params: RwLock::new(circ_net_params),
ntor_keys: RwLock::new(ntor_keys),
}
}
pub fn update_params(&self, circ_net_params: CircNetParameters) {
*self.circ_net_params.write().expect("rwlock poisoned") = circ_net_params;
}
pub fn update_ntor_keys(&self, ntor_keys: RelayNtorKeys) {
*self.ntor_keys.write().expect("rwlock poisoned") = ntor_keys;
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn handle_create<R: Runtime>(
&self,
runtime: &R,
channel: &Arc<Channel>,
our_ed25519_id: &Ed25519Identity,
our_rsa_id: &RsaIdentity,
circ_id: CircId,
msg: &CreateRequest,
memquota: &ChannelAccount,
circ_unique_id: UniqId,
) -> Result<(CreateResponse, RelayCircComponents), Destroy> {
let result = self.handle_create_inner(
runtime,
channel,
our_ed25519_id,
our_rsa_id,
circ_id,
msg,
memquota,
circ_unique_id,
);
match result {
Ok(x) => Ok(x),
Err(e) => {
let cmd = msg.cmd();
debug_report!(&e, %cmd, "Failed to handle circuit create request");
Err(Destroy::new(e.destroy_reason()))
}
}
}
#[allow(clippy::too_many_arguments)]
fn handle_create_inner<R: Runtime>(
&self,
runtime: &R,
channel: &Arc<Channel>,
_our_ed25519_id: &Ed25519Identity,
_our_rsa_id: &RsaIdentity,
circ_id: CircId,
msg: &CreateRequest,
memquota: &ChannelAccount,
circ_unique_id: UniqId,
) -> Result<(CreateResponse, RelayCircComponents), HandleCreateError> {
let handshake_components = match msg {
CreateRequest::CreateFast(msg) => self.handle_create_fast(msg)?,
CreateRequest::Create2(_) => {
return Err(internal!("Not implemented").into());
}
};
let memquota = CircuitAccount::new(memquota)?;
let time_provider = DynTimeProvider::new(runtime.clone());
let account = memquota.as_raw_account();
let (sender, receiver) = MpscSpec::new(10_000_000).new_mq(time_provider, account)?;
let (padding_ctrl, padding_stream) =
crate::client::circuit::padding::new_padding(DynTimeProvider::new(runtime.clone()));
let Some(chan_provider) = self.chan_provider.upgrade() else {
return Err(internal!("Unable to upgrade weak `ChannelProvider`").into());
};
let (reactor, circ) = Reactor::new(
runtime.clone(),
channel,
circ_id,
circ_unique_id,
receiver,
handshake_components.crypto_in,
handshake_components.crypto_out,
&handshake_components.hop_settings,
chan_provider,
padding_ctrl.clone(),
padding_stream,
&memquota,
)
.map_err(into_internal!("Failed to start circuit reactor"))?;
let () = runtime.spawn(async {
match reactor.run().await {
Ok(()) => {}
Err(e) => {
debug_report!(e, "Relay circuit reactor exited with an error");
}
}
})?;
Ok((
handshake_components.response,
RelayCircComponents {
circ,
sender,
padding_ctrl,
},
))
}
fn handle_create_fast(
&self,
msg: &CreateFast,
) -> Result<CompletedHandshakeComponents, HandleCreateError> {
let (keygen, handshake_msg) = CreateFastServer::server(
&mut rand::rng(),
&mut |_: &()| Some(()),
&[()],
msg.handshake(),
)?;
let crypt = tor1::CryptStatePair::<Aes128Ctr, Sha1>::construct(keygen)
.map_err(into_internal!("Circuit crypt state construction failed"))?;
let circ_params = self
.circ_net_params
.read()
.expect("rwlock poisoned")
.as_circ_parameters(AlgorithmDiscriminants::FixedWindow)?;
let protos = tor_protover::Protocols::default();
let hop_settings =
HopSettings::from_params_and_caps(HopNegotiationType::None, &circ_params, &protos)
.map_err(into_internal!("Unable to build `HopSettings`"))?;
let response = CreatedFast::new(handshake_msg);
let response = CreateResponse::CreatedFast(response);
let (crypto_out, crypto_in, _binding) = crypt.split_relay_layer();
let (crypto_out, crypto_in) = (Box::new(crypto_out), Box::new(crypto_in));
Ok(CompletedHandshakeComponents {
response,
hop_settings,
crypto_out,
crypto_in,
})
}
}
#[derive(Debug, thiserror::Error)]
enum HandleCreateError {
#[error("Circuit relay handshake failed")]
Handshake(#[from] RelayHandshakeError),
#[error("Memquota error")]
Memquota(#[from] tor_memquota::Error),
#[error("Runtime task spawn error")]
Spawn(#[from] futures::task::SpawnError),
#[error("Internal error")]
Internal(#[from] tor_error::Bug),
}
impl HandleCreateError {
fn destroy_reason(&self) -> DestroyReason {
match self {
Self::Handshake(e) => e.destroy_reason(),
Self::Memquota(_) => DestroyReason::INTERNAL,
Self::Spawn(_) => DestroyReason::INTERNAL,
Self::Internal(_) => DestroyReason::INTERNAL,
}
}
}
impl HasKind for HandleCreateError {
fn kind(&self) -> ErrorKind {
match self {
Self::Handshake(e) => e.kind(),
Self::Memquota(e) => e.kind(),
Self::Spawn(e) => e.kind(),
Self::Internal(_) => ErrorKind::Internal,
}
}
}
struct CompletedHandshakeComponents {
response: CreateResponse,
hop_settings: HopSettings,
crypto_out: Box<dyn OutboundRelayLayer + Send>,
crypto_in: Box<dyn InboundRelayLayer + Send>,
}
pub(crate) struct RelayCircComponents {
pub(crate) circ: Arc<RelayCirc>,
pub(crate) sender: CircuitRxSender,
pub(crate) padding_ctrl: PaddingController,
}
#[derive(Debug, Clone)]
#[allow(clippy::exhaustive_structs)]
pub struct CongestionControlNetParams {
pub fixed_window: FixedWindowParams,
pub vegas_exit: VegasParams,
pub cwnd: CongestionWindowParams,
pub rtt: RoundTripEstimatorParams,
pub flow_ctrl: FlowCtrlParameters,
}
impl CongestionControlNetParams {
#[cfg(test)]
pub(crate) fn defaults_for_tests() -> Self {
Self {
fixed_window: FixedWindowParams::defaults_for_tests(),
vegas_exit: VegasParams::defaults_for_tests(),
cwnd: CongestionWindowParams::defaults_for_tests(),
rtt: RoundTripEstimatorParams::defaults_for_tests(),
flow_ctrl: FlowCtrlParameters::defaults_for_tests(),
}
}
}
#[derive(Debug, Clone)]
#[allow(clippy::exhaustive_structs)]
pub struct CircNetParameters {
pub extend_by_ed25519_id: bool,
pub cc: CongestionControlNetParams,
}
impl CircNetParameters {
#[warn(unused)]
fn as_circ_parameters(&self, algorithm: AlgorithmDiscriminants) -> Result<CircParameters, Bug> {
let Self {
extend_by_ed25519_id,
cc:
CongestionControlNetParams {
fixed_window,
vegas_exit,
cwnd,
rtt,
flow_ctrl,
},
} = self;
let algorithm = match algorithm {
AlgorithmDiscriminants::FixedWindow => Algorithm::FixedWindow(*fixed_window),
AlgorithmDiscriminants::Vegas => Algorithm::Vegas(*vegas_exit),
};
let cc = CongestionControlParams::builder()
.alg(algorithm)
.fixed_window_params(*fixed_window)
.cwnd_params(*cwnd)
.rtt_params(rtt.clone())
.build()
.map_err(into_internal!("Could not build `CongestionControlParams`"))?;
Ok(CircParameters::new(
*extend_by_ed25519_id,
cc,
flow_ctrl.clone(),
))
}
}