1
//! Declare dirclient-specific errors.
2

            
3
use std::sync::Arc;
4

            
5
use thiserror::Error;
6
use tor_error::{Bug, ErrorKind, HasKind};
7
use tor_linkspec::OwnedChanTarget;
8
use tor_rtcompat::TimeoutError;
9

            
10
use 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
16
pub 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
#[derive(Error, Debug, Clone)]
32
#[allow(clippy::exhaustive_structs)] // TODO should not be exhaustive
33
#[error("Request failed{}", FromSource(.source))]
34
pub struct RequestFailedError {
35
    /// The source that gave us this error.
36
    pub source: Option<SourceInfo>,
37

            
38
    /// The underlying error that occurred.
39
    #[source]
40
    pub error: RequestError,
41
}
42

            
43
/// Helper type to display an optional source of directory information.
44
struct FromSource<'a>(&'a Option<SourceInfo>);
45

            
46
impl std::fmt::Display for FromSource<'_> {
47
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48
        if let Some(si) = self.0 {
49
            write!(f, " from {}", si)
50
        } else {
51
            Ok(())
52
        }
53
    }
54
}
55

            
56
/// An error originating from the tor-dirclient crate.
57
#[derive(Error, Debug, Clone)]
58
#[non_exhaustive]
59
pub enum RequestError {
60
    /// The directory cache took too long to reply to us.
61
    #[error("directory timed out")]
62
    DirTimeout,
63

            
64
    /// We got an EOF before we were done with the headers.
65
    #[error("truncated HTTP headers")]
66
    TruncatedHeaders,
67

            
68
    /// Received a response that was longer than we expected.
69
    #[error("response too long; gave up after {0} bytes")]
70
    ResponseTooLong(usize),
71

            
72
    /// Data received was not UTF-8 encoded.
73
    #[error("Couldn't decode data as UTF-8.")]
74
    Utf8Encoding(#[from] std::string::FromUtf8Error),
75

            
76
    /// Io error while reading on connection
77
    #[error("IO error")]
78
    IoError(#[source] Arc<std::io::Error>),
79

            
80
    /// A protocol error while launching a stream
81
    #[error("Protocol error while launching a stream")]
82
    Proto(#[from] tor_proto::Error),
83

            
84
    /// Error when parsing http
85
    #[error("Couldn't parse HTTP headers")]
86
    HttparseError(#[from] httparse::Error),
87

            
88
    /// Error while creating http request
89
    //
90
    // TODO this should be abolished, in favour of a `Bug` variant,
91
    // so that we get a stack trace, as per the notes for EK::Internal.
92
    // We could convert via into_internal!, or a custom `From` impl.
93
    #[error("Couldn't create HTTP request")]
94
    HttpError(#[source] Arc<http::Error>),
95

            
96
    /// Unrecognized content-encoding
97
    #[error("Unrecognized content encoding: {0:?}")]
98
    ContentEncoding(String),
99

            
100
    /// Too much clock skew between us and the directory.
101
    ///
102
    /// (We've giving up on this request early, since any directory that it
103
    /// believes in, we would reject as untimely.)
104
    #[error("Too much clock skew with directory cache")]
105
    TooMuchClockSkew,
106

            
107
    /// We tried to launch a request without any requested objects.
108
    ///
109
    /// This can happen if (for example) we request an empty list of
110
    /// microdescriptors or certificates.
111
    #[error("We didn't have any objects to request")]
112
    EmptyRequest,
113

            
114
    /// HTTP status code indicates a not completely successful request
115
    #[error("HTTP status code {0}: {1:?}")]
116
    HttpStatus(u16, String),
117
}
118

            
119
impl From<TimeoutError> for RequestError {
120
    fn from(_: TimeoutError) -> Self {
121
        RequestError::DirTimeout
122
    }
123
}
124

            
125
impl From<std::io::Error> for RequestError {
126
534
    fn from(err: std::io::Error) -> Self {
127
534
        Self::IoError(Arc::new(err))
128
534
    }
129
}
130

            
131
impl From<http::Error> for RequestError {
132
    fn from(err: http::Error) -> Self {
133
        Self::HttpError(Arc::new(err))
134
    }
135
}
136

            
137
impl Error {
138
    /// Return true if this error means that the circuit shouldn't be used
139
    /// for any more directory requests.
140
2
    pub fn should_retire_circ(&self) -> bool {
141
2
        // TODO: probably this is too aggressive, and we should
142
2
        // actually _not_ dump the circuit under all circumstances.
143
2
        match self {
144
            Error::CircMgr(_) => true, // should be unreachable.
145
2
            Error::RequestFailed(RequestFailedError { error, .. }) => error.should_retire_circ(),
146
            Error::Bug(_) => true,
147
        }
148
2
    }
149

            
150
    /// Return the peer or peers that are to be blamed for the error.
151
    ///
152
    /// (This can return multiple peers if the request failed because multiple
153
    /// circuit attempts all failed.)
154
    pub fn cache_ids(&self) -> Vec<&OwnedChanTarget> {
155
        match &self {
156
            Error::CircMgr(e) => e.peers(),
157
            Error::RequestFailed(RequestFailedError {
158
                source: Some(source),
159
                ..
160
            }) => vec![source.cache_id()],
161
            _ => Vec::new(),
162
        }
163
    }
164
}
165

            
166
impl RequestError {
167
    /// Return true if this error means that the circuit shouldn't be used
168
    /// for any more directory requests.
169
2
    pub fn should_retire_circ(&self) -> bool {
170
2
        // TODO: probably this is too aggressive, and we should
171
2
        // actually _not_ dump the circuit under all circumstances.
172
2
        true
173
2
    }
174
}
175

            
176
impl HasKind for RequestError {
177
    fn kind(&self) -> ErrorKind {
178
        use ErrorKind as EK;
179
        use RequestError as E;
180
        match self {
181
            E::DirTimeout => EK::TorNetworkTimeout,
182
            E::TruncatedHeaders => EK::TorProtocolViolation,
183
            E::ResponseTooLong(_) => EK::TorProtocolViolation,
184
            E::Utf8Encoding(_) => EK::TorProtocolViolation,
185
            // TODO: it would be good to get more information out of the IoError
186
            // in this case, but that would require a bunch of gnarly
187
            // downcasting.
188
            E::IoError(_) => EK::TorDirectoryError,
189
            E::Proto(e) => e.kind(),
190
            E::HttparseError(_) => EK::TorProtocolViolation,
191
            E::HttpError(_) => EK::Internal,
192
            E::ContentEncoding(_) => EK::TorProtocolViolation,
193
            E::TooMuchClockSkew => EK::TorDirectoryError,
194
            E::EmptyRequest => EK::Internal,
195
            E::HttpStatus(_, _) => EK::TorDirectoryError,
196
        }
197
    }
198
}
199

            
200
impl HasKind for RequestFailedError {
201
    fn kind(&self) -> ErrorKind {
202
        self.error.kind()
203
    }
204
}
205

            
206
impl HasKind for Error {
207
    fn kind(&self) -> ErrorKind {
208
        use Error as E;
209
        match self {
210
            E::CircMgr(e) => e.kind(),
211
            E::RequestFailed(e) => e.kind(),
212
            E::Bug(e) => e.kind(),
213
        }
214
    }
215
}