Move SSL methods to Ssl object, add getter

This commit is contained in:
Steven Fackler 2015-10-26 21:09:30 -07:00
parent 124a0858e8
commit 03e4908c13
2 changed files with 66 additions and 124 deletions

View File

@ -704,7 +704,7 @@ unsafe impl Sync for 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 {
fmt.debug_struct("Ssl") fmt.debug_struct("Ssl")
.field("state", &self.get_state_string_long()) .field("state", &self.state_string_long())
.finish() .finish()
} }
} }
@ -722,24 +722,6 @@ impl Ssl {
Ok(ssl) Ok(ssl)
} }
pub fn get_state_string(&self) -> &'static str {
let state = unsafe {
let ptr = ffi::SSL_state_string(self.ssl);
CStr::from_ptr(ptr)
};
str::from_utf8(state.to_bytes()).unwrap()
}
pub fn get_state_string_long(&self) -> &'static str {
let state = unsafe {
let ptr = ffi::SSL_state_string_long(self.ssl);
CStr::from_ptr(ptr)
};
str::from_utf8(state.to_bytes()).unwrap()
}
fn get_rbio<'a>(&'a self) -> MemBioRef<'a> { fn get_rbio<'a>(&'a self) -> MemBioRef<'a> {
unsafe { self.wrap_bio(ffi::SSL_get_rbio(self.ssl)) } unsafe { self.wrap_bio(ffi::SSL_get_rbio(self.ssl)) }
} }
@ -782,7 +764,25 @@ impl Ssl {
} }
} }
/// Set the host name to be used with SNI (Server Name Indication). pub fn state_string(&self) -> &'static str {
let state = unsafe {
let ptr = ffi::SSL_state_string(self.ssl);
CStr::from_ptr(ptr)
};
str::from_utf8(state.to_bytes()).unwrap()
}
pub fn state_string_long(&self) -> &'static str {
let state = unsafe {
let ptr = ffi::SSL_state_string_long(self.ssl);
CStr::from_ptr(ptr)
};
str::from_utf8(state.to_bytes()).unwrap()
}
/// Sets the host name to be used with SNI (Server Name Indication).
pub fn set_hostname(&self, hostname: &str) -> Result<(), SslError> { pub fn set_hostname(&self, hostname: &str) -> Result<(), SslError> {
let cstr = CString::new(hostname).unwrap(); let cstr = CString::new(hostname).unwrap();
let ret = unsafe { ffi::SSL_set_tlsext_host_name(self.ssl, cstr.as_ptr()) }; let ret = unsafe { ffi::SSL_set_tlsext_host_name(self.ssl, cstr.as_ptr()) };
@ -795,7 +795,8 @@ impl Ssl {
} }
} }
pub fn get_peer_certificate(&self) -> Option<X509> { /// Returns the certificate of the peer, if present.
pub fn peer_certificate(&self) -> Option<X509> {
unsafe { unsafe {
let ptr = ffi::SSL_get_peer_certificate(self.ssl); let ptr = ffi::SSL_get_peer_certificate(self.ssl);
if ptr.is_null() { if ptr.is_null() {
@ -813,7 +814,7 @@ impl Ssl {
/// ///
/// This method needs the `npn` feature. /// This method needs the `npn` feature.
#[cfg(feature = "npn")] #[cfg(feature = "npn")]
pub fn get_selected_npn_protocol(&self) -> Option<&[u8]> { pub fn selected_npn_protocol(&self) -> Option<&[u8]> {
unsafe { unsafe {
let mut data: *const c_uchar = ptr::null(); let mut data: *const c_uchar = ptr::null();
let mut len: c_uint = 0; let mut len: c_uint = 0;
@ -836,7 +837,7 @@ impl Ssl {
/// ///
/// This method needs the `alpn` feature. /// This method needs the `alpn` feature.
#[cfg(feature = "alpn")] #[cfg(feature = "alpn")]
pub fn get_selected_alpn_protocol(&self) -> Option<&[u8]> { pub fn selected_alpn_protocol(&self) -> Option<&[u8]> {
unsafe { unsafe {
let mut data: *const c_uchar = ptr::null(); let mut data: *const c_uchar = ptr::null();
let mut len: c_uint = 0; let mut len: c_uint = 0;
@ -852,13 +853,32 @@ impl Ssl {
} }
} }
/// pending() takes into account only bytes from the TLS/SSL record that is currently being processed (if any). /// Returns the number of bytes remaining in the currently processed TLS
/// record.
pub fn pending(&self) -> usize { pub fn pending(&self) -> usize {
unsafe { unsafe {
ffi::SSL_pending(self.ssl) as usize ffi::SSL_pending(self.ssl) as usize
} }
} }
/// Returns the compression currently in use.
///
/// The result will be either None, indicating no compression is in use, or
/// a string with the compression name.
pub fn compression(&self) -> Option<String> {
let ptr = unsafe { ffi::SSL_get_current_compression(self.ssl) };
if ptr == ptr::null() {
return None;
}
let meth = unsafe { ffi::SSL_COMP_get_name(ptr) };
let s = unsafe {
String::from_utf8(CStr::from_ptr(meth).to_bytes().to_vec()).unwrap()
};
Some(s)
}
pub fn get_ssl_method(&self) -> Option<SslMethod> { pub fn get_ssl_method(&self) -> Option<SslMethod> {
unsafe { unsafe {
let method = ffi::SSL_get_ssl_method(self.ssl); let method = ffi::SSL_get_ssl_method(self.ssl);
@ -1277,42 +1297,11 @@ impl<S: Read+Write> SslStream<S> {
}) })
} }
/// # Deprecated
pub fn new_server(ssl: &SslContext, stream: S) -> Result<SslStream<S>, SslError> {
SslStream::accept_generic(ssl, stream)
}
/// # Deprecated
pub fn new_server_from(ssl: Ssl, stream: S) -> Result<SslStream<S>, SslError> {
SslStream::accept_generic(ssl, stream)
}
/// # Deprecated
pub fn new_from(ssl: Ssl, stream: S) -> Result<SslStream<S>, SslError> {
SslStream::connect_generic(ssl, stream)
}
/// # Deprecated
pub fn new(ctx: &SslContext, stream: S) -> Result<SslStream<S>, SslError> {
SslStream::connect_generic(ctx, stream)
}
/// # Deprecated
#[doc(hidden)]
pub fn get_inner(&mut self) -> &mut S {
self.get_mut()
}
/// Returns a reference to the underlying stream. /// Returns a reference to the underlying stream.
pub fn get_ref(&self) -> &S { pub fn get_ref(&self) -> &S {
self.kind.stream() self.kind.stream()
} }
/// Return the certificate of the peer
pub fn get_peer_certificate(&self) -> Option<X509> {
self.kind.ssl().get_peer_certificate()
}
/// Returns a mutable reference to the underlying stream. /// Returns a mutable reference to the underlying stream.
/// ///
/// ## Warning /// ## Warning
@ -1323,56 +1312,9 @@ impl<S: Read+Write> SslStream<S> {
self.kind.mut_stream() self.kind.mut_stream()
} }
/// Get the compression currently in use. The result will be /// Returns the OpenSSL `Ssl` object associated with this stream.
/// either None, indicating no compression is in use, or a string pub fn ssl(&self) -> &Ssl {
/// with the compression name. self.kind.ssl()
pub fn get_compression(&self) -> Option<String> {
let ptr = unsafe { ffi::SSL_get_current_compression(self.kind.ssl().ssl) };
if ptr == ptr::null() {
return None;
}
let meth = unsafe { ffi::SSL_COMP_get_name(ptr) };
let s = unsafe {
String::from_utf8(CStr::from_ptr(meth).to_bytes().to_vec()).unwrap()
};
Some(s)
}
/// Returns the protocol selected by performing Next Protocol Negotiation, if any.
///
/// The protocol's name is returned is an opaque sequence of bytes. It is up to the client
/// to interpret it.
///
/// This method needs the `npn` feature.
#[cfg(feature = "npn")]
pub fn get_selected_npn_protocol(&self) -> Option<&[u8]> {
self.kind.ssl().get_selected_npn_protocol()
}
/// Returns the protocol selected by performing ALPN, if any.
///
/// The protocol's name is returned is an opaque sequence of bytes. It is up to the client
/// to interpret it.
///
/// This method needs the `alpn` feature.
#[cfg(feature = "alpn")]
pub fn get_selected_alpn_protocol(&self) -> Option<&[u8]> {
self.kind.ssl().get_selected_alpn_protocol()
}
/// pending() takes into account only bytes from the TLS/SSL record that is currently being processed (if any).
pub fn pending(&self) -> usize {
self.kind.ssl().pending()
}
pub fn get_state_string(&self) -> &'static str {
self.kind.ssl().get_state_string()
}
pub fn get_state_string_long(&self) -> &'static str {
self.kind.ssl().get_state_string_long()
} }
} }

View File

@ -455,7 +455,7 @@ fn test_write_direct() {
run_test!(get_peer_certificate, |method, stream| { run_test!(get_peer_certificate, |method, stream| {
let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(), let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(),
stream).unwrap(); stream).unwrap();
let cert = stream.get_peer_certificate().unwrap(); let cert = stream.ssl().peer_certificate().unwrap();
let fingerprint = cert.fingerprint(SHA256).unwrap(); let fingerprint = cert.fingerprint(SHA256).unwrap();
let node_hash_str = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b"; let node_hash_str = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b";
let node_id = node_hash_str.from_hex().unwrap(); let node_id = node_hash_str.from_hex().unwrap();
@ -504,14 +504,14 @@ fn test_pending() {
let mut buf = [0u8; 16*1024]; let mut buf = [0u8; 16*1024];
stream.read(&mut buf[..1]).unwrap(); stream.read(&mut buf[..1]).unwrap();
let pending = stream.pending(); let pending = stream.ssl().pending();
let len = stream.read(&mut buf[1..]).unwrap(); let len = stream.read(&mut buf[1..]).unwrap();
assert_eq!(pending, len); assert_eq!(pending, len);
stream.read(&mut buf[..1]).unwrap(); stream.read(&mut buf[..1]).unwrap();
let pending = stream.pending(); let pending = stream.ssl().pending();
let len = stream.read(&mut buf[1..]).unwrap(); let len = stream.read(&mut buf[1..]).unwrap();
assert_eq!(pending, len); assert_eq!(pending, len);
} }
@ -520,8 +520,8 @@ fn test_pending() {
fn test_state() { fn test_state() {
let (_s, tcp) = Server::new(); let (_s, tcp) = Server::new();
let stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), tcp).unwrap(); let stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), tcp).unwrap();
assert_eq!(stream.get_state_string(), "SSLOK "); assert_eq!(stream.ssl().state_string(), "SSLOK ");
assert_eq!(stream.get_state_string_long(), "SSL negotiation finished successfully"); assert_eq!(stream.ssl().state_string_long(), "SSL negotiation finished successfully");
} }
/// Tests that connecting with the client using ALPN, but the server not does not /// Tests that connecting with the client using ALPN, but the server not does not
@ -537,13 +537,13 @@ fn test_connect_with_unilateral_alpn() {
Ok(_) => {} Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err) Err(err) => panic!("Unexpected error {:?}", err)
} }
let stream = match SslStream::new(&ctx, stream) { let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream, Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err)
}; };
// Since the socket to which we connected is not configured to use ALPN, // Since the socket to which we connected is not configured to use ALPN,
// there should be no selected protocol... // there should be no selected protocol...
assert!(stream.get_selected_alpn_protocol().is_none()); assert!(stream.ssl().selected_alpn_protocol().is_none());
} }
/// Tests that connecting with the client using NPN, but the server not does not /// Tests that connecting with the client using NPN, but the server not does not
@ -565,7 +565,7 @@ fn test_connect_with_unilateral_npn() {
}; };
// Since the socket to which we connected is not configured to use NPN, // Since the socket to which we connected is not configured to use NPN,
// there should be no selected protocol... // there should be no selected protocol...
assert!(stream.get_selected_npn_protocol().is_none()); assert!(stream.ssl().selected_npn_protocol().is_none());
} }
/// Tests that when both the client as well as the server use ALPN and their /// Tests that when both the client as well as the server use ALPN and their
@ -581,13 +581,13 @@ fn test_connect_with_alpn_successful_multiple_matching() {
Ok(_) => {} Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err) Err(err) => panic!("Unexpected error {:?}", err)
} }
let stream = match SslStream::new(&ctx, stream) { let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream, Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err)
}; };
// The server prefers "http/1.1", so that is chosen, even though the client // The server prefers "http/1.1", so that is chosen, even though the client
// would prefer "spdy/3.1" // would prefer "spdy/3.1"
assert_eq!(b"http/1.1", stream.get_selected_alpn_protocol().unwrap()); assert_eq!(b"http/1.1", stream.ssl().selected_alpn_protocol().unwrap());
} }
/// Tests that when both the client as well as the server use NPN and their /// Tests that when both the client as well as the server use NPN and their
@ -609,7 +609,7 @@ fn test_connect_with_npn_successful_multiple_matching() {
}; };
// The server prefers "http/1.1", so that is chosen, even though the client // The server prefers "http/1.1", so that is chosen, even though the client
// would prefer "spdy/3.1" // would prefer "spdy/3.1"
assert_eq!(b"http/1.1", stream.get_selected_npn_protocol().unwrap()); assert_eq!(b"http/1.1", stream.ssl().selected_npn_protocol().unwrap());
} }
/// Tests that when both the client as well as the server use ALPN and their /// Tests that when both the client as well as the server use ALPN and their
@ -626,13 +626,13 @@ fn test_connect_with_alpn_successful_single_match() {
Ok(_) => {} Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err) Err(err) => panic!("Unexpected error {:?}", err)
} }
let stream = match SslStream::new(&ctx, stream) { let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream, Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err)
}; };
// The client now only supports one of the server's protocols, so that one // The client now only supports one of the server's protocols, so that one
// is used. // is used.
assert_eq!(b"spdy/3.1", stream.get_selected_alpn_protocol().unwrap()); assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap());
} }
@ -656,7 +656,7 @@ fn test_connect_with_npn_successful_single_match() {
}; };
// The client now only supports one of the server's protocols, so that one // The client now only supports one of the server's protocols, so that one
// is used. // is used.
assert_eq!(b"spdy/3.1", stream.get_selected_npn_protocol().unwrap()); assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap());
} }
/// Tests that when the `SslStream` is created as a server stream, the protocols /// Tests that when the `SslStream` is created as a server stream, the protocols
@ -697,7 +697,7 @@ fn test_npn_server_advertise_multiple() {
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err)
}; };
// SPDY is selected since that's the only thing the client supports. // SPDY is selected since that's the only thing the client supports.
assert_eq!(b"spdy/3.1", stream.get_selected_npn_protocol().unwrap()); assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap());
} }
/// Tests that when the `SslStream` is created as a server stream, the protocols /// Tests that when the `SslStream` is created as a server stream, the protocols
@ -733,12 +733,12 @@ fn test_alpn_server_advertise_multiple() {
} }
// Now connect to the socket and make sure the protocol negotiation works... // Now connect to the socket and make sure the protocol negotiation works...
let stream = TcpStream::connect(localhost).unwrap(); let stream = TcpStream::connect(localhost).unwrap();
let stream = match SslStream::new(&ctx, stream) { let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream, Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err)
}; };
// SPDY is selected since that's the only thing the client supports. // SPDY is selected since that's the only thing the client supports.
assert_eq!(b"spdy/3.1", stream.get_selected_alpn_protocol().unwrap()); assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap());
} }
/// Test that Servers supporting ALPN don't report a protocol when none of their protocols match /// Test that Servers supporting ALPN don't report a protocol when none of their protocols match
@ -774,13 +774,13 @@ fn test_alpn_server_select_none() {
} }
// Now connect to the socket and make sure the protocol negotiation works... // Now connect to the socket and make sure the protocol negotiation works...
let stream = TcpStream::connect(localhost).unwrap(); let stream = TcpStream::connect(localhost).unwrap();
let stream = match SslStream::new(&ctx, stream) { let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream, Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err)
}; };
// Since the protocols from the server and client don't overlap at all, no protocol is selected // Since the protocols from the server and client don't overlap at all, no protocol is selected
assert_eq!(None, stream.get_selected_alpn_protocol()); assert_eq!(None, stream.ssl().selected_alpn_protocol());
} }