Skip to main content

tor_dirclient/
err.rs

1//! Declare dirclient-specific errors.
2
3use std::sync::Arc;
4
5use thiserror::Error;
6use tor_error::{Bug, ErrorKind, HasKind};
7use tor_linkspec::OwnedChanTarget;
8use tor_rtcompat::TimeoutError;
9
10use crate::SourceInfo;
11
12/// An error originating from the tor-dirclient crate.
13#[derive(Error, Debug, Clone)]
14#[non_exhaustive]
15#[allow(clippy::large_enum_variant)] // TODO(nickm) worth fixing as we do #587
16pub enum Error {
17    /// Error while getting a circuit
18    #[error("Error while getting a circuit")]
19    CircMgr(#[from] tor_circmgr::Error),
20
21    /// An error that has occurred after we have contacted a directory cache and made a circuit to it.
22    #[error("Error fetching directory information")]
23    RequestFailed(#[from] RequestFailedError),
24
25    /// We ran into a problem that is probably due to a programming issue.
26    #[error("Internal error")]
27    Bug(#[from] Bug),
28}
29
30/// An error that has occurred after we have contacted a directory cache and made a circuit to it.
31///
32/// Generally, all errors of these kinds imply that the interfacing application
33/// may retry the request, either at a different time or at a different endpoint
34/// and potentially even both.
35#[derive(Error, Debug, Clone)]
36#[allow(clippy::exhaustive_structs)] // TODO should not be exhaustive
37#[error("Request failed from {}: {error}", FromSource(.source))]
38pub struct RequestFailedError {
39    /// The source that gave us this error.
40    pub source: Option<SourceInfo>,
41
42    /// The underlying error that occurred.
43    #[source]
44    pub error: RequestError,
45}
46
47/// Helper type to display an optional source of directory information.
48struct FromSource<'a>(&'a Option<SourceInfo>);
49
50impl std::fmt::Display for FromSource<'_> {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        if let Some(si) = self.0 {
53            write!(f, "{}", si)
54        } else {
55            write!(f, "N/A")
56        }
57    }
58}
59
60/// An error originating from the tor-dirclient crate.
61///
62/// See [`RequestFailedError`] for notes on retrying failed requests.
63#[derive(Error, Debug, Clone)]
64#[non_exhaustive]
65pub enum RequestError {
66    /// The directory cache took too long to reply to us.
67    #[error("directory timed out")]
68    DirTimeout,
69
70    /// We got an EOF before we were done with the headers.
71    #[error("truncated HTTP headers")]
72    TruncatedHeaders,
73
74    /// Received a response that was longer than we expected.
75    #[error("response too long; gave up after {0} bytes")]
76    ResponseTooLong(usize),
77
78    /// Received too many bytes in our headers.
79    #[error("headers too long; gave up after {0} bytes")]
80    HeadersTooLong(usize),
81
82    /// Data received was not UTF-8 encoded.
83    #[error("Couldn't decode data as UTF-8.")]
84    Utf8Encoding(#[from] std::string::FromUtf8Error),
85
86    /// Io error while reading on connection
87    #[error("IO error")]
88    IoError(#[source] Arc<std::io::Error>),
89
90    /// A protocol error while launching a stream
91    #[error("Protocol error while launching a stream")]
92    Proto(#[from] tor_proto::Error),
93
94    /// A protocol error while launching a stream
95    #[error("Tunnel error")]
96    Tunnel(#[from] tor_circmgr::Error),
97
98    /// Error when parsing http
99    #[error("Couldn't parse HTTP headers")]
100    HttparseError(#[from] httparse::Error),
101
102    /// Error while creating http request
103    //
104    // TODO this should be abolished, in favour of a `Bug` variant,
105    // so that we get a stack trace, as per the notes for EK::Internal.
106    // We could convert via into_internal!, or a custom `From` impl.
107    #[error("Couldn't create HTTP request")]
108    HttpError(#[source] Arc<http::Error>),
109
110    /// Unrecognized content-encoding
111    #[error("Unrecognized content encoding: {0:?}")]
112    ContentEncoding(String),
113
114    /// Too much clock skew between us and the directory.
115    ///
116    /// (We've giving up on this request early, since any directory that it
117    /// believes in, we would reject as untimely.)
118    #[error("Too much clock skew with directory cache")]
119    TooMuchClockSkew,
120
121    /// We tried to launch a request without any requested objects.
122    ///
123    /// This can happen if (for example) we request an empty list of
124    /// microdescriptors or certificates.
125    #[error("We didn't have any objects to request")]
126    EmptyRequest,
127
128    /// HTTP status code indicates a not completely successful request
129    #[error("HTTP status code {0}: {1:?}")]
130    HttpStatus(u16, String),
131}
132
133impl From<TimeoutError> for RequestError {
134    fn from(_: TimeoutError) -> Self {
135        RequestError::DirTimeout
136    }
137}
138
139impl From<std::io::Error> for RequestError {
140    fn from(err: std::io::Error) -> Self {
141        Self::IoError(Arc::new(err))
142    }
143}
144
145impl From<http::Error> for RequestError {
146    fn from(err: http::Error) -> Self {
147        Self::HttpError(Arc::new(err))
148    }
149}
150
151impl Error {
152    /// Return true if this error means that the circuit shouldn't be used
153    /// for any more directory requests.
154    pub fn should_retire_circ(&self) -> bool {
155        // TODO: probably this is too aggressive, and we should
156        // actually _not_ dump the circuit under all circumstances.
157        match self {
158            Error::CircMgr(_) => true, // should be unreachable.
159            Error::RequestFailed(RequestFailedError { error, .. }) => error.should_retire_circ(),
160            Error::Bug(_) => true,
161        }
162    }
163
164    /// Return the peer or peers that are to be blamed for the error.
165    ///
166    /// (This can return multiple peers if the request failed because multiple
167    /// circuit attempts all failed.)
168    pub fn cache_ids(&self) -> Vec<&OwnedChanTarget> {
169        match &self {
170            Error::CircMgr(e) => e.peers(),
171            Error::RequestFailed(RequestFailedError {
172                source: Some(source),
173                ..
174            }) => vec![source.cache_id()],
175            _ => Vec::new(),
176        }
177    }
178}
179
180impl RequestError {
181    /// Return true if this error means that the circuit shouldn't be used
182    /// for any more directory requests.
183    pub fn should_retire_circ(&self) -> bool {
184        // TODO: probably this is too aggressive, and we should
185        // actually _not_ dump the circuit under all circumstances.
186        true
187    }
188}
189
190impl HasKind for RequestError {
191    fn kind(&self) -> ErrorKind {
192        use ErrorKind as EK;
193        use RequestError as E;
194        match self {
195            E::DirTimeout => EK::TorNetworkTimeout,
196            E::TruncatedHeaders => EK::TorProtocolViolation,
197            E::ResponseTooLong(_) => EK::TorProtocolViolation,
198            E::HeadersTooLong(_) => EK::TorProtocolViolation,
199            E::Utf8Encoding(_) => EK::TorProtocolViolation,
200            // TODO: it would be good to get more information out of the IoError
201            // in this case, but that would require a bunch of gnarly
202            // downcasting.
203            E::IoError(_) => EK::TorDirectoryError,
204            E::Proto(e) => e.kind(),
205            E::HttparseError(_) => EK::TorProtocolViolation,
206            E::HttpError(_) => EK::Internal,
207            E::ContentEncoding(_) => EK::TorProtocolViolation,
208            E::TooMuchClockSkew => EK::TorDirectoryError,
209            E::EmptyRequest => EK::Internal,
210            E::HttpStatus(_, _) => EK::TorDirectoryError,
211            E::Tunnel(e) => e.kind(),
212        }
213    }
214}
215
216impl HasKind for RequestFailedError {
217    fn kind(&self) -> ErrorKind {
218        self.error.kind()
219    }
220}
221
222impl HasKind for Error {
223    fn kind(&self) -> ErrorKind {
224        use Error as E;
225        match self {
226            E::CircMgr(e) => e.kind(),
227            E::RequestFailed(e) => e.kind(),
228            E::Bug(e) => e.kind(),
229        }
230    }
231}
232
233#[cfg(any(feature = "hs-client", feature = "hs-service"))]
234impl Error {
235    /// Return true if this error is one that we should report as a suspicious event,
236    /// along with the dirserver and description of the relevant document,
237    /// if the request was made anonymously.
238    pub fn should_report_as_suspicious_if_anon(&self) -> bool {
239        use Error as E;
240        match self {
241            E::CircMgr(_) => false,
242            E::RequestFailed(e) => e.error.should_report_as_suspicious_if_anon(),
243            E::Bug(_) => false,
244        }
245    }
246}
247#[cfg(any(feature = "hs-client", feature = "hs-service"))]
248impl RequestError {
249    /// Return true if this error is one that we should report as a suspicious event,
250    /// along with the dirserver and description of the relevant document,
251    /// if the request was made anonymously.
252    pub fn should_report_as_suspicious_if_anon(&self) -> bool {
253        use tor_proto::Error as PE;
254        match self {
255            RequestError::ResponseTooLong(_) => true,
256            RequestError::HeadersTooLong(_) => true,
257            RequestError::Proto(PE::ExcessInboundCells) => true,
258            RequestError::Proto(_) => false,
259            RequestError::DirTimeout => false,
260            RequestError::TruncatedHeaders => false,
261            RequestError::Utf8Encoding(_) => false,
262            RequestError::IoError(_) => false,
263            RequestError::HttparseError(_) => false,
264            RequestError::HttpError(_) => false,
265            RequestError::ContentEncoding(_) => false,
266            RequestError::TooMuchClockSkew => false,
267            RequestError::EmptyRequest => false,
268            RequestError::HttpStatus(_, _) => false,
269            RequestError::Tunnel(_) => false,
270        }
271    }
272}