1use crate::factory::BootstrapReporter;
4use crate::mgr::state::{ChannelForTarget, PendingChannelHandle};
5use crate::{ChanProvenance, ChannelConfig, ChannelUsage, Dormancy, Error, Result};
6
7use async_trait::async_trait;
8use futures::future::Shared;
9use oneshot_fused_workaround as oneshot;
10use std::result::Result as StdResult;
11use std::sync::Arc;
12use std::time::Duration;
13use tor_error::{error_report, internal};
14use tor_linkspec::{HasChanMethod, HasRelayIds};
15use tor_netdir::params::NetParameters;
16use tor_proto::channel::kist::KistParams;
17use tor_proto::channel::params::ChannelPaddingInstructionsUpdates;
18use tor_proto::memquota::{ChannelAccount, SpecificAccount as _, ToplevelAccount};
19use tracing::{instrument, trace};
20
21#[cfg(feature = "relay")]
22use {
23 safelog::Sensitive, std::net::SocketAddr, std::num::NonZero,
24 tor_async_utils::bw_pool::BandwidthPool,
25 tor_async_utils::global_rate_limit::GlobalRateLimitedConn, tor_proto::RelayChannelAuthMaterial,
26};
27
28mod select;
29mod state;
30
31pub(crate) trait AbstractChannel: HasRelayIds {
35 fn is_canonical(&self) -> bool;
37 fn is_canonical_to_peer(&self) -> bool;
39 fn is_usable(&self) -> bool;
45 fn duration_unused(&self) -> Option<Duration>;
48
49 fn reparameterize(
54 &self,
55 updates: Arc<ChannelPaddingInstructionsUpdates>,
56 ) -> tor_proto::Result<()>;
57
58 fn reparameterize_kist(&self, kist_params: KistParams) -> tor_proto::Result<()>;
63
64 fn engage_padding_activities(&self);
70}
71
72#[async_trait]
78pub(crate) trait AbstractChannelFactory {
79 type Channel: AbstractChannel;
81 type BuildSpec: HasRelayIds + HasChanMethod;
83 type Stream;
85
86 async fn build_channel(
93 &self,
94 target: &Self::BuildSpec,
95 reporter: BootstrapReporter,
96 memquota: ChannelAccount,
97 ) -> Result<Arc<Self::Channel>>;
98
99 #[cfg(feature = "relay")]
101 async fn build_channel_using_incoming(
102 &self,
103 peer: Sensitive<std::net::SocketAddr>,
104 stream: Self::Stream,
105 memquota: ChannelAccount,
106 ) -> Result<Arc<Self::Channel>>;
107}
108
109#[derive(Default)]
111pub struct ChanMgrConfig {
112 pub(crate) cfg: ChannelConfig,
114 #[cfg(feature = "relay")]
116 pub(crate) auth_material: Option<Arc<RelayChannelAuthMaterial>>,
117 #[cfg(feature = "relay")]
120 pub(crate) my_addrs: Vec<SocketAddr>,
121 #[cfg(feature = "relay")]
123 pub(crate) bw_pools: Option<ChannelBandwidthPools>,
124 #[cfg(feature = "relay")]
127 pub(crate) allow_any_addrs: bool,
128 }
130
131impl ChanMgrConfig {
132 pub fn new(cfg: ChannelConfig) -> Self {
134 Self {
135 cfg,
136 #[cfg(feature = "relay")]
137 auth_material: None,
138 #[cfg(feature = "relay")]
139 my_addrs: Vec::new(),
140 #[cfg(feature = "relay")]
141 bw_pools: None,
142 #[cfg(feature = "relay")]
143 allow_any_addrs: false,
144 }
145 }
146
147 #[cfg(feature = "relay")]
152 pub fn allow_any_addrs(mut self, allow_any_addrs: bool) -> Self {
153 self.allow_any_addrs = allow_any_addrs;
154 self
155 }
156
157 #[cfg(feature = "relay")]
159 pub fn with_auth_material(mut self, auth_material: Arc<RelayChannelAuthMaterial>) -> Self {
160 self.auth_material = Some(auth_material);
161 self
162 }
163
164 #[cfg(feature = "relay")]
166 pub fn with_my_addrs(mut self, my_addrs: Vec<SocketAddr>) -> Self {
167 self.my_addrs = my_addrs;
168 self
169 }
170
171 #[cfg(feature = "relay")]
173 pub fn with_bandwidth_pools(mut self, read: BandwidthPool, write: BandwidthPool) -> Self {
174 self.bw_pools = Some(ChannelBandwidthPools { read, write });
175 self
176 }
177}
178
179#[cfg(feature = "relay")]
185const BW_MAX_CHUNK: NonZero<usize> = NonZero::new(16 * 1024).expect("bandwidth max chunk is zero");
186
187#[cfg(feature = "relay")]
189pub(crate) struct ChannelBandwidthPools {
190 pub(crate) read: BandwidthPool,
192 pub(crate) write: BandwidthPool,
194}
195
196#[cfg(feature = "relay")]
197impl ChannelBandwidthPools {
198 pub(crate) fn share(&self) -> Self {
200 Self {
201 read: self.read.share(),
202 write: self.write.share(),
203 }
204 }
205
206 pub(crate) fn rate_limit<S>(&self, stream: S) -> GlobalRateLimitedConn<S> {
208 GlobalRateLimitedConn::new(
209 stream,
210 self.read.new_acquirer(),
211 self.write.new_acquirer(),
212 BW_MAX_CHUNK,
213 )
214 }
215}
216
217pub(crate) struct AbstractChanMgr<CF: AbstractChannelFactory> {
226 pub(crate) channels: state::MgrState<CF>,
231
232 pub(crate) reporter: BootstrapReporter,
234
235 pub(crate) memquota: ToplevelAccount,
237
238 #[cfg(feature = "metrics")]
240 pub(crate) metrics: ChanMgrMetrics,
241}
242
243#[cfg(feature = "metrics")]
248pub(crate) struct ChanMgrMetrics {
249 pub(crate) inbound_channels_built_success: metrics::Counter,
251 pub(crate) inbound_channels_built_failure_unusable_target: metrics::Counter,
253 pub(crate) inbound_channels_built_failure_pending_failed: metrics::Counter,
255 pub(crate) inbound_channels_built_failure_chan_timeout: metrics::Counter,
257 pub(crate) inbound_channels_built_failure_proto: metrics::Counter,
259 pub(crate) inbound_channels_built_failure_io: metrics::Counter,
261 pub(crate) inbound_channels_built_failure_connect: metrics::Counter,
263 pub(crate) inbound_channels_built_failure_spawn: metrics::Counter,
265 pub(crate) inbound_channels_built_failure_missing_id: metrics::Counter,
267 pub(crate) inbound_channels_built_failure_identity_conflict: metrics::Counter,
269 pub(crate) inbound_channels_built_failure_no_such_transport: metrics::Counter,
271 pub(crate) inbound_channels_built_failure_request_cancelled: metrics::Counter,
273 pub(crate) inbound_channels_built_failure_pt: metrics::Counter,
275 pub(crate) inbound_channels_built_failure_memquota: metrics::Counter,
277 pub(crate) inbound_channels_built_failure_internal: metrics::Counter,
279}
280
281#[cfg(feature = "metrics")]
282impl ChanMgrMetrics {
283 pub(crate) fn new() -> Self {
285 ChanMgrMetrics {
286 inbound_channels_built_success: metrics::counter!(
287 description: "Total number of channels built",
288 unit: metrics::Unit::Count,
289 "arti_chanmgr_channels_built",
290 "result" => "success",
291 "direction" => "inbound",
292 ),
293 inbound_channels_built_failure_unusable_target: metrics::counter!(
294 description: "Total number of channels built",
295 unit: metrics::Unit::Count,
296 "arti_chanmgr_channels_built",
297 "result" => "failure",
298 "direction" => "inbound",
299 "error" => "unusable_target",
300 ),
301 inbound_channels_built_failure_pending_failed: metrics::counter!(
302 description: "Total number of channels built",
303 unit: metrics::Unit::Count,
304 "arti_chanmgr_channels_built",
305 "result" => "failure",
306 "direction" => "inbound",
307 "error" => "pending_failed",
308 ),
309 inbound_channels_built_failure_chan_timeout: metrics::counter!(
310 description: "Total number of channels built",
311 unit: metrics::Unit::Count,
312 "arti_chanmgr_channels_built",
313 "result" => "failure",
314 "direction" => "inbound",
315 "error" => "chan_timeout",
316 ),
317 inbound_channels_built_failure_proto: metrics::counter!(
318 description: "Total number of channels built",
319 unit: metrics::Unit::Count,
320 "arti_chanmgr_channels_built",
321 "result" => "failure",
322 "direction" => "inbound",
323 "error" => "proto",
324 ),
325 inbound_channels_built_failure_io: metrics::counter!(
326 description: "Total number of channels built",
327 unit: metrics::Unit::Count,
328 "arti_chanmgr_channels_built",
329 "result" => "failure",
330 "direction" => "inbound",
331 "error" => "io",
332 ),
333 inbound_channels_built_failure_connect: metrics::counter!(
334 description: "Total number of channels built",
335 unit: metrics::Unit::Count,
336 "arti_chanmgr_channels_built",
337 "result" => "failure",
338 "direction" => "inbound",
339 "error" => "connect",
340 ),
341 inbound_channels_built_failure_spawn: metrics::counter!(
342 description: "Total number of channels built",
343 unit: metrics::Unit::Count,
344 "arti_chanmgr_channels_built",
345 "result" => "failure",
346 "direction" => "inbound",
347 "error" => "spawn",
348 ),
349 inbound_channels_built_failure_missing_id: metrics::counter!(
350 description: "Total number of channels built",
351 unit: metrics::Unit::Count,
352 "arti_chanmgr_channels_built",
353 "result" => "failure",
354 "direction" => "inbound",
355 "error" => "missing_id",
356 ),
357 inbound_channels_built_failure_identity_conflict: metrics::counter!(
358 description: "Total number of channels built",
359 unit: metrics::Unit::Count,
360 "arti_chanmgr_channels_built",
361 "result" => "failure",
362 "direction" => "inbound",
363 "error" => "identity_conflict",
364 ),
365 inbound_channels_built_failure_no_such_transport: metrics::counter!(
366 description: "Total number of channels built",
367 unit: metrics::Unit::Count,
368 "arti_chanmgr_channels_built",
369 "result" => "failure",
370 "direction" => "inbound",
371 "error" => "no_such_transport",
372 ),
373 inbound_channels_built_failure_request_cancelled: metrics::counter!(
374 description: "Total number of channels built",
375 unit: metrics::Unit::Count,
376 "arti_chanmgr_channels_built",
377 "result" => "failure",
378 "direction" => "inbound",
379 "error" => "request_cancelled",
380 ),
381 inbound_channels_built_failure_pt: metrics::counter!(
382 description: "Total number of channels built",
383 unit: metrics::Unit::Count,
384 "arti_chanmgr_channels_built",
385 "result" => "failure",
386 "direction" => "inbound",
387 "error" => "pt",
388 ),
389 inbound_channels_built_failure_memquota: metrics::counter!(
390 description: "Total number of channels built",
391 unit: metrics::Unit::Count,
392 "arti_chanmgr_channels_built",
393 "result" => "failure",
394 "direction" => "inbound",
395 "error" => "memquota",
396 ),
397 inbound_channels_built_failure_internal: metrics::counter!(
398 description: "Total number of channels built",
399 unit: metrics::Unit::Count,
400 "arti_chanmgr_channels_built",
401 "result" => "failure",
402 "direction" => "inbound",
403 "error" => "internal",
404 ),
405 }
406 }
407
408 pub(crate) fn increment_inbound_channels_built<R>(&self, result: &Result<R>) {
410 match result {
411 Ok(_) => self.inbound_channels_built_success.increment(1),
412 Err(Error::UnusableTarget(_)) => self
413 .inbound_channels_built_failure_unusable_target
414 .increment(1),
415 Err(Error::PendingFailed { .. }) => self
416 .inbound_channels_built_failure_pending_failed
417 .increment(1),
418 Err(Error::ChanTimeout { .. }) => self
419 .inbound_channels_built_failure_chan_timeout
420 .increment(1),
421 Err(Error::Proto { .. }) => self.inbound_channels_built_failure_proto.increment(1),
422 Err(Error::Io { .. }) => self.inbound_channels_built_failure_io.increment(1),
423 Err(Error::Connect { .. }) => self.inbound_channels_built_failure_connect.increment(1),
424 Err(Error::Spawn { .. }) => self.inbound_channels_built_failure_spawn.increment(1),
425 Err(Error::MissingId) => self.inbound_channels_built_failure_missing_id.increment(1),
426 Err(Error::IdentityConflict) => self
427 .inbound_channels_built_failure_identity_conflict
428 .increment(1),
429 Err(Error::NoSuchTransport(_)) => self
430 .inbound_channels_built_failure_no_such_transport
431 .increment(1),
432 Err(Error::RequestCancelled) => self
433 .inbound_channels_built_failure_request_cancelled
434 .increment(1),
435 Err(Error::Pt(_)) => self.inbound_channels_built_failure_pt.increment(1),
436 Err(Error::Memquota(_)) => self.inbound_channels_built_failure_memquota.increment(1),
437 Err(Error::Internal(_)) => self.inbound_channels_built_failure_internal.increment(1),
438 }
439 }
440}
441
442type Pending = Shared<oneshot::Receiver<Result<()>>>;
445
446type Sending = oneshot::Sender<Result<()>>;
449
450struct PendingLaunchGuard<'a, CF: AbstractChannelFactory> {
457 channels: &'a state::MgrState<CF>,
459 handle: Option<PendingChannelHandle>,
461 send: Option<Sending>,
463 result: Result<()>,
465}
466
467impl<'a, CF: AbstractChannelFactory> PendingLaunchGuard<'a, CF> {
468 fn new(channels: &'a state::MgrState<CF>, handle: PendingChannelHandle, send: Sending) -> Self {
470 Self {
471 channels,
472 handle: Some(handle),
473 send: Some(send),
474 result: Err(Error::RequestCancelled),
475 }
476 }
477
478 fn note_result(&mut self, result: Result<()>) {
480 self.result = result;
481 }
482
483 fn upgrade_pending_channel_to_open(&mut self, channel: Arc<CF::Channel>) -> Result<()> {
485 let handle = self
486 .handle
487 .take()
488 .expect("pending launch guard lost its handle before upgrade");
489 self.channels
490 .upgrade_pending_channel_to_open(handle, channel)
491 }
492}
493
494impl<'a, CF: AbstractChannelFactory> Drop for PendingLaunchGuard<'a, CF> {
495 fn drop(&mut self) {
496 if let Some(handle) = self.handle.take() {
497 if let Err(e) = self.channels.remove_pending_channel(handle) {
498 #[allow(clippy::missing_docs_in_private_items)]
503 const MSG: &str = "Unable to remove the pending channel";
504 error_report!(internal!("{e}"), "{}", MSG);
505 }
506 }
507
508 if let Some(send) = self.send.take() {
509 let _ignore_err = send.send(self.result.clone());
512 }
513 }
514}
515
516impl<CF: AbstractChannelFactory + Clone> AbstractChanMgr<CF> {
517 pub(crate) fn new(
519 connector: CF,
520 config: ChannelConfig,
521 dormancy: Dormancy,
522 netparams: &NetParameters,
523 reporter: BootstrapReporter,
524 memquota: ToplevelAccount,
525 ) -> Self {
526 AbstractChanMgr {
527 channels: state::MgrState::new(connector, config, dormancy, netparams),
528 reporter,
529 memquota,
530 #[cfg(feature = "metrics")]
531 metrics: ChanMgrMetrics::new(),
532 }
533 }
534
535 #[allow(unused)]
537 pub(crate) fn with_mut_builder<F>(&self, func: F)
538 where
539 F: FnOnce(&mut CF),
540 {
541 self.channels.with_mut_builder(func);
542 }
543
544 #[cfg(test)]
546 pub(crate) fn remove_unusable_entries(&self) -> Result<()> {
547 self.channels.remove_unusable()
548 }
549
550 #[cfg(feature = "relay")]
553 pub(crate) async fn handle_incoming(
554 &self,
555 src: Sensitive<std::net::SocketAddr>,
556 stream: CF::Stream,
557 ) -> Result<Arc<CF::Channel>> {
558 let chan_builder = self.channels.builder();
559 let memquota = ChannelAccount::new(&self.memquota)?;
560 let channel = chan_builder
561 .build_channel_using_incoming(src, stream, memquota)
562 .await?;
563 self.channels.add_open(channel.clone())?;
565 Ok(channel)
566 }
567
568 #[instrument(skip_all, level = "trace")]
578 pub(crate) async fn get_or_launch(
579 &self,
580 target: CF::BuildSpec,
581 usage: ChannelUsage,
582 ) -> Result<(Arc<CF::Channel>, ChanProvenance)> {
583 use ChannelUsage as CU;
584
585 let chan = self.get_or_launch_internal(target).await?;
586
587 match usage {
588 CU::Dir | CU::UselessCircuit => {}
589 CU::UserTraffic => chan.0.engage_padding_activities(),
590 }
591
592 Ok(chan)
593 }
594
595 #[instrument(skip_all, level = "trace")]
597 async fn get_or_launch_internal(
598 &self,
599 target: CF::BuildSpec,
600 ) -> Result<(Arc<CF::Channel>, ChanProvenance)> {
601 const N_ATTEMPTS: usize = 2;
603 let mut attempts_so_far = 0;
604 let mut final_attempt = false;
605 let mut provenance = ChanProvenance::Preexisting;
606
607 let mut last_err = None;
609
610 while attempts_so_far < N_ATTEMPTS || final_attempt {
611 attempts_so_far += 1;
612
613 let action = self.choose_action(&target, final_attempt)?;
618
619 match action {
622 None => {
625 if !final_attempt {
626 return Err(Error::Internal(internal!(
627 "No action returned while not on final attempt"
628 )));
629 }
630 break;
631 }
632 Some(Action::Return(v)) => {
634 trace!("Returning existing channel");
635 return v.map(|chan| (chan, provenance));
636 }
637 Some(Action::Wait(pend)) => {
639 trace!("Waiting for in-progress channel");
640 match pend.await {
641 Ok(Ok(())) => {
642 final_attempt = true;
648 provenance = ChanProvenance::NewlyCreated;
649 last_err.get_or_insert(Error::RequestCancelled);
650 }
651 Ok(Err(e)) => {
652 last_err = Some(e);
653 }
654 Err(_) => {
655 last_err =
656 Some(Error::Internal(internal!("channel build task disappeared")));
657 }
658 }
659 }
660 Some(Action::Launch((handle, send))) => {
662 trace!("Launching channel");
663 let connector = self.channels.builder();
664 let mut launch = PendingLaunchGuard::new(&self.channels, handle, send);
665 let memquota = match ChannelAccount::new(&self.memquota) {
666 Ok(memquota) => memquota,
667 Err(e) => {
668 let e: Error = e.into();
669 launch.note_result(Err(e.clone()));
670 return Err(e);
671 }
672 };
673
674 let outcome = connector
675 .build_channel(&target, self.reporter.clone(), memquota)
676 .await;
677
678 match outcome {
679 Ok(ref chan) => {
680 match launch.upgrade_pending_channel_to_open(Arc::clone(chan)) {
682 Ok(()) => launch.note_result(Ok(())),
683 Err(e) => {
684 launch.note_result(Err(e.clone()));
685 return Err(e);
686 }
687 }
688 }
689 Err(_) => {
690 launch.note_result(outcome.clone().map(|_| ()));
691 }
692 }
693
694 match outcome {
695 Ok(chan) => {
696 return Ok((chan, ChanProvenance::NewlyCreated));
697 }
698 Err(e) => last_err = Some(e),
699 }
700 }
701 }
702
703 }
705
706 Err(last_err.unwrap_or_else(|| Error::Internal(internal!("no error was set!?"))))
707 }
708
709 #[instrument(skip_all, level = "trace")]
718 fn choose_action(
719 &self,
720 target: &CF::BuildSpec,
721 final_attempt: bool,
722 ) -> Result<Option<Action<CF::Channel>>> {
723 let response = self.channels.request_channel(
725 target,
726 !final_attempt,
727 );
728
729 match response {
730 Ok(Some(ChannelForTarget::Open(channel))) => Ok(Some(Action::Return(Ok(channel)))),
731 Ok(Some(ChannelForTarget::Pending(pending))) => {
732 if !final_attempt {
733 Ok(Some(Action::Wait(pending)))
734 } else {
735 Ok(None)
737 }
738 }
739 Ok(Some(ChannelForTarget::NewEntry((handle, send)))) => {
740 Ok(Some(Action::Launch((handle, send))))
742 }
743 Ok(None) => Ok(None),
744 Err(e @ Error::IdentityConflict) => Ok(Some(Action::Return(Err(e)))),
745 Err(e) => Err(e),
746 }
747 }
748
749 pub(crate) fn update_netparams(
751 &self,
752 netparams: Arc<dyn AsRef<NetParameters>>,
753 ) -> StdResult<(), tor_error::Bug> {
754 self.channels.reconfigure_general(None, None, netparams)
755 }
756
757 pub(crate) fn set_dormancy(
759 &self,
760 dormancy: Dormancy,
761 netparams: Arc<dyn AsRef<NetParameters>>,
762 ) -> StdResult<(), tor_error::Bug> {
763 self.channels
764 .reconfigure_general(None, Some(dormancy), netparams)
765 }
766
767 pub(crate) fn reconfigure(
769 &self,
770 config: &ChannelConfig,
771 netparams: Arc<dyn AsRef<NetParameters>>,
772 ) -> StdResult<(), tor_error::Bug> {
773 self.channels
774 .reconfigure_general(Some(config), None, netparams)
775 }
776
777 pub(crate) fn expire_channels(&self) -> Duration {
786 self.channels.expire_channels()
787 }
788
789 #[cfg(test)]
791 pub(crate) fn get_nowait<'a, T>(&self, ident: T) -> Vec<Arc<CF::Channel>>
792 where
793 T: Into<tor_linkspec::RelayIdRef<'a>>,
794 {
795 use state::ChannelState::*;
796 self.channels
797 .with_channels(|channel_map| {
798 channel_map
799 .by_id(ident)
800 .filter_map(|entry| match entry {
801 Open(ent) if ent.channel.is_usable() => Some(Arc::clone(&ent.channel)),
802 _ => None,
803 })
804 .collect()
805 })
806 .expect("Poisoned lock")
807 }
808}
809
810#[allow(clippy::large_enum_variant)]
812enum Action<C: AbstractChannel> {
813 Launch((PendingChannelHandle, Sending)),
816 Wait(Pending),
819 Return(Result<Arc<C>>),
821}
822
823#[cfg(test)]
824mod test {
825 #![allow(clippy::bool_assert_comparison)]
827 #![allow(clippy::clone_on_copy)]
828 #![allow(clippy::dbg_macro)]
829 #![allow(clippy::mixed_attributes_style)]
830 #![allow(clippy::print_stderr)]
831 #![allow(clippy::print_stdout)]
832 #![allow(clippy::single_char_pattern)]
833 #![allow(clippy::unwrap_used)]
834 #![allow(clippy::unchecked_time_subtraction)]
835 #![allow(clippy::useless_vec)]
836 #![allow(clippy::needless_pass_by_value)]
837 #![allow(clippy::string_slice)] use super::*;
840 use crate::Error;
841
842 use futures::{join, poll};
843 use std::error::Error as StdError;
844 use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
845 use std::sync::Arc;
846 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
847 use std::time::Duration;
848 use tor_error::bad_api_usage;
849 use tor_linkspec::ChannelMethod;
850 use tor_llcrypto::pk::ed25519::Ed25519Identity;
851 use tor_memquota::ArcMemoryQuotaTrackerExt as _;
852
853 use crate::ChannelUsage as CU;
854 use tor_rtcompat::{Runtime, task::yield_now, test_with_one_runtime};
855
856 const ADDR_A: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(1, 1, 1, 1), 443));
858 const ADDR_B: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(2, 2, 2, 2), 443));
859
860 #[derive(Clone)]
861 struct FakeChannelFactory<RT> {
862 runtime: RT,
863 build_attempts: Arc<AtomicUsize>,
864 }
865
866 #[derive(Clone, Debug)]
867 struct FakeChannel {
868 ed_ident: Ed25519Identity,
869 mood: char,
870 closing: Arc<AtomicBool>,
871 detect_reuse: Arc<char>,
872 }
874
875 impl PartialEq for FakeChannel {
876 fn eq(&self, other: &Self) -> bool {
877 Arc::ptr_eq(&self.detect_reuse, &other.detect_reuse)
878 }
879 }
880
881 impl AbstractChannel for FakeChannel {
882 fn is_canonical(&self) -> bool {
883 unimplemented!()
884 }
885 fn is_canonical_to_peer(&self) -> bool {
886 unimplemented!()
887 }
888 fn is_usable(&self) -> bool {
889 !self.closing.load(Ordering::SeqCst)
890 }
891 fn duration_unused(&self) -> Option<Duration> {
892 None
893 }
894 fn reparameterize(
895 &self,
896 _updates: Arc<ChannelPaddingInstructionsUpdates>,
897 ) -> tor_proto::Result<()> {
898 match self.mood {
900 'r' => Err(tor_proto::Error::ChanProto(
902 "synthetic reparameterize failure".into(),
903 )),
904 _ => Ok(()),
905 }
906 }
907 fn reparameterize_kist(&self, _kist_params: KistParams) -> tor_proto::Result<()> {
908 Ok(())
909 }
910 fn engage_padding_activities(&self) {}
911 }
912
913 impl HasRelayIds for FakeChannel {
914 fn identity(
915 &self,
916 key_type: tor_linkspec::RelayIdType,
917 ) -> Option<tor_linkspec::RelayIdRef<'_>> {
918 match key_type {
919 tor_linkspec::RelayIdType::Ed25519 => Some((&self.ed_ident).into()),
920 _ => None,
921 }
922 }
923 }
924
925 impl FakeChannel {
926 fn start_closing(&self) {
927 self.closing.store(true, Ordering::SeqCst);
928 }
929 }
930
931 impl<RT: Runtime> FakeChannelFactory<RT> {
932 fn new(runtime: RT, build_attempts: Arc<AtomicUsize>) -> Self {
933 FakeChannelFactory {
934 runtime,
935 build_attempts,
936 }
937 }
938 }
939
940 fn new_test_abstract_chanmgr<R: Runtime>(runtime: R) -> AbstractChanMgr<FakeChannelFactory<R>> {
941 new_test_abstract_chanmgr_and_build_attempts(runtime).0
942 }
943
944 fn new_test_abstract_chanmgr_and_build_attempts<R: Runtime>(
945 runtime: R,
946 ) -> (AbstractChanMgr<FakeChannelFactory<R>>, Arc<AtomicUsize>) {
947 let build_attempts = Arc::new(AtomicUsize::new(0));
948 let cf = FakeChannelFactory::new(runtime, Arc::clone(&build_attempts));
949 let mgr = AbstractChanMgr::new(
950 cf,
951 Default::default(),
952 Default::default(),
953 &Default::default(),
954 BootstrapReporter::fake(),
955 ToplevelAccount::new_noop(),
956 );
957 (mgr, build_attempts)
958 }
959
960 #[derive(Clone, Debug)]
961 struct FakeBuildSpec(u32, char, Ed25519Identity, SocketAddr);
962
963 impl HasRelayIds for FakeBuildSpec {
964 fn identity(
965 &self,
966 key_type: tor_linkspec::RelayIdType,
967 ) -> Option<tor_linkspec::RelayIdRef<'_>> {
968 match key_type {
969 tor_linkspec::RelayIdType::Ed25519 => Some((&self.2).into()),
970 _ => None,
971 }
972 }
973 }
974
975 impl HasChanMethod for FakeBuildSpec {
976 fn chan_method(&self) -> ChannelMethod {
977 ChannelMethod::Direct(vec![self.3.clone()])
978 }
979 }
980
981 fn u32_to_ed(n: u32) -> Ed25519Identity {
983 let mut bytes = [0; 32];
984 bytes[0..4].copy_from_slice(&n.to_be_bytes());
985 bytes.into()
986 }
987
988 fn error_contains(err: &Error, needle: &str) -> bool {
990 let mut source: Option<&(dyn StdError + 'static)> = Some(err);
991 while let Some(err) = source {
992 if err.to_string().contains(needle) || format!("{err:?}").contains(needle) {
993 return true;
994 }
995 source = err.source();
996 }
997 false
998 }
999
1000 #[async_trait]
1001 impl<RT: Runtime> AbstractChannelFactory for FakeChannelFactory<RT> {
1002 type Channel = FakeChannel;
1003 type BuildSpec = FakeBuildSpec;
1004 type Stream = ();
1005
1006 async fn build_channel(
1007 &self,
1008 target: &Self::BuildSpec,
1009 _reporter: BootstrapReporter,
1010 _memquota: ChannelAccount,
1011 ) -> Result<Arc<FakeChannel>> {
1012 self.build_attempts.fetch_add(1, Ordering::SeqCst);
1013 yield_now().await;
1014 let FakeBuildSpec(ident, mood, id, _addr) = *target;
1015 let ed_ident = u32_to_ed(ident);
1016 assert_eq!(ed_ident, id);
1017 match mood {
1018 '❌' | '🔥' => return Err(Error::UnusableTarget(bad_api_usage!("emoji"))),
1020 '💤' => {
1022 self.runtime.sleep(Duration::new(15, 0)).await;
1023 }
1024 _ => {}
1025 }
1026 Ok(Arc::new(FakeChannel {
1027 ed_ident,
1028 mood,
1029 closing: Arc::new(AtomicBool::new(false)),
1030 detect_reuse: Default::default(),
1031 }))
1033 }
1034
1035 #[cfg(feature = "relay")]
1036 async fn build_channel_using_incoming(
1037 &self,
1038 _peer: Sensitive<std::net::SocketAddr>,
1039 _stream: Self::Stream,
1040 _memquota: ChannelAccount,
1041 ) -> Result<Arc<Self::Channel>> {
1042 unimplemented!()
1043 }
1044 }
1045
1046 #[test]
1047 fn connect_one_ok() {
1048 test_with_one_runtime!(|runtime| async {
1049 let mgr = new_test_abstract_chanmgr(runtime);
1050 let target = FakeBuildSpec(413, '!', u32_to_ed(413), ADDR_A);
1051 let chan1 = mgr
1052 .get_or_launch(target.clone(), CU::UserTraffic)
1053 .await
1054 .unwrap()
1055 .0;
1056 let chan2 = mgr.get_or_launch(target, CU::UserTraffic).await.unwrap().0;
1057
1058 assert_eq!(chan1, chan2);
1059 assert_eq!(mgr.get_nowait(&u32_to_ed(413)), vec![chan1]);
1060 });
1061 }
1062
1063 #[test]
1064 fn connect_one_fail() {
1065 test_with_one_runtime!(|runtime| async {
1066 let mgr = new_test_abstract_chanmgr(runtime);
1067
1068 let target = FakeBuildSpec(999, '❌', u32_to_ed(999), ADDR_A);
1070 let res1 = mgr.get_or_launch(target, CU::UserTraffic).await;
1071 assert!(matches!(res1, Err(Error::UnusableTarget(_))));
1072
1073 assert!(mgr.get_nowait(&u32_to_ed(999)).is_empty());
1074 });
1075 }
1076
1077 #[test]
1078 fn connect_different_address() {
1079 test_with_one_runtime!(|runtime| async {
1080 let mgr = new_test_abstract_chanmgr(runtime);
1081
1082 let target1 = FakeBuildSpec(413, '!', u32_to_ed(413), ADDR_A);
1084 let mut target2 = target1.clone();
1085 target2.3 = ADDR_B;
1086
1087 let chan1 = mgr.get_or_launch(target1, CU::UserTraffic).await.unwrap().0;
1088 let chan2 = mgr.get_or_launch(target2, CU::UserTraffic).await.unwrap().0;
1089
1090 assert_eq!(chan1, chan2);
1092 assert_eq!(mgr.get_nowait(&u32_to_ed(413)), vec![chan1]);
1093 });
1094 }
1095
1096 #[test]
1097 fn test_concurrent() {
1098 test_with_one_runtime!(|runtime| async {
1099 let mgr = new_test_abstract_chanmgr(runtime);
1100
1101 let usage = CU::UserTraffic;
1102
1103 let (ch3a, ch3b, ch44a, ch44b, ch50a, ch50b, ch86a, ch86b) = join!(
1107 mgr.get_or_launch(FakeBuildSpec(3, 'a', u32_to_ed(3), ADDR_A), usage),
1108 mgr.get_or_launch(FakeBuildSpec(3, 'b', u32_to_ed(3), ADDR_A), usage),
1109 mgr.get_or_launch(FakeBuildSpec(44, 'a', u32_to_ed(44), ADDR_A), usage),
1110 mgr.get_or_launch(FakeBuildSpec(44, 'b', u32_to_ed(44), ADDR_A), usage),
1111 mgr.get_or_launch(FakeBuildSpec(50, 'a', u32_to_ed(50), ADDR_A), usage),
1112 mgr.get_or_launch(FakeBuildSpec(50, 'b', u32_to_ed(50), ADDR_B), usage),
1113 mgr.get_or_launch(FakeBuildSpec(86, '❌', u32_to_ed(86), ADDR_A), usage),
1114 mgr.get_or_launch(FakeBuildSpec(86, '🔥', u32_to_ed(86), ADDR_A), usage),
1115 );
1116 let ch3a = ch3a.unwrap();
1117 let ch3b = ch3b.unwrap();
1118 let ch44a = ch44a.unwrap();
1119 let ch44b = ch44b.unwrap();
1120 let ch50a = ch50a.unwrap();
1121 let ch50b = ch50b.unwrap();
1122 let err_a = ch86a.unwrap_err();
1123 let err_b = ch86b.unwrap_err();
1124
1125 assert_eq!(ch3a, ch3b);
1126 assert_eq!(ch44a, ch44b);
1127 assert_eq!(ch50a, ch50b);
1128 assert_ne!(ch44a, ch3a);
1129
1130 assert!(matches!(err_a, Error::UnusableTarget(_)));
1131 assert!(matches!(err_b, Error::UnusableTarget(_)));
1132 });
1133 }
1134
1135 #[test]
1136 fn dropped_launch_reports_request_cancelled_to_waiters() {
1137 test_with_one_runtime!(|runtime| async {
1138 let mgr = new_test_abstract_chanmgr(runtime);
1139 let target = FakeBuildSpec(777, '💤', u32_to_ed(777), ADDR_A);
1140 let usage = CU::UserTraffic;
1141
1142 let mut owner1 = Box::pin(mgr.get_or_launch(target.clone(), usage));
1143 assert!(poll!(&mut owner1).is_pending());
1144
1145 let mut waiter = Box::pin(mgr.get_or_launch(target.clone(), usage));
1146 assert!(poll!(&mut waiter).is_pending());
1147
1148 drop(owner1);
1149
1150 let mut owner2 = Box::pin(mgr.get_or_launch(target, usage));
1151 assert!(poll!(&mut owner2).is_pending());
1152
1153 assert!(poll!(&mut waiter).is_pending());
1154
1155 drop(owner2);
1156
1157 let waiter = waiter.await;
1158 assert!(
1159 matches!(&waiter, Err(Error::RequestCancelled)),
1160 "{waiter:?}"
1161 );
1162 if let Err(ref err) = waiter {
1163 assert!(!error_contains(err, "channel build task disappeared"));
1164 }
1165 });
1166 }
1167
1168 #[test]
1169 fn failed_upgrade_reports_original_error_without_owner_retry() {
1170 test_with_one_runtime!(|runtime| async {
1171 let (mgr, build_attempts) = new_test_abstract_chanmgr_and_build_attempts(runtime);
1172 let target = FakeBuildSpec(778, 'r', u32_to_ed(778), ADDR_A);
1173 let usage = CU::UserTraffic;
1174
1175 let mut owner = Box::pin(mgr.get_or_launch(target.clone(), usage));
1176 assert!(poll!(&mut owner).is_pending());
1177
1178 let mut waiter = Box::pin(mgr.get_or_launch(target.clone(), usage));
1179 assert!(poll!(&mut waiter).is_pending());
1180
1181 let owner = owner.await;
1182 assert!(matches!(&owner, Err(Error::Internal(_))), "{owner:?}");
1183 if let Err(ref err) = owner {
1184 assert!(error_contains(err, "failure on new channel"));
1185 assert!(!error_contains(err, "channel build task disappeared"));
1186 }
1187
1188 assert_eq!(build_attempts.load(Ordering::SeqCst), 1);
1189 assert!(mgr.get_nowait(&u32_to_ed(778)).is_empty());
1190
1191 let waiter = waiter.await;
1192 assert!(matches!(&waiter, Err(Error::Internal(_))), "{waiter:?}");
1193 if let Err(ref err) = waiter {
1194 assert!(error_contains(err, "failure on new channel"));
1195 assert!(!error_contains(err, "channel build task disappeared"));
1196 }
1197 });
1198 }
1199
1200 #[test]
1201 fn unusable_entries() {
1202 test_with_one_runtime!(|runtime| async {
1203 let mgr = new_test_abstract_chanmgr(runtime);
1204
1205 let (ch3, ch4, ch5) = join!(
1206 mgr.get_or_launch(FakeBuildSpec(3, 'a', u32_to_ed(3), ADDR_A), CU::UserTraffic),
1207 mgr.get_or_launch(FakeBuildSpec(4, 'a', u32_to_ed(4), ADDR_A), CU::UserTraffic),
1208 mgr.get_or_launch(FakeBuildSpec(5, 'a', u32_to_ed(5), ADDR_A), CU::UserTraffic),
1209 );
1210
1211 let ch3 = ch3.unwrap().0;
1212 let _ch4 = ch4.unwrap();
1213 let ch5 = ch5.unwrap().0;
1214
1215 ch3.start_closing();
1216 ch5.start_closing();
1217
1218 let ch3_new = mgr
1219 .get_or_launch(FakeBuildSpec(3, 'b', u32_to_ed(3), ADDR_A), CU::UserTraffic)
1220 .await
1221 .unwrap()
1222 .0;
1223 assert_ne!(ch3, ch3_new);
1224 assert_eq!(ch3_new.mood, 'b');
1225
1226 mgr.remove_unusable_entries().unwrap();
1227
1228 assert!(!mgr.get_nowait(&u32_to_ed(3)).is_empty());
1229 assert!(!mgr.get_nowait(&u32_to_ed(4)).is_empty());
1230 assert!(mgr.get_nowait(&u32_to_ed(5)).is_empty());
1231 });
1232 }
1233}