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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
extern crate libgpg_error_sys as ffi;

use std::borrow::Cow;
use std::error;
use std::ffi::{CStr, NulError};
use std::fmt::{self, Write};
use std::io::{self, ErrorKind};
use std::os::raw::c_int;
use std::result;
use std::str;

pub type ErrorSource = ffi::gpg_err_source_t;
pub type ErrorCode = ffi::gpg_err_code_t;

/// A type wrapping errors produced by GPG libraries.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct Error(ffi::gpg_error_t);

impl Error {
    /// Creates a new error from a raw error value.
    #[inline]
    pub fn new(err: ffi::gpg_error_t) -> Error {
        Error(err)
    }

    /// Returns the raw error value that this error wraps.
    #[inline]
    pub fn raw(&self) -> ffi::gpg_error_t {
        self.0
    }

    /// Creates a new error from an error source and an error code.
    #[inline]
    pub fn from_source(source: ErrorSource, code: ErrorCode) -> Error {
        Error::new(ffi::gpg_err_make(source, code))
    }

    /// Creates a new error from an error code using the default
    /// error source `SOURCE_UNKNOWN`.
    #[inline]
    pub fn from_code(code: ErrorCode) -> Error {
        Error::from_source(Self::SOURCE_UNKNOWN, code)
    }

    /// Returns an error representing the last OS error that occurred.
    #[inline]
    pub fn last_os_error() -> Error {
        unsafe { Error::new(ffi::gpg_error_from_syserror()) }
    }

    /// Creates a new error from an OS error code.
    #[inline]
    pub fn from_errno(code: i32) -> Error {
        unsafe { Error::new(ffi::gpg_error_from_errno(code as c_int)) }
    }

    /// Returns the OS error that this error represents.
    #[inline]
    pub fn to_errno(&self) -> i32 {
        unsafe { ffi::gpg_err_code_to_errno(self.code()) }
    }

    /// Returns the error code.
    #[inline]
    pub fn code(&self) -> ErrorCode {
        ffi::gpg_err_code(self.0)
    }

    /// Returns a description of the source of the error as a UTF-8 string.
    #[inline]
    pub fn source(&self) -> Option<&'static str> {
        self.raw_source().and_then(|s| str::from_utf8(s).ok())
    }

    /// Returns an `Error` with the same code from the provided source.
    #[inline]
    pub fn with_source(&self, src: ErrorSource) -> Self {
        Error::from_source(src, self.code())
    }

    /// Returns a description of the source of the error as a slice of bytes.
    #[inline]
    pub fn raw_source(&self) -> Option<&'static [u8]> {
        unsafe {
            let source = ffi::gpg_strsource(self.0);
            if !source.is_null() {
                Some(CStr::from_ptr(source).to_bytes())
            } else {
                None
            }
        }
    }

    /// Returns a printable description of the error.
    #[inline]
    pub fn description(&self) -> Cow<'static, str> {
        let mut buf = [0; 1024];
        match self.write_description(&mut buf) {
            Ok(b) => Cow::Owned(String::from_utf8_lossy(b).into_owned()),
            Err(_) => Cow::Borrowed("Unknown error"),
        }
    }

    /// Returns a description of the error as a slice of bytes.
    #[inline]
    pub fn raw_description(&self) -> Cow<'static, [u8]> {
        let mut buf = [0; 1024];
        match self.write_description(&mut buf) {
            Ok(b) => Cow::Owned(b.to_owned()),
            Err(_) => Cow::Borrowed(b"Unknown error"),
        }
    }

    /// Writes a description of the error to the provided buffer
    /// and returns a slice of the buffer containing the description.
    ///
    /// # Errors
    ///
    /// Returns an error if the provided buffer is not long enough or
    /// if the error is not recognized.
    #[inline]
    pub fn write_description<'r>(&self, buf: &'r mut [u8]) -> result::Result<&'r mut [u8], ()> {
        let p = buf.as_mut_ptr();
        unsafe {
            if ffi::gpg_strerror_r(self.0, p as *mut _, buf.len()) == 0 {
                match buf.iter().position(|&b| b == b'\0') {
                    Some(x) => Ok(&mut buf[..x]),
                    None => Ok(buf),
                }
            } else {
                Err(())
            }
        }
    }
}

