tor_proto/util/
err.rs

1//! Define an error type for the tor-proto crate.
2use std::{sync::Arc, time::Duration};
3use thiserror::Error;
4use tor_cell::relaycell::{msg::EndReason, StreamId};
5use tor_error::{Bug, ErrorKind, HasKind};
6use tor_linkspec::RelayIdType;
7
8/// An error type for the tor-proto crate.
9///
10/// This type should probably be split into several.  There's more
11/// than one kind of error that can occur while doing something with
12/// the Tor protocol.
13#[derive(Error, Debug, Clone)]
14#[non_exhaustive]
15pub enum Error {
16    /// An error that occurred in the tor_bytes crate while decoding an
17    /// object.
18    #[error("Unable to parse {object}")]
19    BytesErr {
20        /// What we were trying to parse.
21        object: &'static str,
22        /// The error that occurred while parsing it.
23        #[source]
24        err: tor_bytes::Error,
25    },
26    /// An error that occurred from the io system when using a
27    /// channel.
28    #[error("IO error on channel with peer")]
29    ChanIoErr(#[source] Arc<std::io::Error>),
30    /// An error from the io system that occurred when trying to connect a channel.
31    #[error("IO error while handshaking with peer")]
32    HandshakeIoErr(#[source] Arc<std::io::Error>),
33    /// An error occurred while trying to create or encode a cell.
34    #[error("Unable to generate or encode {object}")]
35    CellEncodeErr {
36        /// The object we were trying to create or encode.
37        object: &'static str,
38        /// The error that occurred.
39        #[source]
40        err: tor_cell::Error,
41    },
42    /// An error occurred while trying to decode or parse a cell.
43    #[error("Error while parsing {object}")]
44    CellDecodeErr {
45        /// The object we were trying to decode.
46        object: &'static str,
47        /// The error that occurred.
48        #[source]
49        err: tor_cell::Error,
50    },
51    /// An error occurred while trying to create or encode some non-cell
52    /// message.
53    ///
54    /// This is likely the result of a bug: either in this crate, or the code
55    /// that provided the input.
56    #[error("Problem while encoding {object}")]
57    EncodeErr {
58        /// What we were trying to create or encode.
59        object: &'static str,
60        /// The error that occurred.
61        #[source]
62        err: tor_bytes::EncodeError,
63    },
64    /// We found a problem with one of the certificates in the channel
65    /// handshake.
66    #[error("Problem with certificate on handshake")]
67    HandshakeCertErr(#[source] tor_cert::CertError),
68    /// We tried to produce too much output for a key derivation function.
69    #[error("Tried to extract too many bytes from a KDF")]
70    InvalidKDFOutputLength,
71    /// We tried to encrypt a message to a hop that wasn't there.
72    #[error("Tried to encrypt a cell for a nonexistent hop")]
73    NoSuchHop,
74    /// The authentication information on this cell was completely wrong,
75    /// or the cell was corrupted.
76    #[error("Bad relay cell authentication")]
77    BadCellAuth,
78    /// A circuit-extension handshake failed due to a mismatched authentication
79    /// value.
80    #[error("Circuit-extension handshake authentication failed")]
81    BadCircHandshakeAuth,
82    /// Handshake protocol violation.
83    #[error("Handshake protocol violation: {0}")]
84    HandshakeProto(String),
85    /// Handshake broken, maybe due to clock skew.
86    ///
87    /// (If the problem can't be due to clock skew, we return HandshakeProto
88    /// instead.)
89    #[error("Handshake failed due to expired certificates (possible clock skew)")]
90    HandshakeCertsExpired {
91        /// For how long has the circuit been expired?
92        expired_by: Duration,
93    },
94    /// Protocol violation at the channel level, other than at the handshake
95    /// stage.
96    #[error("Channel protocol violation: {0}")]
97    ChanProto(String),
98    /// Protocol violation at the circuit level
99    #[error("Circuit protocol violation: {0}")]
100    CircProto(String),
101    /// Channel is closed, or became closed while we were trying to do some
102    /// operation.
103    #[error("Channel closed")]
104    ChannelClosed(#[from] ChannelClosed),
105    /// Circuit is closed, or became closed while we were trying to so some
106    /// operation.
107    #[error("Circuit closed")]
108    CircuitClosed,
109    /// Can't allocate any more circuit or stream IDs on a channel.
110    #[error("Too many entries in map: can't allocate ID")]
111    IdRangeFull,
112    /// Received a stream request with a stream ID that is already in use for another stream.
113    #[error("Stream ID {0} is already in use")]
114    IdUnavailable(StreamId),
115    /// Received a cell with a stream ID of zero.
116    #[error("Received a cell with a stream ID of zero")]
117    StreamIdZero,
118    /// Couldn't extend a circuit because the extending relay or the
119    /// target relay refused our request.
120    #[error("Circuit extension refused: {0}")]
121    CircRefused(&'static str),
122    /// Tried to make or use a stream to an invalid destination address.
123    #[error("Invalid stream target address")]
124    BadStreamAddress,
125    /// Received an End cell from the other end of a stream.
126    #[error("Received an END cell with reason {0}")]
127    EndReceived(EndReason),
128    /// Stream was already closed when we tried to use it.
129    #[error("Stream not connected")]
130    NotConnected,
131    /// Stream protocol violation
132    #[error("Stream protocol violation: {0}")]
133    StreamProto(String),
134
135    /// Channel does not match target
136    #[error("Peer identity mismatch: {0}")]
137    ChanMismatch(String),
138    /// There was a programming error somewhere in our code, or the calling code.
139    #[error("Programming error")]
140    Bug(#[from] tor_error::Bug),
141    /// Remote DNS lookup failed.
142    #[error("Remote resolve failed")]
143    ResolveError(#[source] ResolveError),
144    /// We tried to do something with a that we couldn't, because of an identity key type
145    /// that the relay doesn't have.
146    #[error("Relay has no {0} identity")]
147    MissingId(RelayIdType),
148    /// Memory quota error
149    #[error("memory quota error")]
150    Memquota(#[from] tor_memquota::Error),
151}
152
153/// Error which indicates that the channel was closed.
154#[derive(Error, Debug, Clone)]
155#[error("Channel closed")]
156pub struct ChannelClosed;
157
158impl HasKind for ChannelClosed {
159    fn kind(&self) -> ErrorKind {
160        ErrorKind::CircuitCollapse
161    }
162}
163
164/// Details about an error received while resolving a domain
165#[derive(Error, Debug, Clone)]
166#[non_exhaustive]
167pub enum ResolveError {
168    /// A transient error which can be retried
169    #[error("Received retriable transient error")]
170    Transient,
171    /// A non transient error, which shouldn't be retried
172    #[error("Received non-retriable error")]
173    Nontransient,
174    /// Could not parse the response properly
175    #[error("Received unrecognized result")]
176    Unrecognized,
177}
178
179impl Error {
180    /// Create an error from a tor_cell error that has occurred while trying to
181    /// encode or create something of type `object`
182    pub(crate) fn from_cell_enc(err: tor_cell::Error, object: &'static str) -> Error {
183        Error::CellEncodeErr { object, err }
184    }
185
186    /// Create an error from a tor_cell error that has occurred while trying to
187    /// decode something of type `object`
188    pub(crate) fn from_cell_dec(err: tor_cell::Error, object: &'static str) -> Error {
189        match err {
190            tor_cell::Error::ChanProto(msg) => Error::ChanProto(msg),
191            _ => Error::CellDecodeErr { err, object },
192        }
193    }
194
195    /// Create an error for a tor_bytes error that occurred while parsing
196    /// something of type `object`.
197    pub(crate) fn from_bytes_err(err: tor_bytes::Error, object: &'static str) -> Error {
198        Error::BytesErr { err, object }
199    }
200
201    /// Create an error for a tor_bytes error that occurred while encoding
202    /// something of type `object`.
203    pub(crate) fn from_bytes_enc(err: tor_bytes::EncodeError, object: &'static str) -> Error {
204        Error::EncodeErr { err, object }
205    }
206}
207
208impl From<Error> for std::io::Error {
209    fn from(err: Error) -> std::io::Error {
210        use std::io::ErrorKind;
211        use Error::*;
212        let kind = match err {
213            ChanIoErr(e) | HandshakeIoErr(e) => match Arc::try_unwrap(e) {
214                Ok(e) => return e,
215                Err(arc) => return std::io::Error::new(arc.kind(), arc),
216            },
217
218            InvalidKDFOutputLength | NoSuchHop | BadStreamAddress => ErrorKind::InvalidInput,
219
220            NotConnected => ErrorKind::NotConnected,
221
222            EndReceived(end_reason) => end_reason.into(),
223
224            CircuitClosed => ErrorKind::ConnectionReset,
225
226            Memquota { .. } => ErrorKind::OutOfMemory,
227
228            BytesErr { .. }
229            | BadCellAuth
230            | BadCircHandshakeAuth
231            | HandshakeProto(_)
232            | HandshakeCertErr(_)
233            | ChanProto(_)
234            | HandshakeCertsExpired { .. }
235            | ChannelClosed(_)
236            | CircProto(_)
237            | CellDecodeErr { .. }
238            | CellEncodeErr { .. }
239            | EncodeErr { .. }
240            | ChanMismatch(_)
241            | StreamProto(_)
242            | MissingId(_)
243            | IdUnavailable(_)
244            | StreamIdZero => ErrorKind::InvalidData,
245
246            Bug(ref e) if e.kind() == tor_error::ErrorKind::BadApiUsage => ErrorKind::InvalidData,
247
248            IdRangeFull | CircRefused(_) | ResolveError(_) | Bug(_) => ErrorKind::Other,
249        };
250        std::io::Error::new(kind, err)
251    }
252}
253
254impl HasKind for Error {
255    fn kind(&self) -> ErrorKind {
256        use tor_bytes::Error as BytesError;
257        use Error as E;
258        use ErrorKind as EK;
259        match self {
260            E::BytesErr {
261                err: BytesError::Bug(e),
262                ..
263            } => e.kind(),
264            E::BytesErr { .. } => EK::TorProtocolViolation,
265            E::ChanIoErr(_) => EK::LocalNetworkError,
266            E::HandshakeIoErr(_) => EK::TorAccessFailed,
267            E::HandshakeCertErr(_) => EK::TorProtocolViolation,
268            E::CellEncodeErr { err, .. } => err.kind(),
269            E::CellDecodeErr { err, .. } => err.kind(),
270            E::EncodeErr { .. } => EK::BadApiUsage,
271            E::InvalidKDFOutputLength => EK::Internal,
272            E::NoSuchHop => EK::BadApiUsage,
273            E::BadCellAuth => EK::TorProtocolViolation,
274            E::BadCircHandshakeAuth => EK::TorProtocolViolation,
275            E::HandshakeProto(_) => EK::TorAccessFailed,
276            E::HandshakeCertsExpired { .. } => EK::ClockSkew,
277            E::ChanProto(_) => EK::TorProtocolViolation,
278            E::CircProto(_) => EK::TorProtocolViolation,
279            E::ChannelClosed(e) => e.kind(),
280            E::CircuitClosed => EK::CircuitCollapse,
281            E::IdRangeFull => EK::BadApiUsage,
282            E::CircRefused(_) => EK::CircuitRefused,
283            E::BadStreamAddress => EK::BadApiUsage,
284            E::EndReceived(reason) => reason.kind(),
285            E::NotConnected => EK::BadApiUsage,
286            E::StreamProto(_) => EK::TorProtocolViolation,
287            E::ChanMismatch(_) => EK::RelayIdMismatch,
288            E::ResolveError(ResolveError::Nontransient) => EK::RemoteHostNotFound,
289            E::ResolveError(ResolveError::Transient) => EK::RemoteHostResolutionFailed,
290            E::ResolveError(ResolveError::Unrecognized) => EK::RemoteHostResolutionFailed,
291            E::MissingId(_) => EK::BadApiUsage,
292            E::IdUnavailable(_) => EK::BadApiUsage,
293            E::StreamIdZero => EK::BadApiUsage,
294            E::Memquota(err) => err.kind(),
295            E::Bug(e) => e.kind(),
296        }
297    }
298}
299
300/// Internal type: Error return value from reactor's run_once
301/// function: indicates an error or a shutdown.
302#[derive(Debug)]
303pub(crate) enum ReactorError {
304    /// The reactor should shut down with an abnormal exit condition.
305    Err(Error),
306    /// The reactor should shut down without an error, since all is well.
307    Shutdown,
308}
309
310impl From<Error> for ReactorError {
311    fn from(e: Error) -> ReactorError {
312        ReactorError::Err(e)
313    }
314}
315
316impl From<ChannelClosed> for ReactorError {
317    fn from(e: ChannelClosed) -> ReactorError {
318        ReactorError::Err(e.into())
319    }
320}
321
322impl From<Bug> for ReactorError {
323    fn from(e: Bug) -> ReactorError {
324        ReactorError::Err(e.into())
325    }
326}
327
328#[cfg(test)]
329impl ReactorError {
330    /// Tests only: assert that this is an Error, and return it.
331    pub(crate) fn unwrap_err(self) -> Error {
332        match self {
333            ReactorError::Shutdown => panic!(),
334            ReactorError::Err(e) => e,
335        }
336    }
337}
338
339/// An error type for client-side conflux handshakes.
340#[derive(Debug)]
341#[cfg(feature = "conflux")]
342#[allow(unused)] // TODO(conflux): remove
343pub(crate) enum ConfluxHandshakeError {
344    /// Timeout while waiting for CONFLUX_LINKED response.
345    Timeout,
346    /// An error that occurred while sending the CONFLUX_LINK message.
347    Link(Error),
348    /// The channel was closed.
349    ChannelClosed,
350}