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