From cb4263f91e6d772e097c9c4a366921b68d804585 Mon Sep 17 00:00:00 2001 From: Geoffroy Couprie Date: Sat, 21 Nov 2015 17:46:39 +0100 Subject: test SNI support --- openssl/src/ssl/mod.rs | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index cca369a2..f73c263a 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -32,6 +32,7 @@ pub mod error; mod tests; static mut VERIFY_IDX: c_int = -1; +static mut SNI_IDX: c_int = -1; /// Manually initialize SSL. /// It is optional to call this function and safe to do so more than once. @@ -46,6 +47,11 @@ pub fn init() { None, None); assert!(verify_idx >= 0); VERIFY_IDX = verify_idx; + + let sni_idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None, + None, None); + assert!(sni_idx >= 0); + SNI_IDX = sni_idx; }); } } @@ -297,6 +303,51 @@ extern fn raw_verify_with_data(preverify_ok: c_int, } } +extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_void) + -> c_int { + println!("openssl called raw_sni. ad=={:?}", *ad); + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX); + let callback: Option = mem::transmute(callback); + let mut ssl = Ssl { ssl: ssl }; + println!("openssl got callback"); + + let res = match callback { + None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL, + Some(callback) => callback(&mut ssl, ad) + }; + println!("openssl got callback result: {}", res); + res + } +} + +extern fn raw_sni_with_data(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_void) -> c_int + where T: Any + 'static { + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); + + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX); + let callback: Option> = mem::transmute(callback); + let mut ssl = Ssl { ssl: ssl }; + + let data: Box = mem::transmute(arg); + + let res = match callback { + None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL, + Some(callback) => callback(&mut ssl, ad, &*data) + }; + + // Since data might be required on the next verification + // it is time to forget about it and avoid dropping + // data will be freed once OpenSSL considers it is time + // to free all context data + mem::forget(data); + res + } +} + + #[cfg(any(feature = "npn", feature = "alpn"))] unsafe fn select_proto_using(ssl: *mut ffi::SSL, out: *mut *mut c_uchar, outlen: *mut c_uchar, @@ -404,6 +455,11 @@ pub type VerifyCallbackData = fn(preverify_ok: bool, x509_ctx: &X509StoreContext, data: &T) -> bool; +/// The signature of functions that can be used to choose the context depending on the server name +pub type ServerNameCallback = fn(ssl: &mut Ssl, ad: &mut i32) -> i32; + +pub type ServerNameCallbackData = fn(ssl: &mut Ssl, ad: &mut i32, data: &T) -> i32; + // FIXME: macro may be instead of inlining? #[inline] fn wrap_ssl_result(res: c_int) -> Result<(),SslError> { @@ -485,6 +541,31 @@ impl SslContext { } } + /// Configures the certificate verification method for new connections. + pub fn set_servername_callback(&mut self, callback: Option) { + unsafe { + ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, + mem::transmute(callback)); + //let f: extern fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int = raw_sni; + let f: extern fn() = mem::transmute(raw_sni); + ffi::SSL_CTX_callback_ctrl(self.ctx, ffi::SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, Some(f)); + } + } + + pub fn set_servername_callback_with_data(&mut self, callback: ServerNameCallbackData, + data: T) + where T: Any + 'static { + let data = Box::new(data); + unsafe { + ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, + mem::transmute(Some(callback))); + + ffi::SSL_CTX_ctrl(self.ctx, ffi::SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, mem::transmute(data)); + let f: extern fn() = mem::transmute(raw_sni_with_data::); + ffi::SSL_CTX_callback_ctrl(self.ctx, ffi::SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, Some(f)); + } + } + /// Sets verification depth pub fn set_verify_depth(&mut self, depth: u32) { unsafe { @@ -673,6 +754,7 @@ impl SslContext { ffi::SSL_CTX_set_alpn_select_cb(self.ctx, raw_alpn_select_cb, ptr::null_mut()); } } + } #[allow(dead_code)] @@ -886,6 +968,20 @@ impl Ssl { SslMethod::from_raw(method) } } + + /// Returns the server name for the current connection + pub fn get_servername(&self) -> Option { + let name = unsafe { ffi::SSL_get_servername(self.ssl, ffi::TLSEXT_NAMETYPE_host_name) }; + if name == ptr::null() { + return None; + } + + println!("openssl will return servername"); + unsafe { + String::from_utf8(CStr::from_ptr(name).to_bytes().to_vec()).ok() + } + } + } macro_rules! make_LibSslError { -- cgit v1.2.3 From dba3a0ced24147414abaa9f8394b9f249b08f599 Mon Sep 17 00:00:00 2001 From: Geoffroy Couprie Date: Sun, 22 Nov 2015 20:01:41 +0100 Subject: implement get/set ssl context --- openssl/src/ssl/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index f73c263a..736e6b4c 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -982,6 +982,14 @@ impl Ssl { } } + pub fn set_ssl_context(&self, ctx: &SslContext) -> SslContext { + SslContext { ctx: unsafe { ffi::SSL_set_SSL_CTX(self.ssl, ctx.ctx) } } + } + + pub fn get_ssl_context(&self) -> SslContext { + let ssl_ctx = unsafe { ffi::SSL_get_SSL_CTX(self.ssl) }; + SslContext { ctx: ssl_ctx } + } } macro_rules! make_LibSslError { -- cgit v1.2.3 From 667e3f44b99450fbf9b1d80a8949183ce295fbf8 Mon Sep 17 00:00:00 2001 From: Geoffroy Couprie Date: Sun, 22 Nov 2015 20:01:56 +0100 Subject: Avoid freeing the SSL object when Ssl is dropped --- openssl/src/ssl/mod.rs | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 736e6b4c..e49b28b2 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -305,19 +305,19 @@ extern fn raw_verify_with_data(preverify_ok: c_int, extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_void) -> c_int { - println!("openssl called raw_sni. ad=={:?}", *ad); unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX); let callback: Option = mem::transmute(callback); - let mut ssl = Ssl { ssl: ssl }; - println!("openssl got callback"); + let mut s = Ssl { ssl: ssl }; let res = match callback { None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL, - Some(callback) => callback(&mut ssl, ad) + Some(callback) => callback(&mut s, ad) }; - println!("openssl got callback result: {}", res); + + // Allows dropping the Ssl instance without calling SSL_FREE on the SSL object + s.ssl = ptr::null_mut() as *mut ffi::SSL; res } } @@ -329,15 +329,18 @@ extern fn raw_sni_with_data(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_v let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX); let callback: Option> = mem::transmute(callback); - let mut ssl = Ssl { ssl: ssl }; + let mut s = Ssl { ssl: ssl }; let data: Box = mem::transmute(arg); let res = match callback { None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL, - Some(callback) => callback(&mut ssl, ad, &*data) + Some(callback) => callback(&mut s, ad, &*data) }; + // Allows dropping the Ssl instance without calling SSL_FREE on the SSL object + s.ssl = ptr::null_mut() as *mut ffi::SSL; + // Since data might be required on the next verification // it is time to forget about it and avoid dropping // data will be freed once OpenSSL considers it is time @@ -541,7 +544,10 @@ impl SslContext { } } - /// Configures the certificate verification method for new connections. + /// Configures the server name indication (SNI) callback for new connections + /// + /// obtain the server name with `get_servername` then set the corresponding context + /// with `set_ssl_context` pub fn set_servername_callback(&mut self, callback: Option) { unsafe { ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, @@ -552,6 +558,8 @@ impl SslContext { } } + /// Configures the server name indication (SNI) callback for new connections + /// carrying supplied data pub fn set_servername_callback_with_data(&mut self, callback: ServerNameCallbackData, data: T) where T: Any + 'static { @@ -969,23 +977,24 @@ impl Ssl { } } - /// Returns the server name for the current connection + /// Returns the server's name for the current connection pub fn get_servername(&self) -> Option { let name = unsafe { ffi::SSL_get_servername(self.ssl, ffi::TLSEXT_NAMETYPE_host_name) }; if name == ptr::null() { return None; } - println!("openssl will return servername"); unsafe { String::from_utf8(CStr::from_ptr(name).to_bytes().to_vec()).ok() } } + /// change the context corresponding to the current connection pub fn set_ssl_context(&self, ctx: &SslContext) -> SslContext { SslContext { ctx: unsafe { ffi::SSL_set_SSL_CTX(self.ssl, ctx.ctx) } } } + /// obtain the context corresponding to the current connection pub fn get_ssl_context(&self) -> SslContext { let ssl_ctx = unsafe { ffi::SSL_get_SSL_CTX(self.ssl) }; SslContext { ctx: ssl_ctx } -- cgit v1.2.3 From e48694432008c752d17dbe08a26a2f7fbeb18155 Mon Sep 17 00:00:00 2001 From: Geoffroy Couprie Date: Wed, 25 Nov 2015 07:51:22 +0100 Subject: fix memory management --- openssl/src/ssl/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index e49b28b2..8de09396 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -317,7 +317,7 @@ extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_void) }; // Allows dropping the Ssl instance without calling SSL_FREE on the SSL object - s.ssl = ptr::null_mut() as *mut ffi::SSL; + mem::forget(s); res } } @@ -331,7 +331,7 @@ extern fn raw_sni_with_data(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_v let callback: Option> = mem::transmute(callback); let mut s = Ssl { ssl: ssl }; - let data: Box = mem::transmute(arg); + let data: &T = mem::transmute(arg); let res = match callback { None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL, @@ -339,13 +339,12 @@ extern fn raw_sni_with_data(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_v }; // Allows dropping the Ssl instance without calling SSL_FREE on the SSL object - s.ssl = ptr::null_mut() as *mut ffi::SSL; + mem::forget(s); // Since data might be required on the next verification // it is time to forget about it and avoid dropping // data will be freed once OpenSSL considers it is time // to free all context data - mem::forget(data); res } } @@ -552,7 +551,6 @@ impl SslContext { unsafe { ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, mem::transmute(callback)); - //let f: extern fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int = raw_sni; let f: extern fn() = mem::transmute(raw_sni); ffi::SSL_CTX_callback_ctrl(self.ctx, ffi::SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, Some(f)); } -- cgit v1.2.3 From 7835ea1c906450c524b8575a668860ee9e0b2d85 Mon Sep 17 00:00:00 2001 From: Geoffroy Couprie Date: Wed, 25 Nov 2015 08:10:36 +0100 Subject: Make shims for SSL_CTX_ctrl and SSL_CTX_callback_ctrl macro wrappers --- openssl/src/ssl/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 8de09396..b25e7d28 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -552,7 +552,7 @@ impl SslContext { ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, mem::transmute(callback)); let f: extern fn() = mem::transmute(raw_sni); - ffi::SSL_CTX_callback_ctrl(self.ctx, ffi::SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, Some(f)); + ffi_extras::SSL_CTX_set_tlsext_servername_callback(self.ctx, Some(f)); } } @@ -566,9 +566,9 @@ impl SslContext { ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, mem::transmute(Some(callback))); - ffi::SSL_CTX_ctrl(self.ctx, ffi::SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, mem::transmute(data)); + ffi_extras::SSL_CTX_set_tlsext_servername_arg(self.ctx, mem::transmute(data)); let f: extern fn() = mem::transmute(raw_sni_with_data::); - ffi::SSL_CTX_callback_ctrl(self.ctx, ffi::SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, Some(f)); + ffi_extras::SSL_CTX_set_tlsext_servername_callback(self.ctx, Some(f)); } } -- cgit v1.2.3 From f54af75eb7f8c861383119722f548cb2866ca813 Mon Sep 17 00:00:00 2001 From: Ondrej Perutka Date: Mon, 30 Nov 2015 21:06:54 +0100 Subject: Cast correctly c_char raw pointers (fixes build on ARM #314) --- openssl/src/ssl/mod.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index cca369a2..a26b714a 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -510,7 +510,7 @@ impl SslContext { 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(), ptr::null()) + ffi::SSL_CTX_load_verify_locations(self.ctx, file.as_ptr() as *const _, ptr::null()) }) } @@ -520,7 +520,7 @@ impl SslContext { 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, file.as_ptr(), file_type as c_int) + ffi::SSL_CTX_use_certificate_file(self.ctx, file.as_ptr() as *const _, file_type as c_int) }) } @@ -530,7 +530,7 @@ impl SslContext { 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, file.as_ptr(), file_type as c_int) + ffi::SSL_CTX_use_certificate_chain_file(self.ctx, file.as_ptr() as *const _, file_type as c_int) }) } @@ -557,7 +557,7 @@ impl SslContext { 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, file.as_ptr(), file_type as c_int) + ffi::SSL_CTX_use_PrivateKey_file(self.ctx, file.as_ptr() as *const _, file_type as c_int) }) } @@ -581,7 +581,7 @@ impl SslContext { wrap_ssl_result( unsafe { let cipher_list = CString::new(cipher_list).unwrap(); - ffi::SSL_CTX_set_cipher_list(self.ctx, cipher_list.as_ptr()) + ffi::SSL_CTX_set_cipher_list(self.ctx, cipher_list.as_ptr() as *const _) }) } @@ -768,7 +768,7 @@ impl Ssl { pub fn state_string(&self) -> &'static str { let state = unsafe { let ptr = ffi::SSL_state_string(self.ssl); - CStr::from_ptr(ptr) + CStr::from_ptr(ptr as *const _) }; str::from_utf8(state.to_bytes()).unwrap() @@ -777,7 +777,7 @@ impl Ssl { pub fn state_string_long(&self) -> &'static str { let state = unsafe { let ptr = ffi::SSL_state_string_long(self.ssl); - CStr::from_ptr(ptr) + CStr::from_ptr(ptr as *const _) }; str::from_utf8(state.to_bytes()).unwrap() @@ -786,7 +786,7 @@ impl Ssl { /// Sets the host name to be used with SNI (Server Name Indication). pub fn set_hostname(&self, hostname: &str) -> Result<(), SslError> { let cstr = CString::new(hostname).unwrap(); - let ret = unsafe { ffi_extras::SSL_set_tlsext_host_name(self.ssl, cstr.as_ptr()) }; + let ret = unsafe { ffi_extras::SSL_set_tlsext_host_name(self.ssl, cstr.as_ptr() as *const _) }; // For this case, 0 indicates failure. if ret == 0 { @@ -874,7 +874,7 @@ impl Ssl { let meth = unsafe { ffi::SSL_COMP_get_name(ptr) }; let s = unsafe { - String::from_utf8(CStr::from_ptr(meth).to_bytes().to_vec()).unwrap() + String::from_utf8(CStr::from_ptr(meth as *const _).to_bytes().to_vec()).unwrap() }; Some(s) -- cgit v1.2.3 From 6850c810d32a11330c9b1dd4889b447fa8434c36 Mon Sep 17 00:00:00 2001 From: Geoffroy Couprie Date: Thu, 3 Dec 2015 12:26:55 +0100 Subject: Increment SSL_CTX's reference count in Ssl::get_ssl_context() Without this, whenever the returned SslContext is released, the refcount of the underlying SSL_CTX will decrease and it will be freed too soon --- openssl/src/ssl/mod.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index b25e7d28..a2096f41 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -995,6 +995,7 @@ impl Ssl { /// obtain the context corresponding to the current connection pub fn get_ssl_context(&self) -> SslContext { let ssl_ctx = unsafe { ffi::SSL_get_SSL_CTX(self.ssl) }; + let count = unsafe { ffi_extras::SSL_CTX_increment_refcount(ssl_ctx) }; SslContext { ctx: ssl_ctx } } } -- cgit v1.2.3 From 4d883d488eed9431ebd8ec4e2b5a45d9cbf2e0d8 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 8 Dec 2015 21:57:04 -0800 Subject: Custom BIO infrastructure --- openssl/src/ssl/mod.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index a26b714a..2f09e4fa 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -28,6 +28,7 @@ use x509::{X509StoreContext, X509FileType, X509}; use crypto::pkey::PKey; pub mod error; +mod bio; #[cfg(test)] mod tests; -- cgit v1.2.3 From 9ee6f1c5785bb170c04a825ef173d4e336c957b2 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 9 Dec 2015 21:43:02 -0800 Subject: IT LIVES --- openssl/src/ssl/mod.rs | 101 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 2f09e4fa..5d24fc32 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -18,6 +18,7 @@ use std::any::Any; use libc::{c_uchar, c_uint}; #[cfg(any(feature = "npn", feature = "alpn"))] use std::slice; +use std::marker::PhantomData; use bio::{MemBio}; use ffi; @@ -724,6 +725,10 @@ impl Ssl { Ok(ssl) } + fn get_raw_rbio(&self) -> *mut ffi::BIO { + unsafe { ffi::SSL_get_rbio(self.ssl) } + } + fn get_rbio<'a>(&'a self) -> MemBioRef<'a> { unsafe { self.wrap_bio(ffi::SSL_get_rbio(self.ssl)) } } @@ -1345,6 +1350,102 @@ impl Write for SslStream { } } +pub struct SslStreamNg { + ssl: Ssl, + _method: Box, // :( + _p: PhantomData, +} + +impl Drop for SslStreamNg { + fn drop(&mut self) { + unsafe { + let _ = bio::take_stream::(self.ssl.get_raw_rbio()); + } + } +} + +impl SslStreamNg { + fn new_base(ssl: Ssl, stream: S) -> Result { + unsafe { + let (bio, method) = try!(bio::new(stream)); + ffi::SSL_set_bio(ssl.ssl, bio, bio); + + Ok(SslStreamNg { + ssl: ssl, + _method: method, + _p: PhantomData, + }) + } + } + + /// Creates an SSL/TLS client operating over the provided stream. + pub fn connect(ssl: T, stream: S) -> Result { + let ssl = try!(ssl.into_ssl()); + let mut stream = try!(Self::new_base(ssl, stream)); + let ret = stream.ssl.connect(); + if ret > 0 { + Ok(stream) + } else { + Err(stream.make_error(ret)) + } + } + + /// Creates an SSL/TLS server operating over the provided stream. + pub fn accept(ssl: T, stream: S) -> Result { + let ssl = try!(ssl.into_ssl()); + let mut stream = try!(Self::new_base(ssl, stream)); + let ret = stream.ssl.accept(); + if ret > 0 { + Ok(stream) + } else { + Err(stream.make_error(ret)) + } + } + + pub fn get_ref(&self) -> &S { + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_ref(bio) + } + } + + pub fn mut_ref(&mut self) -> &mut S { + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_mut(bio) + } + } + + fn make_error(&mut self, ret: c_int) -> SslError { + match self.ssl.get_error(ret) { + LibSslError::ErrorSsl => 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 { + SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, + "unexpected EOF observed")) + } else { + let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; + SslError::StreamError(error.unwrap()) + } + } else { + err + } + } + LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => { + let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; + SslError::StreamError(error.unwrap()) + } + err => panic!("unexpected error {:?} with ret {}", err, ret), + } + } +} + pub trait IntoSsl { fn into_ssl(self) -> Result; } -- cgit v1.2.3 From 8f56897043f8138980ce3376765b769c764d8701 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 9 Dec 2015 22:02:02 -0800 Subject: Implement read and write --- openssl/src/ssl/mod.rs | 226 ++++++++++++++++++++++++++++--------------------- 1 file changed, 130 insertions(+), 96 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 5d24fc32..e12d694d 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1350,102 +1350,6 @@ impl Write for SslStream { } } -pub struct SslStreamNg { - ssl: Ssl, - _method: Box, // :( - _p: PhantomData, -} - -impl Drop for SslStreamNg { - fn drop(&mut self) { - unsafe { - let _ = bio::take_stream::(self.ssl.get_raw_rbio()); - } - } -} - -impl SslStreamNg { - fn new_base(ssl: Ssl, stream: S) -> Result { - unsafe { - let (bio, method) = try!(bio::new(stream)); - ffi::SSL_set_bio(ssl.ssl, bio, bio); - - Ok(SslStreamNg { - ssl: ssl, - _method: method, - _p: PhantomData, - }) - } - } - - /// Creates an SSL/TLS client operating over the provided stream. - pub fn connect(ssl: T, stream: S) -> Result { - let ssl = try!(ssl.into_ssl()); - let mut stream = try!(Self::new_base(ssl, stream)); - let ret = stream.ssl.connect(); - if ret > 0 { - Ok(stream) - } else { - Err(stream.make_error(ret)) - } - } - - /// Creates an SSL/TLS server operating over the provided stream. - pub fn accept(ssl: T, stream: S) -> Result { - let ssl = try!(ssl.into_ssl()); - let mut stream = try!(Self::new_base(ssl, stream)); - let ret = stream.ssl.accept(); - if ret > 0 { - Ok(stream) - } else { - Err(stream.make_error(ret)) - } - } - - pub fn get_ref(&self) -> &S { - unsafe { - let bio = self.ssl.get_raw_rbio(); - bio::get_ref(bio) - } - } - - pub fn mut_ref(&mut self) -> &mut S { - unsafe { - let bio = self.ssl.get_raw_rbio(); - bio::get_mut(bio) - } - } - - fn make_error(&mut self, ret: c_int) -> SslError { - match self.ssl.get_error(ret) { - LibSslError::ErrorSsl => 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 { - SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, - "unexpected EOF observed")) - } else { - let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; - SslError::StreamError(error.unwrap()) - } - } else { - err - } - } - LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => { - let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; - SslError::StreamError(error.unwrap()) - } - err => panic!("unexpected error {:?} with ret {}", err, ret), - } - } -} - pub trait IntoSsl { fn into_ssl(self) -> Result; } @@ -1756,3 +1660,133 @@ impl NonblockingSslStream { } } } + +pub struct SslStreamNg { + ssl: Ssl, + _method: Box, // :( + _p: PhantomData, +} + +impl Drop for SslStreamNg { + fn drop(&mut self) { + unsafe { + let _ = bio::take_stream::(self.ssl.get_raw_rbio()); + } + } +} + +impl SslStreamNg { + fn new_base(ssl: Ssl, stream: S) -> Result { + unsafe { + let (bio, method) = try!(bio::new(stream)); + ffi::SSL_set_bio(ssl.ssl, bio, bio); + + Ok(SslStreamNg { + ssl: ssl, + _method: method, + _p: PhantomData, + }) + } + } + + /// Creates an SSL/TLS client operating over the provided stream. + pub fn connect(ssl: T, stream: S) -> Result { + let ssl = try!(ssl.into_ssl()); + let mut stream = try!(Self::new_base(ssl, stream)); + let ret = stream.ssl.connect(); + if ret > 0 { + Ok(stream) + } else { + Err(stream.make_error(ret)) + } + } + + /// Creates an SSL/TLS server operating over the provided stream. + pub fn accept(ssl: T, stream: S) -> Result { + let ssl = try!(ssl.into_ssl()); + let mut stream = try!(Self::new_base(ssl, stream)); + let ret = stream.ssl.accept(); + if ret > 0 { + Ok(stream) + } else { + Err(stream.make_error(ret)) + } + } +} + +impl SslStreamNg { + pub fn get_ref(&self) -> &S { + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_ref(bio) + } + } + + pub fn get_mut(&mut self) -> &mut S { + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_mut(bio) + } + } + + fn make_error(&mut self, ret: c_int) -> SslError { + match self.ssl.get_error(ret) { + LibSslError::ErrorSsl => 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 { + SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, + "unexpected EOF observed")) + } else { + let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; + SslError::StreamError(error.unwrap()) + } + } else { + err + } + } + LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => { + let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; + SslError::StreamError(error.unwrap()) + } + err => panic!("unexpected error {:?} with ret {}", err, ret), + } + } +} + +impl Read for SslStreamNg { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let ret = self.ssl.read(buf); + if ret >= 0 { + return Ok(ret as usize); + } + + match self.make_error(ret) { + SslError::StreamError(e) => Err(e), + e => Err(io::Error::new(io::ErrorKind::Other, e)), + } + } +} + +impl Write for SslStreamNg { + fn write(&mut self, buf: &[u8]) -> io::Result { + let ret = self.ssl.write(buf); + if ret > 0 { + return Ok(ret as usize); + } + + match self.make_error(ret) { + SslError::StreamError(e) => Err(e), + e => Err(io::Error::new(io::ErrorKind::Other, e)), + } + } + + fn flush(&mut self) -> io::Result<()> { + self.get_mut().flush() + } +} -- cgit v1.2.3 From 91f8c542f75ff81ce7f3f12f26c469127ff0ab18 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 9 Dec 2015 23:30:29 -0800 Subject: Replace SslStream implementation! --- openssl/src/ssl/mod.rs | 625 +++++++++---------------------------------------- 1 file changed, 113 insertions(+), 512 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index e12d694d..5ac6d33e 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -11,7 +11,6 @@ use std::net; use std::path::Path; use std::ptr; use std::sync::{Once, ONCE_INIT, Arc, Mutex}; -use std::ops::{Deref, DerefMut}; use std::cmp; use std::any::Any; #[cfg(any(feature = "npn", feature = "alpn"))] @@ -20,11 +19,10 @@ use libc::{c_uchar, c_uint}; use std::slice; use std::marker::PhantomData; -use bio::{MemBio}; use ffi; use ffi_extras; use dh::DH; -use ssl::error::{NonblockingSslError, SslError, SslSessionClosed, StreamError, OpenSslErrors}; +use ssl::error::{NonblockingSslError, SslError, StreamError, OpenSslErrors}; use x509::{X509StoreContext, X509FileType, X509}; use crypto::pkey::PKey; @@ -33,6 +31,10 @@ mod bio; #[cfg(test)] mod tests; +extern "C" { + fn rust_SSL_clone(ssl: *mut ffi::SSL); +} + static mut VERIFY_IDX: c_int = -1; /// Manually initialize SSL. @@ -677,26 +679,6 @@ impl SslContext { } } -#[allow(dead_code)] -struct MemBioRef<'ssl> { - ssl: &'ssl Ssl, - bio: MemBio, -} - -impl<'ssl> Deref for MemBioRef<'ssl> { - type Target = MemBio; - - fn deref(&self) -> &MemBio { - &self.bio - } -} - -impl<'ssl> DerefMut for MemBioRef<'ssl> { - fn deref_mut(&mut self) -> &mut MemBio { - &mut self.bio - } -} - pub struct Ssl { ssl: *mut ffi::SSL } @@ -718,6 +700,14 @@ impl Drop for Ssl { } } +impl Clone for Ssl { + fn clone(&self) -> Ssl { + unsafe { rust_SSL_clone(self.ssl) }; + Ssl { ssl: self.ssl } + + } +} + impl Ssl { pub fn new(ctx: &SslContext) -> Result { let ssl = try_ssl_null!(unsafe { ffi::SSL_new(ctx.ctx) }); @@ -729,22 +719,6 @@ impl Ssl { unsafe { ffi::SSL_get_rbio(self.ssl) } } - fn get_rbio<'a>(&'a self) -> MemBioRef<'a> { - unsafe { self.wrap_bio(ffi::SSL_get_rbio(self.ssl)) } - } - - fn get_wbio<'a>(&'a self) -> MemBioRef<'a> { - unsafe { self.wrap_bio(ffi::SSL_get_wbio(self.ssl)) } - } - - fn wrap_bio<'a>(&'a self, bio: *mut ffi::BIO) -> MemBioRef<'a> { - assert!(bio != ptr::null_mut()); - MemBioRef { - ssl: self, - bio: MemBio::borrowed(bio) - } - } - fn connect(&self) -> c_int { unsafe { ffi::SSL_connect(self.ssl) } } @@ -925,182 +899,94 @@ make_LibSslError! { ErrorWantAccept = SSL_ERROR_WANT_ACCEPT } -struct IndirectStream { - stream: S, - ssl: Arc, - // Max TLS record size is 16k - buf: Box<[u8; 16 * 1024]>, -} - -impl Clone for IndirectStream { - fn clone(&self) -> IndirectStream { - IndirectStream { - stream: self.stream.clone(), - ssl: self.ssl.clone(), - buf: Box::new(*self.buf) - } - } -} - -impl IndirectStream { - fn try_clone(&self) -> io::Result> { - Ok(IndirectStream { - stream: try!(self.stream.try_clone()), - ssl: self.ssl.clone(), - buf: Box::new(*self.buf) - }) - } +/// A stream wrapper which handles SSL encryption for an underlying stream. +pub struct SslStream { + ssl: Ssl, + _method: Box, // :( + _p: PhantomData, } -impl IndirectStream { - fn new_base(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - - let rbio = try!(MemBio::new()); - let wbio = try!(MemBio::new()); - - unsafe { ffi::SSL_set_bio(ssl.ssl, rbio.unwrap(), wbio.unwrap()) } - - Ok(IndirectStream { - stream: stream, - ssl: Arc::new(ssl), - buf: Box::new([0; 16 * 1024]), - }) - } - - fn connect(ssl: T, stream: S) -> Result, SslError> { - let mut ssl = try!(IndirectStream::new_base(ssl, stream)); - try!(ssl.in_retry_wrapper(|ssl| ssl.connect())); - Ok(ssl) - } +unsafe impl Send for SslStream {} - fn accept(ssl: T, stream: S) -> Result, SslError> { - let mut ssl = try!(IndirectStream::new_base(ssl, stream)); - try!(ssl.in_retry_wrapper(|ssl| ssl.accept())); - Ok(ssl) - } - - fn in_retry_wrapper(&mut self, mut blk: F) -> Result - where F: FnMut(&Ssl) -> c_int { - loop { - let ret = blk(&self.ssl); - if ret > 0 { - return Ok(ret); - } - - let e = self.ssl.get_error(ret); - match e { - LibSslError::ErrorWantRead => { - try_ssl_stream!(self.flush()); - let len = try_ssl_stream!(self.stream.read(&mut self.buf[..])); - - - if len == 0 { - let method = self.ssl.get_ssl_method(); - - if method.map(|m| m.is_dtls()).unwrap_or(false) { - return Ok(0); - } else { - self.ssl.get_rbio().set_eof(true); - } - } else { - try_ssl_stream!(self.ssl.get_rbio().write_all(&self.buf[..len])); - } - } - LibSslError::ErrorWantWrite => { try_ssl_stream!(self.flush()) } - LibSslError::ErrorZeroReturn => return Err(SslSessionClosed), - LibSslError::ErrorSsl => return Err(SslError::get()), - LibSslError::ErrorSyscall if ret == 0 => return Ok(0), - err => panic!("unexpected error {:?} with ret {}", err, ret), - } - } - } - - fn write_through(&mut self) -> io::Result<()> { - io::copy(&mut *self.ssl.get_wbio(), &mut self.stream).map(|_| ()) +impl Clone for SslStream { + fn clone(&self) -> SslStream { + let stream = self.get_ref().clone(); + Self::new_base(self.ssl.clone(), stream) } } -impl Read for IndirectStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - match self.in_retry_wrapper(|ssl| { ssl.read(buf) }) { - Ok(len) => Ok(len as usize), - Err(SslSessionClosed) => Ok(0), - Err(StreamError(e)) => Err(e), - Err(e @ OpenSslErrors(_)) => { - Err(io::Error::new(io::ErrorKind::Other, e)) - } +impl Drop for SslStream { + fn drop(&mut self) { + unsafe { + let _ = bio::take_stream::(self.ssl.get_raw_rbio()); } } } -impl Write for IndirectStream { - fn write(&mut self, buf: &[u8]) -> io::Result { - let count = match self.in_retry_wrapper(|ssl| ssl.write(buf)) { - Ok(len) => len as usize, - Err(SslSessionClosed) => 0, - Err(StreamError(e)) => return Err(e), - Err(e @ OpenSslErrors(_)) => return Err(io::Error::new(io::ErrorKind::Other, e)), - }; - try!(self.write_through()); - Ok(count) - } - - fn flush(&mut self) -> io::Result<()> { - try!(self.write_through()); - self.stream.flush() - } -} - -#[derive(Clone)] -struct DirectStream { - stream: S, - ssl: Arc, -} - -impl DirectStream { - fn try_clone(&self) -> io::Result> { - Ok(DirectStream { - stream: try!(self.stream.try_clone()), - ssl: self.ssl.clone(), - }) +impl fmt::Debug for SslStream where S: fmt::Debug { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("SslStream") + .field("stream", &self.get_ref()) + .field("ssl", &self.ssl()) + .finish() } } -impl DirectStream { - fn new_base(ssl: Ssl, stream: S, sock: c_int) -> Result, SslError> { +impl SslStream { + fn new_base(ssl: Ssl, stream: S) -> Self { unsafe { - let bio = try_ssl_null!(ffi::BIO_new_socket(sock, 0)); + let (bio, method) = bio::new(stream).unwrap(); ffi::SSL_set_bio(ssl.ssl, bio, bio); - } - Ok(DirectStream { - stream: stream, - ssl: Arc::new(ssl), - }) + SslStream { + ssl: ssl, + _method: method, + _p: PhantomData, + } + } } - fn connect(ssl: Ssl, stream: S, sock: c_int) -> Result, SslError> { - let ssl = try!(DirectStream::new_base(ssl, stream, sock)); - let ret = ssl.ssl.connect(); + /// Creates an SSL/TLS client operating over the provided stream. + 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(ssl) + Ok(stream) } else { - Err(ssl.make_error(ret)) + Err(stream.make_error(ret)) } } - fn accept(ssl: Ssl, stream: S, sock: c_int) -> Result, SslError> { - let ssl = try!(DirectStream::new_base(ssl, stream, sock)); - let ret = ssl.ssl.accept(); + /// Creates an SSL/TLS server operating over the provided stream. + 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(ssl) + Ok(stream) } else { - Err(ssl.make_error(ret)) + Err(stream.make_error(ret)) } } - fn make_error(&self, ret: c_int) -> SslError { + /// ### Deprecated + /// + /// Use `connect`. + pub fn connect_generic(ssl: T, stream: S) -> Result, SslError> { + Self::connect(ssl, stream) + } + + /// ### Deprecated + /// + /// Use `accept`. + pub fn accept_generic(ssl: T, stream: S) -> Result, SslError> { + Self::accept(ssl, stream) + } +} + +impl SslStream { + fn make_error(&mut self, ret: c_int) -> SslError { match self.ssl.get_error(ret) { LibSslError::ErrorSsl => SslError::get(), LibSslError::ErrorSyscall => { @@ -1114,199 +1000,26 @@ impl DirectStream { SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, "unexpected EOF observed")) } else { - SslError::StreamError(io::Error::last_os_error()) + let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; + SslError::StreamError(error.unwrap()) } } else { err } } LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => { - SslError::StreamError(io::Error::last_os_error()) + let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; + SslError::StreamError(error.unwrap()) } err => panic!("unexpected error {:?} with ret {}", err, ret), } } -} - -impl Read for DirectStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let ret = self.ssl.read(buf); - if ret >= 0 { - return Ok(ret as usize); - } - - match self.make_error(ret) { - SslError::StreamError(e) => Err(e), - e => Err(io::Error::new(io::ErrorKind::Other, e)), - } - } -} - -impl Write for DirectStream { - fn write(&mut self, buf: &[u8]) -> io::Result { - let ret = self.ssl.write(buf); - if ret > 0 { - return Ok(ret as usize); - } - - match self.make_error(ret) { - SslError::StreamError(e) => Err(e), - e => Err(io::Error::new(io::ErrorKind::Other, e)), - } - } - - fn flush(&mut self) -> io::Result<()> { - self.stream.flush() - } -} - -#[derive(Clone)] -enum StreamKind { - Indirect(IndirectStream), - Direct(DirectStream), -} - -impl StreamKind { - fn stream(&self) -> &S { - match *self { - StreamKind::Indirect(ref s) => &s.stream, - StreamKind::Direct(ref s) => &s.stream, - } - } - - fn mut_stream(&mut self) -> &mut S { - match *self { - StreamKind::Indirect(ref mut s) => &mut s.stream, - StreamKind::Direct(ref mut s) => &mut s.stream, - } - } - - fn ssl(&self) -> &Ssl { - match *self { - StreamKind::Indirect(ref s) => &s.ssl, - StreamKind::Direct(ref s) => &s.ssl, - } - } -} - -/// A stream wrapper which handles SSL encryption for an underlying stream. -#[derive(Clone)] -pub struct SslStream { - kind: StreamKind, -} - -impl SslStream { - /// Create a new independently owned handle to the underlying socket. - pub fn try_clone(&self) -> io::Result> { - let kind = match self.kind { - StreamKind::Indirect(ref s) => StreamKind::Indirect(try!(s.try_clone())), - StreamKind::Direct(ref s) => StreamKind::Direct(try!(s.try_clone())) - }; - Ok(SslStream { - kind: kind - }) - } -} - -impl fmt::Debug for SslStream where S: fmt::Debug { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("SslStream") - .field("stream", &self.kind.stream()) - .field("ssl", &self.kind.ssl()) - .finish() - } -} - -#[cfg(unix)] -impl SslStream { - /// Creates an SSL/TLS client operating over the provided stream. - /// - /// Streams passed to this method must implement `AsRawFd` on Unixy - /// platforms and `AsRawSocket` on Windows. Use `connect_generic` for - /// streams that do not. - pub fn connect(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_fd() as c_int; - let stream = try!(DirectStream::connect(ssl, stream, fd)); - Ok(SslStream { - kind: StreamKind::Direct(stream) - }) - } - - /// Creates an SSL/TLS server operating over the provided stream. - /// - /// Streams passed to this method must implement `AsRawFd` on Unixy - /// platforms and `AsRawSocket` on Windows. Use `accept_generic` for - /// streams that do not. - pub fn accept(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_fd() as c_int; - let stream = try!(DirectStream::accept(ssl, stream, fd)); - Ok(SslStream { - kind: StreamKind::Direct(stream) - }) - } -} - -#[cfg(windows)] -impl SslStream { - /// Creates an SSL/TLS client operating over the provided stream. - /// - /// Streams passed to this method must implement `AsRawFd` on Unixy - /// platforms and `AsRawSocket` on Windows. Use `connect_generic` for - /// streams that do not. - pub fn connect(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_socket() as c_int; - let stream = try!(DirectStream::connect(ssl, stream, fd)); - Ok(SslStream { - kind: StreamKind::Direct(stream) - }) - } - - /// Creates an SSL/TLS server operating over the provided stream. - /// - /// Streams passed to this method must implement `AsRawFd` on Unixy - /// platforms and `AsRawSocket` on Windows. Use `accept_generic` for - /// streams that do not. - pub fn accept(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_socket() as c_int; - let stream = try!(DirectStream::accept(ssl, stream, fd)); - Ok(SslStream { - kind: StreamKind::Direct(stream) - }) - } -} - -impl SslStream { - /// Creates an SSL/TLS client operating over the provided stream. - /// - /// `SslStream`s returned by this method will be less efficient than ones - /// returned by `connect`, so this method should only be used for streams - /// that do not implement `AsRawFd` and `AsRawSocket`. - pub fn connect_generic(ssl: T, stream: S) -> Result, SslError> { - let stream = try!(IndirectStream::connect(ssl, stream)); - Ok(SslStream { - kind: StreamKind::Indirect(stream) - }) - } - - /// Creates an SSL/TLS server operating over the provided stream. - /// - /// `SslStream`s returned by this method will be less efficient than ones - /// returned by `accept`, so this method should only be used for streams - /// that do not implement `AsRawFd` and `AsRawSocket`. - pub fn accept_generic(ssl: T, stream: S) -> Result, SslError> { - let stream = try!(IndirectStream::accept(ssl, stream)); - Ok(SslStream { - kind: StreamKind::Indirect(stream) - }) - } - /// Returns a reference to the underlying stream. pub fn get_ref(&self) -> &S { - self.kind.stream() + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_ref(bio) + } } /// Returns a mutable reference to the underlying stream. @@ -1316,37 +1029,55 @@ impl SslStream { /// It is inadvisable to read from or write to the underlying stream as it /// will most likely corrupt the SSL session. pub fn get_mut(&mut self) -> &mut S { - self.kind.mut_stream() + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_mut(bio) + } } /// Returns the OpenSSL `Ssl` object associated with this stream. pub fn ssl(&self) -> &Ssl { - self.kind.ssl() + &self.ssl } } -impl Read for SslStream { +impl SslStream<::std::net::TcpStream> { + /// Like `TcpStream::try_clone`. + pub fn try_clone(&self) -> io::Result> { + let stream = try!(self.get_ref().try_clone()); + Ok(Self::new_base(self.ssl.clone(), stream)) + } +} + +impl Read for SslStream { fn read(&mut self, buf: &mut [u8]) -> io::Result { - match self.kind { - StreamKind::Indirect(ref mut s) => s.read(buf), - StreamKind::Direct(ref mut s) => s.read(buf), + let ret = self.ssl.read(buf); + if ret >= 0 { + return Ok(ret as usize); + } + + match self.make_error(ret) { + SslError::StreamError(e) => Err(e), + e => Err(io::Error::new(io::ErrorKind::Other, e)), } } } -impl Write for SslStream { +impl Write for SslStream { fn write(&mut self, buf: &[u8]) -> io::Result { - match self.kind { - StreamKind::Indirect(ref mut s) => s.write(buf), - StreamKind::Direct(ref mut s) => s.write(buf), + let ret = self.ssl.write(buf); + if ret > 0 { + return Ok(ret as usize); + } + + match self.make_error(ret) { + SslError::StreamError(e) => Err(e), + e => Err(io::Error::new(io::ErrorKind::Other, e)), } } fn flush(&mut self) -> io::Result<()> { - match self.kind { - StreamKind::Indirect(ref mut s) => s.flush(), - StreamKind::Direct(ref mut s) => s.flush(), - } + self.get_mut().flush() } } @@ -1660,133 +1391,3 @@ impl NonblockingSslStream { } } } - -pub struct SslStreamNg { - ssl: Ssl, - _method: Box, // :( - _p: PhantomData, -} - -impl Drop for SslStreamNg { - fn drop(&mut self) { - unsafe { - let _ = bio::take_stream::(self.ssl.get_raw_rbio()); - } - } -} - -impl SslStreamNg { - fn new_base(ssl: Ssl, stream: S) -> Result { - unsafe { - let (bio, method) = try!(bio::new(stream)); - ffi::SSL_set_bio(ssl.ssl, bio, bio); - - Ok(SslStreamNg { - ssl: ssl, - _method: method, - _p: PhantomData, - }) - } - } - - /// Creates an SSL/TLS client operating over the provided stream. - pub fn connect(ssl: T, stream: S) -> Result { - let ssl = try!(ssl.into_ssl()); - let mut stream = try!(Self::new_base(ssl, stream)); - let ret = stream.ssl.connect(); - if ret > 0 { - Ok(stream) - } else { - Err(stream.make_error(ret)) - } - } - - /// Creates an SSL/TLS server operating over the provided stream. - pub fn accept(ssl: T, stream: S) -> Result { - let ssl = try!(ssl.into_ssl()); - let mut stream = try!(Self::new_base(ssl, stream)); - let ret = stream.ssl.accept(); - if ret > 0 { - Ok(stream) - } else { - Err(stream.make_error(ret)) - } - } -} - -impl SslStreamNg { - pub fn get_ref(&self) -> &S { - unsafe { - let bio = self.ssl.get_raw_rbio(); - bio::get_ref(bio) - } - } - - pub fn get_mut(&mut self) -> &mut S { - unsafe { - let bio = self.ssl.get_raw_rbio(); - bio::get_mut(bio) - } - } - - fn make_error(&mut self, ret: c_int) -> SslError { - match self.ssl.get_error(ret) { - LibSslError::ErrorSsl => 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 { - SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, - "unexpected EOF observed")) - } else { - let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; - SslError::StreamError(error.unwrap()) - } - } else { - err - } - } - LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => { - let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; - SslError::StreamError(error.unwrap()) - } - err => panic!("unexpected error {:?} with ret {}", err, ret), - } - } -} - -impl Read for SslStreamNg { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let ret = self.ssl.read(buf); - if ret >= 0 { - return Ok(ret as usize); - } - - match self.make_error(ret) { - SslError::StreamError(e) => Err(e), - e => Err(io::Error::new(io::ErrorKind::Other, e)), - } - } -} - -impl Write for SslStreamNg { - fn write(&mut self, buf: &[u8]) -> io::Result { - let ret = self.ssl.write(buf); - if ret > 0 { - return Ok(ret as usize); - } - - match self.make_error(ret) { - SslError::StreamError(e) => Err(e), - e => Err(io::Error::new(io::ErrorKind::Other, e)), - } - } - - fn flush(&mut self) -> io::Result<()> { - self.get_mut().flush() - } -} -- cgit v1.2.3 From aa37dba0bc139fb9c866b6a57b5028227313df7a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 10 Dec 2015 21:58:22 -0800 Subject: Make error handling more reliable --- openssl/src/ssl/mod.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 5ac6d33e..bc64d7c8 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1000,20 +1000,30 @@ impl SslStream { SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, "unexpected EOF observed")) } else { - let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; - SslError::StreamError(error.unwrap()) + SslError::StreamError(self.get_bio_error()) } } else { err } } + LibSslError::ErrorZeroReturn => SslError::SslSessionClosed, LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => { - let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; - SslError::StreamError(error.unwrap()) + SslError::StreamError(self.get_bio_error()) } - err => panic!("unexpected error {:?} with ret {}", err, ret), + err => SslError::StreamError(io::Error::new(io::ErrorKind::Other, + format!("unexpected error {:?}", err))), } } + + fn get_bio_error(&mut self) -> io::Error { + let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; + match error { + Some(error) => error, + None => io::Error::new(io::ErrorKind::Other, + "BUG: got an ErrorSyscall without an error in the BIO?") + } + } + /// Returns a reference to the underlying stream. pub fn get_ref(&self) -> &S { unsafe { @@ -1057,6 +1067,7 @@ impl Read for SslStream { } match self.make_error(ret) { + SslError::SslSessionClosed => Ok(0), SslError::StreamError(e) => Err(e), e => Err(io::Error::new(io::ErrorKind::Other, e)), } -- cgit v1.2.3 From 1df131ff810dabd9d0452688bf8956e0af58b06a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 12 Dec 2015 15:01:16 -0800 Subject: Build out a new error type --- openssl/src/ssl/mod.rs | 118 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 95 insertions(+), 23 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index bc64d7c8..89c8bbfc 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -22,7 +22,7 @@ use std::marker::PhantomData; use ffi; use ffi_extras; use dh::DH; -use ssl::error::{NonblockingSslError, SslError, StreamError, OpenSslErrors}; +use ssl::error::{NonblockingSslError, SslError, StreamError, OpenSslErrors, OpenSslError}; use x509::{X509StoreContext, X509FileType, X509}; use crypto::pkey::PKey; @@ -31,6 +31,9 @@ mod bio; #[cfg(test)] mod tests; +#[doc(inline)] +pub use ssl::error::Error; + extern "C" { fn rust_SSL_clone(ssl: *mut ffi::SSL); } @@ -954,7 +957,17 @@ impl SslStream { if ret > 0 { Ok(stream) } else { - Err(stream.make_error(ret)) + match stream.make_old_error(ret) { + SslError::StreamError(e) => { + // This is fine - nonblocking sockets will finish the handshake in read/write + if e.kind() == io::ErrorKind::WouldBlock { + Ok(stream) + } else { + Err(SslError::StreamError(e)) + } + } + e => Err(e) + } } } @@ -966,7 +979,17 @@ impl SslStream { if ret > 0 { Ok(stream) } else { - Err(stream.make_error(ret)) + match stream.make_old_error(ret) { + SslError::StreamError(e) => { + // This is fine - nonblocking sockets will finish the handshake in read/write + if e.kind() == io::ErrorKind::WouldBlock { + Ok(stream) + } else { + Err(SslError::StreamError(e)) + } + } + e => Err(e) + } } } @@ -986,7 +1009,31 @@ impl SslStream { } impl SslStream { - fn make_error(&mut self, ret: c_int) -> SslError { + fn make_error(&mut self, ret: c_int) -> Error { + match self.ssl.get_error(ret) { + LibSslError::ErrorSsl => Error::Ssl(OpenSslError::get_stack()), + LibSslError::ErrorSyscall => { + let errs = OpenSslError::get_stack(); + if errs.is_empty() { + if ret == 0 { + Error::Stream(io::Error::new(io::ErrorKind::ConnectionAborted, + "unexpected EOF observed")) + } else { + Error::Stream(self.get_bio_error()) + } + } else { + Error::Ssl(errs) + } + } + LibSslError::ErrorZeroReturn => Error::ZeroReturn, + LibSslError::ErrorWantWrite => Error::WantWrite(self.get_bio_error()), + LibSslError::ErrorWantRead => Error::WantRead(self.get_bio_error()), + err => Error::Stream(io::Error::new(io::ErrorKind::Other, + format!("unexpected error {:?}", err))), + } + } + + fn make_old_error(&mut self, ret: c_int) -> SslError { match self.ssl.get_error(ret) { LibSslError::ErrorSsl => SslError::get(), LibSslError::ErrorSyscall => { @@ -1045,6 +1092,32 @@ impl SslStream { } } + /// Like `read`, but returns an `ssl::Error` rather than an `io::Error`. + /// + /// This is particularly useful with a nonblocking socket, where the error + /// value will identify if OpenSSL is waiting on read or write readiness. + pub fn ssl_read(&mut self, buf: &mut [u8]) -> Result { + let ret = self.ssl.read(buf); + if ret >= 0 { + Ok(ret as usize) + } else { + Err(self.make_error(ret)) + } + } + + /// Like `write`, but returns an `ssl::Error` rather than an `io::Error`. + /// + /// This is particularly useful with a nonblocking socket, where the error + /// value will identify if OpenSSL is waiting on read or write readiness. + pub fn ssl_write(&mut self, buf: &[u8]) -> Result { + let ret = self.ssl.write(buf); + if ret >= 0 { + Ok(ret as usize) + } else { + Err(self.make_error(ret)) + } + } + /// Returns the OpenSSL `Ssl` object associated with this stream. pub fn ssl(&self) -> &Ssl { &self.ssl @@ -1061,30 +1134,27 @@ impl SslStream<::std::net::TcpStream> { impl Read for SslStream { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let ret = self.ssl.read(buf); - if ret >= 0 { - return Ok(ret as usize); - } - - match self.make_error(ret) { - SslError::SslSessionClosed => Ok(0), - SslError::StreamError(e) => Err(e), - e => Err(io::Error::new(io::ErrorKind::Other, e)), + match self.ssl_read(buf) { + Ok(n) => Ok(n), + Err(Error::ZeroReturn) => Ok(0), + Err(Error::Stream(e)) => Err(e), + Err(Error::WantRead(e)) => Err(e), + Err(Error::WantWrite(e)) => Err(e), + Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)), } } } impl Write for SslStream { fn write(&mut self, buf: &[u8]) -> io::Result { - let ret = self.ssl.write(buf); - if ret > 0 { - return Ok(ret as usize); - } - - match self.make_error(ret) { - SslError::StreamError(e) => Err(e), - e => Err(io::Error::new(io::ErrorKind::Other, e)), - } + self.ssl_write(buf).map_err(|e| { + match e { + Error::Stream(e) => e, + Error::WantRead(e) => e, + Error::WantWrite(e) => e, + e => io::Error::new(io::ErrorKind::Other, e), + } + }) } fn flush(&mut self) -> io::Result<()> { @@ -1174,7 +1244,9 @@ impl MaybeSslStream { } } -/// An SSL stream wrapping a nonblocking socket. +/// # Deprecated +/// +/// Use `SslStream` with `ssl_read` and `ssl_write`. #[derive(Clone)] pub struct NonblockingSslStream { stream: S, -- cgit v1.2.3 From d6ce9afdf31faacaf435380feffcd13bf387255a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 12 Dec 2015 15:46:17 -0800 Subject: Have NonblockingSslStream delegate to SslStream --- openssl/src/ssl/mod.rs | 213 +++++++++++++++---------------------------------- 1 file changed, 66 insertions(+), 147 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 89c8bbfc..0ffa1120 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -10,7 +10,7 @@ use std::str; use std::net; use std::path::Path; use std::ptr; -use std::sync::{Once, ONCE_INIT, Arc, Mutex}; +use std::sync::{Once, ONCE_INIT, Mutex}; use std::cmp; use std::any::Any; #[cfg(any(feature = "npn", feature = "alpn"))] @@ -18,11 +18,16 @@ use libc::{c_uchar, c_uint}; #[cfg(any(feature = "npn", feature = "alpn"))] use std::slice; use std::marker::PhantomData; +#[cfg(unix)] +use std::os::unix::io::{AsRawFd, RawFd}; +#[cfg(windows)] +use std::os::windows::io::{AsRawSocket, RawSocket}; use ffi; use ffi_extras; use dh::DH; -use ssl::error::{NonblockingSslError, SslError, StreamError, OpenSslErrors, OpenSslError}; +use ssl::error::{NonblockingSslError, SslError, StreamError, OpenSslErrors, OpenSslError, + OpensslError}; use x509::{X509StoreContext, X509FileType, X509}; use crypto::pkey::PKey; @@ -935,6 +940,20 @@ impl fmt::Debug for SslStream where S: fmt::Debug { } } +#[cfg(unix)] +impl AsRawFd for SslStream { + fn as_raw_fd(&self) -> RawFd { + self.get_ref().as_raw_fd() + } +} + +#[cfg(windows)] +impl AsRawSocket for NonblockingSslStream { + fn as_raw_fd(&self) -> RawSocket { + self.0.as_raw_socket() + } +} + impl SslStream { fn new_base(ssl: Ssl, stream: S) -> Self { unsafe { @@ -1247,65 +1266,38 @@ impl MaybeSslStream { /// # Deprecated /// /// Use `SslStream` with `ssl_read` and `ssl_write`. -#[derive(Clone)] -pub struct NonblockingSslStream { - stream: S, - ssl: Arc, -} +pub struct NonblockingSslStream(SslStream); -impl NonblockingSslStream { - pub fn try_clone(&self) -> io::Result> { - Ok(NonblockingSslStream { - stream: try!(self.stream.try_clone()), - ssl: self.ssl.clone(), - }) +impl Clone for NonblockingSslStream { + fn clone(&self) -> Self { + NonblockingSslStream(self.0.clone()) } } -impl NonblockingSslStream { - fn new_base(ssl: Ssl, stream: S, sock: c_int) -> Result, SslError> { - unsafe { - let bio = try_ssl_null!(ffi::BIO_new_socket(sock, 0)); - ffi_extras::BIO_set_nbio(bio, 1); - ffi::SSL_set_bio(ssl.ssl, bio, bio); - } +#[cfg(unix)] +impl AsRawFd for NonblockingSslStream { + fn as_raw_fd(&self) -> RawFd { + self.0.as_raw_fd() + } +} - Ok(NonblockingSslStream { - stream: stream, - ssl: Arc::new(ssl), - }) +#[cfg(windows)] +impl AsRawSocket for NonblockingSslStream { + fn as_raw_fd(&self) -> RawSocket { + self.0.as_raw_socket() } +} - fn make_error(&self, ret: c_int) -> NonblockingSslError { - match self.ssl.get_error(ret) { - LibSslError::ErrorSsl => NonblockingSslError::SslError(SslError::get()), - LibSslError::ErrorSyscall => { - let err = SslError::get(); - let count = match err { - SslError::OpenSslErrors(ref v) => v.len(), - _ => unreachable!(), - }; - let ssl_error = if count == 0 { - if ret == 0 { - SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted, - "unexpected EOF observed")) - } else { - SslError::StreamError(io::Error::last_os_error()) - } - } else { - err - }; - ssl_error.into() - }, - LibSslError::ErrorWantWrite => NonblockingSslError::WantWrite, - LibSslError::ErrorWantRead => NonblockingSslError::WantRead, - err => panic!("unexpected error {:?} with ret {}", err, ret), - } +impl NonblockingSslStream { + pub fn try_clone(&self) -> io::Result> { + self.0.try_clone().map(NonblockingSslStream) } +} +impl NonblockingSslStream { /// Returns a reference to the underlying stream. pub fn get_ref(&self) -> &S { - &self.stream + self.0.get_ref() } /// Returns a mutable reference to the underlying stream. @@ -1315,91 +1307,23 @@ impl NonblockingSslStream { /// It is inadvisable to read from or write to the underlying stream as it /// will most likely corrupt the SSL session. pub fn get_mut(&mut self) -> &mut S { - &mut self.stream + self.0.get_mut() } /// Returns a reference to the Ssl. pub fn ssl(&self) -> &Ssl { - &self.ssl - } -} - -#[cfg(unix)] -impl NonblockingSslStream { - /// Create a new nonblocking client ssl connection on wrapped `stream`. - /// - /// Note that this method will most likely not actually complete the SSL - /// handshake because doing so requires several round trips; the handshake will - /// be completed in subsequent read/write calls managed by your event loop. - pub fn connect(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_fd() as c_int; - let ssl = try!(NonblockingSslStream::new_base(ssl, stream, fd)); - let ret = ssl.ssl.connect(); - if ret > 0 { - Ok(ssl) - } else { - // WantRead/WantWrite is okay here; we'll finish the handshake in - // subsequent send/recv calls. - match ssl.make_error(ret) { - NonblockingSslError::WantRead | NonblockingSslError::WantWrite => Ok(ssl), - NonblockingSslError::SslError(other) => Err(other), - } - } - } - - /// Create a new nonblocking server ssl connection on wrapped `stream`. - /// - /// Note that this method will most likely not actually complete the SSL - /// handshake because doing so requires several round trips; the handshake will - /// be completed in subsequent read/write calls managed by your event loop. - pub fn accept(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_fd() as c_int; - let ssl = try!(NonblockingSslStream::new_base(ssl, stream, fd)); - let ret = ssl.ssl.accept(); - if ret > 0 { - Ok(ssl) - } else { - // WantRead/WantWrite is okay here; we'll finish the handshake in - // subsequent send/recv calls. - match ssl.make_error(ret) { - NonblockingSslError::WantRead | NonblockingSslError::WantWrite => Ok(ssl), - NonblockingSslError::SslError(other) => Err(other), - } - } - } -} - -#[cfg(unix)] -impl ::std::os::unix::io::AsRawFd for NonblockingSslStream { - fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd { - self.stream.as_raw_fd() + self.0.ssl() } } -#[cfg(windows)] -impl NonblockingSslStream { +impl NonblockingSslStream { /// Create a new nonblocking client ssl connection on wrapped `stream`. /// /// Note that this method will most likely not actually complete the SSL /// handshake because doing so requires several round trips; the handshake will /// be completed in subsequent read/write calls managed by your event loop. pub fn connect(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_socket() as c_int; - let ssl = try!(NonblockingSslStream::new_base(ssl, stream, fd)); - let ret = ssl.ssl.connect(); - if ret > 0 { - Ok(ssl) - } else { - // WantRead/WantWrite is okay here; we'll finish the handshake in - // subsequent send/recv calls. - match ssl.make_error(ret) { - NonblockingSslError::WantRead | NonblockingSslError::WantWrite => Ok(ssl), - NonblockingSslError::SslError(other) => Err(other), - } - } + SslStream::connect(ssl, stream).map(NonblockingSslStream) } /// Create a new nonblocking server ssl connection on wrapped `stream`. @@ -1408,24 +1332,25 @@ impl NonblockingSslStream /// handshake because doing so requires several round trips; the handshake will /// be completed in subsequent read/write calls managed by your event loop. pub fn accept(ssl: T, stream: S) -> Result, SslError> { - let ssl = try!(ssl.into_ssl()); - let fd = stream.as_raw_socket() as c_int; - let ssl = try!(NonblockingSslStream::new_base(ssl, stream, fd)); - let ret = ssl.ssl.accept(); - if ret > 0 { - Ok(ssl) - } else { - // WantRead/WantWrite is okay here; we'll finish the handshake in - // subsequent send/recv calls. - match ssl.make_error(ret) { - NonblockingSslError::WantRead | NonblockingSslError::WantWrite => Ok(ssl), - NonblockingSslError::SslError(other) => Err(other), + SslStream::accept(ssl, stream).map(NonblockingSslStream) + } + + fn convert_err(&self, err: Error) -> NonblockingSslError { + match err { + Error::ZeroReturn => SslError::SslSessionClosed.into(), + Error::WantRead(_) => NonblockingSslError::WantRead, + Error::WantWrite(_) => NonblockingSslError::WantWrite, + Error::WantX509Lookup => unreachable!(), + Error::Stream(e) => SslError::StreamError(e).into(), + Error::Ssl(e) => { + SslError::OpenSslErrors(e.iter() + .map(|e| OpensslError::from_error_code(e.error_code())) + .collect()) + .into() } } } -} -impl NonblockingSslStream { /// Read bytes from the SSL stream into `buf`. /// /// Given the SSL state machine, this method may return either `WantWrite` @@ -1442,11 +1367,10 @@ impl NonblockingSslStream { /// On a return value of `Ok(count)`, count is the number of decrypted /// plaintext bytes copied into the `buf` slice. pub fn read(&mut self, buf: &mut [u8]) -> Result { - let ret = self.ssl.read(buf); - if ret >= 0 { - Ok(ret as usize) - } else { - Err(self.make_error(ret)) + match self.0.ssl_read(buf) { + Ok(n) => Ok(n), + Err(Error::ZeroReturn) => Ok(0), + Err(e) => Err(self.convert_err(e)) } } @@ -1466,11 +1390,6 @@ impl NonblockingSslStream { /// Given a return value of `Ok(count)`, count is the number of plaintext bytes /// from the `buf` slice that were encrypted and written onto the stream. pub fn write(&mut self, buf: &[u8]) -> Result { - let ret = self.ssl.write(buf); - if ret > 0 { - Ok(ret as usize) - } else { - Err(self.make_error(ret)) - } + self.0.ssl_write(buf).map_err(|e| self.convert_err(e)) } } -- cgit v1.2.3 From 63a45ac62220857183e55dd15665b73451580896 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 12 Dec 2015 16:33:58 -0800 Subject: Fix AsRawSocket impls --- openssl/src/ssl/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 0ffa1120..6def5241 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -949,7 +949,7 @@ impl AsRawFd for SslStream { #[cfg(windows)] impl AsRawSocket for NonblockingSslStream { - fn as_raw_fd(&self) -> RawSocket { + fn as_raw_socket(&self) -> RawSocket { self.0.as_raw_socket() } } @@ -1283,7 +1283,7 @@ impl AsRawFd for NonblockingSslStream { #[cfg(windows)] impl AsRawSocket for NonblockingSslStream { - fn as_raw_fd(&self) -> RawSocket { + fn as_raw_socket(&self) -> RawSocket { self.0.as_raw_socket() } } -- cgit v1.2.3 From ddedda1d03ae149621ac63ea5169b3b3cc7bacac Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 12 Dec 2015 16:47:03 -0800 Subject: More AsRawSocket fixes --- openssl/src/ssl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 6def5241..3457fa11 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -948,7 +948,7 @@ impl AsRawFd for SslStream { } #[cfg(windows)] -impl AsRawSocket for NonblockingSslStream { +impl AsRawSocket for SslStream { fn as_raw_socket(&self) -> RawSocket { self.0.as_raw_socket() } -- cgit v1.2.3 From b8c8b770e3668b7a207f3a0a360b6155bd8145ed Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 12 Dec 2015 18:01:21 -0800 Subject: Yet more AsRawSocket fixes --- openssl/src/ssl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 3457fa11..c1535900 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -950,7 +950,7 @@ impl AsRawFd for SslStream { #[cfg(windows)] impl AsRawSocket for SslStream { fn as_raw_socket(&self) -> RawSocket { - self.0.as_raw_socket() + self.get_ref().as_raw_socket() } } -- cgit v1.2.3 From 3a0e64dca51f74f6cf1178f6a20949e4063ca9d6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 15 Dec 2015 19:33:36 -0800 Subject: Cleanup --- openssl/src/ssl/mod.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index dffcfdb8..6558e1a4 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -315,7 +315,7 @@ extern fn raw_verify_with_data(preverify_ok: c_int, } } -extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_void) +extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, _arg: *mut c_void) -> c_int { unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); @@ -982,9 +982,11 @@ impl Ssl { /// obtain the context corresponding to the current connection pub fn get_ssl_context(&self) -> SslContext { - let ssl_ctx = unsafe { ffi::SSL_get_SSL_CTX(self.ssl) }; - let count = unsafe { ffi_extras::SSL_CTX_increment_refcount(ssl_ctx) }; - SslContext { ctx: ssl_ctx } + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(self.ssl); + ffi_extras::SSL_CTX_increment_refcount(ssl_ctx); + SslContext { ctx: ssl_ctx } + } } } -- cgit v1.2.3 From 6d559bf1dad5611f15165645aaad3c465cf6e0fe Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 15 Dec 2015 19:39:24 -0800 Subject: Cleanup SNI stuff --- openssl/src/ssl/mod.rs | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) (limited to 'openssl/src/ssl/mod.rs') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 6558e1a4..3b22c755 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -41,6 +41,7 @@ pub use ssl::error::Error; extern "C" { fn rust_SSL_clone(ssl: *mut ffi::SSL); + fn rust_SSL_CTX_clone(cxt: *mut ffi::SSL_CTX); } static mut VERIFY_IDX: c_int = -1; @@ -297,20 +298,15 @@ extern fn raw_verify_with_data(preverify_ok: c_int, let verify: Option> = mem::transmute(verify); let data = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); - let data: Box = mem::transmute(data); + let data: &T = mem::transmute(data); let ctx = X509StoreContext::new(x509_ctx); let res = match verify { None => preverify_ok, - Some(verify) => verify(preverify_ok != 0, &ctx, &*data) as c_int + Some(verify) => verify(preverify_ok != 0, &ctx, data) as c_int }; - // Since data might be required on the next verification - // it is time to forget about it and avoid dropping - // data will be freed once OpenSSL considers it is time - // to free all context data - mem::forget(data); res } } @@ -321,6 +317,7 @@ extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, _arg: *mut c_void) let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX); let callback: Option = mem::transmute(callback); + rust_SSL_clone(ssl); let mut s = Ssl { ssl: ssl }; let res = match callback { @@ -328,8 +325,6 @@ extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, _arg: *mut c_void) Some(callback) => callback(&mut s, ad) }; - // Allows dropping the Ssl instance without calling SSL_FREE on the SSL object - mem::forget(s); res } } @@ -341,6 +336,7 @@ extern fn raw_sni_with_data(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_v let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX); let callback: Option> = mem::transmute(callback); + rust_SSL_clone(ssl); let mut s = Ssl { ssl: ssl }; let data: &T = mem::transmute(arg); @@ -350,9 +346,6 @@ extern fn raw_sni_with_data(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_v Some(callback) => callback(&mut s, ad, &*data) }; - // Allows dropping the Ssl instance without calling SSL_FREE on the SSL object - mem::forget(s); - // Since data might be required on the next verification // it is time to forget about it and avoid dropping // data will be freed once OpenSSL considers it is time @@ -984,7 +977,7 @@ impl Ssl { pub fn get_ssl_context(&self) -> SslContext { unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(self.ssl); - ffi_extras::SSL_CTX_increment_refcount(ssl_ctx); + rust_SSL_CTX_clone(ssl_ctx); SslContext { ctx: ssl_ctx } } } -- cgit v1.2.3