1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] #![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] #![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] #![cfg_attr(not(all(feature = "full", feature = "experimental")), allow(unused))]
54
55use build::TunnelBuilder;
56use mgr::{AbstractTunnel, AbstractTunnelBuilder};
57use tor_basic_utils::retry::RetryDelay;
58use tor_chanmgr::ChanMgr;
59use tor_dircommon::fallback::FallbackList;
60use tor_error::{error_report, warn_report};
61use tor_guardmgr::RetireCircuits;
62use tor_linkspec::ChanTarget;
63use tor_netdir::{DirEvent, NetDir, NetDirProvider, Timeliness};
64use tor_proto::circuit::UniqId;
65use tor_proto::client::circuit::CircParameters;
66use tor_rtcompat::Runtime;
67
68#[cfg(any(feature = "specific-relay", feature = "hs-common"))]
69use tor_linkspec::IntoOwnedChanTarget;
70
71use futures::StreamExt;
72use std::sync::{Arc, Mutex, Weak};
73use std::time::Duration;
74use tor_rtcompat::SpawnExt;
75use tracing::{debug, info, instrument, trace, warn};
76
77#[cfg(feature = "testing")]
78pub use config::test_config::TestConfig;
79
80pub mod build;
81mod config;
82mod err;
83#[cfg(feature = "hs-common")]
84pub mod hspool;
85mod impls;
86pub mod isolation;
87mod mgr;
88#[cfg(test)]
89mod mocks;
90mod preemptive;
91pub mod timeouts;
92mod tunnel;
93mod usage;
94
95cfg_if::cfg_if! {
97 if #[cfg(feature = "experimental-api")] {
98 pub mod path;
99 } else {
100 pub(crate) mod path;
101 }
102}
103
104pub use err::Error;
105pub use isolation::IsolationToken;
106pub use tor_guardmgr::{ClockSkewEvents, GuardMgrConfig, SkewEstimate};
107pub use tunnel::{
108 ClientDataTunnel, ClientDirTunnel, ClientOnionServiceDataTunnel, ClientOnionServiceDirTunnel,
109 ClientOnionServiceIntroTunnel, ServiceOnionServiceDataTunnel, ServiceOnionServiceDirTunnel,
110 ServiceOnionServiceIntroTunnel,
111};
112#[cfg(feature = "conflux")]
113pub use tunnel::{
114 ClientMultiPathDataTunnel, ClientMultiPathOnionServiceDataTunnel,
115 ServiceMultiPathOnionServiceDataTunnel,
116};
117pub use usage::{TargetPort, TargetPorts};
118
119pub use config::{
120 CircMgrConfig, CircuitTiming, CircuitTimingBuilder, PathConfig, PathConfigBuilder,
121 PreemptiveCircuitConfig, PreemptiveCircuitConfigBuilder,
122};
123
124use crate::isolation::StreamIsolation;
125use crate::mgr::TunnelProvenance;
126use crate::preemptive::PreemptiveCircuitPredictor;
127use usage::TargetTunnelUsage;
128
129use safelog::sensitive as sv;
130#[cfg(feature = "geoip")]
131use tor_geoip::CountryCode;
132pub use tor_guardmgr::{ExternalActivity, FirstHopId};
133use tor_persist::StateMgr;
134use tor_rtcompat::scheduler::{TaskHandle, TaskSchedule};
135
136#[cfg(feature = "hs-common")]
137use crate::hspool::{HsCircKind, HsCircStemKind};
138#[cfg(all(feature = "vanguards", feature = "hs-common"))]
139use tor_guardmgr::vanguards::VanguardMgr;
140
141pub type Result<T> = std::result::Result<T, Error>;
143
144type TimeoutStateHandle = tor_persist::DynStorageHandle<timeouts::pareto::ParetoTimeoutState>;
146
147const PARETO_TIMEOUT_DATA_KEY: &str = "circuit_timeouts";
149
150#[derive(Debug, Copy, Clone)]
158#[non_exhaustive]
159pub enum DirInfo<'a> {
160 Fallbacks(&'a FallbackList),
162 Directory(&'a NetDir),
164 Nothing,
167}
168
169impl<'a> From<&'a FallbackList> for DirInfo<'a> {
170 fn from(v: &'a FallbackList) -> DirInfo<'a> {
171 DirInfo::Fallbacks(v)
172 }
173}
174impl<'a> From<&'a NetDir> for DirInfo<'a> {
175 fn from(v: &'a NetDir) -> DirInfo<'a> {
176 DirInfo::Directory(v)
177 }
178}
179impl<'a> DirInfo<'a> {
180 fn circ_params(&self, usage: &TargetTunnelUsage) -> Result<CircParameters> {
182 use tor_netdir::params::NetParameters;
183 let defaults = NetParameters::default();
186 let net_params = match self {
187 DirInfo::Directory(d) => d.params(),
188 _ => &defaults,
189 };
190 match usage {
191 #[cfg(feature = "hs-common")]
192 TargetTunnelUsage::HsCircBase { .. } => {
193 build::onion_circparams_from_netparams(net_params)
194 }
195 _ => build::exit_circparams_from_netparams(net_params),
196 }
197 }
198}
199
200pub struct CircMgr<R: Runtime>(Arc<CircMgrInner<build::TunnelBuilder<R>, R>>);
210
211impl<R: Runtime> CircMgr<R> {
212 pub fn new<SM, CFG: CircMgrConfig>(
218 config: &CFG,
219 storage: SM,
220 runtime: &R,
221 chanmgr: Arc<ChanMgr<R>>,
222 guardmgr: &tor_guardmgr::GuardMgr<R>,
223 ) -> Result<Self>
224 where
225 SM: tor_persist::StateMgr + Clone + Send + Sync + 'static,
226 {
227 Ok(Self(Arc::new(CircMgrInner::new(
228 config, storage, runtime, chanmgr, guardmgr,
229 )?)))
230 }
231
232 #[instrument(level = "trace", skip_all)]
235 pub async fn get_or_launch_dir(&self, netdir: DirInfo<'_>) -> Result<ClientDirTunnel> {
236 let tunnel = self.0.get_or_launch_dir(netdir).await?;
237 Ok(tunnel.into())
238 }
239
240 #[instrument(level = "trace", skip_all)]
246 pub async fn get_or_launch_exit(
247 &self,
248 netdir: DirInfo<'_>, ports: &[TargetPort],
250 isolation: StreamIsolation,
251 #[cfg(feature = "geoip")] country_code: Option<CountryCode>,
254 ) -> Result<ClientDataTunnel> {
255 let tunnel = self
256 .0
257 .get_or_launch_exit(
258 netdir,
259 ports,
260 isolation,
261 #[cfg(feature = "geoip")]
262 country_code,
263 )
264 .await?;
265 Ok(tunnel.into())
266 }
267
268 #[cfg(feature = "specific-relay")]
273 #[instrument(level = "trace", skip_all)]
274 pub async fn get_or_launch_dir_specific<T: IntoOwnedChanTarget>(
275 &self,
276 target: T,
277 ) -> Result<ClientDirTunnel> {
278 let tunnel = self.0.get_or_launch_dir_specific(target).await?;
279 Ok(tunnel.into())
280 }
281
282 #[instrument(level = "trace", skip_all)]
288 pub fn launch_background_tasks<D, S>(
289 self: &Arc<Self>,
290 runtime: &R,
291 dir_provider: &Arc<D>,
292 state_mgr: S,
293 ) -> Result<Vec<TaskHandle>>
294 where
295 D: NetDirProvider + 'static + ?Sized,
296 S: StateMgr + std::marker::Send + 'static,
297 {
298 CircMgrInner::launch_background_tasks(&self.0.clone(), runtime, dir_provider, state_mgr)
299 }
300
301 pub fn netdir_is_sufficient(&self, netdir: &NetDir) -> bool {
307 self.0.netdir_is_sufficient(netdir)
308 }
309
310 pub fn retire_circ(&self, circ_id: &UniqId) {
313 self.0.retire_circ(circ_id);
314 }
315
316 pub fn note_external_failure(
320 &self,
321 target: &impl ChanTarget,
322 external_failure: ExternalActivity,
323 ) {
324 self.0.note_external_failure(target, external_failure);
325 }
326
327 pub fn note_external_success(
330 &self,
331 target: &impl ChanTarget,
332 external_activity: ExternalActivity,
333 ) {
334 self.0.note_external_success(target, external_activity);
335 }
336
337 pub fn skew_events(&self) -> ClockSkewEvents {
345 self.0.skew_events()
346 }
347
348 #[instrument(level = "trace", skip_all)]
354 pub fn reconfigure<CFG: CircMgrConfig>(
355 &self,
356 new_config: &CFG,
357 how: tor_config::Reconfigure,
358 ) -> std::result::Result<RetireCircuits, tor_config::ReconfigureError> {
359 self.0.reconfigure(new_config, how)
360 }
361
362 pub fn estimate_timeout(&self, timeout_action: &timeouts::Action) -> std::time::Duration {
388 self.0.estimate_timeout(timeout_action)
389 }
390
391 #[cfg(feature = "experimental-api")]
394 pub fn builder(&self) -> &TunnelBuilder<R> {
395 CircMgrInner::builder(&self.0)
396 }
397}
398
399#[derive(Clone)]
401pub(crate) struct CircMgrInner<B: AbstractTunnelBuilder<R> + 'static, R: Runtime> {
402 mgr: Arc<mgr::AbstractTunnelMgr<B, R>>,
404 predictor: Arc<Mutex<PreemptiveCircuitPredictor>>,
406}
407
408impl<R: Runtime> CircMgrInner<TunnelBuilder<R>, R> {
409 #[allow(clippy::unnecessary_wraps)]
415 pub(crate) fn new<SM, CFG: CircMgrConfig>(
416 config: &CFG,
417 storage: SM,
418 runtime: &R,
419 chanmgr: Arc<ChanMgr<R>>,
420 guardmgr: &tor_guardmgr::GuardMgr<R>,
421 ) -> Result<Self>
422 where
423 SM: tor_persist::StateMgr + Clone + Send + Sync + 'static,
424 {
425 #[cfg(all(feature = "vanguards", feature = "hs-common"))]
426 let vanguardmgr = {
427 let has_onion_svc = false;
432 VanguardMgr::new(
433 config.vanguard_config(),
434 runtime.clone(),
435 storage.clone(),
436 has_onion_svc,
437 )?
438 };
439
440 let storage_handle = storage.create_handle(PARETO_TIMEOUT_DATA_KEY);
441
442 let builder = build::TunnelBuilder::new(
443 runtime.clone(),
444 chanmgr,
445 config.path_rules().clone(),
446 storage_handle,
447 guardmgr.clone(),
448 #[cfg(all(feature = "vanguards", feature = "hs-common"))]
449 vanguardmgr,
450 );
451
452 Ok(Self::new_generic(config, runtime, guardmgr, builder))
453 }
454}
455
456impl<B: AbstractTunnelBuilder<R> + 'static, R: Runtime> CircMgrInner<B, R> {
457 pub(crate) fn new_generic<CFG: CircMgrConfig>(
459 config: &CFG,
460 runtime: &R,
461 guardmgr: &tor_guardmgr::GuardMgr<R>,
462 builder: B,
463 ) -> Self {
464 let preemptive = Arc::new(Mutex::new(PreemptiveCircuitPredictor::new(
465 config.preemptive_circuits().clone(),
466 )));
467
468 guardmgr.set_filter(config.path_rules().build_guard_filter());
469
470 let mgr =
471 mgr::AbstractTunnelMgr::new(builder, runtime.clone(), config.circuit_timing().clone());
472
473 CircMgrInner {
474 mgr: Arc::new(mgr),
475 predictor: preemptive,
476 }
477 }
478
479 #[instrument(level = "trace", skip_all)]
485 pub(crate) fn launch_background_tasks<D, S>(
486 self: &Arc<Self>,
487 runtime: &R,
488 dir_provider: &Arc<D>,
489 state_mgr: S,
490 ) -> Result<Vec<TaskHandle>>
491 where
492 D: NetDirProvider + 'static + ?Sized,
493 S: StateMgr + std::marker::Send + 'static,
494 {
495 let mut ret = vec![];
496
497 runtime
498 .spawn(Self::keep_circmgr_params_updated(
499 dir_provider.events(),
500 Arc::downgrade(self),
501 Arc::downgrade(dir_provider),
502 ))
503 .map_err(|e| Error::from_spawn("circmgr parameter updater", e))?;
504
505 let (sched, handle) = TaskSchedule::new(runtime.clone());
506 ret.push(handle);
507
508 runtime
509 .spawn(Self::update_persistent_state(
510 sched,
511 Arc::downgrade(self),
512 state_mgr,
513 ))
514 .map_err(|e| Error::from_spawn("persistent state updater", e))?;
515
516 let (sched, handle) = TaskSchedule::new(runtime.clone());
517 ret.push(handle);
518
519 runtime
520 .spawn(Self::continually_launch_timeout_testing_circuits(
521 sched,
522 Arc::downgrade(self),
523 Arc::downgrade(dir_provider),
524 ))
525 .map_err(|e| Error::from_spawn("timeout-probe circuit launcher", e))?;
526
527 let (sched, handle) = TaskSchedule::new(runtime.clone());
528 ret.push(handle);
529
530 runtime
531 .spawn(Self::continually_preemptively_build_circuits(
532 sched,
533 Arc::downgrade(self),
534 Arc::downgrade(dir_provider),
535 ))
536 .map_err(|e| Error::from_spawn("preemptive circuit launcher", e))?;
537
538 self.mgr
539 .peek_builder()
540 .guardmgr()
541 .install_netdir_provider(&dir_provider.clone().upcast_arc())?;
542
543 #[cfg(all(feature = "vanguards", feature = "hs-common"))]
544 {
545 let () = self
546 .mgr
547 .peek_builder()
548 .vanguardmgr()
549 .launch_background_tasks(&dir_provider.clone().upcast_arc())?;
550 }
551
552 Ok(ret)
553 }
554
555 #[instrument(level = "trace", skip_all)]
558 pub(crate) async fn get_or_launch_dir(&self, netdir: DirInfo<'_>) -> Result<Arc<B::Tunnel>> {
559 self.expire_circuits().await;
560 let usage = TargetTunnelUsage::Dir;
561 self.mgr.get_or_launch(&usage, netdir).await.map(|(c, _)| c)
562 }
563
564 #[instrument(level = "trace", skip_all)]
570 pub(crate) async fn get_or_launch_exit(
571 &self,
572 netdir: DirInfo<'_>, ports: &[TargetPort],
574 isolation: StreamIsolation,
575 #[cfg(feature = "geoip")] country_code: Option<CountryCode>,
578 ) -> Result<Arc<B::Tunnel>> {
579 self.expire_circuits().await;
580 let time = self.mgr.peek_runtime().now();
581 {
582 let mut predictive = self.predictor.lock().expect("preemptive lock poisoned");
583 if ports.is_empty() {
584 predictive.note_usage(None, time);
585 } else {
586 for port in ports.iter() {
587 predictive.note_usage(Some(*port), time);
588 }
589 }
590 }
591 let require_stability = ports.iter().any(|p| {
592 self.mgr
593 .peek_builder()
594 .path_config()
595 .long_lived_ports
596 .contains(&p.port)
597 });
598 let ports = ports.iter().map(Clone::clone).collect();
599 #[cfg(not(feature = "geoip"))]
600 let country_code = None;
601 let usage = TargetTunnelUsage::Exit {
602 ports,
603 isolation,
604 country_code,
605 require_stability,
606 };
607 self.mgr.get_or_launch(&usage, netdir).await.map(|(c, _)| c)
608 }
609
610 #[cfg(feature = "specific-relay")]
615 #[instrument(level = "trace", skip_all)]
616 pub(crate) async fn get_or_launch_dir_specific<T: IntoOwnedChanTarget>(
617 &self,
618 target: T,
619 ) -> Result<Arc<B::Tunnel>> {
620 self.expire_circuits().await;
621 let usage = TargetTunnelUsage::DirSpecificTarget(target.to_owned());
622 self.mgr
623 .get_or_launch(&usage, DirInfo::Nothing)
624 .await
625 .map(|(c, _)| c)
626 }
627
628 #[instrument(level = "trace", skip_all)]
634 pub(crate) fn reconfigure<CFG: CircMgrConfig>(
635 &self,
636 new_config: &CFG,
637 how: tor_config::Reconfigure,
638 ) -> std::result::Result<RetireCircuits, tor_config::ReconfigureError> {
639 let old_path_rules = self.mgr.peek_builder().path_config();
640 let predictor = self.predictor.lock().expect("poisoned lock");
641 let preemptive_circuits = predictor.config();
642 if preemptive_circuits.initial_predicted_ports
643 != new_config.preemptive_circuits().initial_predicted_ports
644 {
645 how.cannot_change("preemptive_circuits.initial_predicted_ports")?;
647 }
648
649 if how == tor_config::Reconfigure::CheckAllOrNothing {
650 return Ok(RetireCircuits::None);
651 }
652
653 let retire_because_of_guardmgr =
654 self.mgr.peek_builder().guardmgr().reconfigure(new_config)?;
655
656 #[cfg(all(feature = "vanguards", feature = "hs-common"))]
657 let retire_because_of_vanguardmgr = self
658 .mgr
659 .peek_builder()
660 .vanguardmgr()
661 .reconfigure(new_config.vanguard_config())?;
662
663 let new_reachable = &new_config.path_rules().reachable_addrs;
664 if new_reachable != &old_path_rules.reachable_addrs {
665 let filter = new_config.path_rules().build_guard_filter();
666 self.mgr.peek_builder().guardmgr().set_filter(filter);
667 }
668
669 let discard_all_circuits = !new_config
670 .path_rules()
671 .at_least_as_permissive_as(&old_path_rules)
672 || retire_because_of_guardmgr != tor_guardmgr::RetireCircuits::None;
673
674 #[cfg(all(feature = "vanguards", feature = "hs-common"))]
675 let discard_all_circuits = discard_all_circuits
676 || retire_because_of_vanguardmgr != tor_guardmgr::RetireCircuits::None;
677
678 self.mgr
679 .peek_builder()
680 .set_path_config(new_config.path_rules().clone());
681 self.mgr
682 .set_circuit_timing(new_config.circuit_timing().clone());
683 predictor.set_config(new_config.preemptive_circuits().clone());
684
685 if discard_all_circuits {
686 info!("Path configuration has become more restrictive: retiring existing circuits.");
690 self.retire_all_circuits();
691 return Ok(RetireCircuits::All);
692 }
693 Ok(RetireCircuits::None)
694 }
695
696 #[instrument(level = "trace", skip_all)]
704 async fn keep_circmgr_params_updated<D>(
705 mut events: impl futures::Stream<Item = DirEvent> + Unpin,
706 circmgr: Weak<Self>,
707 dirmgr: Weak<D>,
708 ) where
709 D: NetDirProvider + 'static + ?Sized,
710 {
711 use DirEvent::*;
712 while let Some(event) = events.next().await {
713 if matches!(event, NewConsensus) {
714 if let (Some(cm), Some(dm)) = (Weak::upgrade(&circmgr), Weak::upgrade(&dirmgr)) {
715 if let Ok(netdir) = dm.netdir(Timeliness::Timely) {
716 cm.update_network_parameters(netdir.params());
717 }
718 } else {
719 debug!("Circmgr or dirmgr has disappeared; task exiting.");
720 break;
721 }
722 }
723 }
724 }
725
726 fn update_network_parameters(&self, p: &tor_netdir::params::NetParameters) {
729 self.mgr.update_network_parameters(p);
730 self.mgr.peek_builder().update_network_parameters(p);
731 }
732
733 #[instrument(level = "trace", skip_all)]
740 async fn continually_launch_timeout_testing_circuits<D>(
741 mut sched: TaskSchedule<R>,
742 circmgr: Weak<Self>,
743 dirmgr: Weak<D>,
744 ) where
745 D: NetDirProvider + 'static + ?Sized,
746 {
747 while sched.next().await.is_some() {
748 if let (Some(cm), Some(dm)) = (Weak::upgrade(&circmgr), Weak::upgrade(&dirmgr)) {
749 if let Ok(netdir) = dm.netdir(Timeliness::Unchecked) {
750 if let Err(e) = cm
751 .launch_timeout_testing_circuit_if_appropriate(&netdir)
752 .await
753 {
754 warn_report!(e, "Problem launching a timeout testing circuit");
755 }
756 let delay = netdir
757 .params()
758 .cbt_testing_delay
759 .try_into()
760 .expect("Out-of-bounds value from BoundedInt32");
761
762 drop((cm, dm));
763 sched.fire_in(delay);
764 } else {
765 let _ = dm.events().next().await;
768 sched.fire();
769 }
770 } else {
771 return;
772 }
773 }
774 }
775
776 async fn launch_timeout_testing_circuit_if_appropriate(&self, netdir: &NetDir) -> Result<()> {
784 if !self.mgr.peek_builder().learning_timeouts() {
785 return Ok(());
786 }
787 self.expire_circuits().await;
790 let max_circs: u64 = netdir
791 .params()
792 .cbt_max_open_circuits_for_testing
793 .try_into()
794 .expect("Out-of-bounds result from BoundedInt32");
795 if (self.mgr.n_tunnels() as u64) < max_circs {
796 let usage = TargetTunnelUsage::TimeoutTesting;
798 let dirinfo = netdir.into();
799 let mgr = Arc::clone(&self.mgr);
800 debug!("Launching a circuit to test build times.");
801 let receiver = mgr.launch_by_usage(&usage, dirinfo)?;
802 drop(receiver);
805 }
806
807 Ok(())
808 }
809
810 #[instrument(level = "trace", skip_all)]
817 async fn update_persistent_state<S>(
818 mut sched: TaskSchedule<R>,
819 circmgr: Weak<Self>,
820 statemgr: S,
821 ) where
822 S: StateMgr + std::marker::Send,
823 {
824 while sched.next().await.is_some() {
825 if let Some(circmgr) = Weak::upgrade(&circmgr) {
826 use tor_persist::LockStatus::*;
827
828 match statemgr.try_lock() {
829 Err(e) => {
830 error_report!(e, "Problem with state lock file");
831 break;
832 }
833 Ok(NewlyAcquired) => {
834 info!("We now own the lock on our state files.");
835 if let Err(e) = circmgr.upgrade_to_owned_persistent_state() {
836 error_report!(e, "Unable to upgrade to owned state files");
837 break;
838 }
839 }
840 Ok(AlreadyHeld) => {
841 if let Err(e) = circmgr.store_persistent_state() {
842 error_report!(e, "Unable to flush circmgr state");
843 break;
844 }
845 }
846 Ok(NoLock) => {
847 if let Err(e) = circmgr.reload_persistent_state() {
848 error_report!(e, "Unable to reload circmgr state");
849 break;
850 }
851 }
852 }
853 } else {
854 debug!("Circmgr has disappeared; task exiting.");
855 return;
856 }
857 sched.fire_in(Duration::from_secs(60));
864 }
865
866 debug!("State update task exiting (potentially due to handle drop).");
867 }
868
869 pub(crate) fn upgrade_to_owned_persistent_state(&self) -> Result<()> {
873 self.mgr.peek_builder().upgrade_to_owned_state()?;
874 Ok(())
875 }
876
877 pub(crate) fn reload_persistent_state(&self) -> Result<()> {
882 self.mgr.peek_builder().reload_state()?;
883 Ok(())
884 }
885
886 #[instrument(level = "trace", skip_all)]
898 async fn continually_preemptively_build_circuits<D>(
899 mut sched: TaskSchedule<R>,
900 circmgr: Weak<Self>,
901 dirmgr: Weak<D>,
902 ) where
903 D: NetDirProvider + 'static + ?Sized,
904 {
905 let base_delay = Duration::from_secs(10);
906 let mut retry = RetryDelay::from_duration(base_delay);
907
908 while sched.next().await.is_some() {
909 if let (Some(cm), Some(dm)) = (Weak::upgrade(&circmgr), Weak::upgrade(&dirmgr)) {
910 if let Ok(netdir) = dm.netdir(Timeliness::Timely) {
911 let result = cm
912 .launch_circuits_preemptively(DirInfo::Directory(&netdir))
913 .await;
914
915 let delay = match result {
916 Ok(()) => {
917 retry.reset();
918 base_delay
919 }
920 Err(_) => retry.next_delay(&mut rand::rng()),
921 };
922
923 sched.fire_in(delay);
924 } else {
925 let _ = dm.events().next().await;
928 sched.fire();
929 }
930 } else {
931 return;
932 }
933 }
934 }
935
936 #[instrument(level = "trace", skip_all)]
944 async fn launch_circuits_preemptively(
945 &self,
946 netdir: DirInfo<'_>,
947 ) -> std::result::Result<(), err::PreemptiveCircError> {
948 trace!("Checking preemptive circuit predictions.");
949 let (circs, threshold) = {
950 let path_config = self.mgr.peek_builder().path_config();
951 let preemptive = self.predictor.lock().expect("preemptive lock poisoned");
952 let threshold = preemptive.config().disable_at_threshold;
953 (preemptive.predict(&path_config), threshold)
954 };
955
956 if self.mgr.n_tunnels() >= threshold {
957 return Ok(());
958 }
959 let mut n_created = 0_usize;
960 let mut n_errors = 0_usize;
961
962 let futures = circs
963 .iter()
964 .map(|usage| self.mgr.get_or_launch(usage, netdir));
965 let results = futures::future::join_all(futures).await;
966 for (i, result) in results.into_iter().enumerate() {
967 match result {
968 Ok((t, TunnelProvenance::NewlyCreated)) => {
969 debug!(
970 tunnel_id=%t.unique_id(),
971 "Preemptive circuit was created for {:?}", circs[i]);
972 n_created += 1;
973 }
974 Ok((t, TunnelProvenance::Preexisting)) => {
975 trace!(
976 tunnel_id=%t.unique_id(),
977 "Circuit already existed created for {:?}", circs[i]);
978 }
979 Err(e) => {
980 warn_report!(e, "Failed to build preemptive circuit {:?}", sv(&circs[i]));
981 n_errors += 1;
982 }
983 }
984 }
985
986 if n_created > 0 || n_errors == 0 {
987 Ok(())
991 } else {
992 Err(err::PreemptiveCircError)
995 }
996 }
997
998 #[cfg(feature = "hs-common")]
1015 #[instrument(level = "trace", skip_all)]
1016 pub(crate) async fn launch_hs_unmanaged<T>(
1017 &self,
1018 planned_target: Option<T>,
1019 dir: &NetDir,
1020 stem_kind: HsCircStemKind,
1021 circ_kind: Option<HsCircKind>,
1022 ) -> Result<B::Tunnel>
1023 where
1024 T: IntoOwnedChanTarget,
1025 {
1026 let usage = TargetTunnelUsage::HsCircBase {
1027 compatible_with_target: planned_target.map(IntoOwnedChanTarget::to_owned),
1028 stem_kind,
1029 circ_kind,
1030 };
1031 let (_, client_circ) = self.mgr.launch_unmanaged(&usage, dir.into()).await?;
1032 Ok(client_circ)
1033 }
1034
1035 pub(crate) fn netdir_is_sufficient(&self, netdir: &NetDir) -> bool {
1041 self.mgr
1042 .peek_builder()
1043 .guardmgr()
1044 .netdir_is_sufficient(netdir)
1045 }
1046
1047 pub(crate) fn estimate_timeout(
1049 &self,
1050 timeout_action: &timeouts::Action,
1051 ) -> std::time::Duration {
1052 let (timeout, _abandon) = self.mgr.peek_builder().estimator().timeouts(timeout_action);
1053 timeout
1054 }
1055
1056 pub(crate) fn builder(&self) -> &B {
1058 self.mgr.peek_builder()
1059 }
1060
1061 pub(crate) fn store_persistent_state(&self) -> Result<bool> {
1066 self.mgr.peek_builder().save_state()
1067 }
1068
1069 async fn expire_circuits(&self) {
1074 let now = self.mgr.peek_runtime().now();
1080
1081 let _next_expiration = self.mgr.expire_tunnels(now).await;
1083 }
1084
1085 pub(crate) fn retire_all_circuits(&self) {
1093 self.mgr.retire_all_tunnels();
1094 }
1095
1096 pub(crate) fn retire_circ(&self, circ_id: &<B::Tunnel as AbstractTunnel>::Id) {
1099 let _ = self.mgr.take_tunnel(circ_id);
1100 }
1101
1102 pub(crate) fn skew_events(&self) -> ClockSkewEvents {
1110 self.mgr.peek_builder().guardmgr().skew_events()
1111 }
1112
1113 pub(crate) fn note_external_failure(
1117 &self,
1118 target: &impl ChanTarget,
1119 external_failure: ExternalActivity,
1120 ) {
1121 self.mgr
1122 .peek_builder()
1123 .guardmgr()
1124 .note_external_failure(target, external_failure);
1125 }
1126
1127 pub(crate) fn note_external_success(
1130 &self,
1131 target: &impl ChanTarget,
1132 external_activity: ExternalActivity,
1133 ) {
1134 self.mgr
1135 .peek_builder()
1136 .guardmgr()
1137 .note_external_success(target, external_activity);
1138 }
1139}
1140
1141impl<B: AbstractTunnelBuilder<R> + 'static, R: Runtime> Drop for CircMgrInner<B, R> {
1142 fn drop(&mut self) {
1143 match self.store_persistent_state() {
1144 Ok(true) => info!("Flushed persistent state at exit."),
1145 Ok(false) => debug!("Lock not held; no state to flush."),
1146 Err(e) => error_report!(e, "Unable to flush state on circuit manager drop"),
1147 }
1148 }
1149}
1150
1151#[cfg(test)]
1152mod test {
1153 #![allow(clippy::bool_assert_comparison)]
1155 #![allow(clippy::clone_on_copy)]
1156 #![allow(clippy::dbg_macro)]
1157 #![allow(clippy::mixed_attributes_style)]
1158 #![allow(clippy::print_stderr)]
1159 #![allow(clippy::print_stdout)]
1160 #![allow(clippy::single_char_pattern)]
1161 #![allow(clippy::unwrap_used)]
1162 #![allow(clippy::unchecked_time_subtraction)]
1163 #![allow(clippy::useless_vec)]
1164 #![allow(clippy::needless_pass_by_value)]
1165 #![allow(clippy::string_slice)] use mocks::FakeBuilder;
1168 use tor_guardmgr::GuardMgr;
1169 use tor_linkspec::OwnedChanTarget;
1170 use tor_netdir::testprovider::TestNetDirProvider;
1171 use tor_persist::TestingStateMgr;
1172
1173 use super::*;
1174
1175 #[test]
1176 fn get_params() {
1177 use tor_netdir::{MdReceiver, PartialNetDir};
1178 use tor_netdoc::doc::netstatus::NetParamValues;
1179 let fb = FallbackList::from([]);
1181 let di: DirInfo<'_> = (&fb).into();
1182
1183 let p1 = di.circ_params(&TargetTunnelUsage::Dir).unwrap();
1184 assert!(!p1.extend_by_ed25519_id);
1185
1186 let (consensus, microdescs) = tor_netdir::testnet::construct_network().unwrap();
1188 let mut params = NetParamValues::default();
1189 params.set("circwindow".into(), 100);
1190 params.set("ExtendByEd25519ID".into(), 1);
1191 let mut dir = PartialNetDir::new(consensus, Some(¶ms));
1192 for m in microdescs {
1193 dir.add_microdesc(m);
1194 }
1195 let netdir = dir.unwrap_if_sufficient().unwrap();
1196 let di: DirInfo<'_> = (&netdir).into();
1197 let p2 = di.circ_params(&TargetTunnelUsage::Dir).unwrap();
1198 assert!(p2.extend_by_ed25519_id);
1199
1200 let (consensus, microdescs) = tor_netdir::testnet::construct_network().unwrap();
1202 let mut params = NetParamValues::default();
1203 params.set("circwindow".into(), 100_000);
1204 params.set("ExtendByEd25519ID".into(), 1);
1205 let mut dir = PartialNetDir::new(consensus, Some(¶ms));
1206 for m in microdescs {
1207 dir.add_microdesc(m);
1208 }
1209 let netdir = dir.unwrap_if_sufficient().unwrap();
1210 let di: DirInfo<'_> = (&netdir).into();
1211 let p2 = di.circ_params(&TargetTunnelUsage::Dir).unwrap();
1212 assert!(p2.extend_by_ed25519_id);
1213 }
1214
1215 fn make_circmgr<R: Runtime>(runtime: R) -> Arc<CircMgrInner<FakeBuilder<R>, R>> {
1216 let config = crate::config::test_config::TestConfig::default();
1217 let statemgr = TestingStateMgr::new();
1218 let guardmgr =
1219 GuardMgr::new(runtime.clone(), statemgr.clone(), &config).expect("Create GuardMgr");
1220 let builder = FakeBuilder::new(
1221 &runtime,
1222 statemgr.clone(),
1223 &tor_guardmgr::TestConfig::default(),
1224 );
1225 let circmgr = Arc::new(CircMgrInner::new_generic(
1226 &config, &runtime, &guardmgr, builder,
1227 ));
1228 let netdir = Arc::new(TestNetDirProvider::new());
1229 CircMgrInner::launch_background_tasks(&circmgr, &runtime, &netdir, statemgr)
1230 .expect("launch CircMgrInner background tasks");
1231 circmgr
1232 }
1233
1234 #[test]
1235 #[cfg(feature = "hs-common")]
1236 fn test_launch_hs_unmanaged() {
1237 tor_rtmock::MockRuntime::test_with_various(|runtime| async move {
1238 let circmgr = make_circmgr(runtime.clone());
1239 let netdir = tor_netdir::testnet::construct_netdir()
1240 .unwrap_if_sufficient()
1241 .unwrap();
1242
1243 let (ret_tx, ret_rx) = tor_async_utils::oneshot::channel();
1244 runtime.spawn_identified("launch_hs_unamanged", async move {
1245 ret_tx
1246 .send(
1247 circmgr
1248 .launch_hs_unmanaged::<OwnedChanTarget>(
1249 None,
1250 &netdir,
1251 HsCircStemKind::Naive,
1252 None,
1253 )
1254 .await,
1255 )
1256 .unwrap();
1257 });
1258 runtime.advance_by(Duration::from_millis(60)).await;
1259 ret_rx.await.unwrap().unwrap();
1260 });
1261 }
1262}