diff --git a/openssl/src/asn1/mod.rs b/openssl/src/asn1/mod.rs index d5561b62..202909ec 100644 --- a/openssl/src/asn1/mod.rs +++ b/openssl/src/asn1/mod.rs @@ -2,8 +2,7 @@ use libc::c_long; use std::ptr; use ffi; -use ssl::error::SslError; - +use error::ErrorStack; pub struct Asn1Time { handle: *mut ffi::ASN1_TIME, @@ -19,7 +18,7 @@ impl Asn1Time { } } - fn new_with_period(period: u64) -> Result { + fn new_with_period(period: u64) -> Result { ffi::init(); let handle = unsafe { @@ -29,7 +28,7 @@ impl Asn1Time { } /// Creates a new time on specified interval in days from now - pub fn days_from_now(days: u32) -> Result { + pub fn days_from_now(days: u32) -> Result { Asn1Time::new_with_period(days as u64 * 60 * 60 * 24) } diff --git a/openssl/src/bio/mod.rs b/openssl/src/bio/mod.rs index 4c9b20b0..2e99284f 100644 --- a/openssl/src/bio/mod.rs +++ b/openssl/src/bio/mod.rs @@ -6,7 +6,7 @@ use std::cmp; use ffi; use ffi_extras; -use ssl::error::SslError; +use error::ErrorStack; pub struct MemBio { bio: *mut ffi::BIO, @@ -25,7 +25,7 @@ impl Drop for MemBio { impl MemBio { /// Creates a new owned memory based BIO - pub fn new() -> Result { + pub fn new() -> Result { ffi::init(); let bio = unsafe { ffi::BIO_new(ffi::BIO_s_mem()) }; @@ -81,7 +81,7 @@ impl Read for MemBio { if is_eof != 0 { Ok(0) } else { - Err(io::Error::new(io::ErrorKind::Other, SslError::get())) + Err(io::Error::new(io::ErrorKind::Other, ErrorStack::get())) } } else { Ok(ret as usize) @@ -95,7 +95,7 @@ impl Write for MemBio { let ret = unsafe { ffi::BIO_write(self.bio, buf.as_ptr() as *const c_void, len) }; if ret < 0 { - Err(io::Error::new(io::ErrorKind::Other, SslError::get())) + Err(io::Error::new(io::ErrorKind::Other, ErrorStack::get())) } else { Ok(ret as usize) } diff --git a/openssl/src/bn/mod.rs b/openssl/src/bn/mod.rs index d548e9ef..eb697248 100644 --- a/openssl/src/bn/mod.rs +++ b/openssl/src/bn/mod.rs @@ -4,7 +4,7 @@ use std::cmp::Ordering; use std::{fmt, ptr, mem}; use ffi; -use ssl::error::SslError; +use error::ErrorStack; pub struct BigNum(*mut ffi::BIGNUM); @@ -20,7 +20,7 @@ macro_rules! with_ctx( ($name:ident, $action:block) => ({ let $name = ffi::BN_CTX_new(); if ($name).is_null() { - Err(SslError::get()) + Err(ErrorStack::get()) } else { let r = $action; ffi::BN_CTX_free($name); @@ -37,7 +37,7 @@ macro_rules! with_bn( if $action { Ok($name) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } }, Err(err) => Err(err), @@ -52,13 +52,13 @@ macro_rules! with_bn_in_ctx( Ok($name) => { let $ctx_name = ffi::BN_CTX_new(); if ($ctx_name).is_null() { - Err(SslError::get()) + Err(ErrorStack::get()) } else { let r = if $action { Ok($name) } else { - Err(SslError::get()) + Err(ErrorStack::get()) }; ffi::BN_CTX_free($ctx_name); r @@ -70,7 +70,7 @@ macro_rules! with_bn_in_ctx( ); impl BigNum { - pub fn new() -> Result { + pub fn new() -> Result { unsafe { ffi::init(); @@ -79,14 +79,14 @@ impl BigNum { } } - pub fn new_from(n: u64) -> Result { + pub fn new_from(n: u64) -> Result { BigNum::new().and_then(|v| unsafe { try_ssl!(ffi::BN_set_word(v.raw(), n as c_ulong)); Ok(v) }) } - pub fn from_dec_str(s: &str) -> Result { + pub fn from_dec_str(s: &str) -> Result { BigNum::new().and_then(|v| unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); try_ssl!(ffi::BN_dec2bn(v.raw_ptr(), c_str.as_ptr() as *const _)); @@ -94,7 +94,7 @@ impl BigNum { }) } - pub fn from_hex_str(s: &str) -> Result { + pub fn from_hex_str(s: &str) -> Result { BigNum::new().and_then(|v| unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); try_ssl!(ffi::BN_hex2bn(v.raw_ptr(), c_str.as_ptr() as *const _)); @@ -102,26 +102,26 @@ impl BigNum { }) } - pub unsafe fn new_from_ffi(orig: *mut ffi::BIGNUM) -> Result { + pub unsafe fn new_from_ffi(orig: *mut ffi::BIGNUM) -> Result { if orig.is_null() { panic!("Null Pointer was supplied to BigNum::new_from_ffi"); } let r = ffi::BN_dup(orig); if r.is_null() { - Err(SslError::get()) + Err(ErrorStack::get()) } else { Ok(BigNum(r)) } } - pub fn new_from_slice(n: &[u8]) -> Result { + pub fn new_from_slice(n: &[u8]) -> Result { BigNum::new().and_then(|v| unsafe { try_ssl_null!(ffi::BN_bin2bn(n.as_ptr(), n.len() as c_int, v.raw())); Ok(v) }) } - pub fn checked_sqr(&self) -> Result { + pub fn checked_sqr(&self) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_sqr(r.raw(), self.raw(), ctx) == 1 @@ -129,7 +129,7 @@ impl BigNum { } } - pub fn checked_nnmod(&self, n: &BigNum) -> Result { + pub fn checked_nnmod(&self, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_nnmod(r.raw(), self.raw(), n.raw(), ctx) == 1 @@ -137,7 +137,7 @@ impl BigNum { } } - pub fn checked_mod_add(&self, a: &BigNum, n: &BigNum) -> Result { + pub fn checked_mod_add(&self, a: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_mod_add(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 @@ -145,7 +145,7 @@ impl BigNum { } } - pub fn checked_mod_sub(&self, a: &BigNum, n: &BigNum) -> Result { + pub fn checked_mod_sub(&self, a: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_mod_sub(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 @@ -153,7 +153,7 @@ impl BigNum { } } - pub fn checked_mod_mul(&self, a: &BigNum, n: &BigNum) -> Result { + pub fn checked_mod_mul(&self, a: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_mod_mul(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 @@ -161,7 +161,7 @@ impl BigNum { } } - pub fn checked_mod_sqr(&self, n: &BigNum) -> Result { + pub fn checked_mod_sqr(&self, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_mod_sqr(r.raw(), self.raw(), n.raw(), ctx) == 1 @@ -169,7 +169,7 @@ impl BigNum { } } - pub fn checked_exp(&self, p: &BigNum) -> Result { + pub fn checked_exp(&self, p: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_exp(r.raw(), self.raw(), p.raw(), ctx) == 1 @@ -177,7 +177,7 @@ impl BigNum { } } - pub fn checked_mod_exp(&self, p: &BigNum, n: &BigNum) -> Result { + pub fn checked_mod_exp(&self, p: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_mod_exp(r.raw(), self.raw(), p.raw(), n.raw(), ctx) == 1 @@ -185,7 +185,7 @@ impl BigNum { } } - pub fn checked_mod_inv(&self, n: &BigNum) -> Result { + pub fn checked_mod_inv(&self, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { !ffi::BN_mod_inverse(r.raw(), self.raw(), n.raw(), ctx).is_null() @@ -193,59 +193,59 @@ impl BigNum { } } - pub fn add_word(&mut self, w: c_ulong) -> Result<(), SslError> { + pub fn add_word(&mut self, w: c_ulong) -> Result<(), ErrorStack> { unsafe { if ffi::BN_add_word(self.raw(), w) == 1 { Ok(()) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } - pub fn sub_word(&mut self, w: c_ulong) -> Result<(), SslError> { + pub fn sub_word(&mut self, w: c_ulong) -> Result<(), ErrorStack> { unsafe { if ffi::BN_sub_word(self.raw(), w) == 1 { Ok(()) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } - pub fn mul_word(&mut self, w: c_ulong) -> Result<(), SslError> { + pub fn mul_word(&mut self, w: c_ulong) -> Result<(), ErrorStack> { unsafe { if ffi::BN_mul_word(self.raw(), w) == 1 { Ok(()) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } - pub fn div_word(&mut self, w: c_ulong) -> Result { + pub fn div_word(&mut self, w: c_ulong) -> Result { unsafe { let result = ffi::BN_div_word(self.raw(), w); if result != !0 as c_ulong { Ok(result) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } - pub fn mod_word(&self, w: c_ulong) -> Result { + pub fn mod_word(&self, w: c_ulong) -> Result { unsafe { let result = ffi::BN_mod_word(self.raw(), w); if result != !0 as c_ulong { Ok(result) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } - pub fn checked_gcd(&self, a: &BigNum) -> Result { + pub fn checked_gcd(&self, a: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_gcd(r.raw(), self.raw(), a.raw(), ctx) == 1 @@ -257,7 +257,7 @@ impl BigNum { safe: bool, add: Option<&BigNum>, rem: Option<&BigNum>) - -> Result { + -> Result { unsafe { with_bn_in_ctx!(r, ctx, { let add_arg = add.map(|a| a.raw()).unwrap_or(ptr::null_mut()); @@ -273,7 +273,7 @@ impl BigNum { } } - pub fn is_prime(&self, checks: i32) -> Result { + pub fn is_prime(&self, checks: i32) -> Result { unsafe { with_ctx!(ctx, { Ok(ffi::BN_is_prime_ex(self.raw(), checks as c_int, ctx, ptr::null()) == 1) @@ -281,7 +281,7 @@ impl BigNum { } } - pub fn is_prime_fast(&self, checks: i32, do_trial_division: bool) -> Result { + pub fn is_prime_fast(&self, checks: i32, do_trial_division: bool) -> Result { unsafe { with_ctx!(ctx, { Ok(ffi::BN_is_prime_fasttest_ex(self.raw(), @@ -293,7 +293,7 @@ impl BigNum { } } - pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result { + pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1 @@ -304,7 +304,7 @@ impl BigNum { pub fn checked_new_pseudo_random(bits: i32, prop: RNGProperty, odd: bool) - -> Result { + -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_pseudo_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1 @@ -312,7 +312,7 @@ impl BigNum { } } - pub fn checked_rand_in_range(&self) -> Result { + pub fn checked_rand_in_range(&self) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_rand_range(r.raw(), self.raw()) == 1 @@ -320,7 +320,7 @@ impl BigNum { } } - pub fn checked_pseudo_rand_in_range(&self) -> Result { + pub fn checked_pseudo_rand_in_range(&self) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_pseudo_rand_range(r.raw(), self.raw()) == 1 @@ -328,22 +328,22 @@ impl BigNum { } } - pub fn set_bit(&mut self, n: i32) -> Result<(), SslError> { + pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { if ffi::BN_set_bit(self.raw(), n as c_int) == 1 { Ok(()) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } - pub fn clear_bit(&mut self, n: i32) -> Result<(), SslError> { + pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { if ffi::BN_clear_bit(self.raw(), n as c_int) == 1 { Ok(()) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } @@ -352,17 +352,17 @@ impl BigNum { unsafe { ffi::BN_is_bit_set(self.raw(), n as c_int) == 1 } } - pub fn mask_bits(&mut self, n: i32) -> Result<(), SslError> { + pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { if ffi::BN_mask_bits(self.raw(), n as c_int) == 1 { Ok(()) } else { - Err(SslError::get()) + Err(ErrorStack::get()) } } } - pub fn checked_shl1(&self) -> Result { + pub fn checked_shl1(&self) -> Result { unsafe { with_bn!(r, { ffi::BN_lshift1(r.raw(), self.raw()) == 1 @@ -370,7 +370,7 @@ impl BigNum { } } - pub fn checked_shr1(&self) -> Result { + pub fn checked_shr1(&self) -> Result { unsafe { with_bn!(r, { ffi::BN_rshift1(r.raw(), self.raw()) == 1 @@ -378,7 +378,7 @@ impl BigNum { } } - pub fn checked_add(&self, a: &BigNum) -> Result { + pub fn checked_add(&self, a: &BigNum) -> Result { unsafe { with_bn!(r, { ffi::BN_add(r.raw(), self.raw(), a.raw()) == 1 @@ -386,7 +386,7 @@ impl BigNum { } } - pub fn checked_sub(&self, a: &BigNum) -> Result { + pub fn checked_sub(&self, a: &BigNum) -> Result { unsafe { with_bn!(r, { ffi::BN_sub(r.raw(), self.raw(), a.raw()) == 1 @@ -394,7 +394,7 @@ impl BigNum { } } - pub fn checked_mul(&self, a: &BigNum) -> Result { + pub fn checked_mul(&self, a: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_mul(r.raw(), self.raw(), a.raw(), ctx) == 1 @@ -402,7 +402,7 @@ impl BigNum { } } - pub fn checked_div(&self, a: &BigNum) -> Result { + pub fn checked_div(&self, a: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_div(r.raw(), ptr::null_mut(), self.raw(), a.raw(), ctx) == 1 @@ -410,7 +410,7 @@ impl BigNum { } } - pub fn checked_mod(&self, a: &BigNum) -> Result { + pub fn checked_mod(&self, a: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { ffi::BN_div(ptr::null_mut(), r.raw(), self.raw(), a.raw(), ctx) == 1 @@ -418,7 +418,7 @@ impl BigNum { } } - pub fn checked_shl(&self, a: &i32) -> Result { + pub fn checked_shl(&self, a: &i32) -> Result { unsafe { with_bn!(r, { ffi::BN_lshift(r.raw(), self.raw(), *a as c_int) == 1 @@ -426,7 +426,7 @@ impl BigNum { } } - pub fn checked_shr(&self, a: &i32) -> Result { + pub fn checked_shr(&self, a: &i32) -> Result { unsafe { with_bn!(r, { ffi::BN_rshift(r.raw(), self.raw(), *a as c_int) == 1 diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index ba0a16b6..1020a82e 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -8,8 +8,8 @@ use bio::MemBio; use crypto::hash; use crypto::hash::Type as HashType; use ffi; -use ssl::error::{SslError, StreamError}; use crypto::rsa::RSA; +use error::ErrorStack; #[derive(Copy, Clone)] pub enum Parts { @@ -85,17 +85,18 @@ impl PKey { } /// Reads private key from PEM, takes ownership of handle - pub fn private_key_from_pem(reader: &mut R) -> Result + pub fn private_key_from_pem(reader: &mut R) -> io::Result where R: Read { let mut mem_bio = try!(MemBio::new()); - try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + try!(io::copy(reader, &mut mem_bio)); unsafe { let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.get_handle(), ptr::null_mut(), None, ptr::null_mut())); + Ok(PKey { evp: evp as *mut ffi::EVP_PKEY, parts: Parts::Both, @@ -104,11 +105,11 @@ impl PKey { } /// Reads public key from PEM, takes ownership of handle - pub fn public_key_from_pem(reader: &mut R) -> Result + pub fn public_key_from_pem(reader: &mut R) -> io::Result where R: Read { let mut mem_bio = try!(MemBio::new()); - try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + try!(io::copy(reader, &mut mem_bio)); unsafe { let evp = try_ssl_null!(ffi::PEM_read_bio_PUBKEY(mem_bio.get_handle(), @@ -123,13 +124,15 @@ impl PKey { } /// Reads an RSA private key from PEM, takes ownership of handle - pub fn private_rsa_key_from_pem(reader: &mut R) -> Result + pub fn private_rsa_key_from_pem(reader: &mut R) -> io::Result where R: Read { let rsa = try!(RSA::private_key_from_pem(reader)); unsafe { let evp = try_ssl_null!(ffi::EVP_PKEY_new()); - try_ssl!(ffi::EVP_PKEY_set1_RSA(evp, rsa.as_ptr())); + if ffi::EVP_PKEY_set1_RSA(evp, rsa.as_ptr()) == 0 { + return Err(io::Error::new(io::ErrorKind::Other, ErrorStack::get())); + } Ok(PKey { evp: evp, @@ -139,13 +142,15 @@ impl PKey { } /// Reads an RSA public key from PEM, takes ownership of handle - pub fn public_rsa_key_from_pem(reader: &mut R) -> Result + pub fn public_rsa_key_from_pem(reader: &mut R) -> io::Result where R: Read { let rsa = try!(RSA::public_key_from_pem(reader)); unsafe { let evp = try_ssl_null!(ffi::EVP_PKEY_new()); - try_ssl!(ffi::EVP_PKEY_set1_RSA(evp, rsa.as_ptr())); + if ffi::EVP_PKEY_set1_RSA(evp, rsa.as_ptr()) == 0 { + return Err(io::Error::new(io::ErrorKind::Other, ErrorStack::get())); + } Ok(PKey { evp: evp, @@ -260,7 +265,7 @@ impl PKey { // FIXME: also add password and encryption pub fn write_pem(&self, writer: &mut W /* , password: Option */) - -> Result<(), SslError> { + -> io::Result<()> { let mut mem_bio = try!(MemBio::new()); unsafe { try_ssl!(ffi::PEM_write_bio_PrivateKey(mem_bio.get_handle(), @@ -273,19 +278,19 @@ impl PKey { } let mut buf = vec![]; - try!(mem_bio.read_to_end(&mut buf).map_err(StreamError)); - writer.write_all(&buf).map_err(StreamError) + try!(mem_bio.read_to_end(&mut buf)); + writer.write_all(&buf) } /// Stores public key as a PEM pub fn write_pub_pem(&self, writer: &mut W /* , password: Option */) - -> Result<(), SslError> { + -> io::Result<()> { let mut mem_bio = try!(MemBio::new()); unsafe { try_ssl!(ffi::PEM_write_bio_PUBKEY(mem_bio.get_handle(), self.evp)) } let mut buf = vec![]; - try!(mem_bio.read_to_end(&mut buf).map_err(StreamError)); - writer.write_all(&buf).map_err(StreamError) + try!(mem_bio.read_to_end(&mut buf)); + writer.write_all(&buf) } /** @@ -370,7 +375,7 @@ impl PKey { openssl_padding_code(padding)); if rv < 0 as c_int { - // println!("{:?}", SslError::get()); + // println!("{:?}", ErrorStack::get()); vec![] } else { r.truncate(rv as usize); diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 6fcb5b07..11970933 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -1,11 +1,11 @@ use ffi; use std::fmt; -use ssl::error::{SslError, StreamError}; use std::ptr; use std::io::{self, Read}; use bn::BigNum; use bio::MemBio; +use error::ErrorStack; pub struct RSA(*mut ffi::RSA); @@ -20,7 +20,7 @@ impl Drop for RSA { impl RSA { /// only useful for associating the key material directly with the key, it's safer to use /// the supplied load and save methods for DER formatted keys. - pub fn from_public_components(n: BigNum, e: BigNum) -> Result { + pub fn from_public_components(n: BigNum, e: BigNum) -> Result { unsafe { let rsa = try_ssl_null!(ffi::RSA_new()); (*rsa).n = n.into_raw(); @@ -35,11 +35,11 @@ impl RSA { } /// Reads an RSA private key from PEM formatted data. - pub fn private_key_from_pem(reader: &mut R) -> Result + pub fn private_key_from_pem(reader: &mut R) -> io::Result where R: Read { let mut mem_bio = try!(MemBio::new()); - try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + try!(io::copy(reader, &mut mem_bio)); unsafe { let rsa = try_ssl_null!(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.get_handle(), @@ -51,11 +51,11 @@ impl RSA { } /// Reads an RSA public key from PEM formatted data. - pub fn public_key_from_pem(reader: &mut R) -> Result + pub fn public_key_from_pem(reader: &mut R) -> io::Result where R: Read { let mut mem_bio = try!(MemBio::new()); - try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + try!(io::copy(reader, &mut mem_bio)); unsafe { let rsa = try_ssl_null!(ffi::PEM_read_bio_RSA_PUBKEY(mem_bio.get_handle(), @@ -71,7 +71,7 @@ impl RSA { } // The following getters are unsafe, since BigNum::new_from_ffi fails upon null pointers - pub fn n(&self) -> Result { + pub fn n(&self) -> Result { unsafe { BigNum::new_from_ffi((*self.0).n) } @@ -83,13 +83,13 @@ impl RSA { } } - pub fn d(&self) -> Result { + pub fn d(&self) -> Result { unsafe { BigNum::new_from_ffi((*self.0).d) } } - pub fn e(&self) -> Result { + pub fn e(&self) -> Result { unsafe { BigNum::new_from_ffi((*self.0).e) } @@ -101,13 +101,13 @@ impl RSA { } } - pub fn p(&self) -> Result { + pub fn p(&self) -> Result { unsafe { BigNum::new_from_ffi((*self.0).p) } } - pub fn q(&self) -> Result { + pub fn q(&self) -> Result { unsafe { BigNum::new_from_ffi((*self.0).q) } diff --git a/openssl/src/dh/mod.rs b/openssl/src/dh/mod.rs index d2f26c3f..14bf076d 100644 --- a/openssl/src/dh/mod.rs +++ b/openssl/src/dh/mod.rs @@ -1,7 +1,7 @@ use ffi; use std::io; use std::io::prelude::*; -use ssl::error::{SslError, StreamError}; +use error::ErrorStack; use bio::MemBio; use bn::BigNum; use std::mem; @@ -10,7 +10,7 @@ use std::ptr; pub struct DH(*mut ffi::DH); impl DH { - pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { + pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_new_from_params(p.raw(), g.raw(), q.raw()) }); mem::forget(p); mem::forget(g); @@ -18,11 +18,11 @@ impl DH { Ok(DH(dh)) } - pub fn from_pem(reader: &mut R) -> Result + pub fn from_pem(reader: &mut R) -> io::Result where R: Read { let mut mem_bio = try!(MemBio::new()); - try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + try!(io::copy(reader, &mut mem_bio)); let dh = unsafe { ffi::PEM_read_bio_DHparams(mem_bio.get_handle(), ptr::null_mut(), None, ptr::null_mut()) }; @@ -31,19 +31,19 @@ impl DH { } #[cfg(feature = "rfc5114")] - pub fn get_1024_160() -> Result { + pub fn get_1024_160() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_1024_160() }); Ok(DH(dh)) } #[cfg(feature = "rfc5114")] - pub fn get_2048_224() -> Result { + pub fn get_2048_224() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_224() }); Ok(DH(dh)) } #[cfg(feature = "rfc5114")] - pub fn get_2048_256() -> Result { + pub fn get_2048_256() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_256() }); Ok(DH(dh)) } diff --git a/openssl/src/error.rs b/openssl/src/error.rs new file mode 100644 index 00000000..5fa542c2 --- /dev/null +++ b/openssl/src/error.rs @@ -0,0 +1,137 @@ +use libc::c_ulong; +use std::fmt; +use std::error; +use std::ffi::CStr; +use std::io; +use std::str; + +use ffi; + +#[derive(Debug)] +pub struct ErrorStack(Vec); + +impl ErrorStack { + /// Returns the contents of the OpenSSL error stack. + pub fn get() -> ErrorStack { + let mut vec = vec![]; + while let Some(err) = Error::get() { + vec.push(err); + } + ErrorStack(vec) + } +} + +impl ErrorStack { + /// Returns the errors in the stack. + pub fn errors(&self) -> &[Error] { + &self.0 + } +} + +impl fmt::Display for ErrorStack { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut first = true; + for err in &self.0 { + if first { + try!(fmt.write_str(", ")); + first = false; + } + try!(write!(fmt, "{}", err)); + } + Ok(()) + } +} + +impl error::Error for ErrorStack { + fn description(&self) -> &str { + "An OpenSSL error stack" + } +} + +impl From for io::Error { + fn from(e: ErrorStack) -> io::Error { + io::Error::new(io::ErrorKind::Other, e) + } +} + +/// An error reported from OpenSSL. +pub struct Error(c_ulong); + +impl Error { + /// Returns the first error on the OpenSSL error stack. + pub fn get() -> Option { + ffi::init(); + + match unsafe { ffi::ERR_get_error() } { + 0 => None, + err => Some((Error(err))), + } + } + + /// Returns the raw OpenSSL error code for this error. + pub fn error_code(&self) -> c_ulong { + self.0 + } + + /// Returns the name of the library reporting the error. + pub fn library(&self) -> &'static str { + get_lib(self.0) + } + + /// Returns the name of the function reporting the error. + pub fn function(&self) -> &'static str { + get_func(self.0) + } + + /// Returns the reason for the error. + pub fn reason(&self) -> &'static str { + get_reason(self.0) + } +} + +impl fmt::Debug for Error { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Error") + .field("library", &self.library()) + .field("function", &self.function()) + .field("reason", &self.reason()) + .finish() + } +} + +impl fmt::Display for Error { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str(&self.reason()) + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + "An OpenSSL error" + } +} + +fn get_lib(err: c_ulong) -> &'static str { + unsafe { + let cstr = ffi::ERR_lib_error_string(err); + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + str::from_utf8(bytes).unwrap() + } +} + +fn get_func(err: c_ulong) -> &'static str { + unsafe { + let cstr = ffi::ERR_func_error_string(err); + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + str::from_utf8(bytes).unwrap() + } +} + +fn get_reason(err: c_ulong) -> &'static str { + unsafe { + let cstr = ffi::ERR_reason_error_string(err); + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + str::from_utf8(bytes).unwrap() + } +} + diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 63926615..ae347eee 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -18,11 +18,12 @@ extern crate net2; mod macros; pub mod asn1; -pub mod bn; pub mod bio; +pub mod bn; pub mod crypto; pub mod dh; -pub mod ssl; -pub mod x509; +pub mod error; pub mod nid; +pub mod ssl; pub mod version; +pub mod x509; diff --git a/openssl/src/macros.rs b/openssl/src/macros.rs index 3e4bb429..35221f1c 100644 --- a/openssl/src/macros.rs +++ b/openssl/src/macros.rs @@ -13,7 +13,7 @@ macro_rules! try_ssl_stream { macro_rules! try_ssl_if { ($e:expr) => ( if $e { - return Err(SslError::get()) + return Err(::error::ErrorStack::get().into()) } ) } @@ -45,7 +45,7 @@ macro_rules! try_ssl_null{ macro_rules! lift_ssl_if{ ($e:expr) => ( { if $e { - Err(SslError::get()) + Err(::error::ErrorStack::get().into()) } else { Ok(()) } diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index e53545d7..44893b88 100644 --- a/openssl/src/ssl/bio.rs +++ b/openssl/src/ssl/bio.rs @@ -9,7 +9,7 @@ use std::ptr; use std::slice; use std::sync::Arc; -use ssl::error::SslError; +use error::ErrorStack; pub struct StreamState { pub stream: S, @@ -39,7 +39,7 @@ impl BioMethod { unsafe impl Send for BioMethod {} -pub fn new(stream: S) -> Result<(*mut BIO, Arc), SslError> { +pub fn new(stream: S) -> Result<(*mut BIO, Arc), ErrorStack> { let method = Arc::new(BioMethod::new::()); let state = Box::new(StreamState { diff --git a/openssl/src/ssl/error.rs b/openssl/src/ssl/error.rs index ba0c7458..95213361 100644 --- a/openssl/src/ssl/error.rs +++ b/openssl/src/ssl/error.rs @@ -1,15 +1,8 @@ -pub use self::SslError::*; -pub use self::OpensslError::*; - -use libc::c_ulong; use std::error; use std::error::Error as StdError; use std::fmt; -use std::ffi::CStr; use std::io; -use std::str; - -use ffi; +use error::ErrorStack; /// An SSL error. #[derive(Debug)] @@ -27,30 +20,16 @@ pub enum Error { /// An error reported by the underlying stream. Stream(io::Error), /// An error in the OpenSSL library. - Ssl(Vec), + Ssl(ErrorStack), } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(fmt.write_str(self.description())); - match *self { - Error::Stream(ref err) => write!(fmt, ": {}", err), - Error::WantRead(ref err) => write!(fmt, ": {}", err), - Error::WantWrite(ref err) => write!(fmt, ": {}", err), - Error::Ssl(ref errs) => { - let mut first = true; - for err in errs { - if first { - try!(fmt.write_str(": ")); - first = false; - } else { - try!(fmt.write_str(", ")); - } - try!(fmt.write_str(&err.reason())) - } - Ok(()) - } - _ => Ok(()), + if let Some(err) = self.cause() { + write!(fmt, ": {}", err) + } else { + Ok(()) } } } @@ -72,201 +51,14 @@ impl error::Error for Error { Error::WantRead(ref err) => Some(err), Error::WantWrite(ref err) => Some(err), Error::Stream(ref err) => Some(err), + Error::Ssl(ref err) => Some(err), _ => None, } } } -/// An error reported from OpenSSL. -pub struct OpenSslError(c_ulong); - -impl OpenSslError { - /// Returns the contents of the OpenSSL error stack. - pub fn get_stack() -> Vec { - ffi::init(); - - let mut errs = vec![]; - loop { - match unsafe { ffi::ERR_get_error() } { - 0 => break, - err => errs.push(OpenSslError(err)), - } - } - errs - } - - /// Returns the raw OpenSSL error code for this error. - pub fn error_code(&self) -> c_ulong { - self.0 - } - - /// Returns the name of the library reporting the error. - pub fn library(&self) -> &'static str { - get_lib(self.0) - } - - /// Returns the name of the function reporting the error. - pub fn function(&self) -> &'static str { - get_func(self.0) - } - - /// Returns the reason for the error. - pub fn reason(&self) -> &'static str { - get_reason(self.0) +impl From for Error { + fn from(e: ErrorStack) -> Error { + Error::Ssl(e) } } - -impl fmt::Debug for OpenSslError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("OpenSslError") - .field("library", &self.library()) - .field("function", &self.function()) - .field("reason", &self.reason()) - .finish() - } -} - -impl fmt::Display for OpenSslError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str(&self.reason()) - } -} - -impl error::Error for OpenSslError { - fn description(&self) -> &str { - "An OpenSSL error" - } -} - -/// An SSL error -#[derive(Debug)] -pub enum SslError { - /// The underlying stream reported an error - StreamError(io::Error), - /// The SSL session has been closed by the other end - SslSessionClosed, - /// An error in the OpenSSL library - OpenSslErrors(Vec), -} - -impl fmt::Display for SslError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - try!(fmt.write_str(error::Error::description(self))); - if let OpenSslErrors(ref errs) = *self { - let mut first = true; - for err in errs { - if first { - try!(fmt.write_str(": ")); - first = false; - } else { - try!(fmt.write_str(", ")); - } - match *err { - UnknownError { ref reason, .. } => try!(fmt.write_str(reason)), - } - } - } - - Ok(()) - } -} - -impl error::Error for SslError { - fn description(&self) -> &str { - match *self { - StreamError(_) => "The underlying stream reported an error", - SslSessionClosed => "The SSL session has been closed by the other end", - OpenSslErrors(_) => "An error in the OpenSSL library", - } - } - - fn cause(&self) -> Option<&error::Error> { - match *self { - StreamError(ref err) => Some(err as &error::Error), - _ => None, - } - } -} - -/// An error from the OpenSSL library -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum OpensslError { - /// An unknown error - UnknownError { - /// The library reporting the error - library: String, - /// The function reporting the error - function: String, - /// The reason for the error - reason: String, - }, -} - -impl OpensslError { - pub fn from_error_code(err: c_ulong) -> OpensslError { - ffi::init(); - UnknownError { - library: get_lib(err).to_owned(), - function: get_func(err).to_owned(), - reason: get_reason(err).to_owned(), - } - } -} - -fn get_lib(err: c_ulong) -> &'static str { - unsafe { - let cstr = ffi::ERR_lib_error_string(err); - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - str::from_utf8(bytes).unwrap() - } -} - -fn get_func(err: c_ulong) -> &'static str { - unsafe { - let cstr = ffi::ERR_func_error_string(err); - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - str::from_utf8(bytes).unwrap() - } -} - -fn get_reason(err: c_ulong) -> &'static str { - unsafe { - let cstr = ffi::ERR_reason_error_string(err); - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - str::from_utf8(bytes).unwrap() - } -} - -impl SslError { - /// Creates a new `OpenSslErrors` with the current contents of the error - /// stack. - pub fn get() -> SslError { - let mut errs = vec![]; - loop { - match unsafe { ffi::ERR_get_error() } { - 0 => break, - err => errs.push(OpensslError::from_error_code(err)), - } - } - OpenSslErrors(errs) - } - - /// Creates an `SslError` from the raw numeric error code. - pub fn from_error(err: c_ulong) -> SslError { - OpenSslErrors(vec![OpensslError::from_error_code(err)]) - } -} - -#[test] -fn test_uknown_error_should_have_correct_messages() { - let errs = match SslError::from_error(336032784) { - OpenSslErrors(errs) => errs, - _ => panic!("This should always be an `OpenSslErrors` variant."), - }; - - let UnknownError { ref library, ref function, ref reason } = errs[0]; - - assert_eq!(&library[..], "SSL routines"); - assert_eq!(&function[..], "SSL23_GET_SERVER_HELLO"); - assert_eq!(&reason[..], "sslv3 alert handshake failure"); -} diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index c713aeb2..f9534bc2 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -25,9 +25,9 @@ use std::os::windows::io::{AsRawSocket, RawSocket}; use ffi; use ffi_extras; use dh::DH; -use ssl::error::{SslError, OpenSslError}; use x509::{X509StoreContext, X509FileType, X509}; use crypto::pkey::PKey; +use error::ErrorStack; pub mod error; mod bio; @@ -513,9 +513,9 @@ pub type ServerNameCallbackData = fn(ssl: &mut Ssl, ad: &mut i32, data: &T) - // FIXME: macro may be instead of inlining? #[inline] -fn wrap_ssl_result(res: c_int) -> Result<(), SslError> { +fn wrap_ssl_result(res: c_int) -> Result<(), ErrorStack> { if res == 0 { - Err(SslError::get()) + Err(ErrorStack::get()) } else { Ok(()) } @@ -558,7 +558,7 @@ impl SslContext { } /// Creates a new SSL context. - pub fn new(method: SslMethod) -> Result { + pub fn new(method: SslMethod) -> Result { init(); let ctx = try_ssl_null!(unsafe { ffi::SSL_CTX_new(method.to_raw()) }); @@ -647,7 +647,7 @@ impl SslContext { } } - pub fn set_tmp_dh(&self, dh: DH) -> Result<(), SslError> { + pub fn set_tmp_dh(&self, dh: DH) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_tmp_dh(self.ctx, dh.raw()) as i32 }) } @@ -656,13 +656,13 @@ impl SslContext { /// These locations are read from the `SSL_CERT_FILE` and `SSL_CERT_DIR` /// environment variables if present, or defaults specified at OpenSSL /// build time otherwise. - pub fn set_default_verify_paths(&mut self) -> Result<(), SslError> { + pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi::SSL_CTX_set_default_verify_paths(self.ctx) }) } #[allow(non_snake_case)] /// Specifies the file that contains trusted CA certificates. - pub fn set_CA_file>(&mut self, file: P) -> Result<(), SslError> { + pub fn set_CA_file>(&mut self, file: P) -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); wrap_ssl_result(unsafe { ffi::SSL_CTX_load_verify_locations(self.ctx, file.as_ptr() as *const _, ptr::null()) @@ -677,7 +677,7 @@ impl SslContext { /// /// This value should be set when using client certificates, or each request will fail /// handshake and need to be restarted. - pub fn set_session_id_context(&mut self, sid_ctx: &[u8]) -> Result<(), SslError> { + pub fn set_session_id_context(&mut self, sid_ctx: &[u8]) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi::SSL_CTX_set_session_id_context(self.ctx, sid_ctx.as_ptr(), sid_ctx.len() as u32) }) @@ -687,7 +687,7 @@ impl SslContext { pub fn set_certificate_file>(&mut self, file: P, file_type: X509FileType) - -> Result<(), SslError> { + -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); wrap_ssl_result(unsafe { ffi::SSL_CTX_use_certificate_file(self.ctx, @@ -700,7 +700,7 @@ impl SslContext { pub fn set_certificate_chain_file>(&mut self, file: P, file_type: X509FileType) - -> Result<(), SslError> { + -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); wrap_ssl_result(unsafe { ffi::SSL_CTX_use_certificate_chain_file(self.ctx, @@ -710,13 +710,13 @@ impl SslContext { } /// Specifies the certificate - pub fn set_certificate(&mut self, cert: &X509) -> Result<(), SslError> { + pub fn set_certificate(&mut self, cert: &X509) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi::SSL_CTX_use_certificate(self.ctx, cert.get_handle()) }) } /// Adds a certificate to the certificate chain presented together with the /// certificate specified using set_certificate() - pub fn add_extra_chain_cert(&mut self, cert: &X509) -> Result<(), SslError> { + pub fn add_extra_chain_cert(&mut self, cert: &X509) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_add_extra_chain_cert(self.ctx, cert.get_handle()) as c_int }) @@ -726,7 +726,7 @@ impl SslContext { pub fn set_private_key_file>(&mut self, file: P, file_type: X509FileType) - -> Result<(), SslError> { + -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); wrap_ssl_result(unsafe { ffi::SSL_CTX_use_PrivateKey_file(self.ctx, @@ -736,16 +736,16 @@ impl SslContext { } /// Specifies the private key - pub fn set_private_key(&mut self, key: &PKey) -> Result<(), SslError> { + pub fn set_private_key(&mut self, key: &PKey) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi::SSL_CTX_use_PrivateKey(self.ctx, key.get_handle()) }) } /// Check consistency of private key and certificate - pub fn check_private_key(&mut self) -> Result<(), SslError> { + pub fn check_private_key(&mut self) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi::SSL_CTX_check_private_key(self.ctx) }) } - pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), SslError> { + pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { let cipher_list = CString::new(cipher_list).unwrap(); ffi::SSL_CTX_set_cipher_list(self.ctx, cipher_list.as_ptr() as *const _) @@ -757,7 +757,7 @@ impl SslContext { /// /// This method requires OpenSSL >= 1.0.2 or LibreSSL and the `ecdh_auto` feature. #[cfg(feature = "ecdh_auto")] - pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), SslError> { + pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_ecdh_auto(self.ctx, onoff as c_int) }) } @@ -922,7 +922,7 @@ impl Drop for Ssl { } impl Ssl { - pub fn new(ctx: &SslContext) -> Result { + pub fn new(ctx: &SslContext) -> Result { let ssl = try_ssl_null!(unsafe { ffi::SSL_new(ctx.ctx) }); let ssl = Ssl { ssl: ssl }; Ok(ssl) @@ -950,9 +950,9 @@ impl Ssl { unsafe { ffi::SSL_write(self.ssl, buf.as_ptr() as *const c_void, len) } } - fn get_error(&self, ret: c_int) -> LibSslError { + fn get_error(&self, ret: c_int) -> LibErrorStack { let err = unsafe { ffi::SSL_get_error(self.ssl, ret) }; - match LibSslError::from_i32(err as i32) { + match LibErrorStack::from_i32(err as i32) { Some(err) => err, None => unreachable!(), } @@ -1013,7 +1013,7 @@ impl Ssl { } /// Sets the host name to be used with SNI (Server Name Indication). - pub fn set_hostname(&self, hostname: &str) -> Result<(), SslError> { + pub fn set_hostname(&self, hostname: &str) -> Result<(), ErrorStack> { let cstr = CString::new(hostname).unwrap(); let ret = unsafe { ffi_extras::SSL_set_tlsext_host_name(self.ssl, cstr.as_ptr() as *const _) @@ -1021,7 +1021,7 @@ impl Ssl { // For this case, 0 indicates failure. if ret == 0 { - Err(SslError::get()) + Err(ErrorStack::get()) } else { Ok(()) } @@ -1162,18 +1162,18 @@ impl Ssl { } } -macro_rules! make_LibSslError { +macro_rules! make_LibErrorStack { ($($variant:ident = $value:ident),+) => { #[derive(Debug)] #[repr(i32)] - enum LibSslError { + enum LibErrorStack { $($variant = ffi::$value),+ } - impl LibSslError { - fn from_i32(val: i32) -> Option { + impl LibErrorStack { + fn from_i32(val: i32) -> Option { match val { - $(ffi::$value => Some(LibSslError::$variant),)+ + $(ffi::$value => Some(LibErrorStack::$variant),)+ _ => None } } @@ -1181,7 +1181,7 @@ macro_rules! make_LibSslError { } } -make_LibSslError! { +make_LibErrorStack! { ErrorNone = SSL_ERROR_NONE, ErrorSsl = SSL_ERROR_SSL, ErrorWantRead = SSL_ERROR_WANT_READ, @@ -1241,31 +1241,31 @@ impl SslStream { } /// Creates an SSL/TLS client operating over the provided stream. - pub fn connect(ssl: T, stream: S) -> Result { + pub fn connect(ssl: T, stream: S) -> Result { let ssl = try!(ssl.into_ssl()); let mut stream = Self::new_base(ssl, stream); let ret = stream.ssl.connect(); if ret > 0 { Ok(stream) } else { - match stream.make_old_error(ret) { - Some(err) => Err(err), - None => Ok(stream), + match stream.make_error(ret) { + Error::WantRead(..) | Error::WantWrite(..) => Ok(stream), + err => Err(err) } } } /// Creates an SSL/TLS server operating over the provided stream. - pub fn accept(ssl: T, stream: S) -> Result { + pub fn accept(ssl: T, stream: S) -> Result { let ssl = try!(ssl.into_ssl()); let mut stream = Self::new_base(ssl, stream); let ret = stream.ssl.accept(); if ret > 0 { Ok(stream) } else { - match stream.make_old_error(ret) { - Some(err) => Err(err), - None => Ok(stream), + match stream.make_error(ret) { + Error::WantRead(..) | Error::WantWrite(..) => Ok(stream), + err => Err(err) } } } @@ -1302,10 +1302,10 @@ impl SslStream { self.check_panic(); match self.ssl.get_error(ret) { - LibSslError::ErrorSsl => Error::Ssl(OpenSslError::get_stack()), - LibSslError::ErrorSyscall => { - let errs = OpenSslError::get_stack(); - if errs.is_empty() { + LibErrorStack::ErrorSsl => Error::Ssl(ErrorStack::get()), + LibErrorStack::ErrorSyscall => { + let errs = ErrorStack::get(); + if errs.errors().is_empty() { if ret == 0 { Error::Stream(io::Error::new(io::ErrorKind::ConnectionAborted, "unexpected EOF observed")) @@ -1316,9 +1316,9 @@ impl SslStream { Error::Ssl(errs) } } - LibSslError::ErrorZeroReturn => Error::ZeroReturn, - LibSslError::ErrorWantWrite => Error::WantWrite(self.get_bio_error()), - LibSslError::ErrorWantRead => Error::WantRead(self.get_bio_error()), + LibErrorStack::ErrorZeroReturn => Error::ZeroReturn, + LibErrorStack::ErrorWantWrite => Error::WantWrite(self.get_bio_error()), + LibErrorStack::ErrorWantRead => Error::WantRead(self.get_bio_error()), err => { Error::Stream(io::Error::new(io::ErrorKind::Other, format!("unexpected error {:?}", err))) @@ -1326,37 +1326,6 @@ impl SslStream { } } - fn make_old_error(&mut self, ret: c_int) -> Option { - self.check_panic(); - - match self.ssl.get_error(ret) { - LibSslError::ErrorSsl => Some(SslError::get()), - LibSslError::ErrorSyscall => { - let err = SslError::get(); - let count = match err { - SslError::OpenSslErrors(ref v) => v.len(), - _ => unreachable!(), - }; - if count == 0 { - if ret == 0 { - Some(SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, - "unexpected EOF observed"))) - } else { - Some(SslError::StreamError(self.get_bio_error())) - } - } else { - Some(err) - } - } - LibSslError::ErrorZeroReturn => Some(SslError::SslSessionClosed), - LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => None, - err => { - Some(SslError::StreamError(io::Error::new(io::ErrorKind::Other, - format!("unexpected error {:?}", err)))) - } - } - } - #[cfg(feature = "nightly")] fn check_panic(&mut self) { if let Some(err) = unsafe { bio::take_panic::(self.ssl.get_raw_rbio()) } { @@ -1437,17 +1406,17 @@ impl Write for SslStream { } pub trait IntoSsl { - fn into_ssl(self) -> Result; + fn into_ssl(self) -> Result; } impl IntoSsl for Ssl { - fn into_ssl(self) -> Result { + fn into_ssl(self) -> Result { Ok(self) } } impl<'a> IntoSsl for &'a SslContext { - fn into_ssl(self) -> Result { + fn into_ssl(self) -> Result { Ssl::new(self) } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 2ada0065..7f0f3415 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -403,7 +403,7 @@ run_test!(ssl_verify_callback, |method, stream| { } }); - match SslStream::connect_generic(ssl, stream) { + match SslStream::connect(ssl, stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err) } diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 0a242a15..a928b533 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -21,8 +21,8 @@ use crypto::pkey::{PKey, Parts}; use crypto::rand::rand_bytes; use ffi; use ffi_extras; -use ssl::error::{SslError, StreamError}; use nid::Nid; +use error::ErrorStack; pub mod extension; @@ -256,7 +256,7 @@ impl X509Generator { fn add_extension_internal(x509: *mut ffi::X509, exttype: &extension::ExtensionType, value: &str) - -> Result<(), SslError> { + -> Result<(), ErrorStack> { unsafe { let mut ctx: ffi::X509V3_CTX = mem::zeroed(); ffi::X509V3_set_ctx(&mut ctx, x509, x509, ptr::null_mut(), ptr::null_mut(), 0); @@ -288,7 +288,7 @@ impl X509Generator { fn add_name_internal(name: *mut ffi::X509_NAME, key: &str, value: &str) - -> Result<(), SslError> { + -> Result<(), ErrorStack> { let value_len = value.len() as c_int; lift_ssl!(unsafe { let key = CString::new(key.as_bytes()).unwrap(); @@ -319,7 +319,7 @@ impl X509Generator { } /// Generates a private key and a self-signed certificate and returns them - pub fn generate<'a>(&self) -> Result<(X509<'a>, PKey), SslError> { + pub fn generate<'a>(&self) -> Result<(X509<'a>, PKey), ErrorStack> { ffi::init(); let mut p_key = PKey::new(); @@ -331,7 +331,7 @@ impl X509Generator { /// Sets the certificate public-key, then self-sign and return it /// Note: That the bit-length of the private key is used (set_bitlength is ignored) - pub fn sign<'a>(&self, p_key: &PKey) -> Result, SslError> { + pub fn sign<'a>(&self, p_key: &PKey) -> Result, ErrorStack> { ffi::init(); unsafe { @@ -389,7 +389,7 @@ impl X509Generator { } /// Obtain a certificate signing request (CSR) - pub fn request(&self, p_key: &PKey) -> Result { + pub fn request(&self, p_key: &PKey) -> Result { let cert = match self.sign(p_key) { Ok(c) => c, Err(x) => return Err(x), @@ -442,11 +442,11 @@ impl<'ctx> X509<'ctx> { } /// Reads certificate from PEM, takes ownership of handle - pub fn from_pem(reader: &mut R) -> Result, SslError> + pub fn from_pem(reader: &mut R) -> io::Result> where R: Read { let mut mem_bio = try!(MemBio::new()); - try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + try!(io::copy(reader, &mut mem_bio)); unsafe { let handle = try_ssl_null!(ffi::PEM_read_bio_X509(mem_bio.get_handle(), @@ -521,14 +521,14 @@ impl<'ctx> X509<'ctx> { } /// Writes certificate as PEM - pub fn write_pem(&self, writer: &mut W) -> Result<(), SslError> + pub fn write_pem(&self, writer: &mut W) -> io::Result<()> where W: Write { let mut mem_bio = try!(MemBio::new()); unsafe { try_ssl!(ffi::PEM_write_bio_X509(mem_bio.get_handle(), self.handle)); } - io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ()) + io::copy(&mut mem_bio, writer).map(|_| ()) } } @@ -610,11 +610,11 @@ impl X509Req { } /// Reads CSR from PEM - pub fn from_pem(reader: &mut R) -> Result + pub fn from_pem(reader: &mut R) -> io::Result where R: Read { let mut mem_bio = try!(MemBio::new()); - try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + try!(io::copy(reader, &mut mem_bio)); unsafe { let handle = try_ssl_null!(ffi::PEM_read_bio_X509_REQ(mem_bio.get_handle(), @@ -626,14 +626,14 @@ impl X509Req { } /// Writes CSR as PEM - pub fn write_pem(&self, writer: &mut W) -> Result<(), SslError> + pub fn write_pem(&self, writer: &mut W) -> io::Result<()> where W: Write { let mut mem_bio = try!(MemBio::new()); - unsafe { - try_ssl!(ffi::PEM_write_bio_X509_REQ(mem_bio.get_handle(), self.handle)); + if unsafe { ffi::PEM_write_bio_X509_REQ(mem_bio.get_handle(), self.handle) } != 1 { + return Err(io::Error::new(io::ErrorKind::Other, ErrorStack::get())); } - io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ()) + io::copy(&mut mem_bio, writer).map(|_| ()) } }