#[cfg(ossl300)]
use crate::cvt_long;
use crate::dh::{Dh, DhRef};
use crate::ec::EcKeyRef;
use crate::error::ErrorStack;
use crate::ex_data::Index;
#[cfg(ossl111)]
use crate::hash::MessageDigest;
#[cfg(any(ossl110, libressl))]
use crate::nid::Nid;
use crate::pkey::{HasPrivate, PKeyRef, Params, Private};
#[cfg(ossl300)]
use crate::pkey::{PKey, Public};
#[cfg(not(osslconf = "OPENSSL_NO_SRTP"))]
use crate::srtp::{SrtpProtectionProfile, SrtpProtectionProfileRef};
use crate::ssl::bio::BioMethod;
use crate::ssl::callbacks::*;
use crate::ssl::error::InnerError;
use crate::stack::{Stack, StackRef, Stackable};
use crate::util;
use crate::util::{ForeignTypeExt, ForeignTypeRefExt};
use crate::x509::store::{X509Store, X509StoreBuilderRef, X509StoreRef};
use crate::x509::verify::X509VerifyParamRef;
use crate::x509::{X509Name, X509Ref, X509StoreContextRef, X509VerifyResult, X509};
use crate::{cvt, cvt_n, cvt_p, init};
use bitflags::bitflags;
use cfg_if::cfg_if;
use foreign_types::{ForeignType, ForeignTypeRef, Opaque};
use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_void};
use once_cell::sync::{Lazy, OnceCell};
use openssl_macros::corresponds;
use std::any::TypeId;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop, MaybeUninit};
use std::ops::{Deref, DerefMut};
use std::panic::resume_unwind;
use std::path::Path;
use std::ptr;
use std::str;
use std::sync::{Arc, Mutex};
pub use crate::ssl::connector::{
ConnectConfiguration, SslAcceptor, SslAcceptorBuilder, SslConnector, SslConnectorBuilder,
};
pub use crate::ssl::error::{Error, ErrorCode, HandshakeError};
mod bio;
mod callbacks;
mod connector;
mod error;
#[cfg(test)]
mod test;
#[corresponds(OPENSSL_cipher_name)]
#[cfg(ossl111)]
pub fn cipher_name(std_name: &str) -> &'static str {
unsafe {
ffi::init();
let s = CString::new(std_name).unwrap();
let ptr = ffi::OPENSSL_cipher_name(s.as_ptr());
CStr::from_ptr(ptr).to_str().unwrap()
}
}
cfg_if! {
if #[cfg(ossl300)] {
type SslOptionsRepr = u64;
} else if #[cfg(any(boringssl, awslc))] {
type SslOptionsRepr = u32;
} else {
type SslOptionsRepr = libc::c_ulong;
}
}
bitflags! {
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct SslOptions: SslOptionsRepr {
const DONT_INSERT_EMPTY_FRAGMENTS = ffi::SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS as SslOptionsRepr;
#[cfg(ossl300)]
const IGNORE_UNEXPECTED_EOF = ffi::SSL_OP_IGNORE_UNEXPECTED_EOF as SslOptionsRepr;
#[cfg(not(any(boringssl, awslc)))]
const ALL = ffi::SSL_OP_ALL as SslOptionsRepr;
const NO_QUERY_MTU = ffi::SSL_OP_NO_QUERY_MTU as SslOptionsRepr;
#[cfg(not(any(boringssl, awslc)))]
const COOKIE_EXCHANGE = ffi::SSL_OP_COOKIE_EXCHANGE as SslOptionsRepr;
const NO_TICKET = ffi::SSL_OP_NO_TICKET as SslOptionsRepr;
#[cfg(not(any(boringssl, awslc)))]
const NO_SESSION_RESUMPTION_ON_RENEGOTIATION =
ffi::SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION as SslOptionsRepr;
#[cfg(not(any(boringssl, awslc)))]
const NO_COMPRESSION = ffi::SSL_OP_NO_COMPRESSION as SslOptionsRepr;
const ALLOW_UNSAFE_LEGACY_RENEGOTIATION =
ffi::SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION as SslOptionsRepr;
const SINGLE_ECDH_USE = ffi::SSL_OP_SINGLE_ECDH_USE as SslOptionsRepr;
const SINGLE_DH_USE = ffi::SSL_OP_SINGLE_DH_USE as SslOptionsRepr;
const CIPHER_SERVER_PREFERENCE = ffi::SSL_OP_CIPHER_SERVER_PREFERENCE as SslOptionsRepr;
const TLS_ROLLBACK_BUG = ffi::SSL_OP_TLS_ROLLBACK_BUG as SslOptionsRepr;
const NO_SSLV2 = ffi::SSL_OP_NO_SSLv2 as SslOptionsRepr;
const NO_SSLV3 = ffi::SSL_OP_NO_SSLv3 as SslOptionsRepr;
const NO_TLSV1 = ffi::SSL_OP_NO_TLSv1 as SslOptionsRepr;
const NO_TLSV1_1 = ffi::SSL_OP_NO_TLSv1_1 as SslOptionsRepr;
const NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2 as SslOptionsRepr;
#[cfg(any(ossl111, boringssl, libressl, awslc))]
const NO_TLSV1_3 = ffi::SSL_OP_NO_TLSv1_3 as SslOptionsRepr;
const NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1 as SslOptionsRepr;
const NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2 as SslOptionsRepr;
#[cfg(ossl110)]
const NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK as SslOptionsRepr;
#[cfg(any(boringssl, ossl110h, awslc))]
const NO_RENEGOTIATION = ffi::SSL_OP_NO_RENEGOTIATION as SslOptionsRepr;
#[cfg(ossl111)]
const ENABLE_MIDDLEBOX_COMPAT = ffi::SSL_OP_ENABLE_MIDDLEBOX_COMPAT as SslOptionsRepr;
#[cfg(ossl111)]
const PRIORITIZE_CHACHA = ffi::SSL_OP_PRIORITIZE_CHACHA as SslOptionsRepr;
}
}
bitflags! {
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct SslMode: SslBitType {
const ENABLE_PARTIAL_WRITE = ffi::SSL_MODE_ENABLE_PARTIAL_WRITE;
const ACCEPT_MOVING_WRITE_BUFFER = ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
const AUTO_RETRY = ffi::SSL_MODE_AUTO_RETRY;
const NO_AUTO_CHAIN = ffi::SSL_MODE_NO_AUTO_CHAIN;
const RELEASE_BUFFERS = ffi::SSL_MODE_RELEASE_BUFFERS;
#[cfg(not(libressl))]
const SEND_FALLBACK_SCSV = ffi::SSL_MODE_SEND_FALLBACK_SCSV;
}
}
#[derive(Copy, Clone)]
pub struct SslMethod(*const ffi::SSL_METHOD);
impl SslMethod {
#[corresponds(TLS_method)]
pub fn tls() -> SslMethod {
unsafe { SslMethod(TLS_method()) }
}
#[corresponds(DTLS_method)]
pub fn dtls() -> SslMethod {
unsafe { SslMethod(DTLS_method()) }
}
#[corresponds(TLS_client_method)]
pub fn tls_client() -> SslMethod {
unsafe { SslMethod(TLS_client_method()) }
}
#[corresponds(TLS_server_method)]
pub fn tls_server() -> SslMethod {
unsafe { SslMethod(TLS_server_method()) }
}
#[corresponds(DTLS_client_method)]
pub fn dtls_client() -> SslMethod {
unsafe { SslMethod(DTLS_client_method()) }
}
#[corresponds(DTLS_server_method)]
pub fn dtls_server() -> SslMethod {
unsafe { SslMethod(DTLS_server_method()) }
}
pub unsafe fn from_ptr(ptr: *const ffi::SSL_METHOD) -> SslMethod {
SslMethod(ptr)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn as_ptr(&self) -> *const ffi::SSL_METHOD {
self.0
}
}
unsafe impl Sync for SslMethod {}
unsafe impl Send for SslMethod {}
bitflags! {
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct SslVerifyMode: i32 {
const PEER = ffi::SSL_VERIFY_PEER;
const NONE = ffi::SSL_VERIFY_NONE;
const FAIL_IF_NO_PEER_CERT = ffi::SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
}
}
#[cfg(any(boringssl, awslc))]
type SslBitType = c_int;
#[cfg(not(any(boringssl, awslc)))]
type SslBitType = c_long;
#[cfg(any(boringssl, awslc))]
type SslTimeTy = u64;
#[cfg(not(any(boringssl, awslc)))]
type SslTimeTy = c_long;
bitflags! {
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct SslSessionCacheMode: SslBitType {
const OFF = ffi::SSL_SESS_CACHE_OFF;
const CLIENT = ffi::SSL_SESS_CACHE_CLIENT;
const SERVER = ffi::SSL_SESS_CACHE_SERVER;
const BOTH = ffi::SSL_SESS_CACHE_BOTH;
const NO_AUTO_CLEAR = ffi::SSL_SESS_CACHE_NO_AUTO_CLEAR;
const NO_INTERNAL_LOOKUP = ffi::SSL_SESS_CACHE_NO_INTERNAL_LOOKUP;
const NO_INTERNAL_STORE = ffi::SSL_SESS_CACHE_NO_INTERNAL_STORE;
const NO_INTERNAL = ffi::SSL_SESS_CACHE_NO_INTERNAL;
}
}
#[cfg(ossl111)]
bitflags! {
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct ExtensionContext: c_uint {
const TLS_ONLY = ffi::SSL_EXT_TLS_ONLY;
const DTLS_ONLY = ffi::SSL_EXT_DTLS_ONLY;
const TLS_IMPLEMENTATION_ONLY = ffi::SSL_EXT_TLS_IMPLEMENTATION_ONLY;
const SSL3_ALLOWED = ffi::SSL_EXT_SSL3_ALLOWED;
const TLS1_2_AND_BELOW_ONLY = ffi::SSL_EXT_TLS1_2_AND_BELOW_ONLY;
const TLS1_3_ONLY = ffi::SSL_EXT_TLS1_3_ONLY;
const IGNORE_ON_RESUMPTION = ffi::SSL_EXT_IGNORE_ON_RESUMPTION;
const CLIENT_HELLO = ffi::SSL_EXT_CLIENT_HELLO;
const TLS1_2_SERVER_HELLO = ffi::SSL_EXT_TLS1_2_SERVER_HELLO;
const TLS1_3_SERVER_HELLO = ffi::SSL_EXT_TLS1_3_SERVER_HELLO;
const TLS1_3_ENCRYPTED_EXTENSIONS = ffi::SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
const TLS1_3_HELLO_RETRY_REQUEST = ffi::SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST;
const TLS1_3_CERTIFICATE = ffi::SSL_EXT_TLS1_3_CERTIFICATE;
const TLS1_3_NEW_SESSION_TICKET = ffi::SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
const TLS1_3_CERTIFICATE_REQUEST = ffi::SSL_EXT_TLS1_3_CERTIFICATE_REQUEST;
}
}
#[derive(Copy, Clone)]
pub struct SslFiletype(c_int);
impl SslFiletype {
pub const PEM: SslFiletype = SslFiletype(ffi::SSL_FILETYPE_PEM);
pub const ASN1: SslFiletype = SslFiletype(ffi::SSL_FILETYPE_ASN1);
pub fn from_raw(raw: c_int) -> SslFiletype {
SslFiletype(raw)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn as_raw(&self) -> c_int {
self.0
}
}
#[derive(Copy, Clone)]
pub struct StatusType(c_int);
impl StatusType {
pub const OCSP: StatusType = StatusType(ffi::TLSEXT_STATUSTYPE_ocsp);
pub fn from_raw(raw: c_int) -> StatusType {
StatusType(raw)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn as_raw(&self) -> c_int {
self.0
}
}
#[derive(Copy, Clone)]
pub struct NameType(c_int);
impl NameType {
pub const HOST_NAME: NameType = NameType(ffi::TLSEXT_NAMETYPE_host_name);
pub fn from_raw(raw: c_int) -> StatusType {
StatusType(raw)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn as_raw(&self) -> c_int {
self.0
}
}
static INDEXES: Lazy<Mutex<HashMap<TypeId, c_int>>> = Lazy::new(|| Mutex::new(HashMap::new()));
static SSL_INDEXES: Lazy<Mutex<HashMap<TypeId, c_int>>> = Lazy::new(|| Mutex::new(HashMap::new()));
static SESSION_CTX_INDEX: OnceCell<Index<Ssl, SslContext>> = OnceCell::new();
fn try_get_session_ctx_index() -> Result<&'static Index<Ssl, SslContext>, ErrorStack> {
SESSION_CTX_INDEX.get_or_try_init(Ssl::new_ex_index)
}
unsafe extern "C" fn free_data_box<T>(
_parent: *mut c_void,
ptr: *mut c_void,
_ad: *mut ffi::CRYPTO_EX_DATA,
_idx: c_int,
_argl: c_long,
_argp: *mut c_void,
) {
if !ptr.is_null() {
let _ = Box::<T>::from_raw(ptr as *mut T);
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SniError(c_int);
impl SniError {
pub const ALERT_FATAL: SniError = SniError(ffi::SSL_TLSEXT_ERR_ALERT_FATAL);
pub const ALERT_WARNING: SniError = SniError(ffi::SSL_TLSEXT_ERR_ALERT_WARNING);
pub const NOACK: SniError = SniError(ffi::SSL_TLSEXT_ERR_NOACK);
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SslAlert(c_int);
impl SslAlert {
pub const UNRECOGNIZED_NAME: SslAlert = SslAlert(ffi::SSL_AD_UNRECOGNIZED_NAME);
pub const ILLEGAL_PARAMETER: SslAlert = SslAlert(ffi::SSL_AD_ILLEGAL_PARAMETER);
pub const DECODE_ERROR: SslAlert = SslAlert(ffi::SSL_AD_DECODE_ERROR);
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct AlpnError(c_int);
impl AlpnError {
pub const ALERT_FATAL: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_ALERT_FATAL);
pub const NOACK: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_NOACK);
}
#[cfg(ossl111)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ClientHelloResponse(c_int);
#[cfg(ossl111)]
impl ClientHelloResponse {
pub const SUCCESS: ClientHelloResponse = ClientHelloResponse(ffi::SSL_CLIENT_HELLO_SUCCESS);
pub const RETRY: ClientHelloResponse = ClientHelloResponse(ffi::SSL_CLIENT_HELLO_RETRY);
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SslVersion(c_int);
impl SslVersion {
pub const SSL3: SslVersion = SslVersion(ffi::SSL3_VERSION);
pub const TLS1: SslVersion = SslVersion(ffi::TLS1_VERSION);
pub const TLS1_1: SslVersion = SslVersion(ffi::TLS1_1_VERSION);
pub const TLS1_2: SslVersion = SslVersion(ffi::TLS1_2_VERSION);
#[cfg(any(ossl111, libressl, boringssl, awslc))]
pub const TLS1_3: SslVersion = SslVersion(ffi::TLS1_3_VERSION);
pub const DTLS1: SslVersion = SslVersion(ffi::DTLS1_VERSION);
pub const DTLS1_2: SslVersion = SslVersion(ffi::DTLS1_2_VERSION);
}
cfg_if! {
if #[cfg(any(boringssl, awslc))] {
type SslCacheTy = i64;
type SslCacheSize = libc::c_ulong;
type MtuTy = u32;
type SizeTy = usize;
} else {
type SslCacheTy = i64;
type SslCacheSize = c_long;
type MtuTy = c_long;
type SizeTy = u32;
}
}
#[corresponds(SSL_select_next_proto)]
pub fn select_next_proto<'a>(server: &'a [u8], client: &'a [u8]) -> Option<&'a [u8]> {
unsafe {
let mut out = ptr::null_mut();
let mut outlen = 0;
let r = ffi::SSL_select_next_proto(
&mut out,
&mut outlen,
server.as_ptr(),
server.len() as c_uint,
client.as_ptr(),
client.len() as c_uint,
);
if r == ffi::OPENSSL_NPN_NEGOTIATED {
Some(util::from_raw_parts(out as *const u8, outlen as usize))
} else {
None
}
}
}
pub struct SslContextBuilder(SslContext);
impl SslContextBuilder {
#[corresponds(SSL_CTX_new)]
pub fn new(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> {
unsafe {
init();
let ctx = cvt_p(ffi::SSL_CTX_new(method.as_ptr()))?;
Ok(SslContextBuilder::from_ptr(ctx))
}
}
pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextBuilder {
SslContextBuilder(SslContext::from_ptr(ctx))
}
pub fn as_ptr(&self) -> *mut ffi::SSL_CTX {
self.0.as_ptr()
}
#[corresponds(SSL_CTX_set_verify)]
pub fn set_verify(&mut self, mode: SslVerifyMode) {
unsafe {
ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits() as c_int, None);
}
}
#[corresponds(SSL_CTX_set_verify)]
pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
where
F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), verify);
ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits() as c_int, Some(raw_verify::<F>));
}
}
#[corresponds(SSL_CTX_set_tlsext_servername_callback)]
pub fn set_servername_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send,
{
unsafe {
let arg = self.set_ex_data_inner(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_tlsext_servername_arg(self.as_ptr(), arg);
#[cfg(any(boringssl, awslc))]
ffi::SSL_CTX_set_tlsext_servername_callback(self.as_ptr(), Some(raw_sni::<F>));
#[cfg(not(any(boringssl, awslc)))]
ffi::SSL_CTX_set_tlsext_servername_callback__fixed_rust(
self.as_ptr(),
Some(raw_sni::<F>),
);
}
}
#[corresponds(SSL_CTX_set_verify_depth)]
pub fn set_verify_depth(&mut self, depth: u32) {
unsafe {
ffi::SSL_CTX_set_verify_depth(self.as_ptr(), depth as c_int);
}
}
#[corresponds(SSL_CTX_set0_verify_cert_store)]
#[cfg(ossl110)]
pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> {
unsafe {
let ptr = cert_store.as_ptr();
cvt(ffi::SSL_CTX_set0_verify_cert_store(self.as_ptr(), ptr) as c_int)?;
mem::forget(cert_store);
Ok(())
}
}
#[corresponds(SSL_CTX_set_cert_store)]
pub fn set_cert_store(&mut self, cert_store: X509Store) {
unsafe {
ffi::SSL_CTX_set_cert_store(self.as_ptr(), cert_store.as_ptr());
mem::forget(cert_store);
}
}
#[corresponds(SSL_CTX_set_read_ahead)]
pub fn set_read_ahead(&mut self, read_ahead: bool) {
unsafe {
ffi::SSL_CTX_set_read_ahead(self.as_ptr(), read_ahead as SslBitType);
}
}
#[corresponds(SSL_CTX_set_mode)]
pub fn set_mode(&mut self, mode: SslMode) -> SslMode {
unsafe {
let bits = ffi::SSL_CTX_set_mode(self.as_ptr(), mode.bits() as MtuTy) as SslBitType;
SslMode::from_bits_retain(bits)
}
}
#[corresponds(SSL_CTX_set_tmp_dh)]
pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) }
}
#[corresponds(SSL_CTX_set_tmp_dh_callback)]
pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
#[cfg(not(any(boringssl, awslc)))]
ffi::SSL_CTX_set_tmp_dh_callback__fixed_rust(self.as_ptr(), Some(raw_tmp_dh::<F>));
#[cfg(any(boringssl, awslc))]
ffi::SSL_CTX_set_tmp_dh_callback(self.as_ptr(), Some(raw_tmp_dh::<F>));
}
}
#[corresponds(SSL_CTX_set_tmp_ecdh)]
pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) }
}
#[corresponds(SSL_CTX_set_default_verify_paths)]
pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) }
}
#[corresponds(SSL_CTX_load_verify_locations)]
pub fn set_ca_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), ErrorStack> {
self.load_verify_locations(Some(file.as_ref()), None)
}
#[corresponds(SSL_CTX_load_verify_locations)]
pub fn load_verify_locations(
&mut self,
ca_file: Option<&Path>,
ca_path: Option<&Path>,
) -> Result<(), ErrorStack> {
let ca_file = ca_file.map(|p| CString::new(p.as_os_str().to_str().unwrap()).unwrap());
let ca_path = ca_path.map(|p| CString::new(p.as_os_str().to_str().unwrap()).unwrap());
unsafe {
cvt(ffi::SSL_CTX_load_verify_locations(
self.as_ptr(),
ca_file.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
ca_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_set_client_CA_list)]
pub fn set_client_ca_list(&mut self, list: Stack<X509Name>) {
unsafe {
ffi::SSL_CTX_set_client_CA_list(self.as_ptr(), list.as_ptr());
mem::forget(list);
}
}
#[corresponds(SSL_CTX_add_client_CA)]
pub fn add_client_ca(&mut self, cacert: &X509Ref) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_add_client_CA(self.as_ptr(), cacert.as_ptr())).map(|_| ()) }
}
#[corresponds(SSL_CTX_set_session_id_context)]
pub fn set_session_id_context(&mut self, sid_ctx: &[u8]) -> Result<(), ErrorStack> {
unsafe {
assert!(sid_ctx.len() <= c_uint::MAX as usize);
cvt(ffi::SSL_CTX_set_session_id_context(
self.as_ptr(),
sid_ctx.as_ptr(),
sid_ctx.len() as SizeTy,
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_use_certificate_file)]
pub fn set_certificate_file<P: AsRef<Path>>(
&mut self,
file: P,
file_type: SslFiletype,
) -> Result<(), ErrorStack> {
let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
unsafe {
cvt(ffi::SSL_CTX_use_certificate_file(
self.as_ptr(),
file.as_ptr() as *const _,
file_type.as_raw(),
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_use_certificate_chain_file)]
pub fn set_certificate_chain_file<P: AsRef<Path>>(
&mut self,
file: P,
) -> Result<(), ErrorStack> {
let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
unsafe {
cvt(ffi::SSL_CTX_use_certificate_chain_file(
self.as_ptr(),
file.as_ptr() as *const _,
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_use_certificate)]
pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) }
}
#[corresponds(SSL_CTX_add_extra_chain_cert)]
pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_CTX_add_extra_chain_cert(self.as_ptr(), cert.as_ptr()) as c_int)?;
mem::forget(cert);
Ok(())
}
}
#[corresponds(SSL_CTX_use_PrivateKey_file)]
pub fn set_private_key_file<P: AsRef<Path>>(
&mut self,
file: P,
file_type: SslFiletype,
) -> Result<(), ErrorStack> {
let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
unsafe {
cvt(ffi::SSL_CTX_use_PrivateKey_file(
self.as_ptr(),
file.as_ptr() as *const _,
file_type.as_raw(),
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_use_PrivateKey)]
pub fn set_private_key<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
where
T: HasPrivate,
{
unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) }
}
#[corresponds(SSL_CTX_set_cipher_list)]
pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
let cipher_list = CString::new(cipher_list).unwrap();
unsafe {
cvt(ffi::SSL_CTX_set_cipher_list(
self.as_ptr(),
cipher_list.as_ptr() as *const _,
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_set_ciphersuites)]
#[cfg(any(ossl111, libressl))]
pub fn set_ciphersuites(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
let cipher_list = CString::new(cipher_list).unwrap();
unsafe {
cvt(ffi::SSL_CTX_set_ciphersuites(
self.as_ptr(),
cipher_list.as_ptr() as *const _,
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_set_ecdh_auto)]
#[cfg(libressl)]
pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) }
}
#[corresponds(SSL_CTX_set_options)]
pub fn set_options(&mut self, option: SslOptions) -> SslOptions {
let bits =
unsafe { ffi::SSL_CTX_set_options(self.as_ptr(), option.bits()) } as SslOptionsRepr;
SslOptions::from_bits_retain(bits)
}
#[corresponds(SSL_CTX_get_options)]
pub fn options(&self) -> SslOptions {
let bits = unsafe { ffi::SSL_CTX_get_options(self.as_ptr()) } as SslOptionsRepr;
SslOptions::from_bits_retain(bits)
}
#[corresponds(SSL_CTX_clear_options)]
pub fn clear_options(&mut self, option: SslOptions) -> SslOptions {
let bits =
unsafe { ffi::SSL_CTX_clear_options(self.as_ptr(), option.bits()) } as SslOptionsRepr;
SslOptions::from_bits_retain(bits)
}
#[corresponds(SSL_CTX_set_min_proto_version)]
pub fn set_min_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_CTX_set_min_proto_version(
self.as_ptr(),
version.map_or(0, |v| v.0 as _),
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_set_max_proto_version)]
pub fn set_max_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_CTX_set_max_proto_version(
self.as_ptr(),
version.map_or(0, |v| v.0 as _),
))
.map(|_| ())
}
}
#[corresponds(SSL_CTX_get_min_proto_version)]
#[cfg(any(ossl110g, libressl))]
pub fn min_proto_version(&mut self) -> Option<SslVersion> {
unsafe {
let r = ffi::SSL_CTX_get_min_proto_version(self.as_ptr());
if r == 0 {
None
} else {
Some(SslVersion(r))
}
}
}
#[corresponds(SSL_CTX_get_max_proto_version)]
#[cfg(any(ossl110g, libressl))]
pub fn max_proto_version(&mut self) -> Option<SslVersion> {
unsafe {
let r = ffi::SSL_CTX_get_max_proto_version(self.as_ptr());
if r == 0 {
None
} else {
Some(SslVersion(r))
}
}
}
#[corresponds(SSL_CTX_set_alpn_protos)]
pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack> {
unsafe {
assert!(protocols.len() <= c_uint::MAX as usize);
let r = ffi::SSL_CTX_set_alpn_protos(
self.as_ptr(),
protocols.as_ptr(),
protocols.len() as _,
);
if r == 0 {
Ok(())
} else {
Err(ErrorStack::get())
}
}
}
#[cfg(not(osslconf = "OPENSSL_NO_SRTP"))]
#[corresponds(SSL_CTX_set_tlsext_use_srtp)]
pub fn set_tlsext_use_srtp(&mut self, protocols: &str) -> Result<(), ErrorStack> {
unsafe {
let cstr = CString::new(protocols).unwrap();
let r = ffi::SSL_CTX_set_tlsext_use_srtp(self.as_ptr(), cstr.as_ptr());
if r == 0 {
Ok(())
} else {
Err(ErrorStack::get())
}
}
}
#[corresponds(SSL_CTX_set_alpn_select_cb)]
pub fn set_alpn_select_callback<F>(&mut self, callback: F)
where
F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
#[cfg(not(any(boringssl, awslc)))]
ffi::SSL_CTX_set_alpn_select_cb__fixed_rust(
self.as_ptr(),
Some(callbacks::raw_alpn_select::<F>),
ptr::null_mut(),
);
#[cfg(any(boringssl, awslc))]
ffi::SSL_CTX_set_alpn_select_cb(
self.as_ptr(),
Some(callbacks::raw_alpn_select::<F>),
ptr::null_mut(),
);
}
}
#[corresponds(SSL_CTX_check_private_key)]
pub fn check_private_key(&self) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) }
}
#[corresponds(SSL_CTX_get_cert_store)]
pub fn cert_store(&self) -> &X509StoreBuilderRef {
unsafe { X509StoreBuilderRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) }
}
#[corresponds(SSL_CTX_get_cert_store)]
pub fn cert_store_mut(&mut self) -> &mut X509StoreBuilderRef {
unsafe { X509StoreBuilderRef::from_ptr_mut(ffi::SSL_CTX_get_cert_store(self.as_ptr())) }
}
#[corresponds(SSL_CTX_get0_param)]
pub fn verify_param(&self) -> &X509VerifyParamRef {
unsafe { X509VerifyParamRef::from_ptr(ffi::SSL_CTX_get0_param(self.as_ptr())) }
}
#[corresponds(SSL_CTX_get0_param)]
pub fn verify_param_mut(&mut self) -> &mut X509VerifyParamRef {
unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_CTX_get0_param(self.as_ptr())) }
}
#[corresponds(SSL_CTX_set_tlsext_status_cb)]
pub fn set_status_callback<F>(&mut self, callback: F) -> Result<(), ErrorStack>
where
F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
cvt(
ffi::SSL_CTX_set_tlsext_status_cb(self.as_ptr(), Some(raw_tlsext_status::<F>))
as c_int,
)
.map(|_| ())
}
}
#[corresponds(SSL_CTX_set_psk_client_callback)]
#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
pub fn set_psk_client_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack>
+ 'static
+ Sync
+ Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_psk_client_callback(self.as_ptr(), Some(raw_client_psk::<F>));
}
}
#[deprecated(since = "0.10.10", note = "renamed to `set_psk_client_callback`")]
#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
pub fn set_psk_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack>
+ 'static
+ Sync
+ Send,
{
self.set_psk_client_callback(callback)
}
#[corresponds(SSL_CTX_set_psk_server_callback)]
#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
pub fn set_psk_server_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8]) -> Result<usize, ErrorStack>
+ 'static
+ Sync
+ Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_psk_server_callback(self.as_ptr(), Some(raw_server_psk::<F>));
}
}
#[corresponds(SSL_CTX_sess_set_new_cb)]
pub fn set_new_session_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_sess_set_new_cb(self.as_ptr(), Some(callbacks::raw_new_session::<F>));
}
}
#[corresponds(SSL_CTX_sess_set_remove_cb)]
pub fn set_remove_session_callback<F>(&mut self, callback: F)
where
F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_sess_set_remove_cb(
self.as_ptr(),
Some(callbacks::raw_remove_session::<F>),
);
}
}
#[corresponds(SSL_CTX_sess_set_get_cb)]
pub unsafe fn set_get_session_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,
{
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_sess_set_get_cb(self.as_ptr(), Some(callbacks::raw_get_session::<F>));
}
#[corresponds(SSL_CTX_set_keylog_callback)]
#[cfg(any(ossl111, boringssl, awslc))]
pub fn set_keylog_callback<F>(&mut self, callback: F)
where
F: Fn(&SslRef, &str) + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_keylog_callback(self.as_ptr(), Some(callbacks::raw_keylog::<F>));
}
}
#[corresponds(SSL_CTX_set_session_cache_mode)]
pub fn set_session_cache_mode(&mut self, mode: SslSessionCacheMode) -> SslSessionCacheMode {
unsafe {
let bits = ffi::SSL_CTX_set_session_cache_mode(self.as_ptr(), mode.bits());
SslSessionCacheMode::from_bits_retain(bits)
}
}
#[corresponds(SSL_CTX_set_stateless_cookie_generate_cb)]
#[cfg(ossl111)]
pub fn set_stateless_cookie_generate_cb<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_stateless_cookie_generate_cb(
self.as_ptr(),
Some(raw_stateless_cookie_generate::<F>),
);
}
}
#[corresponds(SSL_CTX_set_stateless_cookie_verify_cb)]
#[cfg(ossl111)]
pub fn set_stateless_cookie_verify_cb<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_stateless_cookie_verify_cb(
self.as_ptr(),
Some(raw_stateless_cookie_verify::<F>),
)
}
}
#[corresponds(SSL_CTX_set_cookie_generate_cb)]
#[cfg(not(any(boringssl, awslc)))]
pub fn set_cookie_generate_cb<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_cookie_generate_cb(self.as_ptr(), Some(raw_cookie_generate::<F>));
}
}
#[corresponds(SSL_CTX_set_cookie_verify_cb)]
#[cfg(not(any(boringssl, awslc)))]
pub fn set_cookie_verify_cb<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_cookie_verify_cb(self.as_ptr(), Some(raw_cookie_verify::<F>));
}
}
#[corresponds(SSL_CTX_set_ex_data)]
pub fn set_ex_data<T>(&mut self, index: Index<SslContext, T>, data: T) {
self.set_ex_data_inner(index, data);
}
fn set_ex_data_inner<T>(&mut self, index: Index<SslContext, T>, data: T) -> *mut c_void {
match self.ex_data_mut(index) {
Some(v) => {
*v = data;
(v as *mut T).cast()
}
_ => unsafe {
let data = Box::into_raw(Box::new(data)) as *mut c_void;
ffi::SSL_CTX_set_ex_data(self.as_ptr(), index.as_raw(), data);
data
},
}
}
fn ex_data_mut<T>(&mut self, index: Index<SslContext, T>) -> Option<&mut T> {
unsafe {
let data = ffi::SSL_CTX_get_ex_data(self.as_ptr(), index.as_raw());
if data.is_null() {
None
} else {
Some(&mut *data.cast())
}
}
}
#[corresponds(SSL_CTX_add_custom_ext)]
#[cfg(ossl111)]
pub fn add_custom_ext<AddFn, ParseFn, T>(
&mut self,
ext_type: u16,
context: ExtensionContext,
add_cb: AddFn,
parse_cb: ParseFn,
) -> Result<(), ErrorStack>
where
AddFn: Fn(
&mut SslRef,
ExtensionContext,
Option<(usize, &X509Ref)>,
) -> Result<Option<T>, SslAlert>
+ 'static
+ Sync
+ Send,
T: AsRef<[u8]> + 'static + Sync + Send,
ParseFn: Fn(
&mut SslRef,
ExtensionContext,
&[u8],
Option<(usize, &X509Ref)>,
) -> Result<(), SslAlert>
+ 'static
+ Sync
+ Send,
{
let ret = unsafe {
self.set_ex_data(SslContext::cached_ex_index::<AddFn>(), add_cb);
self.set_ex_data(SslContext::cached_ex_index::<ParseFn>(), parse_cb);
ffi::SSL_CTX_add_custom_ext(
self.as_ptr(),
ext_type as c_uint,
context.bits(),
Some(raw_custom_ext_add::<AddFn, T>),
Some(raw_custom_ext_free::<T>),
ptr::null_mut(),
Some(raw_custom_ext_parse::<ParseFn>),
ptr::null_mut(),
)
};
if ret == 1 {
Ok(())
} else {
Err(ErrorStack::get())
}
}
#[corresponds(SSL_CTX_set_max_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn set_max_early_data(&mut self, bytes: u32) -> Result<(), ErrorStack> {
if unsafe { ffi::SSL_CTX_set_max_early_data(self.as_ptr(), bytes) } == 1 {
Ok(())
} else {
Err(ErrorStack::get())
}
}
#[corresponds(SSL_CTX_set_client_hello_cb)]
#[cfg(ossl111)]
pub fn set_client_hello_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, &mut SslAlert) -> Result<ClientHelloResponse, ErrorStack>
+ 'static
+ Sync
+ Send,
{
unsafe {
let ptr = self.set_ex_data_inner(SslContext::cached_ex_index::<F>(), callback);
ffi::SSL_CTX_set_client_hello_cb(
self.as_ptr(),
Some(callbacks::raw_client_hello::<F>),
ptr,
);
}
}
#[corresponds(SSL_CTX_sess_set_cache_size)]
#[allow(clippy::useless_conversion)]
pub fn set_session_cache_size(&mut self, size: i32) -> i64 {
unsafe {
ffi::SSL_CTX_sess_set_cache_size(self.as_ptr(), size as SslCacheSize) as SslCacheTy
}
}
#[corresponds(SSL_CTX_set1_sigalgs_list)]
#[cfg(ossl110)]
pub fn set_sigalgs_list(&mut self, sigalgs: &str) -> Result<(), ErrorStack> {
let sigalgs = CString::new(sigalgs).unwrap();
unsafe {
cvt(ffi::SSL_CTX_set1_sigalgs_list(self.as_ptr(), sigalgs.as_ptr()) as c_int)
.map(|_| ())
}
}
#[corresponds(SSL_CTX_set1_groups_list)]
#[cfg(any(ossl111, boringssl, libressl, awslc))]
pub fn set_groups_list(&mut self, groups: &str) -> Result<(), ErrorStack> {
let groups = CString::new(groups).unwrap();
unsafe {
cvt(ffi::SSL_CTX_set1_groups_list(self.as_ptr(), groups.as_ptr()) as c_int).map(|_| ())
}
}
#[corresponds(SSL_CTX_set_num_tickets)]
#[cfg(ossl111)]
pub fn set_num_tickets(&mut self, num_tickets: usize) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_CTX_set_num_tickets(self.as_ptr(), num_tickets)).map(|_| ()) }
}
#[corresponds(SSL_CTX_set_security_level)]
#[cfg(any(ossl110, libressl360))]
pub fn set_security_level(&mut self, level: u32) {
unsafe { ffi::SSL_CTX_set_security_level(self.as_ptr(), level as c_int) }
}
pub fn build(self) -> SslContext {
self.0
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::SSL_CTX;
fn drop = ffi::SSL_CTX_free;
pub struct SslContext;
pub struct SslContextRef;
}
impl Clone for SslContext {
fn clone(&self) -> Self {
(**self).to_owned()
}
}
impl ToOwned for SslContextRef {
type Owned = SslContext;
fn to_owned(&self) -> Self::Owned {
unsafe {
SSL_CTX_up_ref(self.as_ptr());
SslContext::from_ptr(self.as_ptr())
}
}
}
impl fmt::Debug for SslContext {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "SslContext")
}
}
impl SslContext {
pub fn builder(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> {
SslContextBuilder::new(method)
}
#[corresponds(SSL_CTX_get_ex_new_index)]
pub fn new_ex_index<T>() -> Result<Index<SslContext, T>, ErrorStack>
where
T: 'static + Sync + Send,
{
unsafe {
ffi::init();
#[cfg(any(boringssl, awslc))]
let idx = cvt_n(get_new_idx(Some(free_data_box::<T>)))?;
#[cfg(not(any(boringssl, awslc)))]
let idx = cvt_n(get_new_idx(free_data_box::<T>))?;
Ok(Index::from_raw(idx))
}
}
fn cached_ex_index<T>() -> Index<SslContext, T>
where
T: 'static + Sync + Send,
{
unsafe {
let idx = *INDEXES
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(TypeId::of::<T>())
.or_insert_with(|| SslContext::new_ex_index::<T>().unwrap().as_raw());
Index::from_raw(idx)
}
}
}
impl SslContextRef {
#[corresponds(SSL_CTX_get0_certificate)]
#[cfg(any(ossl110, libressl))]
pub fn certificate(&self) -> Option<&X509Ref> {
unsafe {
let ptr = ffi::SSL_CTX_get0_certificate(self.as_ptr());
X509Ref::from_const_ptr_opt(ptr)
}
}
#[corresponds(SSL_CTX_get0_privatekey)]
#[cfg(any(ossl110, libressl))]
pub fn private_key(&self) -> Option<&PKeyRef<Private>> {
unsafe {
let ptr = ffi::SSL_CTX_get0_privatekey(self.as_ptr());
PKeyRef::from_const_ptr_opt(ptr)
}
}
#[corresponds(SSL_CTX_get_cert_store)]
pub fn cert_store(&self) -> &X509StoreRef {
unsafe { X509StoreRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) }
}
#[corresponds(SSL_CTX_get_extra_chain_certs)]
pub fn extra_chain_certs(&self) -> &StackRef<X509> {
unsafe {
let mut chain = ptr::null_mut();
ffi::SSL_CTX_get_extra_chain_certs(self.as_ptr(), &mut chain);
StackRef::from_const_ptr_opt(chain).expect("extra chain certs must not be null")
}
}
#[corresponds(SSL_CTX_get_ex_data)]
pub fn ex_data<T>(&self, index: Index<SslContext, T>) -> Option<&T> {
unsafe {
let data = ffi::SSL_CTX_get_ex_data(self.as_ptr(), index.as_raw());
if data.is_null() {
None
} else {
Some(&*(data as *const T))
}
}
}
#[corresponds(SSL_CTX_get_max_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn max_early_data(&self) -> u32 {
unsafe { ffi::SSL_CTX_get_max_early_data(self.as_ptr()) }
}
#[corresponds(SSL_CTX_add_session)]
pub unsafe fn add_session(&self, session: &SslSessionRef) -> bool {
ffi::SSL_CTX_add_session(self.as_ptr(), session.as_ptr()) != 0
}
#[corresponds(SSL_CTX_remove_session)]
pub unsafe fn remove_session(&self, session: &SslSessionRef) -> bool {
ffi::SSL_CTX_remove_session(self.as_ptr(), session.as_ptr()) != 0
}
#[corresponds(SSL_CTX_sess_get_cache_size)]
#[allow(clippy::unnecessary_cast)]
pub fn session_cache_size(&self) -> i64 {
unsafe { ffi::SSL_CTX_sess_get_cache_size(self.as_ptr()) as i64 }
}
#[corresponds(SSL_CTX_get_verify_mode)]
pub fn verify_mode(&self) -> SslVerifyMode {
let mode = unsafe { ffi::SSL_CTX_get_verify_mode(self.as_ptr()) };
SslVerifyMode::from_bits(mode).expect("SSL_CTX_get_verify_mode returned invalid mode")
}
#[corresponds(SSL_CTX_get_num_tickets)]
#[cfg(ossl111)]
pub fn num_tickets(&self) -> usize {
unsafe { ffi::SSL_CTX_get_num_tickets(self.as_ptr()) }
}
#[corresponds(SSL_CTX_get_security_level)]
#[cfg(any(ossl110, libressl360))]
pub fn security_level(&self) -> u32 {
unsafe { ffi::SSL_CTX_get_security_level(self.as_ptr()) as u32 }
}
}
pub struct CipherBits {
pub secret: i32,
pub algorithm: i32,
}
pub struct SslCipher(*mut ffi::SSL_CIPHER);
impl ForeignType for SslCipher {
type CType = ffi::SSL_CIPHER;
type Ref = SslCipherRef;
#[inline]
unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher {
SslCipher(ptr)
}
#[inline]
fn as_ptr(&self) -> *mut ffi::SSL_CIPHER {
self.0
}
}
impl Stackable for SslCipher {
type StackType = ffi::stack_st_SSL_CIPHER;
}
impl Deref for SslCipher {
type Target = SslCipherRef;
fn deref(&self) -> &SslCipherRef {
unsafe { SslCipherRef::from_ptr(self.0) }
}
}
impl DerefMut for SslCipher {
fn deref_mut(&mut self) -> &mut SslCipherRef {
unsafe { SslCipherRef::from_ptr_mut(self.0) }
}
}
pub struct SslCipherRef(Opaque);
impl ForeignTypeRef for SslCipherRef {
type CType = ffi::SSL_CIPHER;
}
impl SslCipherRef {
#[corresponds(SSL_CIPHER_get_name)]
pub fn name(&self) -> &'static str {
unsafe {
let ptr = ffi::SSL_CIPHER_get_name(self.as_ptr());
CStr::from_ptr(ptr).to_str().unwrap()
}
}
#[corresponds(SSL_CIPHER_standard_name)]
#[cfg(ossl111)]
pub fn standard_name(&self) -> Option<&'static str> {
unsafe {
let ptr = ffi::SSL_CIPHER_standard_name(self.as_ptr());
if ptr.is_null() {
None
} else {
Some(CStr::from_ptr(ptr).to_str().unwrap())
}
}
}
#[corresponds(SSL_CIPHER_get_version)]
pub fn version(&self) -> &'static str {
let version = unsafe {
let ptr = ffi::SSL_CIPHER_get_version(self.as_ptr());
CStr::from_ptr(ptr as *const _)
};
str::from_utf8(version.to_bytes()).unwrap()
}
#[corresponds(SSL_CIPHER_get_bits)]
#[allow(clippy::useless_conversion)]
pub fn bits(&self) -> CipherBits {
unsafe {
let mut algo_bits = 0;
let secret_bits = ffi::SSL_CIPHER_get_bits(self.as_ptr(), &mut algo_bits);
CipherBits {
secret: secret_bits.into(),
algorithm: algo_bits.into(),
}
}
}
#[corresponds(SSL_CIPHER_description)]
pub fn description(&self) -> String {
unsafe {
let mut buf = [0; 128];
let ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128);
String::from_utf8(CStr::from_ptr(ptr as *const _).to_bytes().to_vec()).unwrap()
}
}
#[corresponds(SSL_CIPHER_get_handshake_digest)]
#[cfg(ossl111)]
pub fn handshake_digest(&self) -> Option<MessageDigest> {
unsafe {
let ptr = ffi::SSL_CIPHER_get_handshake_digest(self.as_ptr());
if ptr.is_null() {
None
} else {
Some(MessageDigest::from_ptr(ptr))
}
}
}
#[corresponds(SSL_CIPHER_get_cipher_nid)]
#[cfg(any(ossl110, libressl))]
pub fn cipher_nid(&self) -> Option<Nid> {
let n = unsafe { ffi::SSL_CIPHER_get_cipher_nid(self.as_ptr()) };
if n == 0 {
None
} else {
Some(Nid::from_raw(n))
}
}
#[corresponds(SSL_CIPHER_get_protocol_id)]
#[cfg(ossl111)]
pub fn protocol_id(&self) -> [u8; 2] {
unsafe {
let id = ffi::SSL_CIPHER_get_protocol_id(self.as_ptr());
id.to_be_bytes()
}
}
}
impl fmt::Debug for SslCipherRef {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{}", self.name())
}
}
#[derive(Debug)]
pub struct CipherLists {
pub suites: Stack<SslCipher>,
pub signalling_suites: Stack<SslCipher>,
}
foreign_type_and_impl_send_sync! {
type CType = ffi::SSL_SESSION;
fn drop = ffi::SSL_SESSION_free;
pub struct SslSession;
pub struct SslSessionRef;
}
impl Clone for SslSession {
fn clone(&self) -> SslSession {
SslSessionRef::to_owned(self)
}
}
impl SslSession {
from_der! {
#[corresponds(d2i_SSL_SESSION)]
from_der,
SslSession,
ffi::d2i_SSL_SESSION
}
}
impl ToOwned for SslSessionRef {
type Owned = SslSession;
fn to_owned(&self) -> SslSession {
unsafe {
SSL_SESSION_up_ref(self.as_ptr());
SslSession(self.as_ptr())
}
}
}
impl SslSessionRef {
#[corresponds(SSL_SESSION_get_id)]
pub fn id(&self) -> &[u8] {
unsafe {
let mut len = 0;
let p = ffi::SSL_SESSION_get_id(self.as_ptr(), &mut len);
#[allow(clippy::unnecessary_cast)]
util::from_raw_parts(p as *const u8, len as usize)
}
}
#[corresponds(SSL_SESSION_get_master_key)]
pub fn master_key_len(&self) -> usize {
unsafe { SSL_SESSION_get_master_key(self.as_ptr(), ptr::null_mut(), 0) }
}
#[corresponds(SSL_SESSION_get_master_key)]
pub fn master_key(&self, buf: &mut [u8]) -> usize {
unsafe { SSL_SESSION_get_master_key(self.as_ptr(), buf.as_mut_ptr(), buf.len()) }
}
#[corresponds(SSL_SESSION_get_max_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn max_early_data(&self) -> u32 {
unsafe { ffi::SSL_SESSION_get_max_early_data(self.as_ptr()) }
}
#[corresponds(SSL_SESSION_get_time)]
#[allow(clippy::useless_conversion)]
pub fn time(&self) -> SslTimeTy {
unsafe { ffi::SSL_SESSION_get_time(self.as_ptr()) }
}
#[corresponds(SSL_SESSION_get_timeout)]
#[allow(clippy::useless_conversion)]
pub fn timeout(&self) -> i64 {
unsafe { ffi::SSL_SESSION_get_timeout(self.as_ptr()).into() }
}
#[corresponds(SSL_SESSION_get_protocol_version)]
#[cfg(any(ossl110, libressl))]
pub fn protocol_version(&self) -> SslVersion {
unsafe {
let version = ffi::SSL_SESSION_get_protocol_version(self.as_ptr());
SslVersion(version)
}
}
to_der! {
#[corresponds(i2d_SSL_SESSION)]
to_der,
ffi::i2d_SSL_SESSION
}
}
foreign_type_and_impl_send_sync! {
type CType = ffi::SSL;
fn drop = ffi::SSL_free;
pub struct Ssl;
pub struct SslRef;
}
impl fmt::Debug for Ssl {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, fmt)
}
}
impl Ssl {
#[corresponds(SSL_get_ex_new_index)]
pub fn new_ex_index<T>() -> Result<Index<Ssl, T>, ErrorStack>
where
T: 'static + Sync + Send,
{
unsafe {
ffi::init();
#[cfg(any(boringssl, awslc))]
let idx = cvt_n(get_new_ssl_idx(Some(free_data_box::<T>)))?;
#[cfg(not(any(boringssl, awslc)))]
let idx = cvt_n(get_new_ssl_idx(free_data_box::<T>))?;
Ok(Index::from_raw(idx))
}
}
fn cached_ex_index<T>() -> Index<Ssl, T>
where
T: 'static + Sync + Send,
{
unsafe {
let idx = *SSL_INDEXES
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(TypeId::of::<T>())
.or_insert_with(|| Ssl::new_ex_index::<T>().unwrap().as_raw());
Index::from_raw(idx)
}
}
#[corresponds(SSL_new)]
pub fn new(ctx: &SslContextRef) -> Result<Ssl, ErrorStack> {
let session_ctx_index = try_get_session_ctx_index()?;
unsafe {
let ptr = cvt_p(ffi::SSL_new(ctx.as_ptr()))?;
let mut ssl = Ssl::from_ptr(ptr);
ssl.set_ex_data(*session_ctx_index, ctx.to_owned());
Ok(ssl)
}
}
#[corresponds(SSL_connect)]
#[allow(deprecated)]
pub fn connect<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
where
S: Read + Write,
{
SslStreamBuilder::new(self, stream).connect()
}
#[corresponds(SSL_accept)]
#[allow(deprecated)]
pub fn accept<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
where
S: Read + Write,
{
SslStreamBuilder::new(self, stream).accept()
}
}
impl fmt::Debug for SslRef {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("Ssl")
.field("state", &self.state_string_long())
.field("verify_result", &self.verify_result())
.finish()
}
}
impl SslRef {
fn get_raw_rbio(&self) -> *mut ffi::BIO {
unsafe { ffi::SSL_get_rbio(self.as_ptr()) }
}
fn get_error(&self, ret: c_int) -> ErrorCode {
unsafe { ErrorCode::from_raw(ffi::SSL_get_error(self.as_ptr(), ret)) }
}
#[corresponds(SSL_set_connect_state)]
pub fn set_connect_state(&mut self) {
unsafe { ffi::SSL_set_connect_state(self.as_ptr()) }
}
#[corresponds(SSL_set_accept_state)]
pub fn set_accept_state(&mut self) {
unsafe { ffi::SSL_set_accept_state(self.as_ptr()) }
}
#[corresponds(SSL_set_verify)]
pub fn set_verify(&mut self, mode: SslVerifyMode) {
unsafe { ffi::SSL_set_verify(self.as_ptr(), mode.bits() as c_int, None) }
}
#[corresponds(SSL_set_verify_mode)]
pub fn verify_mode(&self) -> SslVerifyMode {
let mode = unsafe { ffi::SSL_get_verify_mode(self.as_ptr()) };
SslVerifyMode::from_bits(mode).expect("SSL_get_verify_mode returned invalid mode")
}
#[corresponds(SSL_set_verify)]
pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
where
F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(Ssl::cached_ex_index(), Arc::new(verify));
ffi::SSL_set_verify(
self.as_ptr(),
mode.bits() as c_int,
Some(ssl_raw_verify::<F>),
);
}
}
#[corresponds(SSL_set_tmp_dh)]
pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) }
}
#[corresponds(SSL_set_tmp_dh_callback)]
pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
where
F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
{
unsafe {
self.set_ex_data(Ssl::cached_ex_index(), Arc::new(callback));
#[cfg(any(boringssl, awslc))]
ffi::SSL_set_tmp_dh_callback(self.as_ptr(), Some(raw_tmp_dh_ssl::<F>));
#[cfg(not(any(boringssl, awslc)))]
ffi::SSL_set_tmp_dh_callback__fixed_rust(self.as_ptr(), Some(raw_tmp_dh_ssl::<F>));
}
}
#[corresponds(SSL_set_tmp_ecdh)]
pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) }
}
#[corresponds(SSL_set_ecdh_auto)]
#[cfg(libressl)]
pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) }
}
#[corresponds(SSL_set_alpn_protos)]
pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack> {
unsafe {
assert!(protocols.len() <= c_uint::MAX as usize);
let r =
ffi::SSL_set_alpn_protos(self.as_ptr(), protocols.as_ptr(), protocols.len() as _);
if r == 0 {
Ok(())
} else {
Err(ErrorStack::get())
}
}
}
#[corresponds(SSL_get_current_cipher)]
pub fn current_cipher(&self) -> Option<&SslCipherRef> {
unsafe {
let ptr = ffi::SSL_get_current_cipher(self.as_ptr());
SslCipherRef::from_const_ptr_opt(ptr)
}
}
#[corresponds(SSL_state_string)]
pub fn state_string(&self) -> &'static str {
let state = unsafe {
let ptr = ffi::SSL_state_string(self.as_ptr());
CStr::from_ptr(ptr as *const _)
};
str::from_utf8(state.to_bytes()).unwrap()
}
#[corresponds(SSL_state_string_long)]
pub fn state_string_long(&self) -> &'static str {
let state = unsafe {
let ptr = ffi::SSL_state_string_long(self.as_ptr());
CStr::from_ptr(ptr as *const _)
};
str::from_utf8(state.to_bytes()).unwrap()
}
#[corresponds(SSL_set_tlsext_host_name)]
pub fn set_hostname(&mut self, hostname: &str) -> Result<(), ErrorStack> {
let cstr = CString::new(hostname).unwrap();
unsafe {
cvt(ffi::SSL_set_tlsext_host_name(self.as_ptr(), cstr.as_ptr() as *mut _) as c_int)
.map(|_| ())
}
}
#[corresponds(SSL_get_peer_certificate)]
pub fn peer_certificate(&self) -> Option<X509> {
unsafe {
let ptr = SSL_get1_peer_certificate(self.as_ptr());
X509::from_ptr_opt(ptr)
}
}
#[corresponds(SSL_get_peer_cert_chain)]
pub fn peer_cert_chain(&self) -> Option<&StackRef<X509>> {
unsafe {
let ptr = ffi::SSL_get_peer_cert_chain(self.as_ptr());
StackRef::from_const_ptr_opt(ptr)
}
}
#[corresponds(SSL_get0_verified_chain)]
#[cfg(ossl110)]
pub fn verified_chain(&self) -> Option<&StackRef<X509>> {
unsafe {
let ptr = ffi::SSL_get0_verified_chain(self.as_ptr());
StackRef::from_const_ptr_opt(ptr)
}
}
#[corresponds(SSL_get_certificate)]
pub fn certificate(&self) -> Option<&X509Ref> {
unsafe {
let ptr = ffi::SSL_get_certificate(self.as_ptr());
X509Ref::from_const_ptr_opt(ptr)
}
}
#[corresponds(SSL_get_privatekey)]
pub fn private_key(&self) -> Option<&PKeyRef<Private>> {
unsafe {
let ptr = ffi::SSL_get_privatekey(self.as_ptr());
PKeyRef::from_const_ptr_opt(ptr)
}
}
#[deprecated(since = "0.10.5", note = "renamed to `version_str`")]
pub fn version(&self) -> &str {
self.version_str()
}
#[corresponds(SSL_version)]
pub fn version2(&self) -> Option<SslVersion> {
unsafe {
let r = ffi::SSL_version(self.as_ptr());
if r == 0 {
None
} else {
Some(SslVersion(r))
}
}
}
#[corresponds(SSL_get_version)]
pub fn version_str(&self) -> &'static str {
let version = unsafe {
let ptr = ffi::SSL_get_version(self.as_ptr());
CStr::from_ptr(ptr as *const _)
};
str::from_utf8(version.to_bytes()).unwrap()
}
#[corresponds(SSL_get0_alpn_selected)]
pub fn selected_alpn_protocol(&self) -> Option<&[u8]> {
unsafe {
let mut data: *const c_uchar = ptr::null();
let mut len: c_uint = 0;
ffi::SSL_get0_alpn_selected(self.as_ptr(), &mut data, &mut len);
if data.is_null() {
None
} else {
Some(util::from_raw_parts(data, len as usize))
}
}
}
#[cfg(not(osslconf = "OPENSSL_NO_SRTP"))]
#[corresponds(SSL_set_tlsext_use_srtp)]
pub fn set_tlsext_use_srtp(&mut self, protocols: &str) -> Result<(), ErrorStack> {
unsafe {
let cstr = CString::new(protocols).unwrap();
let r = ffi::SSL_set_tlsext_use_srtp(self.as_ptr(), cstr.as_ptr());
if r == 0 {
Ok(())
} else {
Err(ErrorStack::get())
}
}
}
#[cfg(not(osslconf = "OPENSSL_NO_SRTP"))]
#[corresponds(SSL_get_srtp_profiles)]
pub fn srtp_profiles(&self) -> Option<&StackRef<SrtpProtectionProfile>> {
unsafe {
let chain = ffi::SSL_get_srtp_profiles(self.as_ptr());
StackRef::from_const_ptr_opt(chain)
}
}
#[cfg(not(osslconf = "OPENSSL_NO_SRTP"))]
#[corresponds(SSL_get_selected_srtp_profile)]
pub fn selected_srtp_profile(&self) -> Option<&SrtpProtectionProfileRef> {
unsafe {
let profile = ffi::SSL_get_selected_srtp_profile(self.as_ptr());
SrtpProtectionProfileRef::from_const_ptr_opt(profile)
}
}
#[corresponds(SSL_pending)]
pub fn pending(&self) -> usize {
unsafe { ffi::SSL_pending(self.as_ptr()) as usize }
}
#[corresponds(SSL_get_servername)]
pub fn servername(&self, type_: NameType) -> Option<&str> {
self.servername_raw(type_)
.and_then(|b| str::from_utf8(b).ok())
}
#[corresponds(SSL_get_servername)]
pub fn servername_raw(&self, type_: NameType) -> Option<&[u8]> {
unsafe {
let name = ffi::SSL_get_servername(self.as_ptr(), type_.0);
if name.is_null() {
None
} else {
Some(CStr::from_ptr(name as *const _).to_bytes())
}
}
}
#[corresponds(SSL_set_SSL_CTX)]
pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> {
unsafe { cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) }
}
#[corresponds(SSL_get_SSL_CTX)]
pub fn ssl_context(&self) -> &SslContextRef {
unsafe {
let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr());
SslContextRef::from_ptr(ssl_ctx)
}
}
#[corresponds(SSL_get0_param)]
pub fn param_mut(&mut self) -> &mut X509VerifyParamRef {
unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) }
}
#[corresponds(SSL_get_verify_result)]
pub fn verify_result(&self) -> X509VerifyResult {
unsafe { X509VerifyResult::from_raw(ffi::SSL_get_verify_result(self.as_ptr()) as c_int) }
}
#[corresponds(SSL_get_session)]
pub fn session(&self) -> Option<&SslSessionRef> {
unsafe {
let p = ffi::SSL_get_session(self.as_ptr());
SslSessionRef::from_const_ptr_opt(p)
}
}
#[corresponds(SSL_get_client_random)]
#[cfg(any(ossl110, libressl))]
pub fn client_random(&self, buf: &mut [u8]) -> usize {
unsafe {
ffi::SSL_get_client_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len())
}
}
#[corresponds(SSL_get_server_random)]
#[cfg(any(ossl110, libressl))]
pub fn server_random(&self, buf: &mut [u8]) -> usize {
unsafe {
ffi::SSL_get_server_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len())
}
}
#[corresponds(SSL_export_keying_material)]
pub fn export_keying_material(
&self,
out: &mut [u8],
label: &str,
context: Option<&[u8]>,
) -> Result<(), ErrorStack> {
unsafe {
let (context, contextlen, use_context) = match context {
Some(context) => (context.as_ptr() as *const c_uchar, context.len(), 1),
None => (ptr::null(), 0, 0),
};
cvt(ffi::SSL_export_keying_material(
self.as_ptr(),
out.as_mut_ptr() as *mut c_uchar,
out.len(),
label.as_ptr() as *const c_char,
label.len(),
context,
contextlen,
use_context,
))
.map(|_| ())
}
}
#[corresponds(SSL_export_keying_material_early)]
#[cfg(ossl111)]
pub fn export_keying_material_early(
&self,
out: &mut [u8],
label: &str,
context: &[u8],
) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_export_keying_material_early(
self.as_ptr(),
out.as_mut_ptr() as *mut c_uchar,
out.len(),
label.as_ptr() as *const c_char,
label.len(),
context.as_ptr() as *const c_uchar,
context.len(),
))
.map(|_| ())
}
}
#[corresponds(SSL_set_session)]
pub unsafe fn set_session(&mut self, session: &SslSessionRef) -> Result<(), ErrorStack> {
cvt(ffi::SSL_set_session(self.as_ptr(), session.as_ptr())).map(|_| ())
}
#[corresponds(SSL_session_reused)]
pub fn session_reused(&self) -> bool {
unsafe { ffi::SSL_session_reused(self.as_ptr()) != 0 }
}
#[corresponds(SSL_set_tlsext_status_type)]
pub fn set_status_type(&mut self, type_: StatusType) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_set_tlsext_status_type(self.as_ptr(), type_.as_raw()) as c_int).map(|_| ())
}
}
#[corresponds(SSL_get_extms_support)]
#[cfg(ossl110)]
pub fn extms_support(&self) -> Option<bool> {
unsafe {
match ffi::SSL_get_extms_support(self.as_ptr()) {
-1 => None,
ret => Some(ret != 0),
}
}
}
#[corresponds(SSL_get_tlsext_status_ocsp_resp)]
#[cfg(not(any(boringssl, awslc)))]
pub fn ocsp_status(&self) -> Option<&[u8]> {
unsafe {
let mut p = ptr::null_mut();
let len = ffi::SSL_get_tlsext_status_ocsp_resp(self.as_ptr(), &mut p);
if len < 0 {
None
} else {
Some(util::from_raw_parts(p as *const u8, len as usize))
}
}
}
#[corresponds(SSL_set_tlsext_status_oscp_resp)]
#[cfg(not(any(boringssl, awslc)))]
pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack> {
unsafe {
assert!(response.len() <= c_int::MAX as usize);
let p = cvt_p(ffi::OPENSSL_malloc(response.len() as _))?;
ptr::copy_nonoverlapping(response.as_ptr(), p as *mut u8, response.len());
cvt(ffi::SSL_set_tlsext_status_ocsp_resp(
self.as_ptr(),
p as *mut c_uchar,
response.len() as c_long,
) as c_int)
.map(|_| ())
.map_err(|e| {
ffi::OPENSSL_free(p);
e
})
}
}
#[corresponds(SSL_is_server)]
pub fn is_server(&self) -> bool {
unsafe { SSL_is_server(self.as_ptr()) != 0 }
}
#[corresponds(SSL_set_ex_data)]
pub fn set_ex_data<T>(&mut self, index: Index<Ssl, T>, data: T) {
match self.ex_data_mut(index) {
Some(v) => *v = data,
None => unsafe {
let data = Box::new(data);
ffi::SSL_set_ex_data(
self.as_ptr(),
index.as_raw(),
Box::into_raw(data) as *mut c_void,
);
},
}
}
#[corresponds(SSL_get_ex_data)]
pub fn ex_data<T>(&self, index: Index<Ssl, T>) -> Option<&T> {
unsafe {
let data = ffi::SSL_get_ex_data(self.as_ptr(), index.as_raw());
if data.is_null() {
None
} else {
Some(&*(data as *const T))
}
}
}
#[corresponds(SSL_get_ex_data)]
pub fn ex_data_mut<T>(&mut self, index: Index<Ssl, T>) -> Option<&mut T> {
unsafe {
let data = ffi::SSL_get_ex_data(self.as_ptr(), index.as_raw());
if data.is_null() {
None
} else {
Some(&mut *(data as *mut T))
}
}
}
#[corresponds(SSL_set_max_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn set_max_early_data(&mut self, bytes: u32) -> Result<(), ErrorStack> {
if unsafe { ffi::SSL_set_max_early_data(self.as_ptr(), bytes) } == 1 {
Ok(())
} else {
Err(ErrorStack::get())
}
}
#[corresponds(SSL_get_max_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn max_early_data(&self) -> u32 {
unsafe { ffi::SSL_get_max_early_data(self.as_ptr()) }
}
#[corresponds(SSL_get_finished)]
pub fn finished(&self, buf: &mut [u8]) -> usize {
unsafe { ffi::SSL_get_finished(self.as_ptr(), buf.as_mut_ptr() as *mut c_void, buf.len()) }
}
#[corresponds(SSL_get_peer_finished)]
pub fn peer_finished(&self, buf: &mut [u8]) -> usize {
unsafe {
ffi::SSL_get_peer_finished(self.as_ptr(), buf.as_mut_ptr() as *mut c_void, buf.len())
}
}
#[corresponds(SSL_is_init_finished)]
#[cfg(ossl110)]
pub fn is_init_finished(&self) -> bool {
unsafe { ffi::SSL_is_init_finished(self.as_ptr()) != 0 }
}
#[corresponds(SSL_client_hello_isv2)]
#[cfg(ossl111)]
pub fn client_hello_isv2(&self) -> bool {
unsafe { ffi::SSL_client_hello_isv2(self.as_ptr()) != 0 }
}
#[corresponds(SSL_client_hello_get0_legacy_version)]
#[cfg(ossl111)]
pub fn client_hello_legacy_version(&self) -> Option<SslVersion> {
unsafe {
let version = ffi::SSL_client_hello_get0_legacy_version(self.as_ptr());
if version == 0 {
None
} else {
Some(SslVersion(version as c_int))
}
}
}
#[corresponds(SSL_client_hello_get0_random)]
#[cfg(ossl111)]
pub fn client_hello_random(&self) -> Option<&[u8]> {
unsafe {
let mut ptr = ptr::null();
let len = ffi::SSL_client_hello_get0_random(self.as_ptr(), &mut ptr);
if len == 0 {
None
} else {
Some(util::from_raw_parts(ptr, len))
}
}
}
#[corresponds(SSL_client_hello_get0_session_id)]
#[cfg(ossl111)]
pub fn client_hello_session_id(&self) -> Option<&[u8]> {
unsafe {
let mut ptr = ptr::null();
let len = ffi::SSL_client_hello_get0_session_id(self.as_ptr(), &mut ptr);
if len == 0 {
None
} else {
Some(util::from_raw_parts(ptr, len))
}
}
}
#[corresponds(SSL_client_hello_get0_ciphers)]
#[cfg(ossl111)]
pub fn client_hello_ciphers(&self) -> Option<&[u8]> {
unsafe {
let mut ptr = ptr::null();
let len = ffi::SSL_client_hello_get0_ciphers(self.as_ptr(), &mut ptr);
if len == 0 {
None
} else {
Some(util::from_raw_parts(ptr, len))
}
}
}
#[corresponds(SSL_bytes_to_cipher_list)]
#[cfg(ossl111)]
pub fn bytes_to_cipher_list(
&self,
bytes: &[u8],
isv2format: bool,
) -> Result<CipherLists, ErrorStack> {
unsafe {
let ptr = bytes.as_ptr();
let len = bytes.len();
let mut sk = ptr::null_mut();
let mut scsvs = ptr::null_mut();
let res = ffi::SSL_bytes_to_cipher_list(
self.as_ptr(),
ptr,
len,
isv2format as c_int,
&mut sk,
&mut scsvs,
);
if res == 1 {
Ok(CipherLists {
suites: Stack::from_ptr(sk),
signalling_suites: Stack::from_ptr(scsvs),
})
} else {
Err(ErrorStack::get())
}
}
}
#[corresponds(SSL_client_hello_get0_compression_methods)]
#[cfg(ossl111)]
pub fn client_hello_compression_methods(&self) -> Option<&[u8]> {
unsafe {
let mut ptr = ptr::null();
let len = ffi::SSL_client_hello_get0_compression_methods(self.as_ptr(), &mut ptr);
if len == 0 {
None
} else {
Some(util::from_raw_parts(ptr, len))
}
}
}
#[corresponds(SSL_set_mtu)]
pub fn set_mtu(&mut self, mtu: u32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_set_mtu(self.as_ptr(), mtu as MtuTy) as c_int).map(|_| ()) }
}
#[corresponds(SSL_get_psk_identity_hint)]
#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
pub fn psk_identity_hint(&self) -> Option<&[u8]> {
unsafe {
let ptr = ffi::SSL_get_psk_identity_hint(self.as_ptr());
if ptr.is_null() {
None
} else {
Some(CStr::from_ptr(ptr).to_bytes())
}
}
}
#[corresponds(SSL_get_psk_identity)]
#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
pub fn psk_identity(&self) -> Option<&[u8]> {
unsafe {
let ptr = ffi::SSL_get_psk_identity(self.as_ptr());
if ptr.is_null() {
None
} else {
Some(CStr::from_ptr(ptr).to_bytes())
}
}
}
#[corresponds(SSL_add0_chain_cert)]
#[cfg(ossl110)]
pub fn add_chain_cert(&mut self, chain: X509) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_add0_chain_cert(self.as_ptr(), chain.as_ptr()) as c_int).map(|_| ())?;
mem::forget(chain);
}
Ok(())
}
#[cfg(not(any(boringssl, awslc)))]
pub fn set_method(&mut self, method: SslMethod) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_set_ssl_method(self.as_ptr(), method.as_ptr()))?;
};
Ok(())
}
#[corresponds(SSL_use_Private_Key_file)]
pub fn set_private_key_file<P: AsRef<Path>>(
&mut self,
path: P,
ssl_file_type: SslFiletype,
) -> Result<(), ErrorStack> {
let p = path.as_ref().as_os_str().to_str().unwrap();
let key_file = CString::new(p).unwrap();
unsafe {
cvt(ffi::SSL_use_PrivateKey_file(
self.as_ptr(),
key_file.as_ptr(),
ssl_file_type.as_raw(),
))?;
};
Ok(())
}
#[corresponds(SSL_use_PrivateKey)]
pub fn set_private_key(&mut self, pkey: &PKeyRef<Private>) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_use_PrivateKey(self.as_ptr(), pkey.as_ptr()))?;
};
Ok(())
}
#[corresponds(SSL_use_certificate)]
pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_use_certificate(self.as_ptr(), cert.as_ptr()))?;
};
Ok(())
}
#[corresponds(SSL_use_certificate_chain_file)]
#[cfg(any(ossl110, libressl))]
pub fn set_certificate_chain_file<P: AsRef<Path>>(
&mut self,
path: P,
) -> Result<(), ErrorStack> {
let p = path.as_ref().as_os_str().to_str().unwrap();
let cert_file = CString::new(p).unwrap();
unsafe {
cvt(ffi::SSL_use_certificate_chain_file(
self.as_ptr(),
cert_file.as_ptr(),
))?;
};
Ok(())
}
#[corresponds(SSL_add_client_CA)]
pub fn add_client_ca(&mut self, cacert: &X509Ref) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_add_client_CA(self.as_ptr(), cacert.as_ptr()))?;
};
Ok(())
}
#[corresponds(SSL_set_client_CA_list)]
pub fn set_client_ca_list(&mut self, list: Stack<X509Name>) {
unsafe { ffi::SSL_set_client_CA_list(self.as_ptr(), list.as_ptr()) }
mem::forget(list);
}
#[corresponds(SSL_set_min_proto_version)]
pub fn set_min_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_set_min_proto_version(
self.as_ptr(),
version.map_or(0, |v| v.0 as _),
))
.map(|_| ())
}
}
#[corresponds(SSL_set_max_proto_version)]
pub fn set_max_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_set_max_proto_version(
self.as_ptr(),
version.map_or(0, |v| v.0 as _),
))
.map(|_| ())
}
}
#[corresponds(SSL_set_ciphersuites)]
#[cfg(any(ossl111, libressl))]
pub fn set_ciphersuites(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
let cipher_list = CString::new(cipher_list).unwrap();
unsafe {
cvt(ffi::SSL_set_ciphersuites(
self.as_ptr(),
cipher_list.as_ptr() as *const _,
))
.map(|_| ())
}
}
#[corresponds(SSL_set_cipher_list)]
pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
let cipher_list = CString::new(cipher_list).unwrap();
unsafe {
cvt(ffi::SSL_set_cipher_list(
self.as_ptr(),
cipher_list.as_ptr() as *const _,
))
.map(|_| ())
}
}
#[corresponds(SSL_set_cert_store)]
#[cfg(ossl110)]
pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::SSL_set0_verify_cert_store(self.as_ptr(), cert_store.as_ptr()) as c_int)?;
mem::forget(cert_store);
Ok(())
}
}
#[corresponds(SSL_set_num_tickets)]
#[cfg(ossl111)]
pub fn set_num_tickets(&mut self, num_tickets: usize) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::SSL_set_num_tickets(self.as_ptr(), num_tickets)).map(|_| ()) }
}
#[corresponds(SSL_get_num_tickets)]
#[cfg(ossl111)]
pub fn num_tickets(&self) -> usize {
unsafe { ffi::SSL_get_num_tickets(self.as_ptr()) }
}
#[corresponds(SSL_set_security_level)]
#[cfg(any(ossl110, libressl360))]
pub fn set_security_level(&mut self, level: u32) {
unsafe { ffi::SSL_set_security_level(self.as_ptr(), level as c_int) }
}
#[corresponds(SSL_get_security_level)]
#[cfg(any(ossl110, libressl360))]
pub fn security_level(&self) -> u32 {
unsafe { ffi::SSL_get_security_level(self.as_ptr()) as u32 }
}
#[corresponds(SSL_get_peer_tmp_key)]
#[cfg(ossl300)]
pub fn peer_tmp_key(&self) -> Result<PKey<Public>, ErrorStack> {
unsafe {
let mut key = ptr::null_mut();
match cvt_long(ffi::SSL_get_peer_tmp_key(self.as_ptr(), &mut key)) {
Ok(_) => Ok(PKey::<Public>::from_ptr(key)),
Err(e) => Err(e),
}
}
}
#[corresponds(SSL_get_tmp_key)]
#[cfg(ossl300)]
pub fn tmp_key(&self) -> Result<PKey<Private>, ErrorStack> {
unsafe {
let mut key = ptr::null_mut();
match cvt_long(ffi::SSL_get_tmp_key(self.as_ptr(), &mut key)) {
Ok(_) => Ok(PKey::<Private>::from_ptr(key)),
Err(e) => Err(e),
}
}
}
}
#[derive(Debug)]
pub struct MidHandshakeSslStream<S> {
stream: SslStream<S>,
error: Error,
}
impl<S> MidHandshakeSslStream<S> {
pub fn get_ref(&self) -> &S {
self.stream.get_ref()
}
pub fn get_mut(&mut self) -> &mut S {
self.stream.get_mut()
}
pub fn ssl(&self) -> &SslRef {
self.stream.ssl()
}
pub fn error(&self) -> &Error {
&self.error
}
pub fn into_error(self) -> Error {
self.error
}
}
impl<S> MidHandshakeSslStream<S>
where
S: Read + Write,
{
#[corresponds(SSL_do_handshake)]
pub fn handshake(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
match self.stream.do_handshake() {
Ok(()) => Ok(self.stream),
Err(error) => {
self.error = error;
match self.error.code() {
ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
Err(HandshakeError::WouldBlock(self))
}
_ => Err(HandshakeError::Failure(self)),
}
}
}
}
}
pub struct SslStream<S> {
ssl: ManuallyDrop<Ssl>,
method: ManuallyDrop<BioMethod>,
_p: PhantomData<S>,
}
impl<S> Drop for SslStream<S> {
fn drop(&mut self) {
unsafe {
ManuallyDrop::drop(&mut self.ssl);
ManuallyDrop::drop(&mut self.method);
}
}
}
impl<S> fmt::Debug for SslStream<S>
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<S: Read + Write> SslStream<S> {
#[corresponds(SSL_set_bio)]
pub fn new(ssl: Ssl, stream: S) -> Result<Self, ErrorStack> {
let (bio, method) = bio::new(stream)?;
unsafe {
ffi::SSL_set_bio(ssl.as_ptr(), bio, bio);
}
Ok(SslStream {
ssl: ManuallyDrop::new(ssl),
method: ManuallyDrop::new(method),
_p: PhantomData,
})
}
#[deprecated(
since = "0.10.32",
note = "use Ssl::from_ptr and SslStream::new instead"
)]
pub unsafe fn from_raw_parts(ssl: *mut ffi::SSL, stream: S) -> Self {
let ssl = Ssl::from_ptr(ssl);
Self::new(ssl, stream).unwrap()
}
#[corresponds(SSL_read_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn read_early_data(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
let mut read = 0;
let ret = unsafe {
ffi::SSL_read_early_data(
self.ssl.as_ptr(),
buf.as_ptr() as *mut c_void,
buf.len(),
&mut read,
)
};
match ret {
ffi::SSL_READ_EARLY_DATA_ERROR => Err(self.make_error(ret)),
ffi::SSL_READ_EARLY_DATA_SUCCESS => Ok(read),
ffi::SSL_READ_EARLY_DATA_FINISH => Ok(0),
_ => unreachable!(),
}
}
#[corresponds(SSL_write_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn write_early_data(&mut self, buf: &[u8]) -> Result<usize, Error> {
let mut written = 0;
let ret = unsafe {
ffi::SSL_write_early_data(
self.ssl.as_ptr(),
buf.as_ptr() as *const c_void,
buf.len(),
&mut written,
)
};
if ret > 0 {
Ok(written)
} else {
Err(self.make_error(ret))
}
}
#[corresponds(SSL_connect)]
pub fn connect(&mut self) -> Result<(), Error> {
let ret = unsafe { ffi::SSL_connect(self.ssl.as_ptr()) };
if ret > 0 {
Ok(())
} else {
Err(self.make_error(ret))
}
}
#[corresponds(SSL_accept)]
pub fn accept(&mut self) -> Result<(), Error> {
let ret = unsafe { ffi::SSL_accept(self.ssl.as_ptr()) };
if ret > 0 {
Ok(())
} else {
Err(self.make_error(ret))
}
}
#[corresponds(SSL_do_handshake)]
pub fn do_handshake(&mut self) -> Result<(), Error> {
let ret = unsafe { ffi::SSL_do_handshake(self.ssl.as_ptr()) };
if ret > 0 {
Ok(())
} else {
Err(self.make_error(ret))
}
}
#[corresponds(SSL_stateless)]
#[cfg(ossl111)]
pub fn stateless(&mut self) -> Result<bool, ErrorStack> {
match unsafe { ffi::SSL_stateless(self.ssl.as_ptr()) } {
1 => Ok(true),
0 => Ok(false),
-1 => Err(ErrorStack::get()),
_ => unreachable!(),
}
}
#[corresponds(SSL_read_ex)]
pub fn read_uninit(&mut self, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
loop {
match self.ssl_read_uninit(buf) {
Ok(n) => return Ok(n),
Err(ref e) if e.code() == ErrorCode::ZERO_RETURN => return Ok(0),
Err(ref e) if e.code() == ErrorCode::SYSCALL && e.io_error().is_none() => {
return Ok(0);
}
Err(ref e) if e.code() == ErrorCode::WANT_READ && e.io_error().is_none() => {}
Err(e) => {
return Err(e
.into_io_error()
.unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e)));
}
}
}
}
#[corresponds(SSL_read_ex)]
pub fn ssl_read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
unsafe {
self.ssl_read_uninit(util::from_raw_parts_mut(
buf.as_mut_ptr().cast::<MaybeUninit<u8>>(),
buf.len(),
))
}
}
#[corresponds(SSL_read_ex)]
pub fn ssl_read_uninit(&mut self, buf: &mut [MaybeUninit<u8>]) -> Result<usize, Error> {
if buf.is_empty() {
return Ok(0);
}
cfg_if! {
if #[cfg(any(ossl111, libressl))] {
let mut readbytes = 0;
let ret = unsafe {
ffi::SSL_read_ex(
self.ssl().as_ptr(),
buf.as_mut_ptr().cast(),
buf.len(),
&mut readbytes,
)
};
if ret > 0 {
Ok(readbytes)
} else {
Err(self.make_error(ret))
}
} else {
let len = usize::min(c_int::MAX as usize, buf.len()) as c_int;
let ret = unsafe {
ffi::SSL_read(self.ssl().as_ptr(), buf.as_mut_ptr().cast(), len)
};
if ret > 0 {
Ok(ret as usize)
} else {
Err(self.make_error(ret))
}
}
}
}
#[corresponds(SSL_write_ex)]
pub fn ssl_write(&mut self, buf: &[u8]) -> Result<usize, Error> {
if buf.is_empty() {
return Ok(0);
}
cfg_if! {
if #[cfg(any(ossl111, libressl))] {
let mut written = 0;
let ret = unsafe {
ffi::SSL_write_ex(
self.ssl().as_ptr(),
buf.as_ptr().cast(),
buf.len(),
&mut written,
)
};
if ret > 0 {
Ok(written)
} else {
Err(self.make_error(ret))
}
} else {
let len = usize::min(c_int::MAX as usize, buf.len()) as c_int;
let ret = unsafe {
ffi::SSL_write(self.ssl().as_ptr(), buf.as_ptr().cast(), len)
};
if ret > 0 {
Ok(ret as usize)
} else {
Err(self.make_error(ret))
}
}
}
}
#[corresponds(SSL_peek_ex)]
pub fn ssl_peek(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
cfg_if! {
if #[cfg(any(ossl111, libressl))] {
let mut readbytes = 0;
let ret = unsafe {
ffi::SSL_peek_ex(
self.ssl().as_ptr(),
buf.as_mut_ptr().cast(),
buf.len(),
&mut readbytes,
)
};
if ret > 0 {
Ok(readbytes)
} else {
Err(self.make_error(ret))
}
} else {
if buf.is_empty() {
return Ok(0);
}
let len = usize::min(c_int::MAX as usize, buf.len()) as c_int;
let ret = unsafe {
ffi::SSL_peek(self.ssl().as_ptr(), buf.as_mut_ptr().cast(), len)
};
if ret > 0 {
Ok(ret as usize)
} else {
Err(self.make_error(ret))
}
}
}
}
#[corresponds(SSL_shutdown)]
pub fn shutdown(&mut self) -> Result<ShutdownResult, Error> {
match unsafe { ffi::SSL_shutdown(self.ssl.as_ptr()) } {
0 => Ok(ShutdownResult::Sent),
1 => Ok(ShutdownResult::Received),
n => Err(self.make_error(n)),
}
}
#[corresponds(SSL_get_shutdown)]
pub fn get_shutdown(&mut self) -> ShutdownState {
unsafe {
let bits = ffi::SSL_get_shutdown(self.ssl.as_ptr());
ShutdownState::from_bits_retain(bits)
}
}
#[corresponds(SSL_set_shutdown)]
pub fn set_shutdown(&mut self, state: ShutdownState) {
unsafe { ffi::SSL_set_shutdown(self.ssl.as_ptr(), state.bits()) }
}
}
impl<S> SslStream<S> {
fn make_error(&mut self, ret: c_int) -> Error {
self.check_panic();
let code = self.ssl.get_error(ret);
let cause = match code {
ErrorCode::SSL => Some(InnerError::Ssl(ErrorStack::get())),
ErrorCode::SYSCALL => {
let errs = ErrorStack::get();
if errs.errors().is_empty() {
self.get_bio_error().map(InnerError::Io)
} else {
Some(InnerError::Ssl(errs))
}
}
ErrorCode::ZERO_RETURN => None,
ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
self.get_bio_error().map(InnerError::Io)
}
_ => None,
};
Error { code, cause }
}
fn check_panic(&mut self) {
if let Some(err) = unsafe { bio::take_panic::<S>(self.ssl.get_raw_rbio()) } {
resume_unwind(err)
}
}
fn get_bio_error(&mut self) -> Option<io::Error> {
unsafe { bio::take_error::<S>(self.ssl.get_raw_rbio()) }
}
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)
}
}
pub fn ssl(&self) -> &SslRef {
&self.ssl
}
}
impl<S: Read + Write> Read for SslStream<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
unsafe {
self.read_uninit(util::from_raw_parts_mut(
buf.as_mut_ptr().cast::<MaybeUninit<u8>>(),
buf.len(),
))
}
}
}
impl<S: Read + Write> Write for SslStream<S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
loop {
match self.ssl_write(buf) {
Ok(n) => return Ok(n),
Err(ref e) if e.code() == ErrorCode::WANT_READ && e.io_error().is_none() => {}
Err(e) => {
return Err(e
.into_io_error()
.unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e)));
}
}
}
}
fn flush(&mut self) -> io::Result<()> {
self.get_mut().flush()
}
}
#[deprecated(
since = "0.10.32",
note = "use the methods directly on Ssl/SslStream instead"
)]
pub struct SslStreamBuilder<S> {
inner: SslStream<S>,
}
#[allow(deprecated)]
impl<S> SslStreamBuilder<S>
where
S: Read + Write,
{
pub fn new(ssl: Ssl, stream: S) -> Self {
Self {
inner: SslStream::new(ssl, stream).unwrap(),
}
}
#[corresponds(SSL_stateless)]
#[cfg(ossl111)]
pub fn stateless(&mut self) -> Result<bool, ErrorStack> {
match unsafe { ffi::SSL_stateless(self.inner.ssl.as_ptr()) } {
1 => Ok(true),
0 => Ok(false),
-1 => Err(ErrorStack::get()),
_ => unreachable!(),
}
}
#[corresponds(SSL_set_connect_state)]
pub fn set_connect_state(&mut self) {
unsafe { ffi::SSL_set_connect_state(self.inner.ssl.as_ptr()) }
}
#[corresponds(SSL_set_accept_state)]
pub fn set_accept_state(&mut self) {
unsafe { ffi::SSL_set_accept_state(self.inner.ssl.as_ptr()) }
}
pub fn connect(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
match self.inner.connect() {
Ok(()) => Ok(self.inner),
Err(error) => match error.code() {
ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
Err(HandshakeError::WouldBlock(MidHandshakeSslStream {
stream: self.inner,
error,
}))
}
_ => Err(HandshakeError::Failure(MidHandshakeSslStream {
stream: self.inner,
error,
})),
},
}
}
pub fn accept(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
match self.inner.accept() {
Ok(()) => Ok(self.inner),
Err(error) => match error.code() {
ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
Err(HandshakeError::WouldBlock(MidHandshakeSslStream {
stream: self.inner,
error,
}))
}
_ => Err(HandshakeError::Failure(MidHandshakeSslStream {
stream: self.inner,
error,
})),
},
}
}
#[corresponds(SSL_do_handshake)]
pub fn handshake(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
match self.inner.do_handshake() {
Ok(()) => Ok(self.inner),
Err(error) => match error.code() {
ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
Err(HandshakeError::WouldBlock(MidHandshakeSslStream {
stream: self.inner,
error,
}))
}
_ => Err(HandshakeError::Failure(MidHandshakeSslStream {
stream: self.inner,
error,
})),
},
}
}
#[corresponds(SSL_read_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn read_early_data(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.inner.read_early_data(buf)
}
#[corresponds(SSL_write_early_data)]
#[cfg(any(ossl111, libressl))]
pub fn write_early_data(&mut self, buf: &[u8]) -> Result<usize, Error> {
self.inner.write_early_data(buf)
}
}
#[allow(deprecated)]
impl<S> SslStreamBuilder<S> {
pub fn get_ref(&self) -> &S {
unsafe {
let bio = self.inner.ssl.get_raw_rbio();
bio::get_ref(bio)
}
}
pub fn get_mut(&mut self) -> &mut S {
unsafe {
let bio = self.inner.ssl.get_raw_rbio();
bio::get_mut(bio)
}
}
pub fn ssl(&self) -> &SslRef {
&self.inner.ssl
}
#[deprecated(note = "Use SslRef::set_mtu instead", since = "0.10.30")]
pub fn set_dtls_mtu_size(&mut self, mtu_size: usize) {
unsafe {
let bio = self.inner.ssl.get_raw_rbio();
bio::set_dtls_mtu_size::<S>(bio, mtu_size);
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ShutdownResult {
Sent,
Received,
}
bitflags! {
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct ShutdownState: c_int {
const SENT = ffi::SSL_SENT_SHUTDOWN;
const RECEIVED = ffi::SSL_RECEIVED_SHUTDOWN;
}
}
use ffi::{SSL_CTX_up_ref, SSL_SESSION_get_master_key, SSL_SESSION_up_ref, SSL_is_server};
cfg_if! {
if #[cfg(ossl300)] {
use ffi::SSL_get1_peer_certificate;
} else {
use ffi::SSL_get_peer_certificate as SSL_get1_peer_certificate;
}
}
use ffi::{
DTLS_client_method, DTLS_method, DTLS_server_method, TLS_client_method, TLS_method,
TLS_server_method,
};
cfg_if! {
if #[cfg(ossl110)] {
unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int {
ffi::CRYPTO_get_ex_new_index(
ffi::CRYPTO_EX_INDEX_SSL_CTX,
0,
ptr::null_mut(),
None,
None,
Some(f),
)
}
unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int {
ffi::CRYPTO_get_ex_new_index(
ffi::CRYPTO_EX_INDEX_SSL,
0,
ptr::null_mut(),
None,
None,
Some(f),
)
}
} else {
use std::sync::Once;
unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
cfg_if! {
if #[cfg(not(any(boringssl, awslc)))] {
ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), None, None, None);
} else {
ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, None);
}
}
});
cfg_if! {
if #[cfg(not(any(boringssl, awslc)))] {
ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f))
} else {
ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, f)
}
}
}
unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
#[cfg(not(any(boringssl, awslc)))]
ffi::SSL_get_ex_new_index(0, ptr::null_mut(), None, None, None);
#[cfg(any(boringssl, awslc))]
ffi::SSL_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, None);
});
#[cfg(not(any(boringssl, awslc)))]
return ffi::SSL_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f));
#[cfg(any(boringssl, awslc))]
return ffi::SSL_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, f);
}
}
}