Skip to main content

tor_proto/
lib.rs

1#![cfg_attr(docsrs, feature(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_time_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#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45#![allow(clippy::collapsible_if)] // See arti#2342
46#![deny(clippy::unused_async)]
47//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
48
49// TODO #2010: Remove this global allow, and either propagate it to the functions that need it,
50// or make those functions less complex.
51#![allow(clippy::cognitive_complexity)]
52// TODO #1645 (either remove this, or decide to have it everywhere)
53#![cfg_attr(
54    not(all(feature = "full", feature = "experimental")),
55    allow(unused, unreachable_pub)
56)]
57
58#[cfg(feature = "bench")]
59pub mod bench_utils;
60pub mod channel;
61pub mod circuit;
62pub mod client;
63pub(crate) mod conflux;
64mod congestion;
65mod crypto;
66pub mod memquota;
67pub mod peer;
68mod stream;
69pub(crate) mod streammap;
70pub(crate) mod tunnel;
71mod util;
72
73#[cfg(feature = "relay")]
74pub mod relay;
75#[cfg(feature = "relay")]
76pub use relay::channel::{RelayChannelBuilder, RelayIdentities};
77
78pub use util::err::{Error, ResolveError};
79pub use util::skew::ClockSkew;
80
81pub use channel::params::ChannelPaddingInstructions;
82pub use client::{ClientTunnel, HopLocation, TargetHop, channel::ClientChannelBuilder};
83pub use congestion::params as ccparams;
84pub use crypto::cell::{HopNum, HopNumDisplay};
85pub use stream::flow_ctrl::params::{CellCount, FlowCtrlParameters};
86#[cfg(feature = "send-control-msg")]
87pub use {
88    crate::client::Conversation,
89    crate::client::msghandler::{MsgHandler, UserMsgHandler},
90    crate::client::reactor::MetaCellDisposition,
91};
92
93/// A Result type for this crate.
94pub type Result<T> = std::result::Result<T, Error>;
95
96use std::fmt::Debug;
97use tor_memquota::{
98    HasMemoryCost,
99    mq_queue::{self, ChannelSpec as _},
100};
101use tor_rtcompat::DynTimeProvider;
102
103#[doc(hidden)]
104pub use {derive_deftly, tor_memquota};
105
106/// Timestamp object that we update whenever we get incoming traffic.
107///
108/// Used to implement [`time_since_last_incoming_traffic`]
109static LAST_INCOMING_TRAFFIC: util::ts::AtomicOptTimestamp = util::ts::AtomicOptTimestamp::new();
110
111/// Called whenever we receive incoming traffic.
112///
113/// Used to implement [`time_since_last_incoming_traffic`]
114#[inline]
115pub(crate) fn note_incoming_traffic() {
116    LAST_INCOMING_TRAFFIC.update();
117}
118
119/// Return the amount of time since we last received "incoming traffic".
120///
121/// This is a global counter, and is subject to interference from
122/// other users of the `tor_proto`.  Its only permissible use is for
123/// checking how recently we have been definitely able to receive
124/// incoming traffic.
125///
126/// When enabled, this timestamp is updated whenever we receive a valid
127/// cell, and whenever we complete a channel handshake.
128///
129/// Returns `None` if we never received "incoming traffic".
130pub fn time_since_last_incoming_traffic() -> Option<std::time::Duration> {
131    LAST_INCOMING_TRAFFIC.time_since_update().map(Into::into)
132}
133
134/// Make an MPSC queue, of any type, that participates in memquota, but a fake one for testing
135#[cfg(any(test, feature = "testing"))] // Used by Channel::new_fake which is also feature=testing
136pub(crate) fn fake_mpsc<T: HasMemoryCost + Debug + Send>(
137    buffer: usize,
138) -> (
139    mq_queue::Sender<T, mq_queue::MpscSpec>,
140    mq_queue::Receiver<T, mq_queue::MpscSpec>,
141) {
142    mq_queue::MpscSpec::new(buffer)
143        .new_mq(
144            // The fake Account doesn't care about the data ages, so this will do.
145            //
146            // Thiw would be wrong to use generally in tests, where we might want to mock time,
147            // since we end up, here with totally *different* mocked time.
148            // But it's OK here, and saves passing a runtime parameter into this function.
149            DynTimeProvider::new(tor_rtmock::MockRuntime::default()),
150            &tor_memquota::Account::new_noop(),
151        )
152        .expect("create fake mpsc")
153}
154
155/// Return a list of the protocols [supported](tor_protover::doc_supported)
156/// by this crate, running as a client.
157pub fn supported_client_protocols() -> tor_protover::Protocols {
158    use tor_protover::named::*;
159    // WARNING: REMOVING ELEMENTS FROM THIS LIST CAN BE DANGEROUS!
160    // SEE [`tor_protover::doc_changing`]
161    let mut protocols = vec![
162        LINK_V4,
163        LINK_V5,
164        LINKAUTH_ED25519_SHA256_EXPORTER,
165        FLOWCTRL_AUTH_SENDME,
166        RELAY_NTOR,
167        RELAY_EXTEND_IPv6,
168        RELAY_NTORV3,
169        RELAY_NEGOTIATE_SUBPROTO,
170    ];
171    #[cfg(feature = "flowctl-cc")]
172    protocols.push(FLOWCTRL_CC);
173    #[cfg(feature = "counter-galois-onion")]
174    protocols.push(RELAY_CRYPT_CGO);
175
176    protocols.into_iter().collect()
177}
178
179#[cfg(test)]
180mod test {
181    // @@ begin test lint list maintained by maint/add_warning @@
182    #![allow(clippy::bool_assert_comparison)]
183    #![allow(clippy::clone_on_copy)]
184    #![allow(clippy::dbg_macro)]
185    #![allow(clippy::mixed_attributes_style)]
186    #![allow(clippy::print_stderr)]
187    #![allow(clippy::print_stdout)]
188    #![allow(clippy::single_char_pattern)]
189    #![allow(clippy::unwrap_used)]
190    #![allow(clippy::unchecked_time_subtraction)]
191    #![allow(clippy::useless_vec)]
192    #![allow(clippy::needless_pass_by_value)]
193    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
194
195    use cfg_if::cfg_if;
196
197    use super::*;
198
199    #[test]
200    fn protocols() {
201        let pr = supported_client_protocols();
202        cfg_if! {
203            if #[cfg(all(feature="flowctl-cc", feature="counter-galois-onion"))] {
204                let expected = "FlowCtrl=1-2 Link=4-5 LinkAuth=3 Relay=2-6".parse().unwrap();
205            } else if #[cfg(feature="flowctl-cc")] {
206                let expected = "FlowCtrl=1-2 Link=4-5 LinkAuth=3 Relay=2-5".parse().unwrap();
207                // (Note that we don't have to check for cgo without cc, since that isn't possible.)
208            } else {
209                let expected = "FlowCtrl=1 Link=4-5 LinkAuth=3 Relay=2-5".parse().unwrap();
210            }
211        }
212        assert_eq!(pr, expected);
213    }
214}