impl error::Error for Error {
    #[inline]
    fn description(&self) -> &str {
        "gpg error"
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        struct Escaped<'a>(&'a [u8]);
        impl<'a> fmt::Debug for Escaped<'a> {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                use std::ascii;

                f.write_char('"')?;
                for b in self.0.iter().flat_map(|&b| ascii::escape_default(b)) {
                    f.write_char(b as char)?;
                }
                f.write_char('"')
            }
        }

        let mut buf = [0; 1024];
        let desc = self.write_description(&mut buf)
            .map(|x| &*x)
            .unwrap_or(b"Unknown error");
        f.debug_struct("Error")
            .field("source", &self.source())
            .field("code", &self.code())
            .field("description", &Escaped(desc))
            .finish()
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        // TODO: Use write_description and char::decode_utf8
        write!(fmt, "{} (gpg error {})", self.description(), self.code())
    }
}

impl From<NulError> for Error {
    #[inline]
    fn from(_: NulError) -> Error {
        Error::from_code(ffi::GPG_ERR_INV_VALUE)
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        let kind = err.kind();
        if let Some(Ok(err)) = err.into_inner().map(|e| e.downcast::<Error>()) {
            *err
        } else {
            match kind {
                ErrorKind::NotFound => Self::ENOENT,
                ErrorKind::PermissionDenied => Self::EACCES,
                ErrorKind::ConnectionRefused => Self::ECONNREFUSED,
                ErrorKind::ConnectionReset => Self::ECONNRESET,
                ErrorKind::ConnectionAborted => Self::ECONNABORTED,
                ErrorKind::NotConnected => Self::ENOTCONN,
                ErrorKind::AddrInUse => Self::EADDRINUSE,
                ErrorKind::AddrNotAvailable => Self::EADDRNOTAVAIL,
                ErrorKind::BrokenPipe => Self::EPIPE,
                ErrorKind::AlreadyExists => Self::EEXIST,
                ErrorKind::WouldBlock => Self::EWOULDBLOCK,
                ErrorKind::InvalidInput => Self::EINVAL,
                ErrorKind::TimedOut => Self::ETIMEDOUT,
                ErrorKind::Interrupted => Self::EINTR,
                _ => Error::EIO,
            }
        }
    }
}

impl From<Error> for io::Error {
    fn from(err: Error) -> io::Error {
        let kind = match err.with_source(Error::SOURCE_UNKNOWN) {
            Error::ECONNREFUSED => ErrorKind::ConnectionRefused,
            Error::ECONNRESET => ErrorKind::ConnectionReset,
            Error::EPERM | Error::EACCES => ErrorKind::PermissionDenied,
            Error::EPIPE => ErrorKind::BrokenPipe,
            Error::ENOTCONN => ErrorKind::NotConnected,
            Error::ECONNABORTED => ErrorKind::ConnectionAborted,
            Error::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable,
            Error::EADDRINUSE => ErrorKind::AddrInUse,
            Error::ENOENT => ErrorKind::NotFound,
            Error::EINTR => ErrorKind::Interrupted,
            Error::EINVAL => ErrorKind::InvalidInput,
            Error::ETIMEDOUT => ErrorKind::TimedOut,
            Error::EEXIST => ErrorKind::AlreadyExists,
            x if x == Error::EAGAIN || x == Error::EWOULDBLOCK => ErrorKind::WouldBlock,
            _ => ErrorKind::Other,
        };
        io::Error::new(kind, err)
    }
}

include!(concat!(env!("OUT_DIR"), "/constants.rs"));

pub type Result<T> = result::Result<T, Error>;

#[macro_export]
macro_rules! return_err {
    ($e:expr) => (match $crate::Error::new($e) {
        $crate::Error::NO_ERROR => (),
        err => return Err(From::from(err)),
    });
}