Merge pull request #486 from sfackler/ref-overhaul

Use actual references for Ref types
This commit is contained in:
Steven Fackler 2016-10-21 20:50:56 -07:00 committed by GitHub
commit 7267cbeae8
10 changed files with 272 additions and 219 deletions

View File

@ -1,20 +1,48 @@
use libc::c_long; use libc::c_long;
use std::{ptr, fmt}; use std::{ptr, fmt};
use std::marker::PhantomData;
use std::ops::Deref; use std::ops::Deref;
use ffi; use ffi;
use opaque::Opaque;
use {cvt, cvt_p}; use {cvt, cvt_p};
use bio::MemBio; use bio::MemBio;
use error::ErrorStack; use error::ErrorStack;
/// A borrowed Asn1Time
pub struct Asn1TimeRef(Opaque);
impl Asn1TimeRef {
/// Creates a new `Asn1TimeRef` wrapping the provided handle.
pub unsafe fn from_ptr<'a>(handle: *mut ffi::ASN1_TIME) -> &'a Asn1TimeRef {
&*(handle as *mut _)
}
/// Returns the raw handle
pub fn as_ptr(&self) -> *mut ffi::ASN1_TIME {
self as *const _ as *mut _
}
}
impl fmt::Display for Asn1TimeRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mem_bio = try!(MemBio::new());
let as_str = unsafe {
try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr())));
String::from_utf8_unchecked(mem_bio.get_buf().to_owned())
};
write!(f, "{}", as_str)
}
}
/// Corresponds to the ASN.1 structure Time defined in RFC5280 /// Corresponds to the ASN.1 structure Time defined in RFC5280
pub struct Asn1Time(Asn1TimeRef<'static>); pub struct Asn1Time(*mut ffi::ASN1_TIME);
impl Asn1Time { impl Asn1Time {
/// Wraps existing ASN1_TIME and takes ownership /// Wraps existing ASN1_TIME and takes ownership
pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1Time { pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1Time {
Asn1Time(Asn1TimeRef::from_ptr(handle)) Asn1Time(handle)
} }
fn from_period(period: c_long) -> Result<Asn1Time, ErrorStack> { fn from_period(period: c_long) -> Result<Asn1Time, ErrorStack> {
@ -33,36 +61,12 @@ impl Asn1Time {
} }
impl Deref for Asn1Time { impl Deref for Asn1Time {
type Target = Asn1TimeRef<'static>; type Target = Asn1TimeRef;
fn deref(&self) -> &Asn1TimeRef<'static> { fn deref(&self) -> &Asn1TimeRef {
&self.0 unsafe {
} Asn1TimeRef::from_ptr(self.0)
} }
/// A borrowed Asn1Time
pub struct Asn1TimeRef<'a>(*mut ffi::ASN1_TIME, PhantomData<&'a ()>);
impl<'a> Asn1TimeRef<'a> {
/// Creates a new `Asn1TimeRef` wrapping the provided handle.
pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1TimeRef<'a> {
Asn1TimeRef(handle, PhantomData)
}
/// Returns the raw handle
pub fn as_ptr(&self) -> *mut ffi::ASN1_TIME {
self.0
}
}
impl<'a> fmt::Display for Asn1TimeRef<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mem_bio = try!(MemBio::new());
let as_str = unsafe {
try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.0)));
String::from_utf8_unchecked(mem_bio.get_buf().to_owned())
};
write!(f, "{}", as_str)
} }
} }

View File

