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//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
4546// TODO #1645 (either remove this, or decide to have it everywhere)
47#![cfg_attr(not(all(feature = "full")), allow(unused))]
4849pub mod auth;
50#[cfg(feature = "rpc-client")]
51pub mod client;
52mod connpt;
53pub mod load;
54#[cfg(feature = "rpc-server")]
55pub mod server;
56#[cfg(test)]
57mod testing;
5859use std::{io, sync::Arc};
6061pub use connpt::{ParsedConnectPoint, ResolveError, ResolvedConnectPoint};
6263/// An action that an RPC client should take when a connect point fails.
64///
65/// (This terminology is taken from the spec.)
66#[derive(Clone, Copy, Debug, Eq, PartialEq)]
67#[allow(clippy::exhaustive_enums)]
68pub enum ClientErrorAction {
69/// The client must stop, and must not make any more connect attempts.
70Abort,
71/// The connect point has failed; the client can continue to the next connect point.
72Decline,
73}
74/// An error that has a [`ClientErrorAction`].
75pub trait HasClientErrorAction {
76/// Return the action that an RPC client should take based on this error.
77fn client_action(&self) -> ClientErrorAction;
78}
79impl HasClientErrorAction for tor_config_path::CfgPathError {
80fn client_action(&self) -> ClientErrorAction {
81// Every variant of this means a configuration error
82 // or an ill-formed TOML file.
83ClientErrorAction::Abort
84 }
85}
86impl HasClientErrorAction for tor_config_path::addr::CfgAddrError {
87fn client_action(&self) -> ClientErrorAction {
88use tor_config_path::addr::CfgAddrError as CAE;
89use ClientErrorAction as A;
90match self {
91 CAE::NoAfUnixSocketSupport(_) => A::Decline,
92 CAE::Path(cfg_path_error) => cfg_path_error.client_action(),
93 CAE::ConstructAfUnixAddress(_) => A::Abort,
94// No variants are currently captured in this pattern, but they _could_ be in the future.
95_ => A::Abort,
96 }
97 }
98}
99/// Return the ClientErrorAction for an IO error encountered
100/// while accessing the filesystem.
101///
102/// Note that this is not an implementation of `HasClientErrorAction`:
103/// We want to decline on a different set of errors for network operation.
104fn fs_error_action(err: &std::io::Error) -> ClientErrorAction {
105use std::io::ErrorKind as EK;
106use ClientErrorAction as A;
107match err.kind() {
108 EK::NotFound => A::Decline,
109 EK::PermissionDenied => A::Decline,
110_ => A::Abort,
111 }
112}
113/// Return the ClientErrorAction for an IO error encountered
114/// while opening a socket.
115///
116/// Note that this is not an implementation of `HasClientErrorAction`:
117/// We want to decline on a different set of errors for fs operation.
118fn net_error_action(err: &std::io::Error) -> ClientErrorAction {
119use std::io::ErrorKind as EK;
120use ClientErrorAction as A;
121match err.kind() {
122 EK::ConnectionRefused => A::Decline,
123 EK::ConnectionReset => A::Decline,
124// TODO MSRV 1.83; revisit once some of `io_error_more` is stabilized.
125 // see https://github.com/rust-lang/rust/pull/128316
126_ => A::Abort,
127 }
128}
129impl HasClientErrorAction for fs_mistrust::Error {
130fn client_action(&self) -> ClientErrorAction {
131use fs_mistrust::Error as E;
132use ClientErrorAction as A;
133match self {
134 E::Multiple(errs) => {
135if errs.iter().any(|e| e.client_action() == A::Abort) {
136 A::Abort
137 } else {
138 A::Decline
139 }
140 }
141 E::Io { err, .. } => fs_error_action(err),
142 E::CouldNotInspect(_, err) => fs_error_action(err),
143144 E::NotFound(_) => A::Decline,
145 E::BadPermission(_, _, _) | E::BadOwner(_, _) => A::Decline,
146 E::StepsExceeded | E::CurrentDirectory(_) => A::Abort,
147148 E::BadType(_) => A::Abort,
149150// These should be impossible for clients given how we use fs_mistrust in this crate.
151E::CreatingDir(_)
152 | E::Content(_)
153 | E::NoSuchGroup(_)
154 | E::NoSuchUser(_)
155 | E::MissingField(_)
156 | E::InvalidSubdirectory => A::Abort,
157 E::PasswdGroupIoError(_) => A::Abort,
158_ => A::Abort,
159 }
160 }
161}
162163/// A failure to connect or bind to a [`ResolvedConnectPoint`].
164#[derive(Clone, Debug, thiserror::Error)]
165#[non_exhaustive]
166pub enum ConnectError {
167/// We encountered an IO error while actually opening our socket.
168#[error("IO error while connecting")]
169Io(#[source] Arc<io::Error>),
170/// The connect point told us to abort explicitly.
171#[error("Encountered an explicit \"abort\"")]
172ExplicitAbort,
173/// We couldn't load the cookie file for cookie authentication.
174#[error("Unable to load cookie file")]
175LoadCookie(#[from] auth::cookie::CookieAccessError),
176/// We were told to connect to a socket type that we don't support.
177#[error("Unsupported socket type")]
178UnsupportedSocketType,
179/// We were told to connect using an auth type that we don't support.
180#[error("Unsupported authentication type")]
181UnsupportedAuthType,
182/// Unable to access the location of an AF\_UNIX socket.
183#[error("Unix domain socket path access")]
184AfUnixSocketPathAccess(#[from] fs_mistrust::Error),
185/// Another process was holding a lock for this connect point,
186 /// so we couldn't bind to it.
187#[error("Could not acquire lock: Another process is listening on this connect point")]
188AlreadyLocked,
189}
190191impl From<io::Error> for ConnectError {
192fn from(err: io::Error) -> Self {
193 ConnectError::Io(Arc::new(err))
194 }
195}
196impl crate::HasClientErrorAction for ConnectError {
197fn client_action(&self) -> crate::ClientErrorAction {
198use crate::ClientErrorAction as A;
199use ConnectError as E;
200match self {
201 E::Io(err) => crate::net_error_action(err),
202 E::ExplicitAbort => A::Abort,
203 E::LoadCookie(err) => err.client_action(),
204 E::UnsupportedSocketType => A::Decline,
205 E::UnsupportedAuthType => A::Decline,
206 E::AfUnixSocketPathAccess(err) => err.client_action(),
207 E::AlreadyLocked => A::Abort, // (This one can't actually occur for clients.)
208}
209 }
210}
211#[cfg(any(feature = "rpc-client", feature = "rpc-server"))]
212/// Given a `general::SocketAddr`, try to return the path of its parent directory (if any).
213fn socket_parent_path(addr: &tor_general_addr::general::SocketAddr) -> Option<&std::path::Path> {
214 addr.as_pathname().and_then(|p| p.parent())
215}
216217/// Default connect point for a user-owned Arti instance.
218pub const USER_DEFAULT_CONNECT_POINT: &str = {
219cfg_if::cfg_if! {
220if #[cfg(unix)] {
221r#"
222[connect]
223socket = "unix:${ARTI_LOCAL_DATA}/rpc/arti_rpc_socket"
224auth = "none"
225"#
226} else {
227r#"
228[connect]
229socket = "inet:127.0.0.1:9180"
230auth = { cookie = { path = "${ARTI_LOCAL_DATA}/rpc/arti_rpc_cookie" } }
231"#
232}
233 }
234};
235236/// Default connect point for a system-wide Arti instance.
237///
238/// This is `None` if, on this platform, there is no such default connect point.
239pub const SYSTEM_DEFAULT_CONNECT_POINT: Option<&str> = {
240cfg_if::cfg_if! {
241if #[cfg(unix)] {
242Some(
243r#"
244[connect]
245socket = "unix:/var/run/arti-rpc/arti_rpc_socket"
246auth = "none"
247"#
248)
249 } else {
250None
251}
252 }
253};
254255#[cfg(test)]
256mod test {
257// @@ begin test lint list maintained by maint/add_warning @@
258#![allow(clippy::bool_assert_comparison)]
259 #![allow(clippy::clone_on_copy)]
260 #![allow(clippy::dbg_macro)]
261 #![allow(clippy::mixed_attributes_style)]
262 #![allow(clippy::print_stderr)]
263 #![allow(clippy::print_stdout)]
264 #![allow(clippy::single_char_pattern)]
265 #![allow(clippy::unwrap_used)]
266 #![allow(clippy::unchecked_duration_subtraction)]
267 #![allow(clippy::useless_vec)]
268 #![allow(clippy::needless_pass_by_value)]
269//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
270271use super::*;
272273#[test]
274fn parse_defaults() {
275let _parsed: ParsedConnectPoint = USER_DEFAULT_CONNECT_POINT.parse().unwrap();
276if let Some(s) = SYSTEM_DEFAULT_CONNECT_POINT {
277let _parsed: ParsedConnectPoint = s.parse().unwrap();
278 }
279 }
280}