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
#![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
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
// TODO #1645 (either remove this, or decide to have it everywhere)
52
#![cfg_attr(not(all(feature = "full")), allow(unused))]
53

            
54
pub mod auth;
55
#[cfg(feature = "rpc-client")]
56
pub mod client;
57
mod connpt;
58
pub mod load;
59
#[cfg(feature = "rpc-server")]
60
pub mod server;
61
#[cfg(test)]
62
mod testing;
63

            
64
use std::{io, sync::Arc};
65

            
66
pub use connpt::{ParsedConnectPoint, ResolveError, ResolvedConnectPoint};
67
use tor_general_addr::general;
68

            
69
/// An action that an RPC client should take when a connect point fails.
70
///
71
/// (This terminology is taken from the spec.)
72
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
73
#[allow(clippy::exhaustive_enums)]
74
pub enum ClientErrorAction {
75
    /// The client must stop, and must not make any more connect attempts.
76
    Abort,
77
    /// The connect point has failed; the client can continue to the next connect point.
78
    Decline,
79
}
80
/// An error that has a [`ClientErrorAction`].
81
pub trait HasClientErrorAction {
82
    /// Return the action that an RPC client should take based on this error.
83
    fn client_action(&self) -> ClientErrorAction;
84
}
85
impl HasClientErrorAction for tor_config_path::CfgPathError {
86
    fn client_action(&self) -> ClientErrorAction {
87
        // Every variant of this means a configuration error
88
        // or an ill-formed TOML file.
89
        ClientErrorAction::Abort
90
    }
91
}
92
impl HasClientErrorAction for tor_config_path::addr::CfgAddrError {
93
    fn client_action(&self) -> ClientErrorAction {
94
        use ClientErrorAction as A;
95
        use tor_config_path::addr::CfgAddrError as CAE;
96
        match self {
97
            CAE::NoAfUnixSocketSupport(_) => A::Decline,
98
            CAE::Path(cfg_path_error) => cfg_path_error.client_action(),
99
            CAE::ConstructAfUnixAddress(_) => A::Abort,
100
            // No variants are currently captured in this pattern, but they _could_ be in the future.
101
            _ => A::Abort,
102
        }
103
    }
104
}
105
impl HasClientErrorAction for tor_general_addr::general::AddrParseError {
106
    fn client_action(&self) -> ClientErrorAction {
107
        use ClientErrorAction as A;
108
        use tor_general_addr::general::AddrParseError as E;
109
        match self {
110
            E::UnrecognizedSchema(_) => A::Decline,
111
            E::NoSchema => A::Decline,
112
            E::InvalidAfUnixAddress(_) => A::Abort,
113
            // We might want to turn this into an Abort in the future, but I think that we might
114
            // want to allow "auto" as a port format in CfgAddr.
115
            E::InvalidInetAddress(_) => A::Decline,
116
            // No variants are currently captured in this pattern, but they _could_ be in the future.
117
            _ => A::Abort,
118
        }
119
    }
120
}
121

            
122
/// Return the ClientErrorAction for an IO error encountered
123
/// while accessing the filesystem.
124
///
125
/// Note that this is not an implementation of `HasClientErrorAction`:
126
/// We want to decline on a different set of errors for network operation.
127
fn fs_error_action(err: &std::io::Error) -> ClientErrorAction {
128
    use ClientErrorAction as A;
129
    use std::io::ErrorKind as EK;
130
    match err.kind() {
131
        EK::NotFound => A::Decline,
132
        EK::PermissionDenied => A::Decline,
133
        EK::ReadOnlyFilesystem => A::Decline,
134
        _ => A::Abort,
135
    }
136
}
137
/// Return the ClientErrorAction for an IO error encountered
138
/// while opening a socket.
139
///
140
/// Note that this is not an implementation of `HasClientErrorAction`:
141
/// We want to decline on a different set of errors for fs operation.
142
fn net_error_action(err: &std::io::Error) -> ClientErrorAction {
143
    use ClientErrorAction as A;
144
    use std::io::ErrorKind as EK;
145
    match err.kind() {
146
        EK::ConnectionRefused => A::Decline,
147
        EK::ConnectionReset => A::Decline,
148
        EK::HostUnreachable => A::Decline,
149
        EK::NetworkDown => A::Decline,
150
        EK::NetworkUnreachable => A::Decline,
151
        _ => A::Abort,
152
    }
153
}
154
impl HasClientErrorAction for fs_mistrust::Error {
155
    fn client_action(&self) -> ClientErrorAction {
156
        use ClientErrorAction as A;
157
        use fs_mistrust::Error as E;
158
        match self {
159
            E::Multiple(errs) => {
160
                if errs.iter().any(|e| e.client_action() == A::Abort) {
161
                    A::Abort
162
                } else {
163
                    A::Decline
164
                }
165
            }
166
            E::Io { err, .. } => fs_error_action(err),
167
            E::CouldNotInspect(_, err) => fs_error_action(err),
168

            
169
            E::NotFound(_) => A::Decline,
170
            E::BadPermission(_, _, _) | E::BadOwner(_, _) => A::Decline,
171
            E::StepsExceeded | E::CurrentDirectory(_) => A::Abort,
172

            
173
            E::BadType(_) => A::Abort,
174

            
175
            // These should be impossible for clients given how we use fs_mistrust in this crate.
176
            E::CreatingDir(_)
177
            | E::Content(_)
178
            | E::NoSuchGroup(_)
179
            | E::NoSuchUser(_)
180
            | E::MissingField(_)
181
            | E::InvalidSubdirectory => A::Abort,
182
            E::PasswdGroupIoError(_) => A::Abort,
183
            _ => A::Abort,
184
        }
185
    }
186
}
187

            
188
/// A failure to connect or bind to a [`ResolvedConnectPoint`].
189
#[derive(Clone, Debug, thiserror::Error)]
190
#[non_exhaustive]
191
pub enum ConnectError {
192
    /// We encountered an IO error while actually opening our socket.
193
    #[error("IO error while connecting")]
194
    Io(#[source] Arc<io::Error>),
195
    /// The connect point told us to abort explicitly.
196
    #[error("Encountered an explicit \"abort\"")]
197
    ExplicitAbort,
198
    /// We couldn't load the cookie file for cookie authentication.
199
    #[error("Unable to load cookie file")]
200
    LoadCookie(#[from] auth::cookie::CookieAccessError),
201
    /// We were told to connect to a socket type that we don't support.
202
    #[error("Unsupported socket type")]
203
    UnsupportedSocketType,
204
    /// We were told to connect using an auth type that we don't support.
205
    #[error("Unsupported authentication type")]
206
    UnsupportedAuthType,
207
    /// Unable to access the location of an AF\_UNIX socket.
208
    #[error("Unix domain socket path access")]
209
    AfUnixSocketPathAccess(#[from] fs_mistrust::Error),
210
    /// Unable to access the location of `socket_address_file`.
211
    #[error("Problem accessing socket address file")]
212
    SocketAddressFileAccess(#[source] fs_mistrust::Error),
213
    /// We couldn't parse the JSON contents of a socket address file.
214
    #[error("Invalid JSON contents in socket address file")]
215
    SocketAddressFileJson(#[source] Arc<serde_json::Error>),
216
    /// We couldn't parse the address in a socket address file.
217
    #[error("Invalid address in socket address file")]
218
    SocketAddressFileContent(#[source] general::AddrParseError),
219
    /// We found an address in the socket address file that didn't match the connect point.
220
    #[error("Socket address file contents didn't match connect point")]
221
    SocketAddressFileMismatch,
222
    /// Another process was holding a lock for this connect point,
223
    /// so we couldn't bind to it.
224
    #[error("Could not acquire lock: Another process is listening on this connect point")]
225
    AlreadyLocked,
226
    /// We encountered an internal logic error.
227
    //
228
    // (We're not using tor_error::Bug here because we want this code to work properly in rpc-client-core.)
229
    #[error("Internal error: {0}")]
230
    Internal(String),
231
}
232

            
233
impl From<io::Error> for ConnectError {
234
    fn from(err: io::Error) -> Self {
235
        ConnectError::Io(Arc::new(err))
236
    }
237
}
238
impl crate::HasClientErrorAction for ConnectError {
239
    fn client_action(&self) -> crate::ClientErrorAction {
240
        use crate::ClientErrorAction as A;
241
        use ConnectError as E;
242
        match self {
243
            E::Io(err) => crate::net_error_action(err),
244
            E::ExplicitAbort => A::Abort,
245
            E::LoadCookie(err) => err.client_action(),
246
            E::UnsupportedSocketType => A::Decline,
247
            E::UnsupportedAuthType => A::Decline,
248
            E::AfUnixSocketPathAccess(err) => err.client_action(),
249
            E::SocketAddressFileAccess(err) => err.client_action(),
250
            E::SocketAddressFileJson(_) => A::Decline,
251
            E::SocketAddressFileContent(_) => A::Decline,
252
            E::SocketAddressFileMismatch => A::Decline,
253
            E::AlreadyLocked => A::Abort, // (This one can't actually occur for clients.)
254
            E::Internal(_) => A::Abort,
255
        }
256
    }
257
}
258
#[cfg(any(feature = "rpc-client", feature = "rpc-server"))]
259
/// Given a `general::SocketAddr`, try to return the path of its parent directory (if any).
260
fn socket_parent_path(addr: &tor_general_addr::general::SocketAddr) -> Option<&std::path::Path> {
261
    addr.as_pathname().and_then(|p| p.parent())
262
}
263

            
264
/// Default connect point for a user-owned Arti instance.
265
pub const USER_DEFAULT_CONNECT_POINT: &str = {
266
    cfg_if::cfg_if! {
267
        if #[cfg(unix)] {
268
r#"
269
[connect]
270
socket = "unix:${ARTI_LOCAL_DATA}/rpc/arti_rpc_socket"
271
auth = "none"
272
"#
273
        } else {
274
r#"
275
[connect]
276
socket = "inet:127.0.0.1:9180"
277
auth = { cookie = { path = "${ARTI_LOCAL_DATA}/rpc/arti_rpc_cookie" } }
278
"#
279
        }
280
    }
281
};
282

            
283
/// Default connect point for a system-wide Arti instance.
284
///
285
/// This is `None` if, on this platform, there is no such default connect point.
286
pub const SYSTEM_DEFAULT_CONNECT_POINT: Option<&str> = {
287
    cfg_if::cfg_if! {
288
        if #[cfg(unix)] {
289
            Some(
290
r#"
291
[connect]
292
socket = "unix:/var/run/arti-rpc/arti_rpc_socket"
293
auth = "none"
294
"#
295
            )
296
        } else {
297
            None
298
        }
299
    }
300
};
301

            
302
/// An enum to reflect whether an authenticated connection to a connect point is allowed to acquire
303
/// superuser (admin) capabilities.
304
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
305
#[non_exhaustive]
306
pub enum SuperuserPermission {
307
    /// The connection may acquire superuser capabilities.
308
    Allowed,
309
    /// The connection may not acquire superuser capabilities.
310
    NotAllowed,
311
}
312

            
313
#[cfg(test)]
314
mod test {
315
    // @@ begin test lint list maintained by maint/add_warning @@
316
    #![allow(clippy::bool_assert_comparison)]
317
    #![allow(clippy::clone_on_copy)]
318
    #![allow(clippy::dbg_macro)]
319
    #![allow(clippy::mixed_attributes_style)]
320
    #![allow(clippy::print_stderr)]
321
    #![allow(clippy::print_stdout)]
322
    #![allow(clippy::single_char_pattern)]
323
    #![allow(clippy::unwrap_used)]
324
    #![allow(clippy::unchecked_time_subtraction)]
325
    #![allow(clippy::useless_vec)]
326
    #![allow(clippy::needless_pass_by_value)]
327
    #![allow(clippy::string_slice)] // See arti#2571
328
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
329

            
330
    use super::*;
331

            
332
    #[test]
333
    fn parse_defaults() {
334
        let _parsed: ParsedConnectPoint = USER_DEFAULT_CONNECT_POINT.parse().unwrap();
335
        if let Some(s) = SYSTEM_DEFAULT_CONNECT_POINT {
336
            let _parsed: ParsedConnectPoint = s.parse().unwrap();
337
        }
338
    }
339
}