@ -3,11 +3,11 @@ use libc::{c_int, c_void};
use std::cmp::Ordering; use std::cmp::Ordering;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use std::{fmt, ptr}; use std::{fmt, ptr};
use std::marker::PhantomData;
use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut}; use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut};
use {cvt, cvt_p, cvt_n}; use {cvt, cvt_p, cvt_n};
use error::ErrorStack; use error::ErrorStack;
use opaque::Opaque;
/// Specifies the desired properties of a randomly generated `BigNum`. /// Specifies the desired properties of a randomly generated `BigNum`.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
@ -41,6 +41,10 @@ impl BnCtx {
} }
} }
pub fn as_ptr(&self) -> *mut ffi::BN_CTX {
self.0
}
/// Places the result of `a * b` in `r`. /// Places the result of `a * b` in `r`.
pub fn mul(&mut self, pub fn mul(&mut self,
r: &mut BigNumRef, r: &mut BigNumRef,
@ -48,7 +52,7 @@ impl BnCtx {
b: &BigNumRef) b: &BigNumRef)
-> Result<(), ErrorStack> { -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_mul(r.0, a.0, b.0, self.0)).map(|_| ()) cvt(ffi::BN_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ())
} }
} }
@ -60,11 +64,11 @@ impl BnCtx {
b: &BigNumRef) b: &BigNumRef)
-> Result<(), ErrorStack> { -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_div(dv.map(|b| b.0).unwrap_or(ptr::null_mut()), cvt(ffi::BN_div(dv.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()),
rem.map(|b| b.0).unwrap_or(ptr::null_mut()), rem.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()),
a.0, a.as_ptr(),
b.0, b.as_ptr(),
self.0)) self.as_ptr()))
.map(|_| ()) .map(|_| ())
} }
} }
@ -72,7 +76,7 @@ impl BnCtx {
/// Places the result of `a²` in `r`. /// Places the result of `a²` in `r`.
pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.0)).map(|_| ()) cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.as_ptr())).map(|_| ())
} }
} }
@ -159,7 +163,7 @@ impl BnCtx {
a: &BigNumRef, a: &BigNumRef,
n: &BigNumRef) -> Result<(), ErrorStack> { n: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt_p(ffi::BN_mod_inverse(r.0, a.0, n.0, self.0)).map(|_| ()) cvt_p(ffi::BN_mod_inverse(r.as_ptr(), a.as_ptr(), n.as_ptr(), self.as_ptr())).map(|_| ())
} }
} }
@ -169,7 +173,7 @@ impl BnCtx {
a: &BigNumRef, a: &BigNumRef,
b: &BigNumRef) -> Result<(), ErrorStack> { b: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_gcd(r.0, a.0, b.0, self.0)).map(|_| ()) cvt(ffi::BN_gcd(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ())
} }
} }
@ -180,7 +184,7 @@ impl BnCtx {
/// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`.
pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result<bool, ErrorStack> { pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result<bool, ErrorStack> {
unsafe { unsafe {
cvt_n(ffi::BN_is_prime_ex(p.0, checks.into(), self.0, ptr::null_mut())).map(|r| r != 0) cvt_n(ffi::BN_is_prime_ex(p.as_ptr(), checks.into(), self.as_ptr(), ptr::null_mut())).map(|r| r != 0)
} }
} }
@ -198,9 +202,9 @@ impl BnCtx {
checks: i32, checks: i32,
do_trial_division: bool) -> Result<bool, ErrorStack> { do_trial_division: bool) -> Result<bool, ErrorStack> {
unsafe { unsafe {
cvt_n(ffi::BN_is_prime_fasttest_ex(p.0, cvt_n(ffi::BN_is_prime_fasttest_ex(p.as_ptr(),
checks.into(), checks.into(),
self.0, self.as_ptr(),
do_trial_division as c_int, do_trial_division as c_int,
ptr::null_mut())) ptr::null_mut()))
.map(|r| r != 0) .map(|r| r != 0)
@ -220,7 +224,7 @@ impl BnCtx {
odd: bool) odd: bool)
-> Result<(), ErrorStack> { -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_rand(r.0, bits.into(), prop as c_int, odd as c_int)).map(|_| ()) cvt(ffi::BN_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)).map(|_| ())
} }
} }
@ -231,45 +235,52 @@ impl BnCtx {
odd: bool) odd: bool)
-> Result<(), ErrorStack> { -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_pseudo_rand(r.0, bits.into(), prop as c_int, odd as c_int)).map(|_| ()) cvt(ffi::BN_pseudo_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)).map(|_| ())
} }
} }
} }
/// A borrowed, signed, arbitrary-precision integer. /// A borrowed, signed, arbitrary-precision integer.
#[derive(Copy, Clone)] pub struct BigNumRef(Opaque);
pub struct BigNumRef<'a>(*mut ffi::BIGNUM, PhantomData<&'a ()>);
impl<'a> BigNumRef<'a> { impl BigNumRef {
pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNumRef<'a> { pub unsafe fn from_ptr<'a>(handle: *mut ffi::BIGNUM) -> &'a BigNumRef {
BigNumRef(handle, PhantomData) &*(handle as *mut _)
}
pub unsafe fn from_ptr_mut<'a>(handle: *mut ffi::BIGNUM) -> &'a mut BigNumRef {
&mut *(handle as *mut _)
}
pub fn as_ptr(&self) -> *mut ffi::BIGNUM {
self as *const _ as *mut _
} }
/// Adds a `u32` to `self`. /// Adds a `u32` to `self`.
pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_add_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ())
} }
} }
/// Subtracts a `u32` from `self`. /// Subtracts a `u32` from `self`.
pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_sub_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) cvt(ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ())
} }
} }
/// Multiplies a `u32` by `self`. /// Multiplies a `u32` by `self`.
pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_mul_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) cvt(ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ())
} }
} }
/// Divides `self` by a `u32`, returning the remainder. /// Divides `self` by a `u32`, returning the remainder.
pub fn div_word(&mut self, w: u32) -> Result<u64, ErrorStack> { pub fn div_word(&mut self, w: u32) -> Result<u64, ErrorStack> {
unsafe { unsafe {
let r = ffi::BN_div_word(self.0, w.into()); let r = ffi::BN_div_word(self.as_ptr(), w.into());
if r == ffi::BN_ULONG::max_value() { if r == ffi::BN_ULONG::max_value() {
Err(ErrorStack::get()) Err(ErrorStack::get())
} else { } else {
@ -281,7 +292,7 @@ impl<'a> BigNumRef<'a> {
/// Returns the result of `self` modulo `w`. /// Returns the result of `self` modulo `w`.
pub fn mod_word(&self, w: u32) -> Result<u64, ErrorStack> { pub fn mod_word(&self, w: u32) -> Result<u64, ErrorStack> {
unsafe { unsafe {
let r = ffi::BN_mod_word(self.0, w.into()); let r = ffi::BN_mod_word(self.as_ptr(), w.into());
if r == ffi::BN_ULONG::max_value() { if r == ffi::BN_ULONG::max_value() {
Err(ErrorStack::get()) Err(ErrorStack::get())
} else { } else {
@ -294,14 +305,14 @@ impl<'a> BigNumRef<'a> {
/// number less than `self` in `rnd`. /// number less than `self` in `rnd`.
pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_rand_range(self.0, rnd.0)).map(|_| ()) cvt(ffi::BN_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ())
} }
} }
/// The cryptographically weak counterpart to `rand_in_range`. /// The cryptographically weak counterpart to `rand_in_range`.
pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_pseudo_rand_range(self.0, rnd.0)).map(|_| ()) cvt(ffi::BN_pseudo_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ())
} }
} }
@ -310,7 +321,7 @@ impl<'a> BigNumRef<'a> {
/// When setting a bit outside of `self`, it is expanded. /// When setting a bit outside of `self`, it is expanded.
pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_set_bit(self.0, n.into())).map(|_| ()) cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ())
} }
} }
@ -319,14 +330,14 @@ impl<'a> BigNumRef<'a> {
/// When clearing a bit outside of `self`, an error is returned. /// When clearing a bit outside of `self`, an error is returned.
pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_clear_bit(self.0, n.into())).map(|_| ()) cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ())
} }
} }
/// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise.
pub fn is_bit_set(&self, n: i32) -> bool { pub fn is_bit_set(&self, n: i32) -> bool {
unsafe { unsafe {
ffi::BN_is_bit_set(self.0, n.into()) == 1 ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1
} }
} }
@ -335,62 +346,62 @@ impl<'a> BigNumRef<'a> {
/// An error occurs if `self` is already shorter than `n` bits. /// An error occurs if `self` is already shorter than `n` bits.
pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_mask_bits(self.0, n.into())).map(|_| ()) cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ())
} }
} }
/// Places `self << 1` in `r`. /// Places `self << 1` in `r`.
pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_lshift1(r.0, self.0)).map(|_| ()) cvt(ffi::BN_lshift1(r.as_ptr(), self.as_ptr())).map(|_| ())
} }
} }
/// Places `self >> 1` in `r`. /// Places `self >> 1` in `r`.
pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_rshift1(r.0, self.0)).map(|_| ()) cvt(ffi::BN_rshift1(r.as_ptr(), self.as_ptr())).map(|_| ())
} }
} }
/// Places `self + b` in `r`. /// Places `self + b` in `r`.
pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_add(r.0, self.0, b.0)).map(|_| ()) cvt(ffi::BN_add(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ())
} }
} }
/// Places `self - b` in `r`. /// Places `self - b` in `r`.
pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_sub(r.0, self.0, b.0)).map(|_| ()) cvt(ffi::BN_sub(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ())
} }
} }
/// Places `self << n` in `r`. /// Places `self << n` in `r`.
pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> { pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_lshift(r.0, self.0, b.into())).map(|_| ()) cvt(ffi::BN_lshift(r.as_ptr(), self.as_ptr(), b.into())).map(|_| ())
} }
} }
/// Places `self >> n` in `r`. /// Places `self >> n` in `r`.
pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> { pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_rshift(r.0, self.0, n.into())).map(|_| ()) cvt(ffi::BN_rshift(r.as_ptr(), self.as_ptr(), n.into())).map(|_| ())
} }
} }
pub fn to_owned(&self) -> Result<BigNum, ErrorStack> { pub fn to_owned(&self) -> Result<BigNum, ErrorStack> {
unsafe { unsafe {
cvt_p(ffi::BN_dup(self.0)).map(|b| BigNum::from_ptr(b)) cvt_p(ffi::BN_dup(self.as_ptr())).map(|b| BigNum::from_ptr(b))
} }
} }
/// Sets the sign of `self`. /// Sets the sign of `self`.
pub fn set_negative(&mut self, negative: bool) { pub fn set_negative(&mut self, negative: bool) {
unsafe { unsafe {
ffi::BN_set_negative(self.0, negative as c_int) ffi::BN_set_negative(self.as_ptr(), negative as c_int)
} }
} }
@ -406,14 +417,7 @@ impl<'a> BigNumRef<'a> {
/// ``` /// ```
pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { pub fn ucmp(&self, oth: &BigNumRef) -> Ordering {
unsafe { unsafe {
let res = ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()); ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0)
if res < 0 {
Ordering::Less
} else if res > 0 {
Ordering::Greater
} else {
Ordering::Equal
}
} }
} }
@ -441,10 +445,6 @@ impl<'a> BigNumRef<'a> {
(self.num_bits() + 7) / 8 (self.num_bits() + 7) / 8
} }
pub fn as_ptr(&self) -> *mut ffi::BIGNUM {
self.0
}
/// Returns a big-endian byte vector representation of the absolute value of `self`. /// Returns a big-endian byte vector representation of the absolute value of `self`.
/// ///
/// `self` can be recreated by using `new_from_slice`. /// `self` can be recreated by using `new_from_slice`.
@ -510,7 +510,7 @@ impl<'a> BigNumRef<'a> {
/// Additionally, it implements the standard operators (`std::ops`), which /// Additionally, it implements the standard operators (`std::ops`), which
/// perform unchecked arithmetic, unwrapping the returned `Result` of the /// perform unchecked arithmetic, unwrapping the returned `Result` of the
/// checked operations. /// checked operations.
pub struct BigNum(BigNumRef<'static>); pub struct BigNum(*mut ffi::BIGNUM);
impl BigNum { impl BigNum {
/// Creates a new `BigNum` with the value 0. /// Creates a new `BigNum` with the value 0.
@ -550,7 +550,7 @@ impl BigNum {
} }
pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNum { pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNum {
BigNum(BigNumRef::from_ptr(handle)) BigNum(handle)
} }
/// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length.
@ -584,11 +584,11 @@ impl BigNum {
rem: Option<&BigNumRef>) rem: Option<&BigNumRef>)
-> Result<(), ErrorStack> { -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::BN_generate_prime_ex(r.0, cvt(ffi::BN_generate_prime_ex(r.as_ptr(),
bits as c_int, bits as c_int,
safe as c_int, safe as c_int,
add.map(|n| n.0).unwrap_or(ptr::null_mut()), add.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()),
rem.map(|n| n.0).unwrap_or(ptr::null_mut()), rem.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()),
ptr::null_mut())) ptr::null_mut()))
.map(|_| ()) .map(|_| ())
} }
@ -602,26 +602,30 @@ impl Drop for BigNum {
} }
impl Deref for BigNum { impl Deref for BigNum {
type Target = BigNumRef<'static>; type Target = BigNumRef;
fn deref(&self) -> &BigNumRef<'static> { fn deref(&self) -> &BigNumRef {
&self.0 unsafe {
BigNumRef::from_ptr(self.0)
}
} }
} }
impl DerefMut for BigNum { impl DerefMut for BigNum {
fn deref_mut(&mut self) -> &mut BigNumRef<'static> { fn deref_mut(&mut self) -> &mut BigNumRef {
&mut self.0 unsafe {
BigNumRef::from_ptr_mut(self.0)
}
} }
} }
impl AsRef<BigNumRef<'static>> for BigNum { impl AsRef<BigNumRef> for BigNum {
fn as_ref(&self) -> &BigNumRef<'static> { fn as_ref(&self) -> &BigNumRef {
self.deref() self.deref()
} }
} }
impl<'a> fmt::Debug for BigNumRef<'a> { impl fmt::Debug for BigNumRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.to_dec_str() { match self.to_dec_str() {
Ok(s) => f.write_str(&s), Ok(s) => f.write_str(&s),
@ -639,7 +643,7 @@ impl fmt::Debug for BigNum {
} }
} }
impl<'a> fmt::Display for BigNumRef<'a> { impl fmt::Display for BigNumRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.to_dec_str() { match self.to_dec_str() {
Ok(s) => f.write_str(&s), Ok(s) => f.write_str(&s),
@ -657,19 +661,19 @@ impl fmt::Display for BigNum {
} }
} }
impl<'a, 'b> PartialEq<BigNumRef<'b>> for BigNumRef<'a> { impl PartialEq<BigNumRef> for BigNumRef {
fn eq(&self, oth: &BigNumRef) -> bool { fn eq(&self, oth: &BigNumRef) -> bool {
self.cmp(oth) == Ordering::Equal self.cmp(oth) == Ordering::Equal
} }
} }
impl<'a> PartialEq<BigNum> for BigNumRef<'a> { impl PartialEq<BigNum> for BigNumRef {
fn eq(&self, oth: &BigNum) -> bool { fn eq(&self, oth: &BigNum) -> bool {
self.eq(oth.deref()) self.eq(oth.deref())
} }
} }
impl<'a> Eq for BigNumRef<'a> {} impl Eq for BigNumRef {}
impl PartialEq for BigNum { impl PartialEq for BigNum {
fn eq(&self, oth: &BigNum) -> bool { fn eq(&self, oth: &BigNum) -> bool {
@ -677,7 +681,7 @@ impl PartialEq for BigNum {
} }
} }
impl<'a> PartialEq<BigNumRef<'a>> for BigNum { impl PartialEq<BigNumRef> for BigNum {
fn eq(&self, oth: &BigNumRef) -> bool { fn eq(&self, oth: &BigNumRef) -> bool {
self.deref().eq(oth) self.deref().eq(oth)
} }
@ -685,19 +689,19 @@ impl<'a> PartialEq<BigNumRef<'a>> for BigNum {
impl Eq for BigNum {} impl Eq for BigNum {}
impl<'a, 'b> PartialOrd<BigNumRef<'b>> for BigNumRef<'a> { impl PartialOrd<BigNumRef> for BigNumRef {
fn partial_cmp(&self, oth: &BigNumRef) -> Option<Ordering> { fn partial_cmp(&self, oth: &BigNumRef) -> Option<Ordering> {
Some(self.cmp(oth)) Some(self.cmp(oth))
} }
} }
impl<'a> PartialOrd<BigNum> for BigNumRef<'a> { impl PartialOrd<BigNum> for BigNumRef {
fn partial_cmp(&self, oth: &BigNum) -> Option<Ordering> { fn partial_cmp(&self, oth: &BigNum) -> Option<Ordering> {
Some(self.cmp(oth.deref())) Some(self.cmp(oth.deref()))
} }
} }
impl<'a> Ord for BigNumRef<'a> { impl Ord for BigNumRef {
fn cmp(&self, oth: &BigNumRef) -> Ordering { fn cmp(&self, oth: &BigNumRef) -> Ordering {
unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) }
} }
@ -709,7 +713,7 @@ impl PartialOrd for BigNum {
} }
} }
impl<'a> PartialOrd<BigNumRef<'a>> for BigNum { impl PartialOrd<BigNumRef> for BigNum {
fn partial_cmp(&self, oth: &BigNumRef) -> Option<Ordering> { fn partial_cmp(&self, oth: &BigNumRef) -> Option<Ordering> {
self.deref().partial_cmp(oth) self.deref().partial_cmp(oth)
} }
@ -723,7 +727,7 @@ impl Ord for BigNum {
macro_rules! delegate { macro_rules! delegate {
($t:ident, $m:ident) => { ($t:ident, $m:ident) => {
impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef<'a> { impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn $m(self, oth: &BigNum) -> BigNum { fn $m(self, oth: &BigNum) -> BigNum {
@ -731,7 +735,7 @@ macro_rules! delegate {
} }
} }
impl<'a, 'b> $t<&'b BigNumRef<'b>> for &'a BigNum { impl<'a, 'b> $t<&'b BigNumRef> for &'a BigNum {
type Output = BigNum; type Output = BigNum;
fn $m(self, oth: &BigNumRef) -> BigNum { fn $m(self, oth: &BigNumRef) -> BigNum {
@ -749,7 +753,7 @@ macro_rules! delegate {
} }
} }
impl<'a, 'b> Add<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn add(self, oth: &BigNumRef) -> BigNum { fn add(self, oth: &BigNumRef) -> BigNum {
@ -761,7 +765,7 @@ impl<'a, 'b> Add<&'b BigNumRef<'b>> for &'a BigNumRef<'a> {
delegate!(Add, add); delegate!(Add, add);
impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn sub(self, oth: &BigNumRef) -> BigNum { fn sub(self, oth: &BigNumRef) -> BigNum {
@ -773,7 +777,7 @@ impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNumRef<'a> {
delegate!(Sub, sub); delegate!(Sub, sub);
impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn mul(self, oth: &BigNumRef) -> BigNum { fn mul(self, oth: &BigNumRef) -> BigNum {
@ -786,10 +790,10 @@ impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNumRef<'a> {
delegate!(Mul, mul); delegate!(Mul, mul);
impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { fn div(self, oth: &'b BigNumRef) -> BigNum {
let mut ctx = BnCtx::new().unwrap(); let mut ctx = BnCtx::new().unwrap();
let mut dv = BigNum::new().unwrap(); let mut dv = BigNum::new().unwrap();
ctx.div(Some(&mut dv), None, self, oth).unwrap(); ctx.div(Some(&mut dv), None, self, oth).unwrap();
@ -799,10 +803,10 @@ impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNumRef<'a> {
delegate!(Div, div); delegate!(Div, div);
impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { fn rem(self, oth: &'b BigNumRef) -> BigNum {
let mut ctx = BnCtx::new().unwrap(); let mut ctx = BnCtx::new().unwrap();
let mut rem = BigNum::new().unwrap(); let mut rem = BigNum::new().unwrap();
ctx.div(None, Some(&mut rem), self, oth).unwrap(); ctx.div(None, Some(&mut rem), self, oth).unwrap();
@ -812,7 +816,7 @@ impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNumRef<'a> {
delegate!(Rem, rem); delegate!(Rem, rem);
impl<'a> Shl<i32> for &'a BigNumRef<'a> { impl<'a> Shl<i32> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn shl(self, n: i32) -> BigNum { fn shl(self, n: i32) -> BigNum {
@ -830,7 +834,7 @@ impl<'a> Shl<i32> for &'a BigNum {
} }
} }
impl<'a> Shr<i32> for &'a BigNumRef<'a> { impl<'a> Shr<i32> for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn shr(self, n: i32) -> BigNum { fn shr(self, n: i32) -> BigNum {
@ -848,7 +852,7 @@ impl<'a> Shr<i32> for &'a BigNum {
} }
} }
impl<'a> Neg for &'a BigNumRef<'a> { impl<'a> Neg for &'a BigNumRef {
type Output = BigNum; type Output = BigNum;
fn neg(self) -> BigNum { fn neg(self) -> BigNum {

View File

@ -155,7 +155,7 @@ impl DSA {
self.0 self.0
} }
pub fn p<'a>(&'a self) -> Option<BigNumRef<'a>> { pub fn p(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let p = compat::pqg(self.0)[0]; let p = compat::pqg(self.0)[0];
if p.is_null() { if p.is_null() {
@ -166,7 +166,7 @@ impl DSA {
} }
} }
pub fn q<'a>(&'a self) -> Option<BigNumRef<'a>> { pub fn q(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let q = compat::pqg(self.0)[1]; let q = compat::pqg(self.0)[1];
if q.is_null() { if q.is_null() {
@ -177,7 +177,7 @@ impl DSA {
} }
} }
pub fn g<'a>(&'a self) -> Option<BigNumRef<'a>> { pub fn g(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let g = compat::pqg(self.0)[2]; let g = compat::pqg(self.0)[2];
if g.is_null() { if g.is_null() {

View File

@ -267,7 +267,7 @@ impl RSA {
self.0 self.0
} }
pub fn n<'a>(&'a self) -> Option<BigNumRef<'a>> { pub fn n(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let n = compat::key(self.0)[0]; let n = compat::key(self.0)[0];
if n.is_null() { if n.is_null() {
@ -278,7 +278,7 @@ impl RSA {
} }
} }
pub fn d<'a>(&self) -> Option<BigNumRef<'a>> { pub fn d(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let d = compat::key(self.0)[2]; let d = compat::key(self.0)[2];
if d.is_null() { if d.is_null() {
@ -289,7 +289,7 @@ impl RSA {
} }
} }
pub fn e<'a>(&'a self) -> Option<BigNumRef<'a>> { pub fn e(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let e = compat::key(self.0)[1]; let e = compat::key(self.0)[1];
if e.is_null() { if e.is_null() {
@ -300,7 +300,7 @@ impl RSA {
} }
} }
pub fn p<'a>(&'a self) -> Option<BigNumRef<'a>> { pub fn p(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let p = compat::factors(self.0)[0]; let p = compat::factors(self.0)[0];
if p.is_null() { if p.is_null() {
@ -311,7 +311,7 @@ impl RSA {
} }
} }
pub fn q<'a>(&'a self) -> Option<BigNumRef<'a>> { pub fn q(&self) -> Option<&BigNumRef> {
unsafe { unsafe {
let q = compat::factors(self.0)[1]; let q = compat::factors(self.0)[1];
if q.is_null() { if q.is_null() {

View File

@ -32,6 +32,7 @@ pub mod nid;
pub mod ssl; pub mod ssl;
pub mod version; pub mod version;
pub mod x509; pub mod x509;
mod opaque;
pub fn cvt_p<T>(r: *mut T) -> Result<*mut T, ErrorStack> { pub fn cvt_p<T>(r: *mut T) -> Result<*mut T, ErrorStack> {
if r.is_null() { if r.is_null() {

6
openssl/src/opaque.rs Normal file
View File

@ -0,0 +1,6 @@
use std::cell::UnsafeCell;
/// This is intended to be used as the inner type for types designed to be pointed to by references
/// converted from raw C pointers. It has an `UnsafeCell` internally to inform the compiler about
/// aliasability and doesn't implement `Copy`, so it can't be dereferenced.
pub struct Opaque(UnsafeCell<()>);

View File

@ -26,6 +26,7 @@ use x509::{X509StoreContext, X509FileType, X509, X509Ref, X509VerifyError};
use x509::verify::X509VerifyParamRef; use x509::verify::X509VerifyParamRef;
use crypto::pkey::PKey; use crypto::pkey::PKey;
use error::ErrorStack; use error::ErrorStack;
use opaque::Opaque;
pub mod error; pub mod error;
mod bio; mod bio;
@ -210,9 +211,9 @@ extern fn raw_sni<F>(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::<F>()); let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::<F>());
let callback: &F = &*(callback as *mut F); let callback: &F = &*(callback as *mut F);
let mut ssl = SslRef::from_ptr(ssl); let ssl = SslRef::from_ptr_mut(ssl);
match callback(&mut ssl) { match callback(ssl) {
Ok(()) => ffi::SSL_TLSEXT_ERR_OK, Ok(()) => ffi::SSL_TLSEXT_ERR_OK,
Err(SniError::Fatal(e)) => { Err(SniError::Fatal(e)) => {
*al = e; *al = e;
@ -335,15 +336,19 @@ pub enum SniError {
} }
/// A borrowed SSL context object. /// A borrowed SSL context object.
pub struct SslContextRef<'a>(*mut ffi::SSL_CTX, PhantomData<&'a ()>); pub struct SslContextRef(Opaque);
impl<'a> SslContextRef<'a> { impl SslContextRef {
pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextRef<'a> { pub unsafe fn from_ptr<'a>(ctx: *mut ffi::SSL_CTX) -> &'a SslContextRef {
SslContextRef(ctx, PhantomData) &*(ctx as *mut _)
}
pub unsafe fn from_ptr_mut<'a>(ctx: *mut ffi::SSL_CTX) -> &'a mut SslContextRef {
&mut *(ctx as *mut _)
} }
pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { pub fn as_ptr(&self) -> *mut ffi::SSL_CTX {
self.0 self as *const _ as *mut _
} }
/// Configures the certificate verification method for new connections. /// Configures the certificate verification method for new connections.
@ -626,7 +631,7 @@ impl<'a> SslContextRef<'a> {
} }
/// An owned SSL context object. /// An owned SSL context object.
pub struct SslContext(SslContextRef<'static>); pub struct SslContext(*mut ffi::SSL_CTX);
unsafe impl Send for SslContext {} unsafe impl Send for SslContext {}
unsafe impl Sync for SslContext {} unsafe impl Sync for SslContext {}
@ -654,16 +659,20 @@ impl Drop for SslContext {
} }
impl Deref for SslContext { impl Deref for SslContext {
type Target = SslContextRef<'static>; type Target = SslContextRef;
fn deref(&self) -> &SslContextRef<'static> { fn deref(&self) -> &SslContextRef {
&self.0 unsafe {
SslContextRef::from_ptr(self.0)
}
} }
} }
impl DerefMut for SslContext { impl DerefMut for SslContext {
fn deref_mut(&mut self) -> &mut SslContextRef<'static> { fn deref_mut(&mut self) -> &mut SslContextRef {
&mut self.0 unsafe {
SslContextRef::from_ptr_mut(self.0)
}
} }
} }
@ -683,11 +692,11 @@ impl SslContext {
} }
pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContext { pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContext {
SslContext(SslContextRef::from_ptr(ctx)) SslContext(ctx)
} }
pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { pub fn as_ptr(&self) -> *mut ffi::SSL_CTX {
(**self).as_ptr() self.0
} }
} }
@ -700,16 +709,21 @@ pub struct CipherBits {
pub algorithm: i32, pub algorithm: i32,
} }
pub struct SslCipher<'a> { pub struct SslCipherRef(Opaque);
cipher: *const ffi::SSL_CIPHER,
ph: PhantomData<&'a ()>, impl SslCipherRef {
} pub unsafe fn from_ptr<'a>(ptr: *const ffi::SSL_CIPHER) -> &'a SslCipherRef {
&*(ptr as *const _)
}
pub fn as_ptr(&self) -> *const ffi::SSL_CIPHER {
self as *const _ as *const _
}
impl<'a> SslCipher<'a> {
/// Returns the name of cipher. /// Returns the name of cipher.
pub fn name(&self) -> &'static str { pub fn name(&self) -> &'static str {
let name = unsafe { let name = unsafe {
let ptr = ffi::SSL_CIPHER_get_name(self.cipher); let ptr = ffi::SSL_CIPHER_get_name(self.as_ptr());
CStr::from_ptr(ptr as *const _) CStr::from_ptr(ptr as *const _)
}; };
@ -719,7 +733,7 @@ impl<'a> SslCipher<'a> {
/// Returns the SSL/TLS protocol version that first defined the cipher. /// Returns the SSL/TLS protocol version that first defined the cipher.
pub fn version(&self) -> &'static str { pub fn version(&self) -> &'static str {
let version = unsafe { let version = unsafe {
let ptr = ffi::SSL_CIPHER_get_version(self.cipher); let ptr = ffi::SSL_CIPHER_get_version(self.as_ptr());
CStr::from_ptr(ptr as *const _) CStr::from_ptr(ptr as *const _)
}; };
@ -730,7 +744,7 @@ impl<'a> SslCipher<'a> {
pub fn bits(&self) -> CipherBits { pub fn bits(&self) -> CipherBits {
unsafe { unsafe {
let mut algo_bits = 0; let mut algo_bits = 0;
let secret_bits = ffi::SSL_CIPHER_get_bits(self.cipher, &mut algo_bits); let secret_bits = ffi::SSL_CIPHER_get_bits(self.as_ptr(), &mut algo_bits);
CipherBits { CipherBits {
secret: secret_bits.into(), secret: secret_bits.into(),
algorithm: algo_bits.into(), algorithm: algo_bits.into(),
@ -743,7 +757,7 @@ impl<'a> SslCipher<'a> {
unsafe { unsafe {
// SSL_CIPHER_description requires a buffer of at least 128 bytes. // SSL_CIPHER_description requires a buffer of at least 128 bytes.
let mut buf = [0; 128]; let mut buf = [0; 128];
let desc_ptr = ffi::SSL_CIPHER_description(self.cipher, buf.as_mut_ptr(), 128); let desc_ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128);
if !desc_ptr.is_null() { if !desc_ptr.is_null() {
String::from_utf8(CStr::from_ptr(desc_ptr as *const _).to_bytes().to_vec()).ok() String::from_utf8(CStr::from_ptr(desc_ptr as *const _).to_bytes().to_vec()).ok()
@ -754,12 +768,12 @@ impl<'a> SslCipher<'a> {
} }
} }
pub struct SslRef<'a>(*mut ffi::SSL, PhantomData<&'a ()>); pub struct SslRef(Opaque);
unsafe impl<'a> Send for SslRef<'a> {} unsafe impl Send for SslRef {}
unsafe impl<'a> Sync for SslRef<'a> {} unsafe impl Sync for SslRef {}
impl<'a> fmt::Debug for SslRef<'a> { impl fmt::Debug for SslRef {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut builder = fmt.debug_struct("SslRef"); let mut builder = fmt.debug_struct("SslRef");
builder.field("state", &self.state_string_long()); builder.field("state", &self.state_string_long());
@ -770,13 +784,17 @@ impl<'a> fmt::Debug for SslRef<'a> {
} }
} }
impl<'a> SslRef<'a> { impl SslRef {
pub unsafe fn from_ptr(ssl: *mut ffi::SSL) -> SslRef<'a> { pub unsafe fn from_ptr<'a>(ssl: *mut ffi::SSL) -> &'a SslRef {
SslRef(ssl, PhantomData) &*(ssl as *mut _)
}
pub unsafe fn from_ptr_mut<'a>(ssl: *mut ffi::SSL) -> &'a mut SslRef {
&mut *(ssl as *mut _)
} }
pub fn as_ptr(&self) -> *mut ffi::SSL { pub fn as_ptr(&self) -> *mut ffi::SSL {
self.0 self as *const _ as *mut _
} }
fn get_raw_rbio(&self) -> *mut ffi::BIO { fn get_raw_rbio(&self) -> *mut ffi::BIO {
@ -823,17 +841,14 @@ impl<'a> SslRef<'a> {
} }
} }
pub fn current_cipher(&self) -> Option<SslCipher<'a>> { pub fn current_cipher(&self) -> Option<&SslCipherRef> {
unsafe { unsafe {
let ptr = ffi::SSL_get_current_cipher(self.as_ptr()); let ptr = ffi::SSL_get_current_cipher(self.as_ptr());
if ptr.is_null() { if ptr.is_null() {
None None
} else { } else {
Some(SslCipher { Some(SslCipherRef::from_ptr(ptr))
cipher: ptr,
ph: PhantomData,
})
} }
} }
} }
@ -965,13 +980,15 @@ impl<'a> SslRef<'a> {
} }
/// Returns the server's name for the current connection /// Returns the server's name for the current connection
pub fn servername(&self) -> Option<String> { pub fn servername(&self) -> Option<&str> {
let name = unsafe { ffi::SSL_get_servername(self.as_ptr(), ffi::TLSEXT_NAMETYPE_host_name) }; unsafe {
if name == ptr::null() { let name = ffi::SSL_get_servername(self.as_ptr(), ffi::TLSEXT_NAMETYPE_host_name);
return None; if name == ptr::null() {
} return None;
}
unsafe { String::from_utf8(CStr::from_ptr(name as *const _).to_bytes().to_vec()).ok() } Some(str::from_utf8(CStr::from_ptr(name as *const _).to_bytes()).unwrap())
}
} }
/// Changes the context corresponding to the current connection. /// Changes the context corresponding to the current connection.
@ -982,7 +999,7 @@ impl<'a> SslRef<'a> {
} }
/// Returns the context corresponding to the current connection /// Returns the context corresponding to the current connection
pub fn ssl_context(&self) -> SslContextRef<'a> { pub fn ssl_context(&self) -> &SslContextRef {
unsafe { unsafe {
let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr()); let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr());
SslContextRef::from_ptr(ssl_ctx) SslContextRef::from_ptr(ssl_ctx)
@ -993,21 +1010,21 @@ impl<'a> SslRef<'a> {
/// ///
/// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0.
#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))]
pub fn param(&mut self) -> X509VerifyParamRef<'a> { pub fn param_mut(&mut self) -> &mut X509VerifyParamRef {
unsafe { unsafe {
X509VerifyParamRef::from_ptr(ffi::SSL_get0_param(self.as_ptr())) X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr()))
} }
} }
/// Returns the result of X509 certificate verification. /// Returns the result of X509 certificate verification.
pub fn verify_result(&self) -> Option<X509VerifyError> { pub fn verify_result(&self) -> Option<X509VerifyError> {
unsafe { unsafe {
X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.0)) X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.as_ptr()))
} }
} }
} }
pub struct Ssl(SslRef<'static>); pub struct Ssl(*mut ffi::SSL);
impl fmt::Debug for Ssl { impl fmt::Debug for Ssl {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
@ -1027,16 +1044,20 @@ impl Drop for Ssl {
} }
impl Deref for Ssl { impl Deref for Ssl {
type Target = SslRef<'static>; type Target = SslRef;
fn deref(&self) -> &SslRef<'static> { fn deref(&self) -> &SslRef {
&self.0 unsafe {
SslRef::from_ptr(self.0)
}
} }
} }
impl DerefMut for Ssl { impl DerefMut for Ssl {
fn deref_mut(&mut self) -> &mut SslRef<'static> { fn deref_mut(&mut self) -> &mut SslRef {
&mut self.0 unsafe {
SslRef::from_ptr_mut(self.0)
}
} }
} }
@ -1049,7 +1070,7 @@ impl Ssl {
} }
pub unsafe fn from_ptr(ssl: *mut ffi::SSL) -> Ssl { pub unsafe fn from_ptr(ssl: *mut ffi::SSL) -> Ssl {
Ssl(SslRef::from_ptr(ssl)) Ssl(ssl)
} }
/// Creates an SSL/TLS client operating over the provided stream. /// Creates an SSL/TLS client operating over the provided stream.

