From e1d4270acbb12306f5e30927b4f05ff2ff6c6937 Mon Sep 17 00:00:00 2001 From: Till Hoeppner Date: Mon, 4 May 2015 20:09:59 +0200 Subject: Add SSL connections and use them in the example --- src/client.rs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) (limited to 'src/client.rs') diff --git a/src/client.rs b/src/client.rs index a738262..a688565 100644 --- a/src/client.rs +++ b/src/client.rs @@ -20,7 +20,7 @@ use openssl::ssl::{ SslContext, SslMethod, SslStream }; enum StreamKind { Plain(TcpStream), #[cfg(feature = "ssl")] - Ssl(SslStream) + Ssl(SslStream) } impl Write for StreamKind { @@ -82,18 +82,24 @@ impl Client { #[cfg(feature = "ssl")] pub fn connect_ssl(&mut self, host: String, port: u16) -> Result<()> { - let mut s = self.stream.lock(); + let s = &mut self.stream; match *s { Some(_) => return Err(IrscError::AlreadyConnected), _ => () }; let tcp_stream = match TcpStream::connect((host.as_ref(), port)) { Ok(tcp) => Some(tcp), Err(e) => return Err(IrscError::Io(e)) }; - let ssl = SslContext::new(SslMethod::Tlsv1); - let ssl_stream = SslStream::new(&ssl, tcp_stream); - *s = ssl_stream; + let ssl = try!(SslContext::new(SslMethod::Tlsv1)); + match tcp_stream.map(|tcp| SslStream::new(&ssl, tcp)) { + Some(Ok(ssl_stream)) => { *s = Some(StreamKind::Ssl(ssl_stream)); Ok(()) }, + Some(Err(ssl_error)) => Err(IrscError::Ssl(ssl_error)), + None => Err(IrscError::NotConnected) + } + } - Ok(()) + #[cfg(not(feature = "ssl"))] + pub fn connect_ssl(&mut self, _host: String, _port: u16) -> Result<()> { + panic!("Not compiled with ssl feature.") } #[inline] @@ -121,9 +127,9 @@ impl Client { pub fn listen(&mut self, events: F) -> Result<()> where F: Fn(&mut Client, &Message) { let reader = BufReader::new(match self.stream { - Some(StreamKind::Plain(ref s)) => (*s).try_clone().unwrap(), + Some(StreamKind::Plain(ref s)) => StreamKind::Plain((*s).try_clone().unwrap()), #[cfg(feature = "ssl")] - Some(StreamKind::Ssl(ref s)) => (*s).try_clone().unwrap(), + Some(StreamKind::Ssl(ref s)) => StreamKind::Ssl((*s).try_clone().unwrap()), None => return Err(IrscError::NotConnected) }); -- cgit v1.2.3