1
//! Define an error type for the tor-cell crate.
2
use thiserror::Error;
3
use tor_error::{ErrorKind, HasKind};
4

            
5
/// An error type for the tor-cell crate.
6
///
7
/// This type should probably be split into several.  There's more
8
/// than one kind of error that can occur while doing something with
9
/// tor cells.
10
92
#[derive(Error, Debug, Clone)]
11
#[non_exhaustive]
12
pub enum Error {
13
    /// An error that occurred in the tor_bytes crate while decoding an
14
    /// object.
15
    #[error("Error while parsing {parsed}")]
16
    BytesErr {
17
        /// The error that occurred.
18
        #[source]
19
        err: tor_bytes::Error,
20
        /// The thing that was being parsed.
21
        parsed: &'static str,
22
    },
23
    /// We encountered an error while encoding an outgoing message.
24
    ///
25
    /// This is likely to be a bug in somebody's code: either the code in this
26
    /// crate, or in the calling code that provided an unencodable message.
27
    #[error("Error while encoding message")]
28
    EncodeErr(#[from] tor_bytes::EncodeError),
29
    /// There was a programming error somewhere in the code.
30
    #[error("Internal programming error")]
31
    Internal(tor_error::Bug),
32
    /// Protocol violation at the channel level
33
    #[error("Channel protocol violation: {0}")]
34
    ChanProto(String),
35
    /// Protocol violation at the circuit level
36
    #[error("Circuit protocol violation: {0}")]
37
    CircProto(String),
38
    /// Tried to make or use a stream to an invalid destination address.
39
    #[error("Invalid stream target address")]
40
    BadStreamAddress,
41
    /// Tried to construct a message that Tor can't represent.
42
    #[error("Message can't be represented in a Tor cell: {0}")]
43
    CantEncode(&'static str),
44
}
45

            
46
impl HasKind for Error {
47
    fn kind(&self) -> ErrorKind {
48
        use tor_bytes::Error as ByE;
49
        use Error as E;
50
        use ErrorKind as EK;
51
        match self {
52
            E::BytesErr {
53
                err: ByE::Truncated,
54
                ..
55
            } => EK::Internal,
56
            E::EncodeErr(..) => EK::BadApiUsage,
57
            E::BytesErr { .. } => EK::TorProtocolViolation,
58
            E::Internal(_) => EK::Internal,
59
            E::ChanProto(_) => EK::TorProtocolViolation,
60
            E::CircProto(_) => EK::TorProtocolViolation,
61
            E::BadStreamAddress => EK::BadApiUsage,
62
            E::CantEncode(_) => EK::Internal,
63
        }
64
    }
65
}