View File

@ -479,7 +479,7 @@ fn test_pending() {
fn test_state() { fn test_state() {
let (_s, tcp) = Server::new(); let (_s, tcp) = Server::new();
let ctx = SslContext::new(SslMethod::tls()).unwrap(); let ctx = SslContext::new(SslMethod::tls()).unwrap();
let mut stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); let stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap();
assert_eq!(stream.ssl().state_string(), "SSLOK "); assert_eq!(stream.ssl().state_string(), "SSLOK ");
assert_eq!(stream.ssl().state_string_long(), assert_eq!(stream.ssl().state_string_long(),
"SSL negotiation finished successfully"); "SSL negotiation finished successfully");
@ -1053,8 +1053,8 @@ fn valid_hostname() {
ctx.set_verify(SSL_VERIFY_PEER); ctx.set_verify(SSL_VERIFY_PEER);
let mut ssl = Ssl::new(&ctx).unwrap(); let mut ssl = Ssl::new(&ctx).unwrap();
ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); ssl.param_mut().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
ssl.param().set_host("google.com").unwrap(); ssl.param_mut().set_host("google.com").unwrap();
let s = TcpStream::connect("google.com:443").unwrap(); let s = TcpStream::connect("google.com:443").unwrap();
let mut socket = ssl.connect(s).unwrap(); let mut socket = ssl.connect(s).unwrap();
@ -1077,8 +1077,8 @@ fn invalid_hostname() {
ctx.set_verify(SSL_VERIFY_PEER); ctx.set_verify(SSL_VERIFY_PEER);
let mut ssl = Ssl::new(&ctx).unwrap(); let mut ssl = Ssl::new(&ctx).unwrap();
ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); ssl.param_mut().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
ssl.param().set_host("foobar.com").unwrap(); ssl.param_mut().set_host("foobar.com").unwrap();
let s = TcpStream::connect("google.com:443").unwrap(); let s = TcpStream::connect("google.com:443").unwrap();
assert!(ssl.connect(s).is_err()); assert!(ssl.connect(s).is_err());

View File

@ -18,9 +18,10 @@ use bio::{MemBio, MemBioSlice};
use crypto::hash::MessageDigest; use crypto::hash::MessageDigest;
use crypto::pkey::PKey; use crypto::pkey::PKey;
use crypto::rand::rand_bytes; use crypto::rand::rand_bytes;
use error::ErrorStack;
use ffi; use ffi;
use nid::Nid; use nid::Nid;
use error::ErrorStack; use opaque::Opaque;
#[cfg(ossl10x)] #[cfg(ossl10x)]
use ffi::{ use ffi::{
@ -106,7 +107,7 @@ impl X509StoreContext {
} }
} }
pub fn current_cert<'a>(&'a self) -> Option<X509Ref<'a>> { pub fn current_cert<'a>(&'a self) -> Option<&'a X509Ref> {
unsafe { unsafe {
let ptr = ffi::X509_STORE_CTX_get_current_cert(self.ctx); let ptr = ffi::X509_STORE_CTX_get_current_cert(self.ctx);
if ptr.is_null() { if ptr.is_null() {
@ -389,27 +390,29 @@ impl X509Generator {
} }
/// A borrowed public key certificate. /// A borrowed public key certificate.
pub struct X509Ref<'a>(*mut ffi::X509, PhantomData<&'a ()>); pub struct X509Ref(Opaque);
impl<'a> X509Ref<'a> { impl X509Ref {
/// Creates a new `X509Ref` wrapping the provided handle. /// Creates a new `X509Ref` wrapping the provided handle.
pub unsafe fn from_ptr(x509: *mut ffi::X509) -> X509Ref<'a> { pub unsafe fn from_ptr<'a>(x509: *mut ffi::X509) -> &'a X509Ref {
X509Ref(x509, PhantomData) &*(x509 as *mut _)
} }
pub fn as_ptr(&self) -> *mut ffi::X509 { pub fn as_ptr(&self) -> *mut ffi::X509 {
self.0 self as *const _ as *mut _
} }
pub fn subject_name<'b>(&'b self) -> X509Name<'b> { pub fn subject_name(&self) -> &X509NameRef {
let name = unsafe { ffi::X509_get_subject_name(self.0) }; unsafe {
X509Name(name, PhantomData) let name = ffi::X509_get_subject_name(self.as_ptr());
X509NameRef::from_ptr(name)
}
} }
/// Returns this certificate's SAN entries, if they exist. /// Returns this certificate's SAN entries, if they exist.
pub fn subject_alt_names(&self) -> Option<GeneralNames> { pub fn subject_alt_names(&self) -> Option<GeneralNames> {
unsafe { unsafe {
let stack = ffi::X509_get_ext_d2i(self.0, let stack = ffi::X509_get_ext_d2i(self.as_ptr(),
Nid::SubjectAltName as c_int, Nid::SubjectAltName as c_int,
ptr::null_mut(), ptr::null_mut(),
ptr::null_mut()); ptr::null_mut());
@ -425,7 +428,7 @@ impl<'a> X509Ref<'a> {
pub fn public_key(&self) -> Result<PKey, ErrorStack> { pub fn public_key(&self) -> Result<PKey, ErrorStack> {
unsafe { unsafe {
let pkey = try!(cvt_p(ffi::X509_get_pubkey(self.0))); let pkey = try!(cvt_p(ffi::X509_get_pubkey(self.as_ptr())));
Ok(PKey::from_ptr(pkey)) Ok(PKey::from_ptr(pkey))
} }
} }
@ -436,25 +439,25 @@ impl<'a> X509Ref<'a> {
let evp = hash_type.as_ptr(); let evp = hash_type.as_ptr();
let mut len = ffi::EVP_MAX_MD_SIZE; let mut len = ffi::EVP_MAX_MD_SIZE;
let mut buf = vec![0u8; len as usize]; let mut buf = vec![0u8; len as usize];
try!(cvt(ffi::X509_digest(self.0, evp, buf.as_mut_ptr() as *mut _, &mut len))); try!(cvt(ffi::X509_digest(self.as_ptr(), evp, buf.as_mut_ptr() as *mut _, &mut len)));
buf.truncate(len as usize); buf.truncate(len as usize);
Ok(buf) Ok(buf)
} }
} }
/// Returns certificate Not After validity period. /// Returns certificate Not After validity period.
pub fn not_after<'b>(&'b self) -> Asn1TimeRef<'b> { pub fn not_after<'a>(&'a self) -> &'a Asn1TimeRef {
unsafe { unsafe {
let date = compat::X509_get_notAfter(self.0); let date = compat::X509_get_notAfter(self.as_ptr());
assert!(!date.is_null()); assert!(!date.is_null());
Asn1TimeRef::from_ptr(date) Asn1TimeRef::from_ptr(date)
} }
} }
/// Returns certificate Not Before validity period. /// Returns certificate Not Before validity period.
pub fn not_before<'b>(&'b self) -> Asn1TimeRef<'b> { pub fn not_before<'a>(&'a self) -> &'a Asn1TimeRef {
unsafe { unsafe {
let date = compat::X509_get_notBefore(self.0); let date = compat::X509_get_notBefore(self.as_ptr());
assert!(!date.is_null()); assert!(!date.is_null());
Asn1TimeRef::from_ptr(date) Asn1TimeRef::from_ptr(date)
} }
@ -464,7 +467,7 @@ impl<'a> X509Ref<'a> {
pub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack> { pub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
let mem_bio = try!(MemBio::new()); let mem_bio = try!(MemBio::new());
unsafe { unsafe {
try!(cvt(ffi::PEM_write_bio_X509(mem_bio.as_ptr(), self.0))); try!(cvt(ffi::PEM_write_bio_X509(mem_bio.as_ptr(), self.as_ptr())));
} }
Ok(mem_bio.get_buf().to_owned()) Ok(mem_bio.get_buf().to_owned())
} }
@ -473,19 +476,19 @@ impl<'a> X509Ref<'a> {
pub fn to_der(&self) -> Result<Vec<u8>, ErrorStack> { pub fn to_der(&self) -> Result<Vec<u8>, ErrorStack> {
let mem_bio = try!(MemBio::new()); let mem_bio = try!(MemBio::new());
unsafe { unsafe {
ffi::i2d_X509_bio(mem_bio.as_ptr(), self.0); ffi::i2d_X509_bio(mem_bio.as_ptr(), self.as_ptr());
} }
Ok(mem_bio.get_buf().to_owned()) Ok(mem_bio.get_buf().to_owned())
} }
} }
/// An owned public key certificate. /// An owned public key certificate.
pub struct X509(X509Ref<'static>); pub struct X509(*mut ffi::X509);
impl X509 { impl X509 {
/// Returns a new `X509`, taking ownership of the handle. /// Returns a new `X509`, taking ownership of the handle.
pub unsafe fn from_ptr(x509: *mut ffi::X509) -> X509 { pub unsafe fn from_ptr(x509: *mut ffi::X509) -> X509 {
X509(X509Ref::from_ptr(x509)) X509(x509)
} }
/// Reads a certificate from DER. /// Reads a certificate from DER.
@ -512,10 +515,12 @@ impl X509 {
} }
impl Deref for X509 { impl Deref for X509 {
type Target = X509Ref<'static>; type Target = X509Ref;
fn deref(&self) -> &X509Ref<'static> { fn deref(&self) -> &X509Ref {
&self.0 unsafe {
X509Ref::from_ptr(self.0)
}
} }
} }
@ -534,17 +539,25 @@ impl Drop for X509 {
} }
} }
pub struct X509Name<'x>(*mut ffi::X509_NAME, PhantomData<&'x ()>); pub struct X509NameRef(Opaque);
impl X509NameRef {
pub unsafe fn from_ptr<'a>(ptr: *mut ffi::X509_NAME) -> &'a X509NameRef {
&*(ptr as *mut _)
}
pub fn as_ptr(&self) -> *mut ffi::X509_NAME {
self as *const _ as *mut _
}
impl<'x> X509Name<'x> {
pub fn text_by_nid(&self, nid: Nid) -> Option<SslString> { pub fn text_by_nid(&self, nid: Nid) -> Option<SslString> {
unsafe { unsafe {
let loc = ffi::X509_NAME_get_index_by_NID(self.0, nid as c_int, -1); let loc = ffi::X509_NAME_get_index_by_NID(self.as_ptr(), nid as c_int, -1);
if loc == -1 { if loc == -1 {
return None; return None;
} }
let ne = ffi::X509_NAME_get_entry(self.0, loc); let ne = ffi::X509_NAME_get_entry(self.as_ptr(), loc);
if ne.is_null() { if ne.is_null() {
return None; return None;
} }

View File

@ -2,12 +2,12 @@
//! //!
//! Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. //! Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0.
use std::marker::PhantomData;
use libc::c_uint; use libc::c_uint;
use ffi; use ffi;
use cvt; use cvt;
use error::ErrorStack; use error::ErrorStack;
use opaque::Opaque;
bitflags! { bitflags! {
pub flags X509CheckFlags: c_uint { pub flags X509CheckFlags: c_uint {
@ -23,22 +23,26 @@ bitflags! {
} }
} }
pub struct X509VerifyParamRef<'a>(*mut ffi::X509_VERIFY_PARAM, PhantomData<&'a mut ()>); pub struct X509VerifyParamRef(Opaque);
impl<'a> X509VerifyParamRef<'a> { impl X509VerifyParamRef {
pub unsafe fn from_ptr(ptr: *mut ffi::X509_VERIFY_PARAM) -> X509VerifyParamRef<'a> { pub unsafe fn from_ptr_mut<'a>(ptr: *mut ffi::X509_VERIFY_PARAM) -> &'a mut X509VerifyParamRef {
X509VerifyParamRef(ptr, PhantomData) &mut *(ptr as *mut _)
}
pub fn as_ptr(&self) -> *mut ffi::X509_VERIFY_PARAM {
self as *const _ as *mut _
} }
pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) { pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) {
unsafe { unsafe {
ffi::X509_VERIFY_PARAM_set_hostflags(self.0, hostflags.bits); ffi::X509_VERIFY_PARAM_set_hostflags(self.as_ptr(), hostflags.bits);
} }
} }
pub fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> { pub fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> {
unsafe { unsafe {
cvt(ffi::X509_VERIFY_PARAM_set1_host(self.0, cvt(ffi::X509_VERIFY_PARAM_set1_host(self.as_ptr(),
host.as_ptr() as *const _, host.as_ptr() as *const _,
host.len())) host.len()))
.map(|_| ()) .map(|_| ())