From b9e3ed50ad22e72e67c61f69bd3805b43e519122 Mon Sep 17 00:00:00 2001 From: Cody P Schafer Date: Tue, 23 Sep 2014 16:11:34 -0400 Subject: [PATCH] Baseline server support Allows calling SSL_accept() instead of SSL_connect() when creating an SslStream. --- openssl-sys/src/lib.rs | 1 + src/ssl/mod.rs | 37 ++++++++++++++++++++++++------------- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 377ae8e5..b4f90fe7 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -403,6 +403,7 @@ extern "C" { pub fn SSL_set_bio(ssl: *mut SSL, rbio: *mut BIO, wbio: *mut BIO); pub fn SSL_get_rbio(ssl: *mut SSL) -> *mut BIO; pub fn SSL_get_wbio(ssl: *mut SSL) -> *mut BIO; + pub fn SSL_accept(ssl: *mut SSL) -> c_int; pub fn SSL_connect(ssl: *mut SSL) -> c_int; pub fn SSL_ctrl(ssl: *mut SSL, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; diff --git a/src/ssl/mod.rs b/src/ssl/mod.rs index a3eb5c14..1f0599b4 100644 --- a/src/ssl/mod.rs +++ b/src/ssl/mod.rs @@ -326,6 +326,10 @@ impl Ssl { unsafe { ffi::SSL_connect(self.ssl) } } + fn accept(&self) -> c_int { + unsafe { ffi::SSL_accept(self.ssl) } + } + fn read(&self, buf: &mut [u8]) -> c_int { unsafe { ffi::SSL_read(self.ssl, buf.as_ptr() as *mut c_void, buf.len() as c_int) } @@ -390,31 +394,38 @@ pub struct SslStream { } impl SslStream { - /// Attempts to create a new SSL stream from a given `Ssl` instance. - pub fn new_from(ssl: Ssl, stream: S) -> Result, SslError> { - let mut ssl = SslStream { + fn new_base(ssl:Ssl, stream: S) -> SslStream { + SslStream { stream: stream, ssl: ssl, // Maximum TLS record size is 16k buf: Vec::from_elem(16 * 1024, 0u8) - }; - - match ssl.in_retry_wrapper(|ssl| { ssl.connect() }) { - Ok(_) => Ok(ssl), - Err(err) => Err(err) } } + pub fn new_server_from(ssl: Ssl, stream: S) -> Result, SslError> { + let mut ssl = SslStream::new_base(ssl, stream); + ssl.in_retry_wrapper(|ssl| { ssl.accept() }).and(Ok(ssl)) + } + + /// Attempts to create a new SSL stream from a given `Ssl` instance. + pub fn new_from(ssl: Ssl, stream: S) -> Result, SslError> { + let mut ssl = SslStream::new_base(ssl, stream); + ssl.in_retry_wrapper(|ssl| { ssl.connect() }).and(Ok(ssl)) + } + /// Creates a new SSL stream pub fn new(ctx: &SslContext, stream: S) -> Result, SslError> { - let ssl = match Ssl::new(ctx) { - Ok(ssl) => ssl, - Err(err) => return Err(err) - }; - + let ssl = try!(Ssl::new(ctx)); SslStream::new_from(ssl, stream) } + /// Creates a new SSL server stream + pub fn new_server(ctx: &SslContext, stream: S) -> Result, SslError> { + let ssl = try!(Ssl::new(ctx)); + SslStream::new_server_from(ssl, stream) + } + fn in_retry_wrapper(&mut self, blk: |&Ssl| -> c_int) -> Result { loop {