1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use std::error;
use std::ffi::NulError;
use std::fmt;
use std::io;
use std::num::TryFromIntError;
use std::result;
use std::str::Utf8Error;

use milter_sys as sys;

/// A result type specialised for milter errors.
pub type Result<T> = result::Result<T, Error>;

/// Errors of different kinds specialised for milters, with source attached if
/// available.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    error: Option<Box<dyn error::Error + Send + Sync>>,
}

impl Error {
    /// Constructs a new error with the given kind and source.
    pub fn new<E>(kind: ErrorKind, error: E) -> Self
    where
        E: Into<Box<dyn error::Error + Send + Sync>>,
    {
        Error {
            kind,
            error: Some(error.into()),
        }
    }

    /// Returns this error’s kind.
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }
}

impl From<ErrorKind> for Error {
    fn from(kind: ErrorKind) -> Self {
        Error { kind, error: None }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ErrorKind::*;

        match self.kind {
            SocketConfig => write!(f, "invalid socket configuration"),
            TimeoutConfig => write!(f, "invalid timeout configuration"),
            SocketBacklogConfig => write!(f, "invalid socket backlog configuration"),
            MilterRegistration => write!(f, "failed to register configuration with milter library"),
            MainFailureStatus => write!(f, "milter library main function returned failure status"),
            CallbackPanic => write!(f, "milter library main function exited after callback panic"),
            TypeConversion => write!(f, "failed to convert data type at FFI boundary"),
            FailureStatus => write!(f, "milter library function returned failure status"),
            DataAccess => write!(f, "invalid access of context data"),
            Io => write!(f, "I/O error"),
            _ => write!(f, "unspecified error"),
        }
    }
}

// TODO revisit
impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(&**self.error.as_ref()?)
    }
}

/// Various kinds of errors that can occur in a milter.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ErrorKind {
    /// The socket specification provided to the milter could not be used.
    SocketConfig,
    /// The timeout configuration parameter of `Milter` could not be used.
    TimeoutConfig,
    /// The socket backlog configuration parameter of `Milter` could not be
    /// used.
    SocketBacklogConfig,
    /// Registration of the milter’s configuration with the milter library
    /// failed.
    MilterRegistration,
    /// The milter library’s main event loop exited with a failure status.
    MainFailureStatus,
    /// The milter library’s main event loop exited due to a panic in a
    /// callback.
    CallbackPanic,

    /// Type conversion at the FFI boundary (Rust/C) failed.
    TypeConversion,
    /// A milter library function returned the failure status code.
    FailureStatus,
    /// Erroneous access of context data, such as violation of dynamic borrowing
    /// rules.
    DataAccess,

    /// An I/O error occurred (provided for convenience).
    Io,
    /// An unspecified error occurred (provided for convenience).
    Other,
}

impl From<NulError> for Error {
    fn from(error: NulError) -> Self {
        Error::new(ErrorKind::TypeConversion, error)
    }
}

impl From<Utf8Error> for Error {
    fn from(error: Utf8Error) -> Self {
        Error::new(ErrorKind::TypeConversion, error)
    }
}

impl From<TryFromIntError> for Error {
    fn from(error: TryFromIntError) -> Self {
        Error::new(ErrorKind::TypeConversion, error)
    }
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        Error::new(ErrorKind::Io, error)
    }
}

// TODO StatusCode? consider renaming ... MilterStatus?

/// Status returned from calls to the milter library.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) enum StatusCode {
    Success,
    Failure,
}

impl From<i32> for StatusCode {
    fn from(status: i32) -> Self {
        match status {
            sys::MI_SUCCESS => Self::Success,
            sys::MI_FAILURE => Self::Failure,
            _ => panic!("unknown return status code {}", status),
        }
    }
}

impl From<StatusCode> for Result<()> {
    fn from(status_code: StatusCode) -> Self {
        match status_code {
            StatusCode::Success => Ok(()),
            StatusCode::Failure => Err(Error::from(ErrorKind::FailureStatus)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error as EError;

    #[test]
    fn source_error() {
        let e = Error::from(ErrorKind::TypeConversion);

        assert!(e.source().is_none());
    }
}