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
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46

            
47
// TODO #2010: Remove this global allow, and either propagate it to the functions that need it,
48
// or make those functions less complex.
49
#![allow(clippy::cognitive_complexity)]
50
// TODO #1645 (either remove this, or decide to have it everywhere)
51
#![cfg_attr(
52
    not(all(feature = "full", feature = "experimental")),
53
    allow(unused, unreachable_pub)
54
)]
55

            
56
#[cfg(feature = "bench")]
57
pub mod bench_utils;
58
pub mod channel;
59
pub mod circuit;
60
pub mod client;
61
mod congestion;
62
mod crypto;
63
pub mod memquota;
64
pub(crate) mod tunnel;
65
mod util;
66

            
67
#[cfg(feature = "relay")]
68
pub(crate) mod relay;
69

            
70
pub use util::err::{Error, ResolveError};
71
pub use util::skew::ClockSkew;
72

            
73
pub use channel::params::ChannelPaddingInstructions;
74
pub use client::{ClientTunnel, HopLocation, TargetHop};
75
pub use congestion::params as ccparams;
76
pub use crypto::cell::{HopNum, HopNumDisplay};
77
#[cfg(feature = "send-control-msg")]
78
#[cfg_attr(docsrs, doc(cfg(feature = "send-control-msg")))]
79
pub use {
80
    crate::client::Conversation,
81
    crate::client::msghandler::{MsgHandler, UserMsgHandler},
82
    crate::client::reactor::MetaCellDisposition,
83
};
84

            
85
/// A Result type for this crate.
86
pub type Result<T> = std::result::Result<T, Error>;
87

            
88
use std::fmt::Debug;
89
use tor_memquota::{
90
    HasMemoryCost,
91
    mq_queue::{self, ChannelSpec as _},
92
};
93
use tor_rtcompat::DynTimeProvider;
94

            
95
#[doc(hidden)]
96
pub use {derive_deftly, tor_memquota};
97

            
98
/// Timestamp object that we update whenever we get incoming traffic.
99
///
100
/// Used to implement [`time_since_last_incoming_traffic`]
101
static LAST_INCOMING_TRAFFIC: util::ts::AtomicOptTimestamp = util::ts::AtomicOptTimestamp::new();
102

            
103
/// Called whenever we receive incoming traffic.
104
///
105
/// Used to implement [`time_since_last_incoming_traffic`]
106
#[inline]
107
436
pub(crate) fn note_incoming_traffic() {
108
436
    LAST_INCOMING_TRAFFIC.update();
109
436
}
110

            
111
/// Return the amount of time since we last received "incoming traffic".
112
///
113
/// This is a global counter, and is subject to interference from
114
/// other users of the `tor_proto`.  Its only permissible use is for
115
/// checking how recently we have been definitely able to receive
116
/// incoming traffic.
117
///
118
/// When enabled, this timestamp is updated whenever we receive a valid
119
/// cell, and whenever we complete a channel handshake.
120
///
121
/// Returns `None` if we never received "incoming traffic".
122
585902
pub fn time_since_last_incoming_traffic() -> Option<std::time::Duration> {
123
585902
    LAST_INCOMING_TRAFFIC.time_since_update().map(Into::into)
124
585902
}
125

            
126
/// Make an MPSC queue, of any type, that participates in memquota, but a fake one for testing
127
#[cfg(any(test, feature = "testing"))] // Used by Channel::new_fake which is also feature=testing
128
1364
pub(crate) fn fake_mpsc<T: HasMemoryCost + Debug + Send>(
129
1364
    buffer: usize,
130
1364
) -> (
131
1364
    mq_queue::Sender<T, mq_queue::MpscSpec>,
132
1364
    mq_queue::Receiver<T, mq_queue::MpscSpec>,
133
1364
) {
134
1364
    mq_queue::MpscSpec::new(buffer)
135
1364
        .new_mq(
136
            // The fake Account doesn't care about the data ages, so this will do.
137
            //
138
            // Thiw would be wrong to use generally in tests, where we might want to mock time,
139
            // since we end up, here with totally *different* mocked time.
140
            // But it's OK here, and saves passing a runtime parameter into this function.
141
1364
            DynTimeProvider::new(tor_rtmock::MockRuntime::default()),
142
1364
            &tor_memquota::Account::new_noop(),
143
        )
144
1364
        .expect("create fake mpsc")
145
1364
}
146

            
147
/// Return a list of the protocols [supported](tor_protover::doc_supported)
148
/// by this crate, running as a client.
149
370
pub fn supported_client_protocols() -> tor_protover::Protocols {
150
    use tor_protover::named::*;
151
    // WARNING: REMOVING ELEMENTS FROM THIS LIST CAN BE DANGEROUS!
152
    // SEE [`tor_protover::doc_changing`]
153
370
    let mut protocols = vec![
154
        LINK_V4,
155
        LINK_V5,
156
        LINKAUTH_ED25519_SHA256_EXPORTER,
157
        FLOWCTRL_AUTH_SENDME,
158
        RELAY_NTOR,
159
        RELAY_EXTEND_IPv6,
160
        RELAY_NTORV3,
161
        RELAY_NEGOTIATE_SUBPROTO,
162
    ];
163
    #[cfg(feature = "flowctl-cc")]
164
370
    protocols.push(FLOWCTRL_CC);
165
    #[cfg(feature = "counter-galois-onion")]
166
370
    protocols.push(RELAY_CRYPT_CGO);
167

            
168
370
    protocols.into_iter().collect()
169
370
}
170

            
171
#[cfg(test)]
172
mod test {
173
    // @@ begin test lint list maintained by maint/add_warning @@
174
    #![allow(clippy::bool_assert_comparison)]
175
    #![allow(clippy::clone_on_copy)]
176
    #![allow(clippy::dbg_macro)]
177
    #![allow(clippy::mixed_attributes_style)]
178
    #![allow(clippy::print_stderr)]
179
    #![allow(clippy::print_stdout)]
180
    #![allow(clippy::single_char_pattern)]
181
    #![allow(clippy::unwrap_used)]
182
    #![allow(clippy::unchecked_duration_subtraction)]
183
    #![allow(clippy::useless_vec)]
184
    #![allow(clippy::needless_pass_by_value)]
185
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
186

            
187
    use cfg_if::cfg_if;
188

            
189
    use super::*;
190

            
191
    #[test]
192
    fn protocols() {
193
        let pr = supported_client_protocols();
194
        cfg_if! {
195
            if #[cfg(all(feature="flowctl-cc", feature="counter-galois-onion"))] {
196
                let expected = "FlowCtrl=1-2 Link=4-5 LinkAuth=3 Relay=2-6".parse().unwrap();
197
            } else if #[cfg(feature="flowctl-cc")] {
198
                let expected = "FlowCtrl=1-2 Link=4-5 LinkAuth=3 Relay=2-5".parse().unwrap();
199
                // (Note that we don't have to check for cgo without cc, since that isn't possible.)
200
            } else {
201
                let expected = "FlowCtrl=1 Link=4-5 LinkAuth=3 Relay=2-5".parse().unwrap();
202
            }
203
        }
204
        assert_eq!(pr, expected);
205
    }
206
}