tor_proto/
lib.rs

1#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![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#![warn(clippy::cognitive_complexity)]
15#![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#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_duration_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39#![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43#![allow(clippy::needless_lifetimes)] // See arti#1765
44//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
45
46// TODO #1645 (either remove this, or decide to have it everywhere)
47#![cfg_attr(
48    not(all(feature = "full", feature = "experimental")),
49    allow(unused, unreachable_pub)
50)]
51
52#[cfg(feature = "bench")]
53pub mod bench_utils;
54pub mod channel;
55mod congestion;
56mod crypto;
57pub mod memquota;
58pub mod stream;
59pub(crate) mod tunnel;
60mod util;
61
62pub use util::err::{Error, ResolveError};
63pub use util::skew::ClockSkew;
64
65pub use channel::params::ChannelPaddingInstructions;
66pub use congestion::params as ccparams;
67pub use crypto::cell::{HopNum, HopNumDisplay};
68pub use tunnel::circuit;
69
70/// A Result type for this crate.
71pub type Result<T> = std::result::Result<T, Error>;
72
73use std::fmt::Debug;
74use tor_memquota::{
75    mq_queue::{self, ChannelSpec as _},
76    HasMemoryCost,
77};
78use tor_rtcompat::DynTimeProvider;
79
80#[doc(hidden)]
81pub use {derive_deftly, tor_memquota};
82
83/// Timestamp object that we update whenever we get incoming traffic.
84///
85/// Used to implement [`time_since_last_incoming_traffic`]
86static LAST_INCOMING_TRAFFIC: util::ts::AtomicOptTimestamp = util::ts::AtomicOptTimestamp::new();
87
88/// Called whenever we receive incoming traffic.
89///
90/// Used to implement [`time_since_last_incoming_traffic`]
91#[inline]
92pub(crate) fn note_incoming_traffic() {
93    LAST_INCOMING_TRAFFIC.update();
94}
95
96/// Return the amount of time since we last received "incoming traffic".
97///
98/// This is a global counter, and is subject to interference from
99/// other users of the `tor_proto`.  Its only permissible use is for
100/// checking how recently we have been definitely able to receive
101/// incoming traffic.
102///
103/// When enabled, this timestamp is updated whenever we receive a valid
104/// cell, and whenever we complete a channel handshake.
105///
106/// Returns `None` if we never received "incoming traffic".
107pub fn time_since_last_incoming_traffic() -> Option<std::time::Duration> {
108    LAST_INCOMING_TRAFFIC.time_since_update().map(Into::into)
109}
110
111/// Make an MPSC queue, of any type, that participates in memquota, but a fake one for testing
112#[cfg(any(test, feature = "testing"))] // Used by Channel::new_fake which is also feature=testing
113pub(crate) fn fake_mpsc<T: HasMemoryCost + Debug + Send>(
114    buffer: usize,
115) -> (
116    mq_queue::Sender<T, mq_queue::MpscSpec>,
117    mq_queue::Receiver<T, mq_queue::MpscSpec>,
118) {
119    mq_queue::MpscSpec::new(buffer)
120        .new_mq(
121            // The fake Account doesn't care about the data ages, so this will do.
122            //
123            // Thiw would be wrong to use generally in tests, where we might want to mock time,
124            // since we end up, here with totally *different* mocked time.
125            // But it's OK here, and saves passing a runtime parameter into this function.
126            DynTimeProvider::new(tor_rtmock::MockRuntime::default()),
127            &tor_memquota::Account::new_noop(),
128        )
129        .expect("create fake mpsc")
130}
131
132/// Return a list of the protocols [supported](tor_protover::doc_supported)
133/// by this crate, running as a client.
134pub fn supported_client_protocols() -> tor_protover::Protocols {
135    use tor_protover::named::*;
136    // WARNING: REMOVING ELEMENTS FROM THIS LIST CAN BE DANGEROUS!
137    // SEE [`tor_protover::doc_changing`]
138    [
139        LINK_V4,
140        LINK_V5,
141        LINKAUTH_ED25519_SHA256_EXPORTER,
142        FLOWCTRL_AUTH_SENDME,
143        RELAY_NTOR,
144        RELAY_EXTEND_IPv6,
145        RELAY_NTORV3,
146    ]
147    .into_iter()
148    .collect()
149}
150
151#[cfg(test)]
152mod test {
153    // @@ begin test lint list maintained by maint/add_warning @@
154    #![allow(clippy::bool_assert_comparison)]
155    #![allow(clippy::clone_on_copy)]
156    #![allow(clippy::dbg_macro)]
157    #![allow(clippy::mixed_attributes_style)]
158    #![allow(clippy::print_stderr)]
159    #![allow(clippy::print_stdout)]
160    #![allow(clippy::single_char_pattern)]
161    #![allow(clippy::unwrap_used)]
162    #![allow(clippy::unchecked_duration_subtraction)]
163    #![allow(clippy::useless_vec)]
164    #![allow(clippy::needless_pass_by_value)]
165    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
166
167    use super::*;
168
169    #[test]
170    fn protocols() {
171        let pr = supported_client_protocols();
172        let expected = "FlowCtrl=1 Link=4-5 LinkAuth=3 Relay=2-4".parse().unwrap();
173        assert_eq!(pr, expected);
174    }
175}