Skip to main content

tor_circmgr/
build.rs

1//! Facilities to build circuits directly, instead of via a circuit manager.
2
3use crate::path::{OwnedPath, TorPath};
4use crate::timeouts::{self, Action};
5use crate::{Error, Result};
6use async_trait::async_trait;
7use futures::Future;
8use oneshot_fused_workaround as oneshot;
9use std::sync::{
10    Arc,
11    atomic::{AtomicU32, Ordering},
12};
13use tor_chanmgr::{ChanMgr, ChanProvenance, ChannelUsage};
14use tor_error::into_internal;
15use tor_guardmgr::GuardStatus;
16use tor_linkspec::{IntoOwnedChanTarget, OwnedChanTarget, OwnedCircTarget};
17use tor_netdir::params::NetParameters;
18use tor_proto::ccparams::{self, AlgorithmType};
19use tor_proto::client::circuit::{CircParameters, PendingClientTunnel};
20use tor_proto::{CellCount, ClientTunnel, FlowCtrlParameters};
21use tor_rtcompat::SpawnExt;
22use tor_rtcompat::{Runtime, SleepProviderExt};
23use tor_units::Percentage;
24use tracing::instrument;
25use web_time_compat::{Duration, Instant};
26
27#[cfg(all(feature = "vanguards", feature = "hs-common"))]
28use tor_guardmgr::vanguards::VanguardMgr;
29
30mod guardstatus;
31
32pub(crate) use guardstatus::GuardStatusHandle;
33
34/// Represents an objects that can be constructed in a circuit-like way.
35///
36/// This is only a separate trait for testing purposes, so that we can swap
37/// our some other type when we're testing Builder.
38///
39/// TODO: I'd like to have a simpler testing strategy here; this one
40/// complicates things a bit.
41#[async_trait]
42pub(crate) trait Buildable: Sized {
43    /// Our equivalent to a tor_proto::Channel.
44    type Chan: Send + Sync;
45
46    /// Use a channel manager to open a new channel (or find an existing channel)
47    /// to a provided [`OwnedChanTarget`].
48    async fn open_channel<RT: Runtime>(
49        chanmgr: &ChanMgr<RT>,
50        ct: &OwnedChanTarget,
51        guard_status: &GuardStatusHandle,
52        usage: ChannelUsage,
53    ) -> Result<Arc<Self::Chan>>;
54
55    /// Launch a new one-hop circuit to a given relay, given only a
56    /// channel target `ct` specifying that relay.
57    ///
58    /// (Since we don't have a CircTarget here, we can't extend the circuit
59    /// to be multihop later on.)
60    async fn create_chantarget<RT: Runtime>(
61        chan: Arc<Self::Chan>,
62        rt: &RT,
63        ct: &OwnedChanTarget,
64        params: CircParameters,
65        timeouts: Arc<dyn tor_proto::client::circuit::TimeoutEstimator>,
66    ) -> Result<Self>;
67
68    /// Launch a new circuit through a given relay, given a circuit target
69    /// `ct` specifying that relay.
70    async fn create<RT: Runtime>(
71        chan: Arc<Self::Chan>,
72        rt: &RT,
73        ct: &OwnedCircTarget,
74        params: CircParameters,
75        timeouts: Arc<dyn tor_proto::client::circuit::TimeoutEstimator>,
76    ) -> Result<Self>;
77
78    /// Extend this circuit-like object by one hop, to the location described
79    /// in `ct`.
80    async fn extend<RT: Runtime>(
81        &self,
82        rt: &RT,
83        ct: &OwnedCircTarget,
84        params: CircParameters,
85    ) -> Result<()>;
86}
87
88/// Try to make a [`PendingClientTunnel`] to a given relay, and start its
89/// reactor.
90///
91/// This is common code, shared by all the first-hop functions in the
92/// implementation of `Buildable` for `ClientTunnel`.
93#[instrument(level = "trace", skip_all)]
94async fn create_common<RT: Runtime>(
95    chan: Arc<tor_proto::channel::Channel>,
96    timeouts: Arc<dyn tor_proto::client::circuit::TimeoutEstimator>,
97    rt: &RT,
98) -> Result<PendingClientTunnel> {
99    // Construct the (zero-hop) circuit.
100    let (pending_tunnel, reactor) =
101        chan.new_tunnel(timeouts)
102            .await
103            .map_err(|error| Error::Protocol {
104                error,
105                peer: None, // we don't blame the peer, because new_tunnel() does no networking.
106                action: "initializing circuit",
107                unique_id: None,
108            })?;
109
110    tracing::debug!("Spawning reactor...");
111
112    rt.spawn(async {
113        let _ = reactor.run().await;
114    })
115    .map_err(|e| Error::from_spawn("circuit reactor task", e))?;
116
117    Ok(pending_tunnel)
118}
119
120#[async_trait]
121impl Buildable for ClientTunnel {
122    type Chan = tor_proto::channel::Channel;
123
124    #[instrument(level = "trace", skip_all)]
125    async fn open_channel<RT: Runtime>(
126        chanmgr: &ChanMgr<RT>,
127        target: &OwnedChanTarget,
128        guard_status: &GuardStatusHandle,
129        usage: ChannelUsage,
130    ) -> Result<Arc<Self::Chan>> {
131        // If we fail now, it's the guard's fault.
132        guard_status.pending(GuardStatus::Failure);
133
134        // Get or construct the channel.
135        let result = chanmgr.get_or_launch(target, usage).await;
136
137        // Report the clock skew if appropriate, and exit if there has been an error.
138        match result {
139            Ok((chan, ChanProvenance::NewlyCreated)) => {
140                guard_status.skew(chan.clock_skew());
141                Ok(chan)
142            }
143            Ok((chan, _)) => Ok(chan),
144            Err(cause) => {
145                if let Some(skew) = cause.clock_skew() {
146                    guard_status.skew(skew);
147                }
148                Err(Error::Channel {
149                    peer: target.to_logged(),
150                    cause,
151                })
152            }
153        }
154    }
155
156    #[instrument(level = "trace", skip_all)]
157    async fn create_chantarget<RT: Runtime>(
158        chan: Arc<Self::Chan>,
159        rt: &RT,
160        ct: &OwnedChanTarget,
161        params: CircParameters,
162        timeouts: Arc<dyn tor_proto::client::circuit::TimeoutEstimator>,
163    ) -> Result<Self> {
164        let pending_tunnel = create_common(chan, timeouts, rt).await?;
165        let unique_id = Some(pending_tunnel.peek_unique_id());
166        pending_tunnel
167            .create_firsthop_fast(params)
168            .await
169            .map_err(|error| Error::Protocol {
170                peer: Some(ct.to_logged()),
171                error,
172                action: "running CREATE_FAST handshake",
173                unique_id,
174            })
175    }
176    #[instrument(level = "trace", skip_all)]
177    async fn create<RT: Runtime>(
178        chan: Arc<Self::Chan>,
179        rt: &RT,
180        ct: &OwnedCircTarget,
181        params: CircParameters,
182        timeouts: Arc<dyn tor_proto::client::circuit::TimeoutEstimator>,
183    ) -> Result<Self> {
184        let pending_tunnel = create_common(chan, timeouts, rt).await?;
185        let unique_id = Some(pending_tunnel.peek_unique_id());
186
187        let handshake_res = pending_tunnel.create_firsthop(ct, params).await;
188        handshake_res.map_err(|error| Error::Protocol {
189            peer: Some(ct.to_logged()),
190            error,
191            action: "creating first hop",
192            unique_id,
193        })
194    }
195    async fn extend<RT: Runtime>(
196        &self,
197        _rt: &RT,
198        ct: &OwnedCircTarget,
199        params: CircParameters,
200    ) -> Result<()> {
201        let circ = self.as_single_circ().map_err(|error| Error::Protocol {
202            peer: Some(ct.to_logged()),
203            error,
204            action: "extend tunnel",
205            unique_id: Some(self.unique_id()),
206        })?;
207
208        let res = circ.extend(ct, params).await;
209        res.map_err(|error| Error::Protocol {
210            error,
211            // We can't know who caused the error, since it may have been
212            // the hop we were extending from, or the hop we were extending
213            // to.
214            peer: None,
215            action: "extending circuit",
216            unique_id: Some(self.unique_id()),
217        })
218    }
219}
220
221/// An implementation type for [`TunnelBuilder`].
222///
223/// A `TunnelBuilder` holds references to all the objects that are needed
224/// to build circuits correctly.
225///
226/// In general, you should not need to construct or use this object yourself,
227/// unless you are choosing your own paths.
228struct Builder<R: Runtime, C: Buildable + Sync + Send + 'static> {
229    /// The runtime used by this circuit builder.
230    runtime: R,
231    /// A channel manager that this circuit builder uses to make channels.
232    chanmgr: Arc<ChanMgr<R>>,
233    /// An estimator to determine the correct timeouts for circuit building.
234    timeouts: Arc<timeouts::Estimator>,
235    /// We don't actually hold any clientcircs, so we need to put this
236    /// type here so the compiler won't freak out.
237    _phantom: std::marker::PhantomData<C>,
238}
239
240impl<R: Runtime, C: Buildable + Sync + Send + 'static> Builder<R, C> {
241    /// Construct a new [`Builder`].
242    fn new(runtime: R, chanmgr: Arc<ChanMgr<R>>, timeouts: timeouts::Estimator) -> Self {
243        Builder {
244            runtime,
245            chanmgr,
246            timeouts: Arc::new(timeouts),
247            _phantom: std::marker::PhantomData,
248        }
249    }
250
251    /// Build a circuit, without performing any timeout operations.
252    ///
253    /// After each hop is built, increments n_hops_built.  Make sure that
254    /// `guard_status` has its pending status set correctly to correspond
255    /// to a circuit failure at any given stage.
256    ///
257    /// Requires that `channel` is a channel to the first hop of `path`.
258    ///
259    /// (TODO: Find
260    /// a better design there.)
261    #[instrument(level = "trace", skip_all)]
262    async fn build_notimeout(
263        self: Arc<Self>,
264        path: OwnedPath,
265        channel: Arc<C::Chan>,
266        params: CircParameters,
267        start_time: Instant,
268        n_hops_built: Arc<AtomicU32>,
269        guard_status: Arc<GuardStatusHandle>,
270    ) -> Result<C> {
271        match path {
272            OwnedPath::ChannelOnly(target) => {
273                let timeouts = Arc::clone(&self.timeouts);
274                let circ =
275                    C::create_chantarget(channel, &self.runtime, &target, params, timeouts).await?;
276                self.timeouts
277                    .note_hop_completed(0, self.runtime.now() - start_time, true);
278                n_hops_built.fetch_add(1, Ordering::SeqCst);
279                Ok(circ)
280            }
281            OwnedPath::Normal(p) => {
282                assert!(!p.is_empty());
283                let n_hops = p.len() as u8;
284                let timeouts = Arc::clone(&self.timeouts);
285                // Each hop has its own circ parameters. This is for the first hop (CREATE).
286                let circ =
287                    C::create(channel, &self.runtime, &p[0], params.clone(), timeouts).await?;
288                self.timeouts
289                    .note_hop_completed(0, self.runtime.now() - start_time, n_hops == 0);
290                // If we fail after this point, we can't tell whether it's
291                // the fault of the guard or some later relay.
292                guard_status.pending(GuardStatus::Indeterminate);
293                n_hops_built.fetch_add(1, Ordering::SeqCst);
294                for (hop_num, relay) in (1..).zip(p[1..].iter()) {
295                    // Get the params per subsequent hop (EXTEND).
296                    circ.extend(&self.runtime, relay, params.clone()).await?;
297                    n_hops_built.fetch_add(1, Ordering::SeqCst);
298                    self.timeouts.note_hop_completed(
299                        hop_num,
300                        self.runtime.now() - start_time,
301                        hop_num == (n_hops - 1),
302                    );
303                }
304                Ok(circ)
305            }
306        }
307    }
308
309    /// Build a circuit from an [`OwnedPath`].
310    #[instrument(level = "trace", skip_all)]
311    async fn build_owned(
312        self: &Arc<Self>,
313        path: OwnedPath,
314        params: &CircParameters,
315        guard_status: Arc<GuardStatusHandle>,
316        usage: ChannelUsage,
317    ) -> Result<C> {
318        let action = Action::BuildCircuit { length: path.len() };
319        let (timeout, abandon_timeout) = self.timeouts.timeouts(&action);
320
321        // TODO: This is probably not the best way for build_notimeout to
322        // tell us how many hops it managed to build, but at least it is
323        // isolated here.
324        let hops_built = Arc::new(AtomicU32::new(0));
325
326        let self_clone = Arc::clone(self);
327        let params = params.clone();
328
329        // We open the channel separately from the rest of the circuit, since we don't want to count
330        // it towards the circuit timeout.
331        //
332        // We don't need a separate timeout here, since ChanMgr already implements its own timeouts.
333        let channel = C::open_channel(
334            &self.chanmgr,
335            path.first_hop_as_chantarget(),
336            guard_status.as_ref(),
337            usage,
338        )
339        .await?;
340
341        let start_time = self.runtime.now();
342
343        let circuit_future = self_clone.build_notimeout(
344            path,
345            channel,
346            params,
347            start_time,
348            Arc::clone(&hops_built),
349            guard_status,
350        );
351
352        match double_timeout(&self.runtime, circuit_future, timeout, abandon_timeout).await {
353            Ok(circuit) => Ok(circuit),
354            Err(Error::CircTimeout(unique_id)) => {
355                let n_built = hops_built.load(Ordering::SeqCst);
356                self.timeouts
357                    .note_circ_timeout(n_built as u8, self.runtime.now() - start_time);
358                Err(Error::CircTimeout(unique_id))
359            }
360            Err(e) => Err(e),
361        }
362    }
363
364    /// Return a reference to this Builder runtime.
365    pub(crate) fn runtime(&self) -> &R {
366        &self.runtime
367    }
368
369    /// Return a reference to this Builder's timeout estimator.
370    pub(crate) fn estimator(&self) -> &timeouts::Estimator {
371        &self.timeouts
372    }
373}
374
375/// A factory object to build circuits.
376///
377/// A `TunnelBuilder` holds references to all the objects that are needed
378/// to build circuits correctly.
379///
380/// In general, you should not need to construct or use this object yourself,
381/// unless you are choosing your own paths.
382pub struct TunnelBuilder<R: Runtime> {
383    /// The underlying [`Builder`] object
384    builder: Arc<Builder<R, ClientTunnel>>,
385    /// Configuration for how to choose paths for circuits.
386    path_config: tor_config::MutCfg<crate::PathConfig>,
387    /// State-manager object to use in storing current state.
388    storage: crate::TimeoutStateHandle,
389    /// Guard manager to tell us which guards nodes to use for the circuits
390    /// we build.
391    guardmgr: tor_guardmgr::GuardMgr<R>,
392    /// The vanguard manager object used for HS circuits.
393    #[cfg(all(feature = "vanguards", feature = "hs-common"))]
394    vanguardmgr: Arc<VanguardMgr<R>>,
395}
396
397impl<R: Runtime> TunnelBuilder<R> {
398    /// Construct a new [`TunnelBuilder`].
399    // TODO: eventually I'd like to make this a public function, but
400    // TimeoutStateHandle is private.
401    pub(crate) fn new(
402        runtime: R,
403        chanmgr: Arc<ChanMgr<R>>,
404        path_config: crate::PathConfig,
405        storage: crate::TimeoutStateHandle,
406        guardmgr: tor_guardmgr::GuardMgr<R>,
407        #[cfg(all(feature = "vanguards", feature = "hs-common"))] vanguardmgr: VanguardMgr<R>,
408    ) -> Self {
409        let timeouts = timeouts::Estimator::from_storage(&storage);
410
411        TunnelBuilder {
412            builder: Arc::new(Builder::new(runtime, chanmgr, timeouts)),
413            path_config: path_config.into(),
414            storage,
415            guardmgr,
416            #[cfg(all(feature = "vanguards", feature = "hs-common"))]
417            vanguardmgr: Arc::new(vanguardmgr),
418        }
419    }
420
421    /// Return this builder's [`PathConfig`](crate::PathConfig).
422    pub(crate) fn path_config(&self) -> Arc<crate::PathConfig> {
423        self.path_config.get()
424    }
425
426    /// Replace this builder's [`PathConfig`](crate::PathConfig).
427    pub(crate) fn set_path_config(&self, new_config: crate::PathConfig) {
428        self.path_config.replace(new_config);
429    }
430
431    /// Flush state to the state manager if we own the lock.
432    ///
433    /// Return `Ok(true)` if we saved, and `Ok(false)` if we didn't hold the lock.
434    pub(crate) fn save_state(&self) -> Result<bool> {
435        if !self.storage.can_store() {
436            return Ok(false);
437        }
438        // TODO: someday we'll want to only do this if there is something
439        // changed.
440        self.builder.timeouts.save_state(&self.storage)?;
441        self.guardmgr.store_persistent_state()?;
442        Ok(true)
443    }
444
445    /// Replace our state with a new owning state, assuming we have
446    /// storage permission.
447    pub(crate) fn upgrade_to_owned_state(&self) -> Result<()> {
448        self.builder
449            .timeouts
450            .upgrade_to_owning_storage(&self.storage);
451        self.guardmgr.upgrade_to_owned_persistent_state()?;
452        Ok(())
453    }
454
455    /// Reload persistent state from disk, if we don't have storage permission.
456    #[instrument(level = "trace", skip_all)]
457    pub(crate) fn reload_state(&self) -> Result<()> {
458        if !self.storage.can_store() {
459            self.builder
460                .timeouts
461                .reload_readonly_from_storage(&self.storage);
462        }
463        self.guardmgr.reload_persistent_state()?;
464        Ok(())
465    }
466
467    /// Reconfigure this builder using the latest set of network parameters.
468    ///
469    /// (NOTE: for now, this only affects circuit timeout estimation.)
470    pub fn update_network_parameters(&self, p: &tor_netdir::params::NetParameters) {
471        self.builder.timeouts.update_params(p);
472    }
473
474    /// Like `build`, but construct a new circuit from an [`OwnedPath`].
475    #[instrument(level = "trace", skip_all)]
476    pub(crate) async fn build_owned(
477        &self,
478        path: OwnedPath,
479        params: &CircParameters,
480        guard_status: Arc<GuardStatusHandle>,
481        usage: ChannelUsage,
482    ) -> Result<ClientTunnel> {
483        self.builder
484            .build_owned(path, params, guard_status, usage)
485            .await
486    }
487
488    /// Try to construct a new circuit from a given path, using appropriate
489    /// timeouts.
490    ///
491    /// This circuit is _not_ automatically registered with any
492    /// circuit manager; if you don't hang on it it, it will
493    /// automatically go away when the last reference is dropped.
494    #[instrument(level = "trace", skip_all)]
495    pub async fn build(
496        &self,
497        path: &TorPath<'_>,
498        params: &CircParameters,
499        usage: ChannelUsage,
500    ) -> Result<ClientTunnel> {
501        let owned = path.try_into()?;
502        self.build_owned(owned, params, Arc::new(None.into()), usage)
503            .await
504    }
505
506    /// Return true if this builder is currently learning timeout info.
507    pub(crate) fn learning_timeouts(&self) -> bool {
508        self.builder.timeouts.learning_timeouts()
509    }
510
511    /// Return a reference to this builder's `GuardMgr`.
512    pub(crate) fn guardmgr(&self) -> &tor_guardmgr::GuardMgr<R> {
513        &self.guardmgr
514    }
515
516    /// Return a reference to this builder's `VanguardMgr`.
517    #[cfg(all(feature = "vanguards", feature = "hs-common"))]
518    pub(crate) fn vanguardmgr(&self) -> &Arc<VanguardMgr<R>> {
519        &self.vanguardmgr
520    }
521
522    /// Return a reference to this builder's runtime
523    pub(crate) fn runtime(&self) -> &R {
524        self.builder.runtime()
525    }
526
527    /// Return a reference to this builder's timeout estimator.
528    pub(crate) fn estimator(&self) -> &timeouts::Estimator {
529        self.builder.estimator()
530    }
531}
532
533/// Return the congestion control Vegas algorithm using the given network parameters.
534fn build_cc_vegas(
535    inp: &NetParameters,
536    vegas_queue_params: ccparams::VegasQueueParams,
537) -> ccparams::Algorithm {
538    ccparams::Algorithm::Vegas(
539        ccparams::VegasParamsBuilder::default()
540            .cell_in_queue_params(vegas_queue_params)
541            .ss_cwnd_max(inp.cc_ss_max.into())
542            .cwnd_full_gap(inp.cc_cwnd_full_gap.into())
543            .cwnd_full_min_pct(Percentage::new(
544                inp.cc_cwnd_full_minpct.as_percent().get() as u32
545            ))
546            .cwnd_full_per_cwnd(inp.cc_cwnd_full_per_cwnd.into())
547            .build()
548            .expect("Unable to build Vegas params from NetParams"),
549    )
550}
551
552/// Return the congestion control FixedWindow algorithm using the given network parameters.
553fn build_cc_fixedwindow(inp: &NetParameters) -> ccparams::Algorithm {
554    ccparams::Algorithm::FixedWindow(build_cc_fixedwindow_params(inp))
555}
556
557/// Return the parameters for the congestion control FixedWindow algorithm
558/// using the given network parameters.
559fn build_cc_fixedwindow_params(inp: &NetParameters) -> ccparams::FixedWindowParams {
560    ccparams::FixedWindowParamsBuilder::default()
561        .circ_window_start(inp.circuit_window.get() as u16)
562        .circ_window_min(inp.circuit_window.lower() as u16)
563        .circ_window_max(inp.circuit_window.upper() as u16)
564        .build()
565        .expect("Unable to build FixedWindow params from NetParams")
566}
567
568/// Return a new circuit parameter struct using the given network parameters and algorithm to use.
569fn circparameters_from_netparameters(
570    inp: &NetParameters,
571    alg: ccparams::Algorithm,
572) -> Result<CircParameters> {
573    let cwnd_params = ccparams::CongestionWindowParamsBuilder::default()
574        .cwnd_init(inp.cc_cwnd_init.into())
575        .cwnd_inc_pct_ss(Percentage::new(
576            inp.cc_cwnd_inc_pct_ss.as_percent().get() as u32
577        ))
578        .cwnd_inc(inp.cc_cwnd_inc.into())
579        .cwnd_inc_rate(inp.cc_cwnd_inc_rate.into())
580        .cwnd_min(inp.cc_cwnd_min.into())
581        .cwnd_max(inp.cc_cwnd_max.into())
582        .sendme_inc(inp.cc_sendme_inc.into())
583        .build()
584        .map_err(into_internal!(
585            "Unable to build CongestionWindow params from NetParams"
586        ))?;
587    let rtt_params = ccparams::RoundTripEstimatorParamsBuilder::default()
588        .ewma_cwnd_pct(Percentage::new(
589            inp.cc_ewma_cwnd_pct.as_percent().get() as u32
590        ))
591        .ewma_max(inp.cc_ewma_max.into())
592        .ewma_ss_max(inp.cc_ewma_ss.into())
593        .rtt_reset_pct(Percentage::new(
594            inp.cc_rtt_reset_pct.as_percent().get() as u32
595        ))
596        .build()
597        .map_err(into_internal!("Unable to build RTT params from NetParams"))?;
598    let ccontrol = ccparams::CongestionControlParamsBuilder::default()
599        .alg(alg)
600        .fixed_window_params(build_cc_fixedwindow_params(inp))
601        .cwnd_params(cwnd_params)
602        .rtt_params(rtt_params)
603        .build()
604        .map_err(into_internal!(
605            "Unable to build CongestionControl params from NetParams"
606        ))?;
607    let flow_ctrl_params = FlowCtrlParameters {
608        cc_xoff_client: CellCount::new(inp.cc_xoff_client.get_u32()),
609        cc_xoff_exit: CellCount::new(inp.cc_xoff_exit.get_u32()),
610        cc_xon_rate: CellCount::new(inp.cc_xon_rate.get_u32()),
611        cc_xon_change_pct: inp.cc_xon_change_pct.get_u32(),
612        cc_xon_ewma_cnt: inp.cc_xon_ewma_cnt.get_u32(),
613    };
614    Ok(CircParameters::new(
615        inp.extend_by_ed25519_id.into(),
616        ccontrol,
617        flow_ctrl_params,
618    ))
619}
620
621/// Extract a [`CircParameters`] from the [`NetParameters`] from a consensus for an exit circuit or
622/// single onion service (when implemented).
623pub fn exit_circparams_from_netparams(inp: &NetParameters) -> Result<CircParameters> {
624    let alg = match AlgorithmType::from(inp.cc_alg.get()) {
625        AlgorithmType::VEGAS => build_cc_vegas(
626            inp,
627            (
628                inp.cc_vegas_alpha_exit.into(),
629                inp.cc_vegas_beta_exit.into(),
630                inp.cc_vegas_delta_exit.into(),
631                inp.cc_vegas_gamma_exit.into(),
632                inp.cc_vegas_sscap_exit.into(),
633            )
634                .into(),
635        ),
636        // Unrecognized, fallback to fixed window as in SENDME v0.
637        _ => build_cc_fixedwindow(inp),
638    };
639    circparameters_from_netparameters(inp, alg)
640}
641
642/// Extract a [`CircParameters`] from the [`NetParameters`] from a consensus for an onion circuit
643/// which also includes an onion service with Vanguard.
644pub fn onion_circparams_from_netparams(inp: &NetParameters) -> Result<CircParameters> {
645    let alg = match AlgorithmType::from(inp.cc_alg.get()) {
646        // Note: As with other CircParams, we will fall back to fixed-window
647        // if we find that the target does not support the FLOWCTRL_CC capability.
648        AlgorithmType::VEGAS => build_cc_vegas(
649            inp,
650            (
651                inp.cc_vegas_alpha_onion.into(),
652                inp.cc_vegas_beta_onion.into(),
653                inp.cc_vegas_delta_onion.into(),
654                inp.cc_vegas_gamma_onion.into(),
655                inp.cc_vegas_sscap_onion.into(),
656            )
657                .into(),
658        ),
659        // Unrecognized, fallback to fixed window as in SENDME v0.
660        _ => build_cc_fixedwindow(inp),
661    };
662    circparameters_from_netparameters(inp, alg)
663}
664
665/// Helper function: spawn a future as a background task, and run it with
666/// two separate timeouts.
667///
668/// If the future does not complete by `timeout`, then return a
669/// timeout error immediately, but keep running the future in the
670/// background.
671///
672/// If the future does not complete by `abandon`, then abandon the
673/// future completely.
674async fn double_timeout<R, F, T>(
675    runtime: &R,
676    fut: F,
677    timeout: Duration,
678    abandon: Duration,
679) -> Result<T>
680where
681    R: Runtime,
682    F: Future<Output = Result<T>> + Send + 'static,
683    T: Send + 'static,
684{
685    let (snd, rcv) = oneshot::channel();
686    let rt = runtime.clone();
687    // We create these futures now, since we want them to look at the current
688    // time when they decide when to expire.
689    let inner_timeout_future = rt.timeout(abandon, fut);
690    let outer_timeout_future = rt.timeout(timeout, rcv);
691
692    runtime
693        .spawn(async move {
694            let result = inner_timeout_future.await;
695            let _ignore_cancelled_error = snd.send(result);
696        })
697        .map_err(|e| Error::from_spawn("circuit construction task", e))?;
698
699    let outcome = outer_timeout_future.await;
700    // 4 layers of error to collapse:
701    //     One from the receiver being cancelled.
702    //     One from the outer timeout.
703    //     One from the inner timeout.
704    //     One from the actual future's result.
705    //
706    // (Technically, we could refrain from unwrapping the future's result,
707    // but doing it this way helps make it more certain that we really are
708    // collapsing all the layers into one.)
709    outcome
710        .map_err(|_| Error::CircTimeout(None))??
711        .map_err(|_| Error::CircTimeout(None))?
712}
713
714#[cfg(test)]
715mod test {
716    // @@ begin test lint list maintained by maint/add_warning @@
717    #![allow(clippy::bool_assert_comparison)]
718    #![allow(clippy::clone_on_copy)]
719    #![allow(clippy::dbg_macro)]
720    #![allow(clippy::mixed_attributes_style)]
721    #![allow(clippy::print_stderr)]
722    #![allow(clippy::print_stdout)]
723    #![allow(clippy::single_char_pattern)]
724    #![allow(clippy::unwrap_used)]
725    #![allow(clippy::unchecked_time_subtraction)]
726    #![allow(clippy::useless_vec)]
727    #![allow(clippy::needless_pass_by_value)]
728    #![allow(clippy::string_slice)] // See arti#2571
729    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
730    use super::*;
731    use crate::timeouts::TimeoutEstimator;
732    use futures::FutureExt;
733    use std::sync::Mutex;
734    use tor_chanmgr::ChannelUsage as CU;
735    use tor_linkspec::ChanTarget;
736    use tor_linkspec::{HasRelayIds, RelayIdType, RelayIds};
737    use tor_llcrypto::pk::ed25519::Ed25519Identity;
738    use tor_memquota::ArcMemoryQuotaTrackerExt as _;
739    use tor_proto::memquota::ToplevelAccount;
740    use tor_rtcompat::SleepProvider;
741    use tracing::trace;
742
743    /// Make a new nonfunctional `Arc<GuardStatusHandle>`
744    fn gs() -> Arc<GuardStatusHandle> {
745        Arc::new(None.into())
746    }
747
748    #[test]
749    // Re-enabled after work from eta, discussed in arti#149
750    fn test_double_timeout() {
751        let t1 = Duration::from_secs(1);
752        let t10 = Duration::from_secs(10);
753        /// Return true if d1 is in range [d2...d2 + 0.5sec]
754        fn duration_close_to(d1: Duration, d2: Duration) -> bool {
755            d1 >= d2 && d1 <= d2 + Duration::from_millis(500)
756        }
757
758        tor_rtmock::MockRuntime::test_with_various(|rto| async move {
759            // Try a future that's ready immediately.
760            let x = double_timeout(&rto, async { Ok(3_u32) }, t1, t10).await;
761            assert!(x.is_ok());
762            assert_eq!(x.unwrap(), 3_u32);
763
764            trace!("acquiesce after test1");
765            #[allow(clippy::clone_on_copy)]
766            #[allow(deprecated)] // TODO #1885
767            let rt = tor_rtmock::MockSleepRuntime::new(rto.clone());
768
769            // Try a future that's ready after a short delay.
770            let rt_clone = rt.clone();
771            // (We only want the short delay to fire, not any of the other timeouts.)
772            rt_clone.block_advance("manually controlling advances");
773            let x = rt
774                .wait_for(double_timeout(
775                    &rt,
776                    async move {
777                        let sl = rt_clone.sleep(Duration::from_millis(100));
778                        rt_clone.allow_one_advance(Duration::from_millis(100));
779                        sl.await;
780                        Ok(4_u32)
781                    },
782                    t1,
783                    t10,
784                ))
785                .await;
786            assert!(x.is_ok());
787            assert_eq!(x.unwrap(), 4_u32);
788
789            trace!("acquiesce after test2");
790            #[allow(clippy::clone_on_copy)]
791            #[allow(deprecated)] // TODO #1885
792            let rt = tor_rtmock::MockSleepRuntime::new(rto.clone());
793
794            // Try a future that passes the first timeout, and make sure that
795            // it keeps running after it times out.
796            let rt_clone = rt.clone();
797            let (snd, rcv) = oneshot::channel();
798            let start = rt.now();
799            rt.block_advance("manually controlling advances");
800            let x = rt
801                .wait_for(double_timeout(
802                    &rt,
803                    async move {
804                        let sl = rt_clone.sleep(Duration::from_secs(2));
805                        rt_clone.allow_one_advance(Duration::from_secs(2));
806                        sl.await;
807                        snd.send(()).unwrap();
808                        Ok(4_u32)
809                    },
810                    t1,
811                    t10,
812                ))
813                .await;
814            assert!(matches!(x, Err(Error::CircTimeout(_))));
815            let end = rt.now();
816            assert!(duration_close_to(end - start, Duration::from_secs(1)));
817            let waited = rt.wait_for(rcv).await;
818            assert_eq!(waited, Ok(()));
819
820            trace!("acquiesce after test3");
821            #[allow(clippy::clone_on_copy)]
822            #[allow(deprecated)] // TODO #1885
823            let rt = tor_rtmock::MockSleepRuntime::new(rto.clone());
824
825            // Try a future that times out and gets abandoned.
826            let rt_clone = rt.clone();
827            rt.block_advance("manually controlling advances");
828            let (snd, rcv) = oneshot::channel();
829            let start = rt.now();
830            // Let it hit the first timeout...
831            rt.allow_one_advance(Duration::from_secs(1));
832            let x = rt
833                .wait_for(double_timeout(
834                    &rt,
835                    async move {
836                        rt_clone.sleep(Duration::from_secs(30)).await;
837                        snd.send(()).unwrap();
838                        Ok(4_u32)
839                    },
840                    t1,
841                    t10,
842                ))
843                .await;
844            assert!(matches!(x, Err(Error::CircTimeout(_))));
845            let end = rt.now();
846            // ...and let it hit the second, too.
847            rt.allow_one_advance(Duration::from_secs(9));
848            let waited = rt.wait_for(rcv).await;
849            assert!(waited.is_err());
850            let end2 = rt.now();
851            assert!(duration_close_to(end - start, Duration::from_secs(1)));
852            assert!(duration_close_to(end2 - start, Duration::from_secs(10)));
853        });
854    }
855
856    /// Get a pair of timeouts that we've encoded as an Ed25519 identity.
857    ///
858    /// In our FakeCircuit code below, the first timeout is the amount of
859    /// time that we should sleep while building a hop to this key,
860    /// and the second timeout is the length of time-advance we should allow
861    /// after the hop is built.
862    ///
863    /// (This is pretty silly, but it's good enough for testing.)
864    fn timeouts_from_key(id: &Ed25519Identity) -> (Duration, Duration) {
865        let mut be = [0; 8];
866        be[..].copy_from_slice(&id.as_bytes()[0..8]);
867        let dur = u64::from_be_bytes(be);
868        be[..].copy_from_slice(&id.as_bytes()[8..16]);
869        let dur2 = u64::from_be_bytes(be);
870        (Duration::from_millis(dur), Duration::from_millis(dur2))
871    }
872    /// Encode a pair of timeouts as an Ed25519 identity.
873    ///
874    /// In our FakeCircuit code below, the first timeout is the amount of
875    /// time that we should sleep while building a hop to this key,
876    /// and the second timeout is the length of time-advance we should allow
877    /// after the hop is built.
878    ///
879    /// (This is pretty silly but it's good enough for testing.)
880    fn key_from_timeouts(d1: Duration, d2: Duration) -> Ed25519Identity {
881        let mut bytes = [0; 32];
882        let dur = (d1.as_millis() as u64).to_be_bytes();
883        bytes[0..8].copy_from_slice(&dur);
884        let dur = (d2.as_millis() as u64).to_be_bytes();
885        bytes[8..16].copy_from_slice(&dur);
886        bytes.into()
887    }
888
889    /// As [`timeouts_from_key`], but first extract the relevant key from the
890    /// OwnedChanTarget.
891    fn timeouts_from_chantarget<CT: ChanTarget>(ct: &CT) -> (Duration, Duration) {
892        // Extracting the Ed25519 identity should always succeed in this case:
893        // we put it there ourselves!
894        let ed_id = ct
895            .identity(RelayIdType::Ed25519)
896            .expect("No ed25519 key was present for fake ChanTarget‽")
897            .try_into()
898            .expect("ChanTarget provided wrong key type");
899        timeouts_from_key(ed_id)
900    }
901
902    /// Replacement type for circuit, to implement buildable.
903    #[derive(Debug, Clone)]
904    struct FakeCirc {
905        hops: Vec<RelayIds>,
906        onehop: bool,
907    }
908    #[async_trait]
909    impl Buildable for Mutex<FakeCirc> {
910        type Chan = ();
911
912        async fn open_channel<RT: Runtime>(
913            _chanmgr: &ChanMgr<RT>,
914            _ct: &OwnedChanTarget,
915            _guard_status: &GuardStatusHandle,
916            _usage: ChannelUsage,
917        ) -> Result<Arc<Self::Chan>> {
918            Ok(Arc::new(()))
919        }
920
921        async fn create_chantarget<RT: Runtime>(
922            _: Arc<Self::Chan>,
923            rt: &RT,
924            ct: &OwnedChanTarget,
925            _: CircParameters,
926            _timeouts: Arc<dyn tor_proto::client::circuit::TimeoutEstimator>,
927        ) -> Result<Self> {
928            let (d1, d2) = timeouts_from_chantarget(ct);
929            rt.sleep(d1).await;
930            if !d2.is_zero() {
931                rt.allow_one_advance(d2);
932            }
933
934            let c = FakeCirc {
935                hops: vec![RelayIds::from_relay_ids(ct)],
936                onehop: true,
937            };
938            Ok(Mutex::new(c))
939        }
940        async fn create<RT: Runtime>(
941            _: Arc<Self::Chan>,
942            rt: &RT,
943            ct: &OwnedCircTarget,
944            _: CircParameters,
945            _timeouts: Arc<dyn tor_proto::client::circuit::TimeoutEstimator>,
946        ) -> Result<Self> {
947            let (d1, d2) = timeouts_from_chantarget(ct);
948            rt.sleep(d1).await;
949            if !d2.is_zero() {
950                rt.allow_one_advance(d2);
951            }
952
953            let c = FakeCirc {
954                hops: vec![RelayIds::from_relay_ids(ct)],
955                onehop: false,
956            };
957            Ok(Mutex::new(c))
958        }
959        async fn extend<RT: Runtime>(
960            &self,
961            rt: &RT,
962            ct: &OwnedCircTarget,
963            _: CircParameters,
964        ) -> Result<()> {
965            let (d1, d2) = timeouts_from_chantarget(ct);
966            rt.sleep(d1).await;
967            if !d2.is_zero() {
968                rt.allow_one_advance(d2);
969            }
970
971            {
972                let mut c = self.lock().unwrap();
973                c.hops.push(RelayIds::from_relay_ids(ct));
974            }
975            Ok(())
976        }
977    }
978
979    /// Fake implementation of TimeoutEstimator that just records its inputs.
980    struct TimeoutRecorder<R> {
981        runtime: R,
982        hist: Vec<(bool, u8, Duration)>,
983        // How much advance to permit after being told of a timeout?
984        on_timeout: Duration,
985        // How much advance to permit after being told of a success?
986        on_success: Duration,
987
988        snd_success: Option<oneshot::Sender<()>>,
989        rcv_success: Option<oneshot::Receiver<()>>,
990    }
991
992    impl<R> TimeoutRecorder<R> {
993        fn new(runtime: R) -> Self {
994            Self::with_delays(runtime, Duration::from_secs(0), Duration::from_secs(0))
995        }
996
997        fn with_delays(runtime: R, on_timeout: Duration, on_success: Duration) -> Self {
998            let (snd_success, rcv_success) = oneshot::channel();
999            Self {
1000                runtime,
1001                hist: Vec::new(),
1002                on_timeout,
1003                on_success,
1004                rcv_success: Some(rcv_success),
1005                snd_success: Some(snd_success),
1006            }
1007        }
1008    }
1009    impl<R: Runtime> TimeoutEstimator for Arc<Mutex<TimeoutRecorder<R>>> {
1010        fn note_hop_completed(&mut self, hop: u8, delay: Duration, is_last: bool) {
1011            if !is_last {
1012                return;
1013            }
1014            let (rt, advance) = {
1015                let mut this = self.lock().unwrap();
1016                this.hist.push((true, hop, delay));
1017                let _ = this.snd_success.take().unwrap().send(());
1018                (this.runtime.clone(), this.on_success)
1019            };
1020            if !advance.is_zero() {
1021                rt.allow_one_advance(advance);
1022            }
1023        }
1024        fn note_circ_timeout(&mut self, hop: u8, delay: Duration) {
1025            let (rt, advance) = {
1026                let mut this = self.lock().unwrap();
1027                this.hist.push((false, hop, delay));
1028                (this.runtime.clone(), this.on_timeout)
1029            };
1030            if !advance.is_zero() {
1031                rt.allow_one_advance(advance);
1032            }
1033        }
1034        fn timeouts(&mut self, _action: &Action) -> (Duration, Duration) {
1035            (Duration::from_secs(3), Duration::from_secs(100))
1036        }
1037        fn learning_timeouts(&self) -> bool {
1038            false
1039        }
1040        fn update_params(&mut self, _params: &tor_netdir::params::NetParameters) {}
1041
1042        fn build_state(&mut self) -> Option<crate::timeouts::pareto::ParetoTimeoutState> {
1043            None
1044        }
1045    }
1046
1047    /// Testing only: create a bogus circuit target
1048    fn circ_t(id: Ed25519Identity) -> OwnedCircTarget {
1049        let mut builder = OwnedCircTarget::builder();
1050        builder
1051            .chan_target()
1052            .ed_identity(id)
1053            .rsa_identity([0x20; 20].into());
1054        builder
1055            .ntor_onion_key([0x33; 32].into())
1056            .protocols("".parse().unwrap())
1057            .build()
1058            .unwrap()
1059    }
1060    /// Testing only: create a bogus channel target
1061    fn chan_t(id: Ed25519Identity) -> OwnedChanTarget {
1062        OwnedChanTarget::builder()
1063            .ed_identity(id)
1064            .rsa_identity([0x20; 20].into())
1065            .build()
1066            .unwrap()
1067    }
1068
1069    async fn run_builder_test(
1070        rt: tor_rtmock::MockRuntime,
1071        advance_initial: Duration,
1072        path: OwnedPath,
1073        advance_on_timeout: Option<(Duration, Duration)>,
1074        usage: ChannelUsage,
1075    ) -> (Result<FakeCirc>, Vec<(bool, u8, Duration)>) {
1076        let chanmgr = Arc::new(
1077            ChanMgr::new(
1078                rt.clone(),
1079                Default::default(),
1080                Default::default(),
1081                &Default::default(),
1082                ToplevelAccount::new_noop(),
1083            )
1084            .unwrap(),
1085        );
1086        // always has 3 second timeout, 100 second abandon.
1087        let timeouts = match advance_on_timeout {
1088            Some((d1, d2)) => TimeoutRecorder::with_delays(rt.clone(), d1, d2),
1089            None => TimeoutRecorder::new(rt.clone()),
1090        };
1091        let timeouts = Arc::new(Mutex::new(timeouts));
1092        let builder: Builder<_, Mutex<FakeCirc>> = Builder::new(
1093            rt.clone(),
1094            chanmgr,
1095            timeouts::Estimator::new(Arc::clone(&timeouts)),
1096        );
1097
1098        rt.block_advance("manually controlling advances");
1099        rt.allow_one_advance(advance_initial);
1100        let outcome = rt.spawn_join("build-owned", async move {
1101            let arcbuilder = Arc::new(builder);
1102            let params = exit_circparams_from_netparams(&NetParameters::default())?;
1103            arcbuilder.build_owned(path, &params, gs(), usage).await
1104        });
1105
1106        // Now we wait for a success to finally, finally be reported.
1107        if advance_on_timeout.is_some() {
1108            let receiver = { timeouts.lock().unwrap().rcv_success.take().unwrap() };
1109            rt.spawn_identified("receiver", async move {
1110                receiver.await.unwrap();
1111            });
1112        }
1113        rt.advance_until_stalled().await;
1114
1115        let circ = outcome.map(|m| Ok(m?.lock().unwrap().clone())).await;
1116        let timeouts = timeouts.lock().unwrap().hist.clone();
1117
1118        (circ, timeouts)
1119    }
1120
1121    #[test]
1122    fn build_onehop() {
1123        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1124            let id_100ms = key_from_timeouts(Duration::from_millis(100), Duration::from_millis(0));
1125            let path = OwnedPath::ChannelOnly(chan_t(id_100ms));
1126
1127            let (outcome, timeouts) =
1128                run_builder_test(rt, Duration::from_millis(100), path, None, CU::UserTraffic).await;
1129            let circ = outcome.unwrap();
1130            assert!(circ.onehop);
1131            assert_eq!(circ.hops.len(), 1);
1132            assert!(circ.hops[0].same_relay_ids(&chan_t(id_100ms)));
1133
1134            assert_eq!(timeouts.len(), 1);
1135            assert!(timeouts[0].0); // success
1136            assert_eq!(timeouts[0].1, 0); // one-hop
1137            assert_eq!(timeouts[0].2, Duration::from_millis(100));
1138        });
1139    }
1140
1141    #[test]
1142    fn build_threehop() {
1143        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1144            let id_100ms =
1145                key_from_timeouts(Duration::from_millis(100), Duration::from_millis(200));
1146            let id_200ms =
1147                key_from_timeouts(Duration::from_millis(200), Duration::from_millis(300));
1148            let id_300ms = key_from_timeouts(Duration::from_millis(300), Duration::from_millis(0));
1149            let path =
1150                OwnedPath::Normal(vec![circ_t(id_100ms), circ_t(id_200ms), circ_t(id_300ms)]);
1151
1152            let (outcome, timeouts) =
1153                run_builder_test(rt, Duration::from_millis(100), path, None, CU::UserTraffic).await;
1154            let circ = outcome.unwrap();
1155            assert!(!circ.onehop);
1156            assert_eq!(circ.hops.len(), 3);
1157            assert!(circ.hops[0].same_relay_ids(&chan_t(id_100ms)));
1158            assert!(circ.hops[1].same_relay_ids(&chan_t(id_200ms)));
1159            assert!(circ.hops[2].same_relay_ids(&chan_t(id_300ms)));
1160
1161            assert_eq!(timeouts.len(), 1);
1162            assert!(timeouts[0].0); // success
1163            assert_eq!(timeouts[0].1, 2); // three-hop
1164            assert_eq!(timeouts[0].2, Duration::from_millis(600));
1165        });
1166    }
1167
1168    #[test]
1169    fn build_huge_timeout() {
1170        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1171            let id_100ms =
1172                key_from_timeouts(Duration::from_millis(100), Duration::from_millis(200));
1173            let id_200ms =
1174                key_from_timeouts(Duration::from_millis(200), Duration::from_millis(2700));
1175            let id_hour = key_from_timeouts(Duration::from_secs(3600), Duration::from_secs(0));
1176
1177            let path = OwnedPath::Normal(vec![circ_t(id_100ms), circ_t(id_200ms), circ_t(id_hour)]);
1178
1179            let (outcome, timeouts) =
1180                run_builder_test(rt, Duration::from_millis(100), path, None, CU::UserTraffic).await;
1181            assert!(matches!(outcome, Err(Error::CircTimeout(_))));
1182
1183            assert_eq!(timeouts.len(), 1);
1184            assert!(!timeouts[0].0); // timeout
1185
1186            // BUG: Sometimes this is 1 and sometimes this is 2.
1187            // assert_eq!(timeouts[0].1, 2); // at third hop.
1188            assert_eq!(timeouts[0].2, Duration::from_millis(3000));
1189        });
1190    }
1191
1192    #[test]
1193    fn build_modest_timeout() {
1194        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1195            let id_100ms =
1196                key_from_timeouts(Duration::from_millis(100), Duration::from_millis(200));
1197            let id_200ms =
1198                key_from_timeouts(Duration::from_millis(200), Duration::from_millis(2700));
1199            let id_3sec = key_from_timeouts(Duration::from_millis(3000), Duration::from_millis(0));
1200
1201            let timeout_advance = (Duration::from_millis(4000), Duration::from_secs(0));
1202
1203            let path = OwnedPath::Normal(vec![circ_t(id_100ms), circ_t(id_200ms), circ_t(id_3sec)]);
1204
1205            let (outcome, timeouts) = run_builder_test(
1206                rt.clone(),
1207                Duration::from_millis(100),
1208                path,
1209                Some(timeout_advance),
1210                CU::UserTraffic,
1211            )
1212            .await;
1213            assert!(matches!(outcome, Err(Error::CircTimeout(_))));
1214
1215            assert_eq!(timeouts.len(), 2);
1216            assert!(!timeouts[0].0); // timeout
1217
1218            // BUG: Sometimes this is 1 and sometimes this is 2.
1219            //assert_eq!(timeouts[0].1, 2); // at third hop.
1220            assert_eq!(timeouts[0].2, Duration::from_millis(3000));
1221
1222            assert!(timeouts[1].0); // success
1223            assert_eq!(timeouts[1].1, 2); // three-hop
1224            // BUG: This timer is not always reliable, due to races.
1225            //assert_eq!(timeouts[1].2, Duration::from_millis(3300));
1226        });
1227    }
1228}