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 #1645 (either remove this, or decide to have it everywhere)
50
#![cfg_attr(not(all(feature = "full")), allow(unused))]
51

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

            
62
use std::{io, sync::Arc};
63

            
64
pub use connpt::{ParsedConnectPoint, ResolveError, ResolvedConnectPoint};
65
use tor_general_addr::general;
66

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

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

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

            
171
            E::BadType(_) => A::Abort,
172

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

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

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

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

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

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

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

            
327
    use super::*;
328

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