1
//! Define an error type for the tor-proto crate.
2
use safelog::Sensitive;
3
use std::{sync::Arc, time::Duration};
4
use thiserror::Error;
5
use tor_cell::relaycell::{StreamId, msg::EndReason};
6
use tor_error::{Bug, ErrorKind, HasKind};
7
use tor_linkspec::RelayIdType;
8

            
9
use crate::HopNum;
10
use crate::client::circuit::PathEntry;
11

            
12
/// An error type for the tor-proto crate.
13
///
14
/// This type should probably be split into several.  There's more
15
/// than one kind of error that can occur while doing something with
16
/// the Tor protocol.
17
#[derive(Error, Debug, Clone)]
18
#[non_exhaustive]
19
pub enum Error {
20
    /// An error that occurred in the tor_bytes crate while decoding an
21
    /// object.
22
    #[error("Unable to parse {object}")]
23
    BytesErr {
24
        /// What we were trying to parse.
25
        object: &'static str,
26
        /// The error that occurred while parsing it.
27
        #[source]
28
        err: tor_bytes::Error,
29
    },
30
    /// An error that occurred from the io system when using a
31
    /// channel.
32
    #[error("IO error on channel with peer")]
33
    ChanIoErr(#[source] Arc<std::io::Error>),
34
    /// An error from the io system that occurred when trying to connect a channel.
35
    #[error("IO error while handshaking with peer")]
36
    HandshakeIoErr(#[source] Arc<std::io::Error>),
37
    /// An error occurred while trying to create or encode a cell.
38
    #[error("Unable to generate or encode {object}")]
39
    CellEncodeErr {
40
        /// The object we were trying to create or encode.
41
        object: &'static str,
42
        /// The error that occurred.
43
        #[source]
44
        err: tor_cell::Error,
45
    },
46
    /// An error occurred while trying to decode or parse a cell.
47
    #[error("Error while parsing {object}")]
48
    CellDecodeErr {
49
        /// The object we were trying to decode.
50
        object: &'static str,
51
        /// The error that occurred.
52
        #[source]
53
        err: tor_cell::Error,
54
    },
55
    /// An error occurred while trying to create or encode some non-cell
56
    /// message.
57
    ///
58
    /// This is likely the result of a bug: either in this crate, or the code
59
    /// that provided the input.
60
    #[error("Problem while encoding {object}")]
61
    EncodeErr {
62
        /// What we were trying to create or encode.
63
        object: &'static str,
64
        /// The error that occurred.
65
        #[source]
66
        err: tor_bytes::EncodeError,
67
    },
68
    /// An error occurred while trying to decode a link specifier.
69
    #[error("Error while parsing {object}")]
70
    #[cfg(feature = "relay")]
71
    LinkspecDecodeErr {
72
        /// The object we were trying to decode.
73
        object: &'static str,
74
        /// The error that occurred.
75
        #[source]
76
        err: tor_linkspec::decode::ChanTargetDecodeError,
77
    },
78
    /// We found a problem with one of the certificates in the channel
79
    /// handshake.
80
    #[error("Problem with certificate on handshake")]
81
    HandshakeCertErr(#[source] tor_cert::CertError),
82
    /// We tried to produce too much output for a key derivation function.
83
    #[error("Tried to extract too many bytes from a KDF")]
84
    InvalidKDFOutputLength,
85
    /// We tried to encrypt a message to a hop that wasn't there.
86
    #[error("Tried to encrypt a cell for a nonexistent hop")]
87
    NoSuchHop,
88
    /// The authentication information on this cell was completely wrong,
89
    /// or the cell was corrupted.
90
    #[error("Bad relay cell authentication")]
91
    BadCellAuth,
92
    /// A circuit-extension handshake failed due to a mismatched authentication
93
    /// value.
94
    #[error("Circuit-extension handshake authentication failed")]
95
    BadCircHandshakeAuth,
96
    /// Handshake protocol violation.
97
    #[error("Handshake protocol violation: {0}")]
98
    HandshakeProto(String),
99
    /// Handshake broken, maybe due to clock skew.
100
    ///
101
    /// (If the problem can't be due to clock skew, we return HandshakeProto
102
    /// instead.)
103
    #[error("Handshake failed due to expired certificates (possible clock skew)")]
104
    HandshakeCertsExpired {
105
        /// For how long has the circuit been expired?
106
        expired_by: Duration,
107
    },
108
    /// Protocol violation at the channel level, other than at the handshake
109
    /// stage.
110
    #[error("Channel protocol violation: {0}")]
111
    ChanProto(String),
112
    /// Protocol violation at the circuit level
113
    #[error("Circuit protocol violation: {0}")]
114
    CircProto(String),
115
    /// Channel is closed, or became closed while we were trying to do some
116
    /// operation.
117
    #[error("Channel closed")]
118
    ChannelClosed(#[from] ChannelClosed),
119
    /// Circuit is closed, or became closed while we were trying to so some
120
    /// operation.
121
    #[error("Circuit closed")]
122
    CircuitClosed,
123
    /// Can't allocate any more circuit or stream IDs on a channel.
124
    #[error("Too many entries in map: can't allocate ID")]
125
    IdRangeFull,
126
    /// Received a stream request with a stream ID that is already in use for another stream.
127
    #[error("Stream ID {0} is already in use")]
128
    IdUnavailable(StreamId),
129
    /// Received a cell with a stream ID of zero.
130
    #[error("Received a cell with a stream ID of zero")]
131
    StreamIdZero,
132
    /// Received a cell on a closed or non-existent stream.
133
    #[error(
134
        "Received a cell from {} on a closed or non-existent stream {}. \
135
         Either they are violating the protocol, or we are expiring streams too aggressively",
136
        src,
137
        streamid
138
    )]
139
    UnknownStream {
140
        /// The hop the cell originated from.
141
        src: Sensitive<PathEntry>,
142
        /// The stream ID of the cell.
143
        streamid: StreamId,
144
    },
145
    /// Couldn't extend a circuit because the extending relay or the
146
    /// target relay refused our request.
147
    #[error("Circuit extension refused: {0}")]
148
    CircRefused(&'static str),
149
    /// Tried to make or use a stream to an invalid destination address.
150
    #[error("Invalid stream target address")]
151
    BadStreamAddress,
152
    /// Received an End cell from the other end of a stream.
153
    #[error("Received an END cell with reason {0}")]
154
    EndReceived(EndReason),
155
    /// Stream was already closed when we tried to use it.
156
    #[error("Stream not connected")]
157
    NotConnected,
158
    /// Stream protocol violation
159
    #[error("Stream protocol violation: {0}")]
160
    StreamProto(String),
161

            
162
    /// Excessive data received from a circuit hop.
163
    #[error("Received too many inbound cells")]
164
    ExcessInboundCells,
165
    /// Tried to send too many cells to a circuit hop.
166
    #[error("Tried to send too many outbound cells")]
167
    ExcessOutboundCells,
168

            
169
    /// Received unexpected or excessive inbound circuit
170
    #[error("Received unexpected or excessive circuit padding from {}", _1.display())]
171
    ExcessPadding(#[source] ExcessPadding, HopNum),
172

            
173
    /// Channel does not match target
174
    #[error("Peer identity mismatch: {0}")]
175
    ChanMismatch(String),
176
    /// There was a programming error somewhere in our code, or the calling code.
177
    #[error("Programming error")]
178
    Bug(#[from] tor_error::Bug),
179
    /// Remote DNS lookup failed.
180
    #[error("Remote resolve failed")]
181
    ResolveError(#[source] ResolveError),
182
    /// We tried to do something with a that we couldn't, because of an identity key type
183
    /// that the relay doesn't have.
184
    #[error("Relay has no {0} identity")]
185
    MissingId(RelayIdType),
186
    /// Memory quota error
187
    #[error("memory quota error")]
188
    Memquota(#[from] tor_memquota::Error),
189
}
190

            
191
/// Error which indicates that the channel was closed.
192
#[derive(Error, Debug, Clone)]
193
#[error("Channel closed")]
194
pub struct ChannelClosed;
195

            
196
impl HasKind for ChannelClosed {
197
2
    fn kind(&self) -> ErrorKind {
198
2
        ErrorKind::CircuitCollapse
199
2
    }
200
}
201

            
202
/// Details about an error received while resolving a domain
203
#[derive(Error, Debug, Clone)]
204
#[non_exhaustive]
205
pub enum ResolveError {
206
    /// A transient error which can be retried
207
    #[error("Received retriable transient error")]
208
    Transient,
209
    /// A non transient error, which shouldn't be retried
210
    #[error("Received non-retriable error")]
211
    Nontransient,
212
    /// Could not parse the response properly
213
    #[error("Received unrecognized result")]
214
    Unrecognized,
215
}
216

            
217
impl Error {
218
    /// Create an error from a tor_cell error that has occurred while trying to
219
    /// encode or create something of type `object`
220
    pub(crate) fn from_cell_enc(err: tor_cell::Error, object: &'static str) -> Error {
221
        Error::CellEncodeErr { object, err }
222
    }
223

            
224
    /// Create an error for a tor_bytes error that occurred while parsing
225
    /// something of type `object`.
226
12
    pub(crate) fn from_bytes_err(err: tor_bytes::Error, object: &'static str) -> Error {
227
12
        Error::BytesErr { err, object }
228
12
    }
229

            
230
    /// Create an error for a tor_bytes error that occurred while encoding
231
    /// something of type `object`.
232
    pub(crate) fn from_bytes_enc(err: tor_bytes::EncodeError, object: &'static str) -> Error {
233
        Error::EncodeErr { err, object }
234
    }
235
}
236

            
237
impl From<std::io::Error> for Error {
238
    fn from(err: std::io::Error) -> Self {
239
        Self::ChanIoErr(Arc::new(err))
240
    }
241
}
242

            
243
impl From<Error> for std::io::Error {
244
    fn from(err: Error) -> std::io::Error {
245
        use Error::*;
246
        use std::io::ErrorKind;
247
        let kind = match err {
248
            ChanIoErr(e) | HandshakeIoErr(e) => match Arc::try_unwrap(e) {
249
                Ok(e) => return e,
250
                Err(arc) => return std::io::Error::new(arc.kind(), arc),
251
            },
252

            
253
            InvalidKDFOutputLength | NoSuchHop | BadStreamAddress => ErrorKind::InvalidInput,
254

            
255
            NotConnected => ErrorKind::NotConnected,
256

            
257
            EndReceived(end_reason) => end_reason.into(),
258

            
259
            CircuitClosed => ErrorKind::ConnectionReset,
260

            
261
            Memquota { .. } => ErrorKind::OutOfMemory,
262

            
263
            BytesErr { .. }
264
            | BadCellAuth
265
            | BadCircHandshakeAuth
266
            | HandshakeProto(_)
267
            | HandshakeCertErr(_)
268
            | ChanProto(_)
269
            | HandshakeCertsExpired { .. }
270
            | ChannelClosed(_)
271
            | CircProto(_)
272
            | CellDecodeErr { .. }
273
            | CellEncodeErr { .. }
274
            | EncodeErr { .. }
275
            | ChanMismatch(_)
276
            | StreamProto(_)
277
            | MissingId(_)
278
            | IdUnavailable(_)
279
            | StreamIdZero
280
            | UnknownStream { .. }
281
            | ExcessInboundCells
282
            | ExcessOutboundCells
283
            | ExcessPadding(_, _) => ErrorKind::InvalidData,
284

            
285
            #[cfg(feature = "relay")]
286
            LinkspecDecodeErr { .. } => ErrorKind::InvalidData,
287

            
288
            Bug(ref e) if e.kind() == tor_error::ErrorKind::BadApiUsage => ErrorKind::InvalidData,
289

            
290
            IdRangeFull | CircRefused(_) | ResolveError(_) | Bug(_) => ErrorKind::Other,
291
        };
292
        std::io::Error::new(kind, err)
293
    }
294
}
295

            
296
impl HasKind for Error {
297
248
    fn kind(&self) -> ErrorKind {
298
        use Error as E;
299
        use ErrorKind as EK;
300
        use tor_bytes::Error as BytesError;
301
12
        match self {
302
            E::BytesErr {
303
                err: BytesError::Bug(e),
304
                ..
305
            } => e.kind(),
306
12
            E::BytesErr { .. } => EK::TorProtocolViolation,
307
            E::ChanIoErr(_) => EK::LocalNetworkError,
308
            E::HandshakeIoErr(_) => EK::TorAccessFailed,
309
            E::HandshakeCertErr(_) => EK::TorProtocolViolation,
310
            E::CellEncodeErr { err, .. } => err.kind(),
311
150
            E::CellDecodeErr { err, .. } => err.kind(),
312
            #[cfg(feature = "relay")]
313
            E::LinkspecDecodeErr { .. } => EK::TorProtocolViolation,
314
            E::EncodeErr { .. } => EK::BadApiUsage,
315
            E::InvalidKDFOutputLength => EK::Internal,
316
            E::NoSuchHop => EK::BadApiUsage,
317
            E::BadCellAuth => EK::TorProtocolViolation,
318
12
            E::BadCircHandshakeAuth => EK::TorProtocolViolation,
319
            E::HandshakeProto(_) => EK::TorAccessFailed,
320
            E::HandshakeCertsExpired { .. } => EK::ClockSkew,
321
12
            E::ChanProto(_) => EK::TorProtocolViolation,
322
56
            E::CircProto(_) => EK::TorProtocolViolation,
323
2
            E::ChannelClosed(e) => e.kind(),
324
            E::CircuitClosed => EK::CircuitCollapse,
325
            E::IdRangeFull => EK::BadApiUsage,
326
            E::CircRefused(_) => EK::CircuitRefused,
327
            E::BadStreamAddress => EK::BadApiUsage,
328
            E::EndReceived(reason) => reason.kind(),
329
            E::NotConnected => EK::BadApiUsage,
330
            E::StreamProto(_) => EK::TorProtocolViolation,
331
            E::ChanMismatch(_) => EK::RelayIdMismatch,
332
            E::ResolveError(ResolveError::Nontransient) => EK::RemoteHostNotFound,
333
            E::ResolveError(ResolveError::Transient) => EK::RemoteHostResolutionFailed,
334
            E::ResolveError(ResolveError::Unrecognized) => EK::RemoteHostResolutionFailed,
335
            E::MissingId(_) => EK::BadApiUsage,
336
            E::IdUnavailable(_) => EK::BadApiUsage,
337
            E::StreamIdZero => EK::BadApiUsage,
338
4
            E::UnknownStream { .. } => EK::TorProtocolViolation,
339
            E::ExcessInboundCells => EK::TorProtocolViolation,
340
            E::ExcessOutboundCells => EK::Internal,
341
            E::ExcessPadding(_, _) => EK::TorProtocolViolation,
342
            E::Memquota(err) => err.kind(),
343
            E::Bug(e) => e.kind(),
344
        }
345
248
    }
346
}
347

            
348
/// Internal type: Error return value from reactor's run_once
349
/// function: indicates an error or a shutdown.
350
#[derive(Debug)]
351
pub(crate) enum ReactorError {
352
    /// The reactor should shut down with an abnormal exit condition.
353
    Err(Error),
354
    /// The reactor should shut down without an error, since all is well.
355
    Shutdown,
356
}
357

            
358
impl From<Error> for ReactorError {
359
320
    fn from(e: Error) -> ReactorError {
360
320
        ReactorError::Err(e)
361
320
    }
362
}
363

            
364
impl From<ChannelClosed> for ReactorError {
365
    fn from(e: ChannelClosed) -> ReactorError {
366
        ReactorError::Err(e.into())
367
    }
368
}
369

            
370
impl From<Bug> for ReactorError {
371
    fn from(e: Bug) -> ReactorError {
372
        ReactorError::Err(e.into())
373
    }
374
}
375

            
376
#[cfg(test)]
377
impl ReactorError {
378
    /// Tests only: assert that this is an Error, and return it.
379
72
    pub(crate) fn unwrap_err(self) -> Error {
380
72
        match self {
381
            ReactorError::Shutdown => panic!(),
382
72
            ReactorError::Err(e) => e,
383
        }
384
72
    }
385
}
386

            
387
/// An error type for client-side conflux handshakes.
388
#[derive(Debug)]
389
#[cfg(feature = "conflux")]
390
#[allow(unused)] // TODO(conflux): remove
391
pub(crate) enum ConfluxHandshakeError {
392
    /// Timeout while waiting for CONFLUX_LINKED response.
393
    Timeout,
394
    /// An error that occurred while sending the CONFLUX_LINK message.
395
    Link(Error),
396
    /// The channel was closed.
397
    ChannelClosed,
398
}
399

            
400
/// An error returned when we receive excessive or unexpected padding.
401
#[derive(Debug, Clone, Error)]
402
#[non_exhaustive]
403
pub enum ExcessPadding {
404
    /// We received circuit padding when we hadn't negotiated a padding framework.
405
    #[error("Padding received when not negotiated with given hop")]
406
    NoPaddingNegotiated,
407
    /// We received more padding than our negotiated framework permits.
408
    #[error("Received padding in excess of negotiated framework's limit")]
409
    PaddingExceedsLimit,
410
}