1use 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#[async_trait]
42pub(crate) trait Buildable: Sized {
43 type Chan: Send + Sync;
45
46 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 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 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 async fn extend<RT: Runtime>(
81 &self,
82 rt: &RT,
83 ct: &OwnedCircTarget,
84 params: CircParameters,
85 ) -> Result<()>;
86}
87
88#[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 let (pending_tunnel, reactor) =
101 chan.new_tunnel(timeouts)
102 .await
103 .map_err(|error| Error::Protocol {
104 error,
105 peer: None, 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 guard_status.pending(GuardStatus::Failure);
133
134 let result = chanmgr.get_or_launch(target, usage).await;
136
137 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 peer: None,
215 action: "extending circuit",
216 unique_id: Some(self.unique_id()),
217 })
218 }
219}
220
221struct Builder<R: Runtime, C: Buildable + Sync + Send + 'static> {
229 runtime: R,
231 chanmgr: Arc<ChanMgr<R>>,
233 timeouts: Arc<timeouts::Estimator>,
235 _phantom: std::marker::PhantomData<C>,
238}
239
240impl<R: Runtime, C: Buildable + Sync + Send + 'static> Builder<R, C> {
241 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 #[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 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 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 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 #[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 let hops_built = Arc::new(AtomicU32::new(0));
325
326 let self_clone = Arc::clone(self);
327 let params = params.clone();
328
329 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 pub(crate) fn runtime(&self) -> &R {
366 &self.runtime
367 }
368
369 pub(crate) fn estimator(&self) -> &timeouts::Estimator {
371 &self.timeouts
372 }
373}
374
375pub struct TunnelBuilder<R: Runtime> {
383 builder: Arc<Builder<R, ClientTunnel>>,
385 path_config: tor_config::MutCfg<crate::PathConfig>,
387 storage: crate::TimeoutStateHandle,
389 guardmgr: tor_guardmgr::GuardMgr<R>,
392 #[cfg(all(feature = "vanguards", feature = "hs-common"))]
394 vanguardmgr: Arc<VanguardMgr<R>>,
395}
396
397impl<R: Runtime> TunnelBuilder<R> {
398 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 pub(crate) fn path_config(&self) -> Arc<crate::PathConfig> {
423 self.path_config.get()
424 }
425
426 pub(crate) fn set_path_config(&self, new_config: crate::PathConfig) {
428 self.path_config.replace(new_config);
429 }
430
431 pub(crate) fn save_state(&self) -> Result<bool> {
435 if !self.storage.can_store() {
436 return Ok(false);
437 }
438 self.builder.timeouts.save_state(&self.storage)?;
441 self.guardmgr.store_persistent_state()?;
442 Ok(true)
443 }
444
445 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 #[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 pub fn update_network_parameters(&self, p: &tor_netdir::params::NetParameters) {
471 self.builder.timeouts.update_params(p);
472 }
473
474 #[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 #[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 pub(crate) fn learning_timeouts(&self) -> bool {
508 self.builder.timeouts.learning_timeouts()
509 }
510
511 pub(crate) fn guardmgr(&self) -> &tor_guardmgr::GuardMgr<R> {
513 &self.guardmgr
514 }
515
516 #[cfg(all(feature = "vanguards", feature = "hs-common"))]
518 pub(crate) fn vanguardmgr(&self) -> &Arc<VanguardMgr<R>> {
519 &self.vanguardmgr
520 }
521
522 pub(crate) fn runtime(&self) -> &R {
524 self.builder.runtime()
525 }
526
527 pub(crate) fn estimator(&self) -> &timeouts::Estimator {
529 self.builder.estimator()
530 }
531}
532
533fn 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
552fn build_cc_fixedwindow(inp: &NetParameters) -> ccparams::Algorithm {
554 ccparams::Algorithm::FixedWindow(build_cc_fixedwindow_params(inp))
555}
556
557fn 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
568fn 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
621pub 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 _ => build_cc_fixedwindow(inp),
638 };
639 circparameters_from_netparameters(inp, alg)
640}
641
642pub fn onion_circparams_from_netparams(inp: &NetParameters) -> Result<CircParameters> {
645 let alg = match AlgorithmType::from(inp.cc_alg.get()) {
646 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 _ => build_cc_fixedwindow(inp),
661 };
662 circparameters_from_netparameters(inp, alg)
663}
664
665async 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 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 outcome
710 .map_err(|_| Error::CircTimeout(None))??
711 .map_err(|_| Error::CircTimeout(None))?
712}
713
714#[cfg(test)]
715mod test {
716 #![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)] 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 fn gs() -> Arc<GuardStatusHandle> {
745 Arc::new(None.into())
746 }
747
748 #[test]
749 fn test_double_timeout() {
751 let t1 = Duration::from_secs(1);
752 let t10 = Duration::from_secs(10);
753 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 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)] let rt = tor_rtmock::MockSleepRuntime::new(rto.clone());
768
769 let rt_clone = rt.clone();
771 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)] let rt = tor_rtmock::MockSleepRuntime::new(rto.clone());
793
794 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)] let rt = tor_rtmock::MockSleepRuntime::new(rto.clone());
824
825 let rt_clone = rt.clone();
827 rt.block_advance("manually controlling advances");
828 let (snd, rcv) = oneshot::channel();
829 let start = rt.now();
830 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 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 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 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 fn timeouts_from_chantarget<CT: ChanTarget>(ct: &CT) -> (Duration, Duration) {
892 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 #[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 struct TimeoutRecorder<R> {
981 runtime: R,
982 hist: Vec<(bool, u8, Duration)>,
983 on_timeout: Duration,
985 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 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 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 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, ¶ms, gs(), usage).await
1104 });
1105
1106 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); assert_eq!(timeouts[0].1, 0); 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); assert_eq!(timeouts[0].1, 2); 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); 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); assert_eq!(timeouts[0].2, Duration::from_millis(3000));
1221
1222 assert!(timeouts[1].0); assert_eq!(timeouts[1].1, 2); });
1227 }
1228}