variant_ssl/ssl/
mod.rs

1//! SSL/TLS support.
2//!
3//! `SslConnector` and `SslAcceptor` should be used in most cases - they handle
4//! configuration of the OpenSSL primitives for you.
5//!
6//! # Examples
7//!
8//! To connect as a client to a remote server:
9//!
10//! ```no_run
11//! use openssl::ssl::{SslMethod, SslConnector};
12//! use std::io::{Read, Write};
13//! use std::net::TcpStream;
14//!
15//! let connector = SslConnector::builder(SslMethod::tls()).unwrap().build();
16//!
17//! let stream = TcpStream::connect("google.com:443").unwrap();
18//! let mut stream = connector.connect("google.com", stream).unwrap();
19//!
20//! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
21//! let mut res = vec![];
22//! stream.read_to_end(&mut res).unwrap();
23//! println!("{}", String::from_utf8_lossy(&res));
24//! ```
25//!
26//! To accept connections as a server from remote clients:
27//!
28//! ```no_run
29//! use openssl::ssl::{SslMethod, SslAcceptor, SslStream, SslFiletype};
30//! use std::net::{TcpListener, TcpStream};
31//! use std::sync::Arc;
32//! use std::thread;
33//!
34//!
35//! let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
36//! acceptor.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
37//! acceptor.set_certificate_chain_file("certs.pem").unwrap();
38//! acceptor.check_private_key().unwrap();
39//! let acceptor = Arc::new(acceptor.build());
40//!
41//! let listener = TcpListener::bind("0.0.0.0:8443").unwrap();
42//!
43//! fn handle_client(stream: SslStream<TcpStream>) {
44//!     // ...
45//! }
46//!
47//! for stream in listener.incoming() {
48//!     match stream {
49//!         Ok(stream) => {
50//!             let acceptor = acceptor.clone();
51//!             thread::spawn(move || {
52//!                 let stream = acceptor.accept(stream).unwrap();
53//!                 handle_client(stream);
54//!             });
55//!         }
56//!         Err(e) => { /* connection failed */ }
57//!     }
58//! }
59//! ```
60use crate::cipher_ctx::CipherCtxRef;
61#[cfg(ossl300)]
62use crate::cvt_long;
63use crate::dh::{Dh, DhRef};
64use crate::ec::EcKeyRef;
65use crate::error::ErrorStack;
66use crate::ex_data::Index;
67#[cfg(ossl111)]
68use crate::hash::MessageDigest;
69use crate::hmac::HMacCtxRef;
70#[cfg(ossl300)]
71use crate::mac_ctx::MacCtxRef;
72#[cfg(any(ossl110, libressl270))]
73use crate::nid::Nid;
74use crate::pkey::{HasPrivate, PKeyRef, Params, Private};
75#[cfg(ossl300)]
76use crate::pkey::{PKey, Public};
77use crate::srtp::{SrtpProtectionProfile, SrtpProtectionProfileRef};
78use crate::ssl::bio::BioMethod;
79use crate::ssl::callbacks::*;
80use crate::ssl::error::InnerError;
81use crate::stack::{Stack, StackRef, Stackable};
82use crate::util;
83use crate::util::{ForeignTypeExt, ForeignTypeRefExt};
84use crate::x509::store::{X509Store, X509StoreBuilderRef, X509StoreRef};
85#[cfg(any(ossl102, boringssl, libressl261, awslc))]
86use crate::x509::verify::X509VerifyParamRef;
87use crate::x509::{X509Name, X509Ref, X509StoreContextRef, X509VerifyResult, X509};
88use crate::{cvt, cvt_n, cvt_p, init};
89use bitflags::bitflags;
90use cfg_if::cfg_if;
91use foreign_types::{ForeignType, ForeignTypeRef, Opaque};
92use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_void};
93use once_cell::sync::{Lazy, OnceCell};
94use openssl_macros::corresponds;
95use std::any::TypeId;
96use std::collections::HashMap;
97use std::ffi::{CStr, CString};
98use std::fmt;
99use std::io;
100use std::io::prelude::*;
101use std::marker::PhantomData;
102use std::mem::{self, ManuallyDrop, MaybeUninit};
103use std::ops::{Deref, DerefMut};
104use std::panic::resume_unwind;
105use std::path::Path;
106use std::ptr;
107use std::str;
108use std::sync::{Arc, Mutex};
109
110pub use crate::ssl::connector::{
111    ConnectConfiguration, SslAcceptor, SslAcceptorBuilder, SslConnector, SslConnectorBuilder,
112};
113pub use crate::ssl::error::{Error, ErrorCode, HandshakeError};
114
115mod bio;
116mod callbacks;
117#[cfg(any(boringssl, awslc))]
118mod client_hello;
119mod connector;
120mod error;
121#[cfg(test)]
122mod test;
123
124#[cfg(any(boringssl, awslc))]
125pub use client_hello::ClientHello;
126
127/// Returns the OpenSSL name of a cipher corresponding to an RFC-standard cipher name.
128///
129/// If the cipher has no corresponding OpenSSL name, the string `(NONE)` is returned.
130///
131/// Requires OpenSSL 1.1.1 or newer.
132#[corresponds(OPENSSL_cipher_name)]
133#[cfg(ossl111)]
134pub fn cipher_name(std_name: &str) -> &'static str {
135    unsafe {
136        ffi::init();
137
138        let s = CString::new(std_name).unwrap();
139        let ptr = ffi::OPENSSL_cipher_name(s.as_ptr());
140        CStr::from_ptr(ptr).to_str().unwrap()
141    }
142}
143
144cfg_if! {
145    if #[cfg(ossl300)] {
146        type SslOptionsRepr = u64;
147    } else if #[cfg(any(boringssl, awslc))] {
148        type SslOptionsRepr = u32;
149    } else {
150        type SslOptionsRepr = libc::c_ulong;
151    }
152}
153
154bitflags! {
155    /// Options controlling the behavior of an `SslContext`.
156    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
157    #[repr(transparent)]
158    pub struct SslOptions: SslOptionsRepr {
159        /// Disables a countermeasure against an SSLv3/TLSv1.0 vulnerability affecting CBC ciphers.
160        const DONT_INSERT_EMPTY_FRAGMENTS = ffi::SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS as SslOptionsRepr;
161
162        /// A "reasonable default" set of options which enables compatibility flags.
163        #[cfg(not(any(boringssl, awslc)))]
164        const ALL = ffi::SSL_OP_ALL as SslOptionsRepr;
165
166        /// Do not query the MTU.
167        ///
168        /// Only affects DTLS connections.
169        const NO_QUERY_MTU = ffi::SSL_OP_NO_QUERY_MTU as SslOptionsRepr;
170
171        /// Enables Cookie Exchange as described in [RFC 4347 Section 4.2.1].
172        ///
173        /// Only affects DTLS connections.
174        ///
175        /// [RFC 4347 Section 4.2.1]: https://tools.ietf.org/html/rfc4347#section-4.2.1
176        #[cfg(not(any(boringssl, awslc)))]
177        const COOKIE_EXCHANGE = ffi::SSL_OP_COOKIE_EXCHANGE as SslOptionsRepr;
178
179        /// Disables the use of session tickets for session resumption.
180        const NO_TICKET = ffi::SSL_OP_NO_TICKET as SslOptionsRepr;
181
182        /// Always start a new session when performing a renegotiation on the server side.
183        #[cfg(not(any(boringssl, awslc)))]
184        const NO_SESSION_RESUMPTION_ON_RENEGOTIATION =
185            ffi::SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION as SslOptionsRepr;
186
187        /// Disables the use of TLS compression.
188        #[cfg(not(any(boringssl, awslc)))]
189        const NO_COMPRESSION = ffi::SSL_OP_NO_COMPRESSION as SslOptionsRepr;
190
191        /// Allow legacy insecure renegotiation with servers or clients that do not support secure
192        /// renegotiation.
193        const ALLOW_UNSAFE_LEGACY_RENEGOTIATION =
194            ffi::SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION as SslOptionsRepr;
195
196        /// Creates a new key for each session when using ECDHE.
197        ///
198        /// This is always enabled in OpenSSL 1.1.0.
199        const SINGLE_ECDH_USE = ffi::SSL_OP_SINGLE_ECDH_USE as SslOptionsRepr;
200
201        /// Creates a new key for each session when using DHE.
202        ///
203        /// This is always enabled in OpenSSL 1.1.0.
204        const SINGLE_DH_USE = ffi::SSL_OP_SINGLE_DH_USE as SslOptionsRepr;
205
206        /// Use the server's preferences rather than the client's when selecting a cipher.
207        ///
208        /// This has no effect on the client side.
209        const CIPHER_SERVER_PREFERENCE = ffi::SSL_OP_CIPHER_SERVER_PREFERENCE as SslOptionsRepr;
210
211        /// Disables version rollback attach detection.
212        const TLS_ROLLBACK_BUG = ffi::SSL_OP_TLS_ROLLBACK_BUG as SslOptionsRepr;
213
214        /// Disables the use of SSLv2.
215        const NO_SSLV2 = ffi::SSL_OP_NO_SSLv2 as SslOptionsRepr;
216
217        /// Disables the use of SSLv3.
218        const NO_SSLV3 = ffi::SSL_OP_NO_SSLv3 as SslOptionsRepr;
219
220        /// Disables the use of TLSv1.0.
221        const NO_TLSV1 = ffi::SSL_OP_NO_TLSv1 as SslOptionsRepr;
222
223        /// Disables the use of TLSv1.1.
224        const NO_TLSV1_1 = ffi::SSL_OP_NO_TLSv1_1 as SslOptionsRepr;
225
226        /// Disables the use of TLSv1.2.
227        const NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2 as SslOptionsRepr;
228
229        /// Disables the use of TLSv1.3.
230        ///
231        /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
232        #[cfg(any(boringssl, ossl111, libressl340, awslc))]
233        const NO_TLSV1_3 = ffi::SSL_OP_NO_TLSv1_3 as SslOptionsRepr;
234
235        /// Disables the use of DTLSv1.0
236        ///
237        /// Requires OpenSSL 1.0.2 or LibreSSL 3.3.2 or newer.
238        #[cfg(any(boringssl, ossl102, ossl110, libressl332, awslc))]
239        const NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1 as SslOptionsRepr;
240
241        /// Disables the use of DTLSv1.2.
242        ///
243        /// Requires OpenSSL 1.0.2 or LibreSSL 3.3.2 or newer.
244        #[cfg(any(boringssl, ossl102, ossl110, libressl332, awslc))]
245        const NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2 as SslOptionsRepr;
246
247        /// Disables the use of all (D)TLS protocol versions.
248        ///
249        /// This can be used as a mask when whitelisting protocol versions.
250        ///
251        /// Requires OpenSSL 1.0.2 or newer.
252        ///
253        /// # Examples
254        ///
255        /// Only support TLSv1.2:
256        ///
257        /// ```rust
258        /// use openssl::ssl::SslOptions;
259        ///
260        /// let options = SslOptions::NO_SSL_MASK & !SslOptions::NO_TLSV1_2;
261        /// ```
262        #[cfg(any(ossl102, ossl110))]
263        const NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK as SslOptionsRepr;
264
265        /// Disallow all renegotiation in TLSv1.2 and earlier.
266        ///
267        /// Requires OpenSSL 1.1.0h or newer.
268        #[cfg(any(boringssl, ossl110h, awslc))]
269        const NO_RENEGOTIATION = ffi::SSL_OP_NO_RENEGOTIATION as SslOptionsRepr;
270
271        /// Enable TLSv1.3 Compatibility mode.
272        ///
273        /// Requires OpenSSL 1.1.1 or newer. This is on by default in 1.1.1, but a future version
274        /// may have this disabled by default.
275        #[cfg(ossl111)]
276        const ENABLE_MIDDLEBOX_COMPAT = ffi::SSL_OP_ENABLE_MIDDLEBOX_COMPAT as SslOptionsRepr;
277
278        /// Prioritize ChaCha ciphers when preferred by clients.
279        ///
280        /// Temporarily reprioritize ChaCha20-Poly1305 ciphers to the top of the server cipher list
281        /// if a ChaCha20-Poly1305 cipher is at the top of the client cipher list. This helps those
282        /// clients (e.g. mobile) use ChaCha20-Poly1305 if that cipher is anywhere in the server
283        /// cipher list; but still allows other clients to use AES and other ciphers.
284        ///
285        /// Requires enable [`SslOptions::CIPHER_SERVER_PREFERENCE`].
286        /// Requires OpenSSL 1.1.1 or newer.
287        ///
288        /// [`SslOptions::CIPHER_SERVER_PREFERENCE`]: struct.SslOptions.html#associatedconstant.CIPHER_SERVER_PREFERENCE
289        #[cfg(ossl111)]
290        const PRIORITIZE_CHACHA = ffi::SSL_OP_PRIORITIZE_CHACHA as SslOptionsRepr;
291    }
292}
293
294bitflags! {
295    /// Options controlling the behavior of an `SslContext`.
296    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
297    #[repr(transparent)]
298    pub struct SslMode: SslBitType {
299        /// Enables "short writes".
300        ///
301        /// Normally, a write in OpenSSL will always write out all of the requested data, even if it
302        /// requires more than one TLS record or write to the underlying stream. This option will
303        /// cause a write to return after writing a single TLS record instead.
304        const ENABLE_PARTIAL_WRITE = ffi::SSL_MODE_ENABLE_PARTIAL_WRITE;
305
306        /// Disables a check that the data buffer has not moved between calls when operating in a
307        /// non-blocking context.
308        const ACCEPT_MOVING_WRITE_BUFFER = ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
309
310        /// Enables automatic retries after TLS session events such as renegotiations or heartbeats.
311        ///
312        /// By default, OpenSSL will return a `WantRead` error after a renegotiation or heartbeat.
313        /// This option will cause OpenSSL to automatically continue processing the requested
314        /// operation instead.
315        ///
316        /// Note that `SslStream::read` and `SslStream::write` will automatically retry regardless
317        /// of the state of this option. It only affects `SslStream::ssl_read` and
318        /// `SslStream::ssl_write`.
319        const AUTO_RETRY = ffi::SSL_MODE_AUTO_RETRY;
320
321        /// Disables automatic chain building when verifying a peer's certificate.
322        ///
323        /// TLS peers are responsible for sending the entire certificate chain from the leaf to a
324        /// trusted root, but some will incorrectly not do so. OpenSSL will try to build the chain
325        /// out of certificates it knows of, and this option will disable that behavior.
326        const NO_AUTO_CHAIN = ffi::SSL_MODE_NO_AUTO_CHAIN;
327
328        /// Release memory buffers when the session does not need them.
329        ///
330        /// This saves ~34 KiB of memory for idle streams.
331        const RELEASE_BUFFERS = ffi::SSL_MODE_RELEASE_BUFFERS;
332
333        /// Sends the fake `TLS_FALLBACK_SCSV` cipher suite in the ClientHello message of a
334        /// handshake.
335        ///
336        /// This should only be enabled if a client has failed to connect to a server which
337        /// attempted to downgrade the protocol version of the session.
338        ///
339        /// Do not use this unless you know what you're doing!
340        #[cfg(not(libressl))]
341        const SEND_FALLBACK_SCSV = ffi::SSL_MODE_SEND_FALLBACK_SCSV;
342
343        /// Enable asynchronous processing.
344        ///
345        /// TLS I/O operations may indicate a retry with SSL_ERROR_WANT_ASYNC with this mode set
346        /// if an asynchronous capable engine is used to perform cryptographic operations.
347        ///
348        /// Do not use this unless you know what you're doing!
349        #[cfg(ossl110)]
350        const ASYNC = ffi::SSL_MODE_ASYNC;
351    }
352}
353
354/// A type specifying the kind of protocol an `SslContext` will speak.
355#[derive(Copy, Clone)]
356pub struct SslMethod(*const ffi::SSL_METHOD);
357
358impl SslMethod {
359    /// Support all versions of the TLS protocol.
360    #[corresponds(TLS_method)]
361    pub fn tls() -> SslMethod {
362        unsafe { SslMethod(TLS_method()) }
363    }
364
365    /// Support all versions of the DTLS protocol.
366    #[corresponds(DTLS_method)]
367    pub fn dtls() -> SslMethod {
368        unsafe { SslMethod(DTLS_method()) }
369    }
370
371    /// Support all versions of the TLS protocol, explicitly as a client.
372    #[corresponds(TLS_client_method)]
373    pub fn tls_client() -> SslMethod {
374        unsafe { SslMethod(TLS_client_method()) }
375    }
376
377    /// Support all versions of the TLS protocol, explicitly as a server.
378    #[corresponds(TLS_server_method)]
379    pub fn tls_server() -> SslMethod {
380        unsafe { SslMethod(TLS_server_method()) }
381    }
382
383    #[cfg(tongsuo)]
384    #[corresponds(NTLS_client_method)]
385    pub fn ntls_client() -> SslMethod {
386        unsafe { SslMethod(ffi::NTLS_client_method()) }
387    }
388
389    #[cfg(tongsuo)]
390    #[corresponds(NTLS_server_method)]
391    pub fn ntls_server() -> SslMethod {
392        unsafe { SslMethod(ffi::NTLS_server_method()) }
393    }
394
395    /// Support all versions of the DTLS protocol, explicitly as a client.
396    #[corresponds(DTLS_client_method)]
397    #[cfg(any(boringssl, ossl110, libressl291, awslc))]
398    pub fn dtls_client() -> SslMethod {
399        unsafe { SslMethod(DTLS_client_method()) }
400    }
401
402    /// Support all versions of the DTLS protocol, explicitly as a server.
403    #[corresponds(DTLS_server_method)]
404    #[cfg(any(boringssl, ossl110, libressl291, awslc))]
405    pub fn dtls_server() -> SslMethod {
406        unsafe { SslMethod(DTLS_server_method()) }
407    }
408
409    /// Constructs an `SslMethod` from a pointer to the underlying OpenSSL value.
410    ///
411    /// # Safety
412    ///
413    /// The caller must ensure the pointer is valid.
414    pub unsafe fn from_ptr(ptr: *const ffi::SSL_METHOD) -> SslMethod {
415        SslMethod(ptr)
416    }
417
418    /// Returns a pointer to the underlying OpenSSL value.
419    #[allow(clippy::trivially_copy_pass_by_ref)]
420    pub fn as_ptr(&self) -> *const ffi::SSL_METHOD {
421        self.0
422    }
423}
424
425unsafe impl Sync for SslMethod {}
426unsafe impl Send for SslMethod {}
427
428bitflags! {
429    /// Options controlling the behavior of certificate verification.
430    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
431    #[repr(transparent)]
432    pub struct SslVerifyMode: i32 {
433        /// Verifies that the peer's certificate is trusted.
434        ///
435        /// On the server side, this will cause OpenSSL to request a certificate from the client.
436        const PEER = ffi::SSL_VERIFY_PEER;
437
438        /// Disables verification of the peer's certificate.
439        ///
440        /// On the server side, this will cause OpenSSL to not request a certificate from the
441        /// client. On the client side, the certificate will be checked for validity, but the
442        /// negotiation will continue regardless of the result of that check.
443        const NONE = ffi::SSL_VERIFY_NONE;
444
445        /// On the server side, abort the handshake if the client did not send a certificate.
446        ///
447        /// This should be paired with `SSL_VERIFY_PEER`. It has no effect on the client side.
448        const FAIL_IF_NO_PEER_CERT = ffi::SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
449    }
450}
451
452#[cfg(any(boringssl, awslc))]
453type SslBitType = c_int;
454#[cfg(not(any(boringssl, awslc)))]
455type SslBitType = c_long;
456
457#[cfg(any(boringssl, awslc))]
458type SslTimeTy = u64;
459#[cfg(not(any(boringssl, awslc)))]
460type SslTimeTy = c_long;
461
462bitflags! {
463    /// Options controlling the behavior of session caching.
464    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
465    #[repr(transparent)]
466    pub struct SslSessionCacheMode: SslBitType {
467        /// No session caching for the client or server takes place.
468        const OFF = ffi::SSL_SESS_CACHE_OFF;
469
470        /// Enable session caching on the client side.
471        ///
472        /// OpenSSL has no way of identifying the proper session to reuse automatically, so the
473        /// application is responsible for setting it explicitly via [`SslRef::set_session`].
474        ///
475        /// [`SslRef::set_session`]: struct.SslRef.html#method.set_session
476        const CLIENT = ffi::SSL_SESS_CACHE_CLIENT;
477
478        /// Enable session caching on the server side.
479        ///
480        /// This is the default mode.
481        const SERVER = ffi::SSL_SESS_CACHE_SERVER;
482
483        /// Enable session caching on both the client and server side.
484        const BOTH = ffi::SSL_SESS_CACHE_BOTH;
485
486        /// Disable automatic removal of expired sessions from the session cache.
487        const NO_AUTO_CLEAR = ffi::SSL_SESS_CACHE_NO_AUTO_CLEAR;
488
489        /// Disable use of the internal session cache for session lookups.
490        const NO_INTERNAL_LOOKUP = ffi::SSL_SESS_CACHE_NO_INTERNAL_LOOKUP;
491
492        /// Disable use of the internal session cache for session storage.
493        const NO_INTERNAL_STORE = ffi::SSL_SESS_CACHE_NO_INTERNAL_STORE;
494
495        /// Disable use of the internal session cache for storage and lookup.
496        const NO_INTERNAL = ffi::SSL_SESS_CACHE_NO_INTERNAL;
497    }
498}
499
500#[cfg(ossl111)]
501bitflags! {
502    /// Which messages and under which conditions an extension should be added or expected.
503    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
504    #[repr(transparent)]
505    pub struct ExtensionContext: c_uint {
506        /// This extension is only allowed in TLS
507        const TLS_ONLY = ffi::SSL_EXT_TLS_ONLY;
508        /// This extension is only allowed in DTLS
509        const DTLS_ONLY = ffi::SSL_EXT_DTLS_ONLY;
510        /// Some extensions may be allowed in DTLS but we don't implement them for it
511        const TLS_IMPLEMENTATION_ONLY = ffi::SSL_EXT_TLS_IMPLEMENTATION_ONLY;
512        /// Most extensions are not defined for SSLv3 but EXT_TYPE_renegotiate is
513        const SSL3_ALLOWED = ffi::SSL_EXT_SSL3_ALLOWED;
514        /// Extension is only defined for TLS1.2 and below
515        const TLS1_2_AND_BELOW_ONLY = ffi::SSL_EXT_TLS1_2_AND_BELOW_ONLY;
516        /// Extension is only defined for TLS1.3 and above
517        const TLS1_3_ONLY = ffi::SSL_EXT_TLS1_3_ONLY;
518        /// Ignore this extension during parsing if we are resuming
519        const IGNORE_ON_RESUMPTION = ffi::SSL_EXT_IGNORE_ON_RESUMPTION;
520        const CLIENT_HELLO = ffi::SSL_EXT_CLIENT_HELLO;
521        /// Really means TLS1.2 or below
522        const TLS1_2_SERVER_HELLO = ffi::SSL_EXT_TLS1_2_SERVER_HELLO;
523        const TLS1_3_SERVER_HELLO = ffi::SSL_EXT_TLS1_3_SERVER_HELLO;
524        const TLS1_3_ENCRYPTED_EXTENSIONS = ffi::SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
525        const TLS1_3_HELLO_RETRY_REQUEST = ffi::SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST;
526        const TLS1_3_CERTIFICATE = ffi::SSL_EXT_TLS1_3_CERTIFICATE;
527        const TLS1_3_NEW_SESSION_TICKET = ffi::SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
528        const TLS1_3_CERTIFICATE_REQUEST = ffi::SSL_EXT_TLS1_3_CERTIFICATE_REQUEST;
529    }
530}
531
532/// TLS Extension Type
533#[derive(Copy, Clone)]
534pub struct TlsExtType(c_uint);
535
536impl TlsExtType {
537    /// server name.
538    ///
539    /// This corresponds to `TLSEXT_TYPE_server_name`.
540    pub const SERVER_NAME: TlsExtType = TlsExtType(ffi::TLSEXT_TYPE_server_name as _);
541
542    /// application layer protocol negotiation.
543    ///
544    /// This corresponds to `TLSEXT_TYPE_application_layer_protocol_negotiation`.
545    pub const ALPN: TlsExtType =
546        TlsExtType(ffi::TLSEXT_TYPE_application_layer_protocol_negotiation as _);
547
548    /// Constructs an `TlsExtType` from a raw value.
549    pub fn from_raw(raw: c_uint) -> TlsExtType {
550        TlsExtType(raw)
551    }
552
553    /// Returns the raw value represented by this type.
554    #[allow(clippy::trivially_copy_pass_by_ref)]
555    pub fn as_raw(&self) -> c_uint {
556        self.0
557    }
558}
559
560/// An identifier of the format of a certificate or key file.
561#[derive(Copy, Clone)]
562pub struct SslFiletype(c_int);
563
564impl SslFiletype {
565    /// The PEM format.
566    ///
567    /// This corresponds to `SSL_FILETYPE_PEM`.
568    pub const PEM: SslFiletype = SslFiletype(ffi::SSL_FILETYPE_PEM);
569
570    /// The ASN1 format.
571    ///
572    /// This corresponds to `SSL_FILETYPE_ASN1`.
573    pub const ASN1: SslFiletype = SslFiletype(ffi::SSL_FILETYPE_ASN1);
574
575    /// Constructs an `SslFiletype` from a raw OpenSSL value.
576    pub fn from_raw(raw: c_int) -> SslFiletype {
577        SslFiletype(raw)
578    }
579
580    /// Returns the raw OpenSSL value represented by this type.
581    #[allow(clippy::trivially_copy_pass_by_ref)]
582    pub fn as_raw(&self) -> c_int {
583        self.0
584    }
585}
586
587/// An identifier of a certificate status type.
588#[derive(Copy, Clone)]
589pub struct StatusType(c_int);
590
591impl StatusType {
592    /// An OSCP status.
593    pub const OCSP: StatusType = StatusType(ffi::TLSEXT_STATUSTYPE_ocsp);
594
595    /// Constructs a `StatusType` from a raw OpenSSL value.
596    pub fn from_raw(raw: c_int) -> StatusType {
597        StatusType(raw)
598    }
599
600    /// Returns the raw OpenSSL value represented by this type.
601    #[allow(clippy::trivially_copy_pass_by_ref)]
602    pub fn as_raw(&self) -> c_int {
603        self.0
604    }
605}
606
607/// An identifier of a session name type.
608#[derive(Copy, Clone)]
609pub struct NameType(c_int);
610
611impl NameType {
612    /// A host name.
613    pub const HOST_NAME: NameType = NameType(ffi::TLSEXT_NAMETYPE_host_name);
614
615    /// Constructs a `StatusType` from a raw OpenSSL value.
616    pub fn from_raw(raw: c_int) -> StatusType {
617        StatusType(raw)
618    }
619
620    /// Returns the raw OpenSSL value represented by this type.
621    #[allow(clippy::trivially_copy_pass_by_ref)]
622    pub fn as_raw(&self) -> c_int {
623        self.0
624    }
625}
626
627static INDEXES: Lazy<Mutex<HashMap<TypeId, c_int>>> = Lazy::new(|| Mutex::new(HashMap::new()));
628static SSL_INDEXES: Lazy<Mutex<HashMap<TypeId, c_int>>> = Lazy::new(|| Mutex::new(HashMap::new()));
629static SESSION_CTX_INDEX: OnceCell<Index<Ssl, SslContext>> = OnceCell::new();
630
631fn try_get_session_ctx_index() -> Result<&'static Index<Ssl, SslContext>, ErrorStack> {
632    SESSION_CTX_INDEX.get_or_try_init(Ssl::new_ex_index)
633}
634
635unsafe extern "C" fn free_data_box<T>(
636    _parent: *mut c_void,
637    ptr: *mut c_void,
638    _ad: *mut ffi::CRYPTO_EX_DATA,
639    _idx: c_int,
640    _argl: c_long,
641    _argp: *mut c_void,
642) {
643    if !ptr.is_null() {
644        let _ = Box::<T>::from_raw(ptr as *mut T);
645    }
646}
647
648/// An error returned from the SNI callback.
649#[derive(Debug, Copy, Clone, PartialEq, Eq)]
650pub struct SniError(c_int);
651
652impl SniError {
653    /// Abort the handshake with a fatal alert.
654    pub const ALERT_FATAL: SniError = SniError(ffi::SSL_TLSEXT_ERR_ALERT_FATAL);
655
656    /// Send a warning alert to the client and continue the handshake.
657    pub const ALERT_WARNING: SniError = SniError(ffi::SSL_TLSEXT_ERR_ALERT_WARNING);
658
659    pub const NOACK: SniError = SniError(ffi::SSL_TLSEXT_ERR_NOACK);
660}
661
662/// An SSL/TLS alert.
663#[derive(Debug, Copy, Clone, PartialEq, Eq)]
664pub struct SslAlert(c_int);
665
666impl SslAlert {
667    /// Alert 112 - `unrecognized_name`.
668    pub const UNRECOGNIZED_NAME: SslAlert = SslAlert(ffi::SSL_AD_UNRECOGNIZED_NAME);
669    pub const ILLEGAL_PARAMETER: SslAlert = SslAlert(ffi::SSL_AD_ILLEGAL_PARAMETER);
670    pub const DECODE_ERROR: SslAlert = SslAlert(ffi::SSL_AD_DECODE_ERROR);
671    pub const NO_APPLICATION_PROTOCOL: SslAlert = SslAlert(ffi::SSL_AD_NO_APPLICATION_PROTOCOL);
672}
673
674/// An error returned from an ALPN selection callback.
675///
676/// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.
677#[cfg(any(ossl102, libressl261, boringssl, awslc))]
678#[derive(Debug, Copy, Clone, PartialEq, Eq)]
679pub struct AlpnError(c_int);
680
681#[cfg(any(ossl102, libressl261, boringssl, awslc))]
682impl AlpnError {
683    /// Terminate the handshake with a fatal alert.
684    ///
685    /// Requires AWS-LC or BoringSSL or OpenSSL 1.1.0 or newer.
686    #[cfg(any(ossl110, boringssl, awslc))]
687    pub const ALERT_FATAL: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_ALERT_FATAL);
688
689    /// Do not select a protocol, but continue the handshake.
690    pub const NOACK: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_NOACK);
691}
692
693/// An error returned from a client hello callback.
694///
695/// Requires OpenSSL 1.1.1 or newer.
696#[cfg(ossl111)]
697#[derive(Debug, Copy, Clone, PartialEq, Eq)]
698pub struct ClientHelloError(c_int);
699
700#[cfg(ossl111)]
701impl ClientHelloError {
702    /// Terminate the connection.
703    pub const ERROR: ClientHelloError = ClientHelloError(ffi::SSL_CLIENT_HELLO_ERROR);
704
705    /// Return from the handshake with an `ErrorCode::WANT_CLIENT_HELLO_CB` error.
706    pub const RETRY: ClientHelloError = ClientHelloError(ffi::SSL_CLIENT_HELLO_RETRY);
707}
708
709/// Session Ticket Key CB result type
710#[derive(Debug, Copy, Clone, PartialEq, Eq)]
711pub struct TicketKeyStatus(c_int);
712
713impl TicketKeyStatus {
714    /// Session Ticket Key is not set/retrieved for current session
715    pub const FAILED: TicketKeyStatus = TicketKeyStatus(0);
716    /// Session Ticket Key is set, and no renew is needed
717    pub const SUCCESS: TicketKeyStatus = TicketKeyStatus(1);
718    /// Session Ticket Key is set, and a new ticket will be needed
719    pub const SUCCESS_AND_RENEW: TicketKeyStatus = TicketKeyStatus(2);
720}
721
722/// An error returned from a certificate selection callback.
723#[derive(Debug, Copy, Clone, PartialEq, Eq)]
724#[cfg(any(boringssl, awslc))]
725pub struct SelectCertError(ffi::ssl_select_cert_result_t);
726
727#[cfg(any(boringssl, awslc))]
728impl SelectCertError {
729    /// A fatal error occurred and the handshake should be terminated.
730    pub const ERROR: Self = Self(ffi::ssl_select_cert_result_t_ssl_select_cert_error);
731
732    /// The operation could not be completed and should be retried later.
733    pub const RETRY: Self = Self(ffi::ssl_select_cert_result_t_ssl_select_cert_retry);
734
735    /// Although an encrypted ClientHelloInner was decrypted, it should be discarded.
736    /// The certificate selection callback will then be called again, passing in the
737    /// ClientHelloOuter instead. From there, the handshake will proceed
738    /// without retry_configs, to signal to the client to disable ECH.
739    /// This value may only be returned when |SSL_ech_accepted| returnes one.
740    #[cfg(boringssl)]
741    pub const DISABLE_ECH: Self = Self(ffi::ssl_select_cert_result_t_ssl_select_cert_disable_ech);
742}
743
744/// SSL CT validation mode.
745#[cfg(ossl111)]
746#[derive(Debug, Copy, Clone, PartialEq, Eq)]
747pub struct SslCtValidationMode(c_int);
748
749#[cfg(ossl111)]
750impl SslCtValidationMode {
751    pub const PERMISSIVE: SslCtValidationMode =
752        SslCtValidationMode(ffi::SSL_CT_VALIDATION_PERMISSIVE as c_int);
753    pub const STRICT: SslCtValidationMode =
754        SslCtValidationMode(ffi::SSL_CT_VALIDATION_STRICT as c_int);
755}
756
757/// TLS Certificate Compression Algorithm IDs, defined by IANA
758#[derive(Debug, Copy, Clone, PartialEq, Eq)]
759pub struct CertCompressionAlgorithm(c_int);
760
761impl CertCompressionAlgorithm {
762    pub const ZLIB: CertCompressionAlgorithm = CertCompressionAlgorithm(1);
763    pub const BROTLI: CertCompressionAlgorithm = CertCompressionAlgorithm(2);
764    pub const ZSTD: CertCompressionAlgorithm = CertCompressionAlgorithm(3);
765}
766
767/// An SSL/TLS protocol version.
768#[derive(Debug, Copy, Clone, PartialEq, Eq)]
769pub struct SslVersion(c_int);
770
771impl SslVersion {
772    /// SSLv3
773    pub const SSL3: SslVersion = SslVersion(ffi::SSL3_VERSION);
774
775    /// TLSv1.0
776    pub const TLS1: SslVersion = SslVersion(ffi::TLS1_VERSION);
777
778    /// TLSv1.1
779    pub const TLS1_1: SslVersion = SslVersion(ffi::TLS1_1_VERSION);
780
781    /// TLSv1.2
782    pub const TLS1_2: SslVersion = SslVersion(ffi::TLS1_2_VERSION);
783
784    /// TLSv1.3
785    ///
786    /// Requires AWS-LC or BoringSSL or OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
787    #[cfg(any(ossl111, libressl340, boringssl, awslc))]
788    pub const TLS1_3: SslVersion = SslVersion(ffi::TLS1_3_VERSION);
789
790    #[cfg(tongsuo)]
791    pub const NTLS1_1: SslVersion = SslVersion(ffi::NTLS1_1_VERSION);
792
793    /// DTLSv1.0
794    ///
795    /// DTLS 1.0 corresponds to TLS 1.1.
796    pub const DTLS1: SslVersion = SslVersion(ffi::DTLS1_VERSION);
797
798    /// DTLSv1.2
799    ///
800    /// DTLS 1.2 corresponds to TLS 1.2 to harmonize versions. There was never a DTLS 1.1.
801    #[cfg(any(ossl102, libressl332, boringssl, awslc))]
802    pub const DTLS1_2: SslVersion = SslVersion(ffi::DTLS1_2_VERSION);
803}
804
805cfg_if! {
806    if #[cfg(any(boringssl, awslc))] {
807        type SslCacheTy = i64;
808        type SslCacheSize = libc::c_ulong;
809        type MtuTy = u32;
810        type ModeTy = u32;
811        type SizeTy = usize;
812    } else {
813        type SslCacheTy = i64;
814        type SslCacheSize = c_long;
815        type MtuTy = c_long;
816        type ModeTy = c_long;
817        type SizeTy = u32;
818    }
819}
820
821/// A standard implementation of protocol selection for Application Layer Protocol Negotiation
822/// (ALPN).
823///
824/// `server` should contain the server's list of supported protocols and `client` the client's. They
825/// must both be in the ALPN wire format. See the documentation for
826/// [`SslContextBuilder::set_alpn_protos`] for details.
827///
828/// It will select the first protocol supported by the server which is also supported by the client.
829///
830/// [`SslContextBuilder::set_alpn_protos`]: struct.SslContextBuilder.html#method.set_alpn_protos
831#[corresponds(SSL_select_next_proto)]
832pub fn select_next_proto<'a>(server: &'a [u8], client: &'a [u8]) -> Option<&'a [u8]> {
833    unsafe {
834        let mut out = ptr::null_mut();
835        let mut outlen = 0;
836        let r = ffi::SSL_select_next_proto(
837            &mut out,
838            &mut outlen,
839            server.as_ptr(),
840            server.len() as c_uint,
841            client.as_ptr(),
842            client.len() as c_uint,
843        );
844        if r == ffi::OPENSSL_NPN_NEGOTIATED {
845            Some(util::from_raw_parts(out as *const u8, outlen as usize))
846        } else {
847            None
848        }
849    }
850}
851
852/// A builder for `SslContext`s.
853pub struct SslContextBuilder(SslContext);
854
855impl SslContextBuilder {
856    /// Creates a new `SslContextBuilder`.
857    #[corresponds(SSL_CTX_new)]
858    pub fn new(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> {
859        unsafe {
860            init();
861            let ctx = cvt_p(ffi::SSL_CTX_new(method.as_ptr()))?;
862
863            Ok(SslContextBuilder::from_ptr(ctx))
864        }
865    }
866
867    /// Creates an `SslContextBuilder` from a pointer to a raw OpenSSL value.
868    ///
869    /// # Safety
870    ///
871    /// The caller must ensure that the pointer is valid and uniquely owned by the builder.
872    pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextBuilder {
873        SslContextBuilder(SslContext::from_ptr(ctx))
874    }
875
876    /// Returns a pointer to the raw OpenSSL value.
877    pub fn as_ptr(&self) -> *mut ffi::SSL_CTX {
878        self.0.as_ptr()
879    }
880
881    #[cfg(tongsuo)]
882    #[corresponds(SSL_CTX_enable_ntls)]
883    pub fn enable_ntls(&mut self) {
884        unsafe { ffi::SSL_CTX_enable_ntls(self.as_ptr()) }
885    }
886
887    #[cfg(tongsuo)]
888    #[corresponds(SSL_CTX_disable_ntls)]
889    pub fn disable_ntls(&mut self) {
890        unsafe { ffi::SSL_CTX_disable_ntls(self.as_ptr()) }
891    }
892
893    #[cfg(all(tongsuo, ossl300))]
894    #[corresponds(SSL_CTX_enable_force_ntls)]
895    pub fn enable_force_ntls(&mut self) {
896        unsafe { ffi::SSL_CTX_enable_force_ntls(self.as_ptr()) }
897    }
898
899    #[cfg(all(tongsuo, ossl300))]
900    #[corresponds(SSL_CTX_disable_force_ntls)]
901    pub fn disable_force_ntls(&mut self) {
902        unsafe { ffi::SSL_CTX_disable_force_ntls(self.as_ptr()) }
903    }
904
905    #[cfg(tongsuo)]
906    #[corresponds(SSL_CTX_enable_sm_tls13_strict)]
907    pub fn enable_sm_tls13_strict(&mut self) {
908        unsafe { ffi::SSL_CTX_enable_sm_tls13_strict(self.as_ptr()) }
909    }
910
911    #[cfg(tongsuo)]
912    #[corresponds(SSL_CTX_disable_sm_tls13_strict)]
913    pub fn disable_sm_tls13_strict(&mut self) {
914        unsafe { ffi::SSL_CTX_disable_sm_tls13_strict(self.as_ptr()) }
915    }
916
917    /// Configures the certificate verification method for new connections.
918    #[corresponds(SSL_CTX_set_verify)]
919    pub fn set_verify(&mut self, mode: SslVerifyMode) {
920        unsafe {
921            ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits() as c_int, None);
922        }
923    }
924
925    /// Configures the certificate verification method for new connections and
926    /// registers a verification callback.
927    ///
928    /// The callback is passed a boolean indicating if OpenSSL's internal verification succeeded as
929    /// well as a reference to the `X509StoreContext` which can be used to examine the certificate
930    /// chain. It should return a boolean indicating if verification succeeded.
931    #[corresponds(SSL_CTX_set_verify)]
932    pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
933    where
934        F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
935    {
936        unsafe {
937            self.set_ex_data(SslContext::cached_ex_index::<F>(), verify);
938            ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits() as c_int, Some(raw_verify::<F>));
939        }
940    }
941
942    /// Configures the server name indication (SNI) callback for new connections.
943    ///
944    /// SNI is used to allow a single server to handle requests for multiple domains, each of which
945    /// has its own certificate chain and configuration.
946    ///
947    /// Obtain the server name with the `servername` method and then set the corresponding context
948    /// with `set_ssl_context`
949    #[corresponds(SSL_CTX_set_tlsext_servername_callback)]
950    // FIXME tlsext prefix?
951    pub fn set_servername_callback<F>(&mut self, callback: F)
952    where
953        F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send,
954    {
955        unsafe {
956            // The SNI callback is somewhat unique in that the callback associated with the original
957            // context associated with an SSL can be used even if the SSL's context has been swapped
958            // out. When that happens, we wouldn't be able to look up the callback's state in the
959            // context's ex data. Instead, pass the pointer directly as the servername arg. It's
960            // still stored in ex data to manage the lifetime.
961            let arg = self.set_ex_data_inner(SslContext::cached_ex_index::<F>(), callback);
962            ffi::SSL_CTX_set_tlsext_servername_arg(self.as_ptr(), arg);
963            ffi::SSL_CTX_set_tlsext_servername_callback(self.as_ptr(), Some(raw_sni::<F>));
964        }
965    }
966
967    /// Sets the certificate verification depth.
968    ///
969    /// If the peer's certificate chain is longer than this value, verification will fail.
970    #[corresponds(SSL_CTX_set_verify_depth)]
971    pub fn set_verify_depth(&mut self, depth: u32) {
972        unsafe {
973            ffi::SSL_CTX_set_verify_depth(self.as_ptr(), depth as c_int);
974        }
975    }
976
977    /// Sets a custom certificate store for verifying peer certificates.
978    ///
979    /// Requires AWS-LC or OpenSSL 1.0.2 or newer.
980    #[corresponds(SSL_CTX_set0_verify_cert_store)]
981    #[cfg(any(ossl102, boringssl, awslc))]
982    pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> {
983        unsafe {
984            let ptr = cert_store.as_ptr();
985            cvt(ffi::SSL_CTX_set0_verify_cert_store(self.as_ptr(), ptr) as c_int)?;
986            mem::forget(cert_store);
987
988            Ok(())
989        }
990    }
991
992    /// Replaces the context's certificate store.
993    #[corresponds(SSL_CTX_set_cert_store)]
994    pub fn set_cert_store(&mut self, cert_store: X509Store) {
995        unsafe {
996            ffi::SSL_CTX_set_cert_store(self.as_ptr(), cert_store.as_ptr());
997            mem::forget(cert_store);
998        }
999    }
1000
1001    /// Controls read ahead behavior.
1002    ///
1003    /// If enabled, OpenSSL will read as much data as is available from the underlying stream,
1004    /// instead of a single record at a time.
1005    ///
1006    /// It has no effect when used with DTLS.
1007    #[corresponds(SSL_CTX_set_read_ahead)]
1008    pub fn set_read_ahead(&mut self, read_ahead: bool) {
1009        unsafe {
1010            ffi::SSL_CTX_set_read_ahead(self.as_ptr(), read_ahead as SslBitType);
1011        }
1012    }
1013
1014    /// Sets the mode used by the context, returning the new mode bit mask.
1015    ///
1016    /// Options already set before are not cleared.
1017    #[corresponds(SSL_CTX_set_mode)]
1018    pub fn set_mode(&mut self, mode: SslMode) -> SslMode {
1019        unsafe {
1020            let bits = ffi::SSL_CTX_set_mode(self.as_ptr(), mode.bits() as ModeTy) as SslBitType;
1021            SslMode::from_bits_retain(bits)
1022        }
1023    }
1024
1025    /// Clear the mode used by the context, returning the new mode bit mask.
1026    #[corresponds(SSL_CTX_clear_mode)]
1027    pub fn clear_mode(&mut self, mode: SslMode) -> SslMode {
1028        unsafe {
1029            let bits = ffi::SSL_CTX_clear_mode(self.as_ptr(), mode.bits() as ModeTy) as SslBitType;
1030            SslMode::from_bits_retain(bits)
1031        }
1032    }
1033
1034    /// Returns the mode set for the context.
1035    #[corresponds(SSL_CTX_get_mode)]
1036    pub fn mode(&self) -> SslMode {
1037        unsafe {
1038            let bits = ffi::SSL_CTX_get_mode(self.as_ptr()) as SslBitType;
1039            SslMode::from_bits_retain(bits)
1040        }
1041    }
1042
1043    /// Configure OpenSSL to use the default built-in DH parameters.
1044    ///
1045    /// If “auto” DH parameters are switched on then the parameters will be selected to be
1046    /// consistent with the size of the key associated with the server's certificate.
1047    /// If there is no certificate (e.g. for PSK ciphersuites), then it it will be consistent
1048    /// with the size of the negotiated symmetric cipher key.
1049    ///
1050    /// Requires OpenSSL 3.0.0.
1051    #[corresponds(SSL_CTX_set_dh_auto)]
1052    #[cfg(ossl300)]
1053    pub fn set_dh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> {
1054        unsafe { cvt(ffi::SSL_CTX_set_dh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) }
1055    }
1056
1057    /// Sets the parameters to be used during ephemeral Diffie-Hellman key exchange.
1058    #[corresponds(SSL_CTX_set_tmp_dh)]
1059    pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack> {
1060        unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) }
1061    }
1062
1063    /// Sets the callback which will generate parameters to be used during ephemeral Diffie-Hellman
1064    /// key exchange.
1065    ///
1066    /// The callback is provided with a reference to the `Ssl` for the session, as well as a boolean
1067    /// indicating if the selected cipher is export-grade, and the key length. The export and key
1068    /// length options are archaic and should be ignored in almost all cases.
1069    #[corresponds(SSL_CTX_set_tmp_dh_callback)]
1070    pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
1071    where
1072        F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
1073    {
1074        unsafe {
1075            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1076
1077            ffi::SSL_CTX_set_tmp_dh_callback(self.as_ptr(), Some(raw_tmp_dh::<F>));
1078        }
1079    }
1080
1081    /// Sets the parameters to be used during ephemeral elliptic curve Diffie-Hellman key exchange.
1082    #[corresponds(SSL_CTX_set_tmp_ecdh)]
1083    pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack> {
1084        unsafe { cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) }
1085    }
1086
1087    /// Use the default locations of trusted certificates for verification.
1088    ///
1089    /// These locations are read from the `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables
1090    /// if present, or defaults specified at OpenSSL build time otherwise.
1091    #[corresponds(SSL_CTX_set_default_verify_paths)]
1092    pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack> {
1093        unsafe { cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) }
1094    }
1095
1096    /// Loads trusted root certificates from a file.
1097    ///
1098    /// The file should contain a sequence of PEM-formatted CA certificates.
1099    #[corresponds(SSL_CTX_load_verify_locations)]
1100    pub fn set_ca_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), ErrorStack> {
1101        self.load_verify_locations(Some(file.as_ref()), None)
1102    }
1103
1104    /// Loads trusted root certificates from a file and/or a directory.
1105    #[corresponds(SSL_CTX_load_verify_locations)]
1106    pub fn load_verify_locations(
1107        &mut self,
1108        ca_file: Option<&Path>,
1109        ca_path: Option<&Path>,
1110    ) -> Result<(), ErrorStack> {
1111        let ca_file = ca_file.map(|p| CString::new(p.as_os_str().to_str().unwrap()).unwrap());
1112        let ca_path = ca_path.map(|p| CString::new(p.as_os_str().to_str().unwrap()).unwrap());
1113        unsafe {
1114            cvt(ffi::SSL_CTX_load_verify_locations(
1115                self.as_ptr(),
1116                ca_file.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1117                ca_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1118            ))
1119            .map(|_| ())
1120        }
1121    }
1122
1123    /// Sets the list of CA names sent to the client.
1124    ///
1125    /// The CA certificates must still be added to the trust root - they are not automatically set
1126    /// as trusted by this method.
1127    #[corresponds(SSL_CTX_set_client_CA_list)]
1128    pub fn set_client_ca_list(&mut self, list: Stack<X509Name>) {
1129        unsafe {
1130            ffi::SSL_CTX_set_client_CA_list(self.as_ptr(), list.as_ptr());
1131            mem::forget(list);
1132        }
1133    }
1134
1135    /// Add the provided CA certificate to the list sent by the server to the client when
1136    /// requesting client-side TLS authentication.
1137    #[corresponds(SSL_CTX_add_client_CA)]
1138    pub fn add_client_ca(&mut self, cacert: &X509Ref) -> Result<(), ErrorStack> {
1139        unsafe { cvt(ffi::SSL_CTX_add_client_CA(self.as_ptr(), cacert.as_ptr())).map(|_| ()) }
1140    }
1141
1142    /// Set the context identifier for sessions.
1143    ///
1144    /// This value identifies the server's session cache to clients, telling them when they're
1145    /// able to reuse sessions. It should be set to a unique value per server, unless multiple
1146    /// servers share a session cache.
1147    ///
1148    /// This value should be set when using client certificates, or each request will fail its
1149    /// handshake and need to be restarted.
1150    #[corresponds(SSL_CTX_set_session_id_context)]
1151    pub fn set_session_id_context(&mut self, sid_ctx: &[u8]) -> Result<(), ErrorStack> {
1152        unsafe {
1153            assert!(sid_ctx.len() <= c_uint::MAX as usize);
1154            cvt(ffi::SSL_CTX_set_session_id_context(
1155                self.as_ptr(),
1156                sid_ctx.as_ptr(),
1157                sid_ctx.len() as SizeTy,
1158            ))
1159            .map(|_| ())
1160        }
1161    }
1162
1163    /// Loads a leaf certificate from a file.
1164    ///
1165    /// Only a single certificate will be loaded - use `add_extra_chain_cert` to add the remainder
1166    /// of the certificate chain, or `set_certificate_chain_file` to load the entire chain from a
1167    /// single file.
1168    #[corresponds(SSL_CTX_use_certificate_file)]
1169    pub fn set_certificate_file<P: AsRef<Path>>(
1170        &mut self,
1171        file: P,
1172        file_type: SslFiletype,
1173    ) -> Result<(), ErrorStack> {
1174        let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
1175        unsafe {
1176            cvt(ffi::SSL_CTX_use_certificate_file(
1177                self.as_ptr(),
1178                file.as_ptr() as *const _,
1179                file_type.as_raw(),
1180            ))
1181            .map(|_| ())
1182        }
1183    }
1184
1185    /// Loads a certificate chain from a file.
1186    ///
1187    /// The file should contain a sequence of PEM-formatted certificates, the first being the leaf
1188    /// certificate, and the remainder forming the chain of certificates up to and including the
1189    /// trusted root certificate.
1190    #[corresponds(SSL_CTX_use_certificate_chain_file)]
1191    pub fn set_certificate_chain_file<P: AsRef<Path>>(
1192        &mut self,
1193        file: P,
1194    ) -> Result<(), ErrorStack> {
1195        let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
1196        unsafe {
1197            cvt(ffi::SSL_CTX_use_certificate_chain_file(
1198                self.as_ptr(),
1199                file.as_ptr() as *const _,
1200            ))
1201            .map(|_| ())
1202        }
1203    }
1204
1205    /// Sets the leaf certificate.
1206    ///
1207    /// Use `add_extra_chain_cert` to add the remainder of the certificate chain.
1208    #[corresponds(SSL_CTX_use_certificate)]
1209    pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
1210        unsafe { cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) }
1211    }
1212
1213    /// Appends a certificate to the certificate chain.
1214    ///
1215    /// This chain should contain all certificates necessary to go from the certificate specified by
1216    /// `set_certificate` to a trusted root.
1217    #[corresponds(SSL_CTX_add_extra_chain_cert)]
1218    pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack> {
1219        unsafe {
1220            cvt(ffi::SSL_CTX_add_extra_chain_cert(self.as_ptr(), cert.as_ptr()) as c_int)?;
1221            mem::forget(cert);
1222            Ok(())
1223        }
1224    }
1225
1226    #[cfg(tongsuo)]
1227    #[corresponds(SSL_CTX_use_enc_certificate_file)]
1228    pub fn set_enc_certificate_file<P: AsRef<Path>>(
1229        &mut self,
1230        file: P,
1231        file_type: SslFiletype,
1232    ) -> Result<(), ErrorStack> {
1233        let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
1234        unsafe {
1235            cvt(ffi::SSL_CTX_use_enc_certificate_file(
1236                self.as_ptr(),
1237                file.as_ptr() as *const _,
1238                file_type.as_raw(),
1239            ))
1240            .map(|_| ())
1241        }
1242    }
1243
1244    #[cfg(tongsuo)]
1245    #[corresponds(SSL_CTX_use_enc_certificate)]
1246    pub fn set_enc_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
1247        unsafe {
1248            cvt(ffi::SSL_CTX_use_enc_certificate(
1249                self.as_ptr(),
1250                cert.as_ptr(),
1251            ))
1252            .map(|_| ())
1253        }
1254    }
1255
1256    #[cfg(tongsuo)]
1257    #[corresponds(SSL_CTX_use_sign_certificate_file)]
1258    pub fn set_sign_certificate_file<P: AsRef<Path>>(
1259        &mut self,
1260        file: P,
1261        file_type: SslFiletype,
1262    ) -> Result<(), ErrorStack> {
1263        let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
1264        unsafe {
1265            cvt(ffi::SSL_CTX_use_sign_certificate_file(
1266                self.as_ptr(),
1267                file.as_ptr() as *const _,
1268                file_type.as_raw(),
1269            ))
1270            .map(|_| ())
1271        }
1272    }
1273
1274    #[cfg(tongsuo)]
1275    #[corresponds(SSL_CTX_use_sign_certificate)]
1276    pub fn set_sign_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
1277        unsafe {
1278            cvt(ffi::SSL_CTX_use_sign_certificate(
1279                self.as_ptr(),
1280                cert.as_ptr(),
1281            ))
1282            .map(|_| ())
1283        }
1284    }
1285
1286    /// Loads the private key from a file.
1287    #[corresponds(SSL_CTX_use_PrivateKey_file)]
1288    pub fn set_private_key_file<P: AsRef<Path>>(
1289        &mut self,
1290        file: P,
1291        file_type: SslFiletype,
1292    ) -> Result<(), ErrorStack> {
1293        let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
1294        unsafe {
1295            cvt(ffi::SSL_CTX_use_PrivateKey_file(
1296                self.as_ptr(),
1297                file.as_ptr() as *const _,
1298                file_type.as_raw(),
1299            ))
1300            .map(|_| ())
1301        }
1302    }
1303
1304    /// Sets the private key.
1305    #[corresponds(SSL_CTX_use_PrivateKey)]
1306    pub fn set_private_key<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
1307    where
1308        T: HasPrivate,
1309    {
1310        unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) }
1311    }
1312
1313    #[cfg(tongsuo)]
1314    #[corresponds(SSL_CTX_use_enc_PrivateKey_file)]
1315    pub fn set_enc_private_key_file<P: AsRef<Path>>(
1316        &mut self,
1317        file: P,
1318        file_type: SslFiletype,
1319    ) -> Result<(), ErrorStack> {
1320        let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
1321        unsafe {
1322            cvt(ffi::SSL_CTX_use_enc_PrivateKey_file(
1323                self.as_ptr(),
1324                file.as_ptr() as *const _,
1325                file_type.as_raw(),
1326            ))
1327            .map(|_| ())
1328        }
1329    }
1330
1331    #[cfg(tongsuo)]
1332    #[corresponds(SSL_CTX_use_enc_PrivateKey)]
1333    pub fn set_enc_private_key<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
1334    where
1335        T: HasPrivate,
1336    {
1337        unsafe { cvt(ffi::SSL_CTX_use_enc_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) }
1338    }
1339
1340    #[cfg(tongsuo)]
1341    #[corresponds(SSL_CTX_use_sign_PrivateKey_file)]
1342    pub fn set_sign_private_key_file<P: AsRef<Path>>(
1343        &mut self,
1344        file: P,
1345        file_type: SslFiletype,
1346    ) -> Result<(), ErrorStack> {
1347        let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap();
1348        unsafe {
1349            cvt(ffi::SSL_CTX_use_sign_PrivateKey_file(
1350                self.as_ptr(),
1351                file.as_ptr() as *const _,
1352                file_type.as_raw(),
1353            ))
1354            .map(|_| ())
1355        }
1356    }
1357
1358    #[cfg(tongsuo)]
1359    #[corresponds(SSL_CTX_use_sign_PrivateKey)]
1360    pub fn set_sign_private_key<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
1361    where
1362        T: HasPrivate,
1363    {
1364        unsafe {
1365            cvt(ffi::SSL_CTX_use_sign_PrivateKey(
1366                self.as_ptr(),
1367                key.as_ptr(),
1368            ))
1369            .map(|_| ())
1370        }
1371    }
1372
1373    /// Sets the list of supported ciphers for protocols before TLSv1.3.
1374    ///
1375    /// The `set_ciphersuites` method controls the cipher suites for TLSv1.3.
1376    ///
1377    /// See [`ciphers`] for details on the format.
1378    ///
1379    /// [`ciphers`]: https://www.openssl.org/docs/manmaster/apps/ciphers.html
1380    #[corresponds(SSL_CTX_set_cipher_list)]
1381    pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
1382        let cipher_list = CString::new(cipher_list).unwrap();
1383        unsafe {
1384            cvt(ffi::SSL_CTX_set_cipher_list(
1385                self.as_ptr(),
1386                cipher_list.as_ptr() as *const _,
1387            ))
1388            .map(|_| ())
1389        }
1390    }
1391
1392    /// Sets the list of supported ciphers for the TLSv1.3 protocol.
1393    ///
1394    /// The `set_cipher_list` method controls the cipher suites for protocols before TLSv1.3.
1395    ///
1396    /// The format consists of TLSv1.3 cipher suite names separated by `:` characters in order of
1397    /// preference.
1398    ///
1399    /// Requires AWS-LC or OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
1400    #[corresponds(SSL_CTX_set_ciphersuites)]
1401    #[cfg(any(ossl111, libressl340, awslc))]
1402    pub fn set_ciphersuites(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
1403        let cipher_list = CString::new(cipher_list).unwrap();
1404        unsafe {
1405            cvt(ffi::SSL_CTX_set_ciphersuites(
1406                self.as_ptr(),
1407                cipher_list.as_ptr() as *const _,
1408            ))
1409            .map(|_| ())
1410        }
1411    }
1412
1413    /// Enables ECDHE key exchange with an automatically chosen curve list.
1414    ///
1415    /// Requires OpenSSL 1.0.2.
1416    #[corresponds(SSL_CTX_set_ecdh_auto)]
1417    #[cfg(any(libressl, all(ossl102, not(ossl110))))]
1418    pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> {
1419        unsafe { cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) }
1420    }
1421
1422    /// Sets the options used by the context, returning the old set.
1423    ///
1424    /// # Note
1425    ///
1426    /// This *enables* the specified options, but does not disable unspecified options. Use
1427    /// `clear_options` for that.
1428    #[corresponds(SSL_CTX_set_options)]
1429    pub fn set_options(&mut self, option: SslOptions) -> SslOptions {
1430        let bits =
1431            unsafe { ffi::SSL_CTX_set_options(self.as_ptr(), option.bits()) } as SslOptionsRepr;
1432        SslOptions::from_bits_retain(bits)
1433    }
1434
1435    /// Returns the options used by the context.
1436    #[corresponds(SSL_CTX_get_options)]
1437    pub fn options(&self) -> SslOptions {
1438        let bits = unsafe { ffi::SSL_CTX_get_options(self.as_ptr()) } as SslOptionsRepr;
1439        SslOptions::from_bits_retain(bits)
1440    }
1441
1442    /// Clears the options used by the context, returning the old set.
1443    #[corresponds(SSL_CTX_clear_options)]
1444    pub fn clear_options(&mut self, option: SslOptions) -> SslOptions {
1445        let bits =
1446            unsafe { ffi::SSL_CTX_clear_options(self.as_ptr(), option.bits()) } as SslOptionsRepr;
1447        SslOptions::from_bits_retain(bits)
1448    }
1449
1450    /// Sets the minimum supported protocol version.
1451    ///
1452    /// A value of `None` will enable protocol versions down to the lowest version supported by
1453    /// OpenSSL.
1454    ///
1455    /// Requires AWS-LC or BoringSSL or OpenSSL 1.1.0 or LibreSSL 2.6.1 or newer.
1456    #[corresponds(SSL_CTX_set_min_proto_version)]
1457    #[cfg(any(ossl110, libressl261, boringssl, awslc))]
1458    pub fn set_min_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
1459        unsafe {
1460            cvt(ffi::SSL_CTX_set_min_proto_version(
1461                self.as_ptr(),
1462                version.map_or(0, |v| v.0 as _),
1463            ))
1464            .map(|_| ())
1465        }
1466    }
1467
1468    /// Sets the maximum supported protocol version.
1469    ///
1470    /// A value of `None` will enable protocol versions up to the highest version supported by
1471    /// OpenSSL.
1472    ///
1473    /// Requires AWS-LC or BoringSSL or OpenSSL 1.1.0 or or LibreSSL 2.6.1 or newer.
1474    #[corresponds(SSL_CTX_set_max_proto_version)]
1475    #[cfg(any(ossl110, libressl261, boringssl, awslc))]
1476    pub fn set_max_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
1477        unsafe {
1478            cvt(ffi::SSL_CTX_set_max_proto_version(
1479                self.as_ptr(),
1480                version.map_or(0, |v| v.0 as _),
1481            ))
1482            .map(|_| ())
1483        }
1484    }
1485
1486    /// Gets the minimum supported protocol version.
1487    ///
1488    /// A value of `None` indicates that all versions down to the lowest version supported by
1489    /// OpenSSL are enabled.
1490    ///
1491    /// Requires OpenSSL 1.1.0g or LibreSSL 2.7.0 or newer.
1492    #[corresponds(SSL_CTX_get_min_proto_version)]
1493    #[cfg(any(ossl110g, libressl270))]
1494    pub fn min_proto_version(&mut self) -> Option<SslVersion> {
1495        unsafe {
1496            let r = ffi::SSL_CTX_get_min_proto_version(self.as_ptr());
1497            if r == 0 {
1498                None
1499            } else {
1500                Some(SslVersion(r))
1501            }
1502        }
1503    }
1504
1505    /// Gets the maximum supported protocol version.
1506    ///
1507    /// A value of `None` indicates that all versions up to the highest version supported by
1508    /// OpenSSL are enabled.
1509    ///
1510    /// Requires OpenSSL 1.1.0g or LibreSSL 2.7.0 or newer.
1511    #[corresponds(SSL_CTX_get_max_proto_version)]
1512    #[cfg(any(ossl110g, libressl270))]
1513    pub fn max_proto_version(&mut self) -> Option<SslVersion> {
1514        unsafe {
1515            let r = ffi::SSL_CTX_get_max_proto_version(self.as_ptr());
1516            if r == 0 {
1517                None
1518            } else {
1519                Some(SslVersion(r))
1520            }
1521        }
1522    }
1523
1524    /// Sets the protocols to sent to the server for Application Layer Protocol Negotiation (ALPN).
1525    ///
1526    /// The input must be in ALPN "wire format". It consists of a sequence of supported protocol
1527    /// names prefixed by their byte length. For example, the protocol list consisting of `spdy/1`
1528    /// and `http/1.1` is encoded as `b"\x06spdy/1\x08http/1.1"`. The protocols are ordered by
1529    /// preference.
1530    ///
1531    /// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.
1532    #[corresponds(SSL_CTX_set_alpn_protos)]
1533    #[cfg(any(ossl102, libressl261, boringssl, awslc))]
1534    pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack> {
1535        unsafe {
1536            assert!(protocols.len() <= c_uint::MAX as usize);
1537            let r = ffi::SSL_CTX_set_alpn_protos(
1538                self.as_ptr(),
1539                protocols.as_ptr(),
1540                protocols.len() as _,
1541            );
1542            // fun fact, SSL_CTX_set_alpn_protos has a reversed return code D:
1543            if r == 0 {
1544                Ok(())
1545            } else {
1546                Err(ErrorStack::get())
1547            }
1548        }
1549    }
1550
1551    /// Enables the DTLS extension "use_srtp" as defined in RFC5764.
1552    #[corresponds(SSL_CTX_set_tlsext_use_srtp)]
1553    pub fn set_tlsext_use_srtp(&mut self, protocols: &str) -> Result<(), ErrorStack> {
1554        unsafe {
1555            let cstr = CString::new(protocols).unwrap();
1556
1557            let r = ffi::SSL_CTX_set_tlsext_use_srtp(self.as_ptr(), cstr.as_ptr());
1558            // fun fact, set_tlsext_use_srtp has a reversed return code D:
1559            if r == 0 {
1560                Ok(())
1561            } else {
1562                Err(ErrorStack::get())
1563            }
1564        }
1565    }
1566
1567    /// Sets the callback used by a server to select a protocol for Application Layer Protocol
1568    /// Negotiation (ALPN).
1569    ///
1570    /// The callback is provided with the client's protocol list in ALPN wire format. See the
1571    /// documentation for [`SslContextBuilder::set_alpn_protos`] for details. It should return one
1572    /// of those protocols on success. The [`select_next_proto`] function implements the standard
1573    /// protocol selection algorithm.
1574    ///
1575    /// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.
1576    ///
1577    /// [`SslContextBuilder::set_alpn_protos`]: struct.SslContextBuilder.html#method.set_alpn_protos
1578    /// [`select_next_proto`]: fn.select_next_proto.html
1579    #[corresponds(SSL_CTX_set_alpn_select_cb)]
1580    #[cfg(any(ossl102, libressl261, boringssl, awslc))]
1581    pub fn set_alpn_select_callback<F>(&mut self, callback: F)
1582    where
1583        F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send,
1584    {
1585        unsafe {
1586            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1587            ffi::SSL_CTX_set_alpn_select_cb(
1588                self.as_ptr(),
1589                Some(callbacks::raw_alpn_select::<F>),
1590                ptr::null_mut(),
1591            );
1592        }
1593    }
1594
1595    /// Checks for consistency between the private key and certificate.
1596    #[corresponds(SSL_CTX_check_private_key)]
1597    pub fn check_private_key(&self) -> Result<(), ErrorStack> {
1598        unsafe { cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) }
1599    }
1600
1601    /// Returns a shared reference to the context's certificate store.
1602    #[corresponds(SSL_CTX_get_cert_store)]
1603    pub fn cert_store(&self) -> &X509StoreBuilderRef {
1604        unsafe { X509StoreBuilderRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) }
1605    }
1606
1607    /// Returns a mutable reference to the context's certificate store.
1608    #[corresponds(SSL_CTX_get_cert_store)]
1609    pub fn cert_store_mut(&mut self) -> &mut X509StoreBuilderRef {
1610        unsafe { X509StoreBuilderRef::from_ptr_mut(ffi::SSL_CTX_get_cert_store(self.as_ptr())) }
1611    }
1612
1613    /// Returns a reference to the X509 verification configuration.
1614    ///
1615    /// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or newer.
1616    #[corresponds(SSL_CTX_get0_param)]
1617    #[cfg(any(ossl102, boringssl, libressl261, awslc))]
1618    pub fn verify_param(&self) -> &X509VerifyParamRef {
1619        unsafe { X509VerifyParamRef::from_ptr(ffi::SSL_CTX_get0_param(self.as_ptr())) }
1620    }
1621
1622    /// Returns a mutable reference to the X509 verification configuration.
1623    ///
1624    /// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or newer.
1625    #[corresponds(SSL_CTX_get0_param)]
1626    #[cfg(any(ossl102, boringssl, libressl261, awslc))]
1627    pub fn verify_param_mut(&mut self) -> &mut X509VerifyParamRef {
1628        unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_CTX_get0_param(self.as_ptr())) }
1629    }
1630
1631    /// Registers a certificate decompression algorithm on ctx with ID alg_id.
1632    ///
1633    /// This corresponds to [`SSL_CTX_add_cert_compression_alg`].
1634    ///
1635    /// [`SSL_CTX_add_cert_compression_alg`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_CTX_add_cert_compression_alg
1636    ///
1637    /// Requires BoringSSL or Tongsuo.
1638    #[cfg(any(boringssl, tongsuo, awslc))]
1639    pub fn add_cert_decompression_alg<F>(
1640        &mut self,
1641        alg_id: CertCompressionAlgorithm,
1642        decompress: F,
1643    ) -> Result<(), ErrorStack>
1644    where
1645        F: Fn(&[u8], &mut [u8]) -> usize + Send + Sync + 'static,
1646    {
1647        unsafe {
1648            self.set_ex_data(SslContext::cached_ex_index::<F>(), decompress);
1649            cvt(ffi::SSL_CTX_add_cert_compression_alg(
1650                self.as_ptr(),
1651                alg_id.0 as _,
1652                None,
1653                Some(raw_cert_decompression::<F>),
1654            ))
1655            .map(|_| ())
1656        }
1657    }
1658
1659    /// Specify the preferred cert compression algorithms
1660    #[corresponds(SSL_CTX_set1_cert_comp_preference)]
1661    #[cfg(ossl320)]
1662    pub fn set_cert_comp_preference(
1663        &mut self,
1664        algs: &[CertCompressionAlgorithm],
1665    ) -> Result<(), ErrorStack> {
1666        let mut algs = algs.iter().map(|v| v.0).collect::<Vec<c_int>>();
1667        unsafe {
1668            cvt(ffi::SSL_CTX_set1_cert_comp_preference(
1669                self.as_ptr(),
1670                algs.as_mut_ptr(),
1671                algs.len(),
1672            ))
1673            .map(|_| ())
1674        }
1675    }
1676
1677    /// Enables OCSP stapling on all client SSL objects created from ctx
1678    ///
1679    /// This corresponds to [`SSL_CTX_enable_ocsp_stapling`].
1680    ///
1681    /// [`SSL_CTX_enable_ocsp_stapling`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_CTX_enable_ocsp_stapling
1682    ///
1683    /// Requires BoringSSL.
1684    #[cfg(any(boringssl, awslc))]
1685    pub fn enable_ocsp_stapling(&mut self) {
1686        unsafe { ffi::SSL_CTX_enable_ocsp_stapling(self.as_ptr()) }
1687    }
1688
1689    /// Enables SCT requests on all client SSL objects created from ctx
1690    ///
1691    /// This corresponds to [`SSL_CTX_enable_signed_cert_timestamps`].
1692    ///
1693    /// [`SSL_CTX_enable_signed_cert_timestamps`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_CTX_enable_signed_cert_timestamps
1694    ///
1695    /// Requires BoringSSL.
1696    #[cfg(any(boringssl, awslc))]
1697    pub fn enable_signed_cert_timestamps(&mut self) {
1698        unsafe { ffi::SSL_CTX_enable_signed_cert_timestamps(self.as_ptr()) }
1699    }
1700
1701    /// Set whether to enable GREASE on all client SSL objects created from ctx
1702    ///
1703    /// This corresponds to [`SSL_CTX_set_grease_enabled`].
1704    ///
1705    /// [`SSL_CTX_set_grease_enabled`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_CTX_set_grease_enabled
1706    ///
1707    /// Requires BoringSSL.
1708    #[cfg(any(boringssl, awslc))]
1709    pub fn set_grease_enabled(&mut self, enabled: bool) {
1710        unsafe { ffi::SSL_CTX_set_grease_enabled(self.as_ptr(), enabled as c_int) }
1711    }
1712
1713    /// Configures whether sockets on ctx should permute extensions.
1714    ///
1715    /// This corresponds to [`SSL_CTX_set_permute_extensions`].
1716    ///
1717    /// [`SSL_CTX_set_permute_extensions`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_CTX_set_permute_extensions
1718    ///
1719    /// Requires BoringSSL.
1720    #[cfg(any(boringssl, awslc))]
1721    pub fn set_permute_extensions(&mut self, enabled: bool) {
1722        unsafe { ffi::SSL_CTX_set_permute_extensions(self.as_ptr(), enabled as c_int) }
1723    }
1724
1725    /// Enable the processing of signed certificate timestamps (SCTs) for all connections that share the given SSL context.
1726    #[corresponds(SSL_CTX_enable_ct)]
1727    #[cfg(ossl111)]
1728    pub fn enable_ct(&mut self, validation_mode: SslCtValidationMode) -> Result<(), ErrorStack> {
1729        unsafe { cvt(ffi::SSL_CTX_enable_ct(self.as_ptr(), validation_mode.0)).map(|_| ()) }
1730    }
1731
1732    /// Check whether CT processing is enabled.
1733    #[corresponds(SSL_CTX_ct_is_enabled)]
1734    #[cfg(ossl111)]
1735    pub fn ct_is_enabled(&self) -> bool {
1736        unsafe { ffi::SSL_CTX_ct_is_enabled(self.as_ptr()) == 1 }
1737    }
1738
1739    /// Sets the status response a client wishes the server to reply with.
1740    #[corresponds(SSL_CTX_set_tlsext_status_type)]
1741    #[cfg(not(any(boringssl, awslc)))]
1742    pub fn set_status_type(&mut self, type_: StatusType) -> Result<(), ErrorStack> {
1743        unsafe {
1744            cvt(ffi::SSL_CTX_set_tlsext_status_type(self.as_ptr(), type_.as_raw()) as c_int)
1745                .map(|_| ())
1746        }
1747    }
1748
1749    /// Sets the callback dealing with OCSP stapling.
1750    ///
1751    /// On the client side, this callback is responsible for validating the OCSP status response
1752    /// returned by the server. The status may be retrieved with the `SslRef::ocsp_status` method.
1753    /// A response of `Ok(true)` indicates that the OCSP status is valid, and a response of
1754    /// `Ok(false)` indicates that the OCSP status is invalid and the handshake should be
1755    /// terminated.
1756    ///
1757    /// On the server side, this callback is responsible for setting the OCSP status response to be
1758    /// returned to clients. The status may be set with the `SslRef::set_ocsp_status` method. A
1759    /// response of `Ok(true)` indicates that the OCSP status should be returned to the client, and
1760    /// `Ok(false)` indicates that the status should not be returned to the client.
1761    #[corresponds(SSL_CTX_set_tlsext_status_cb)]
1762    pub fn set_status_callback<F>(&mut self, callback: F) -> Result<(), ErrorStack>
1763    where
1764        F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,
1765    {
1766        unsafe {
1767            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1768            cvt(
1769                ffi::SSL_CTX_set_tlsext_status_cb(self.as_ptr(), Some(raw_tlsext_status::<F>))
1770                    as c_int,
1771            )
1772            .map(|_| ())
1773        }
1774    }
1775
1776    #[corresponds(SSL_CTX_set_tlsext_ticket_key_evp_cb)]
1777    #[cfg(ossl300)]
1778    pub fn set_ticket_key_evp_callback<F>(&mut self, callback: F) -> Result<(), ErrorStack>
1779    where
1780        F: Fn(
1781                &mut SslRef,
1782                &mut [u8],
1783                &mut [u8],
1784                &mut CipherCtxRef,
1785                &mut MacCtxRef,
1786                bool,
1787            ) -> Result<TicketKeyStatus, ErrorStack>
1788            + 'static
1789            + Sync
1790            + Send,
1791    {
1792        unsafe {
1793            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1794            cvt(ffi::SSL_CTX_set_tlsext_ticket_key_evp_cb(
1795                self.as_ptr(),
1796                Some(raw_tlsext_ticket_key_evp::<F>),
1797            ) as c_int)
1798            .map(|_| ())
1799        }
1800    }
1801
1802    #[corresponds(SSL_CTX_set_tlsext_ticket_key_cb)]
1803    pub fn set_ticket_key_callback<F>(&mut self, callback: F) -> Result<(), ErrorStack>
1804    where
1805        F: Fn(
1806                &mut SslRef,
1807                &mut [u8],
1808                &mut [u8],
1809                &mut CipherCtxRef,
1810                &mut HMacCtxRef,
1811                bool,
1812            ) -> Result<TicketKeyStatus, ErrorStack>
1813            + 'static
1814            + Sync
1815            + Send,
1816    {
1817        unsafe {
1818            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1819            cvt(ffi::SSL_CTX_set_tlsext_ticket_key_cb(
1820                self.as_ptr(),
1821                Some(raw_tlsext_ticket_key::<F>),
1822            ) as c_int)
1823            .map(|_| ())
1824        }
1825    }
1826
1827    /// Sets the callback for providing an identity and pre-shared key for a TLS-PSK client.
1828    ///
1829    /// The callback will be called with the SSL context, an identity hint if one was provided
1830    /// by the server, a mutable slice for each of the identity and pre-shared key bytes. The
1831    /// identity must be written as a null-terminated C string.
1832    #[corresponds(SSL_CTX_set_psk_client_callback)]
1833    #[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
1834    pub fn set_psk_client_callback<F>(&mut self, callback: F)
1835    where
1836        F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack>
1837            + 'static
1838            + Sync
1839            + Send,
1840    {
1841        unsafe {
1842            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1843            ffi::SSL_CTX_set_psk_client_callback(self.as_ptr(), Some(raw_client_psk::<F>));
1844        }
1845    }
1846
1847    /// Sets the callback for providing an identity and pre-shared key for a TLS-PSK server.
1848    ///
1849    /// The callback will be called with the SSL context, an identity provided by the client,
1850    /// and, a mutable slice for the pre-shared key bytes. The callback returns the number of
1851    /// bytes in the pre-shared key.
1852    #[corresponds(SSL_CTX_set_psk_server_callback)]
1853    #[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
1854    pub fn set_psk_server_callback<F>(&mut self, callback: F)
1855    where
1856        F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8]) -> Result<usize, ErrorStack>
1857            + 'static
1858            + Sync
1859            + Send,
1860    {
1861        unsafe {
1862            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1863            ffi::SSL_CTX_set_psk_server_callback(self.as_ptr(), Some(raw_server_psk::<F>));
1864        }
1865    }
1866
1867    /// Sets the callback which is called when new sessions are negotiated.
1868    ///
1869    /// This can be used by clients to implement session caching. While in TLSv1.2 the session is
1870    /// available to access via [`SslRef::session`] immediately after the handshake completes, this
1871    /// is not the case for TLSv1.3. There, a session is not generally available immediately, and
1872    /// the server may provide multiple session tokens to the client over a single session. The new
1873    /// session callback is a portable way to deal with both cases.
1874    ///
1875    /// Note that session caching must be enabled for the callback to be invoked, and it defaults
1876    /// off for clients. [`set_session_cache_mode`] controls that behavior.
1877    ///
1878    /// [`SslRef::session`]: struct.SslRef.html#method.session
1879    /// [`set_session_cache_mode`]: #method.set_session_cache_mode
1880    #[corresponds(SSL_CTX_sess_set_new_cb)]
1881    pub fn set_new_session_callback<F>(&mut self, callback: F)
1882    where
1883        F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send,
1884    {
1885        unsafe {
1886            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1887            ffi::SSL_CTX_sess_set_new_cb(self.as_ptr(), Some(callbacks::raw_new_session::<F>));
1888        }
1889    }
1890
1891    /// Sets the callback which is called when sessions are removed from the context.
1892    ///
1893    /// Sessions can be removed because they have timed out or because they are considered faulty.
1894    #[corresponds(SSL_CTX_sess_set_remove_cb)]
1895    pub fn set_remove_session_callback<F>(&mut self, callback: F)
1896    where
1897        F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send,
1898    {
1899        unsafe {
1900            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1901            ffi::SSL_CTX_sess_set_remove_cb(
1902                self.as_ptr(),
1903                Some(callbacks::raw_remove_session::<F>),
1904            );
1905        }
1906    }
1907
1908    /// Sets the callback which is called when a client proposed to resume a session but it was not
1909    /// found in the internal cache.
1910    ///
1911    /// The callback is passed a reference to the session ID provided by the client. It should
1912    /// return the session corresponding to that ID if available. This is only used for servers, not
1913    /// clients.
1914    ///
1915    /// # Safety
1916    ///
1917    /// The returned `SslSession` must not be associated with a different `SslContext`.
1918    #[corresponds(SSL_CTX_sess_set_get_cb)]
1919    pub unsafe fn set_get_session_callback<F>(&mut self, callback: F)
1920    where
1921        F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,
1922    {
1923        self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1924        ffi::SSL_CTX_sess_set_get_cb(self.as_ptr(), Some(callbacks::raw_get_session::<F>));
1925    }
1926
1927    /// Sets the TLS key logging callback.
1928    ///
1929    /// The callback is invoked whenever TLS key material is generated, and is passed a line of NSS
1930    /// SSLKEYLOGFILE-formatted text. This can be used by tools like Wireshark to decrypt message
1931    /// traffic. The line does not contain a trailing newline.
1932    ///
1933    /// Requires OpenSSL 1.1.1 or newer.
1934    #[corresponds(SSL_CTX_set_keylog_callback)]
1935    #[cfg(any(ossl111, boringssl, awslc))]
1936    pub fn set_keylog_callback<F>(&mut self, callback: F)
1937    where
1938        F: Fn(&SslRef, &str) + 'static + Sync + Send,
1939    {
1940        unsafe {
1941            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1942            ffi::SSL_CTX_set_keylog_callback(self.as_ptr(), Some(callbacks::raw_keylog::<F>));
1943        }
1944    }
1945
1946    /// Sets the session caching mode use for connections made with the context.
1947    ///
1948    /// Returns the previous session caching mode.
1949    #[corresponds(SSL_CTX_set_session_cache_mode)]
1950    pub fn set_session_cache_mode(&mut self, mode: SslSessionCacheMode) -> SslSessionCacheMode {
1951        unsafe {
1952            let bits = ffi::SSL_CTX_set_session_cache_mode(self.as_ptr(), mode.bits());
1953            SslSessionCacheMode::from_bits_retain(bits)
1954        }
1955    }
1956
1957    /// Sets the callback for generating an application cookie for TLS1.3
1958    /// stateless handshakes.
1959    ///
1960    /// The callback will be called with the SSL context and a slice into which the cookie
1961    /// should be written. The callback should return the number of bytes written.
1962    #[corresponds(SSL_CTX_set_stateless_cookie_generate_cb)]
1963    #[cfg(ossl111)]
1964    pub fn set_stateless_cookie_generate_cb<F>(&mut self, callback: F)
1965    where
1966        F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
1967    {
1968        unsafe {
1969            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1970            ffi::SSL_CTX_set_stateless_cookie_generate_cb(
1971                self.as_ptr(),
1972                Some(raw_stateless_cookie_generate::<F>),
1973            );
1974        }
1975    }
1976
1977    /// Sets the callback for verifying an application cookie for TLS1.3
1978    /// stateless handshakes.
1979    ///
1980    /// The callback will be called with the SSL context and the cookie supplied by the
1981    /// client. It should return true if and only if the cookie is valid.
1982    ///
1983    /// Note that the OpenSSL implementation independently verifies the integrity of
1984    /// application cookies using an HMAC before invoking the supplied callback.
1985    #[corresponds(SSL_CTX_set_stateless_cookie_verify_cb)]
1986    #[cfg(ossl111)]
1987    pub fn set_stateless_cookie_verify_cb<F>(&mut self, callback: F)
1988    where
1989        F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
1990    {
1991        unsafe {
1992            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
1993            ffi::SSL_CTX_set_stateless_cookie_verify_cb(
1994                self.as_ptr(),
1995                Some(raw_stateless_cookie_verify::<F>),
1996            )
1997        }
1998    }
1999
2000    /// Sets the callback for generating a DTLSv1 cookie
2001    ///
2002    /// The callback will be called with the SSL context and a slice into which the cookie
2003    /// should be written. The callback should return the number of bytes written.
2004    #[corresponds(SSL_CTX_set_cookie_generate_cb)]
2005    #[cfg(not(any(boringssl, awslc)))]
2006    pub fn set_cookie_generate_cb<F>(&mut self, callback: F)
2007    where
2008        F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
2009    {
2010        unsafe {
2011            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
2012            ffi::SSL_CTX_set_cookie_generate_cb(self.as_ptr(), Some(raw_cookie_generate::<F>));
2013        }
2014    }
2015
2016    /// Sets the callback for verifying a DTLSv1 cookie
2017    ///
2018    /// The callback will be called with the SSL context and the cookie supplied by the
2019    /// client. It should return true if and only if the cookie is valid.
2020    #[corresponds(SSL_CTX_set_cookie_verify_cb)]
2021    #[cfg(not(any(boringssl, awslc)))]
2022    pub fn set_cookie_verify_cb<F>(&mut self, callback: F)
2023    where
2024        F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
2025    {
2026        unsafe {
2027            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
2028            ffi::SSL_CTX_set_cookie_verify_cb(self.as_ptr(), Some(raw_cookie_verify::<F>));
2029        }
2030    }
2031
2032    /// Sets the extra data at the specified index.
2033    ///
2034    /// This can be used to provide data to callbacks registered with the context. Use the
2035    /// `SslContext::new_ex_index` method to create an `Index`.
2036    // FIXME should return a result
2037    #[corresponds(SSL_CTX_set_ex_data)]
2038    pub fn set_ex_data<T>(&mut self, index: Index<SslContext, T>, data: T) {
2039        self.set_ex_data_inner(index, data);
2040    }
2041
2042    fn set_ex_data_inner<T>(&mut self, index: Index<SslContext, T>, data: T) -> *mut c_void {
2043        match self.ex_data_mut(index) {
2044            Some(v) => {
2045                *v = data;
2046                (v as *mut T).cast()
2047            }
2048            _ => unsafe {
2049                let data = Box::into_raw(Box::new(data)) as *mut c_void;
2050                ffi::SSL_CTX_set_ex_data(self.as_ptr(), index.as_raw(), data);
2051                data
2052            },
2053        }
2054    }
2055
2056    fn ex_data_mut<T>(&mut self, index: Index<SslContext, T>) -> Option<&mut T> {
2057        unsafe {
2058            let data = ffi::SSL_CTX_get_ex_data(self.as_ptr(), index.as_raw());
2059            if data.is_null() {
2060                None
2061            } else {
2062                Some(&mut *data.cast())
2063            }
2064        }
2065    }
2066
2067    /// Adds a custom extension for a TLS/DTLS client or server for all supported protocol versions.
2068    ///
2069    /// Requires OpenSSL 1.1.1 or newer.
2070    #[corresponds(SSL_CTX_add_custom_ext)]
2071    #[cfg(ossl111)]
2072    pub fn add_custom_ext<AddFn, ParseFn, T>(
2073        &mut self,
2074        ext_type: u16,
2075        context: ExtensionContext,
2076        add_cb: AddFn,
2077        parse_cb: ParseFn,
2078    ) -> Result<(), ErrorStack>
2079    where
2080        AddFn: Fn(
2081                &mut SslRef,
2082                ExtensionContext,
2083                Option<(usize, &X509Ref)>,
2084            ) -> Result<Option<T>, SslAlert>
2085            + 'static
2086            + Sync
2087            + Send,
2088        T: AsRef<[u8]> + 'static + Sync + Send,
2089        ParseFn: Fn(
2090                &mut SslRef,
2091                ExtensionContext,
2092                &[u8],
2093                Option<(usize, &X509Ref)>,
2094            ) -> Result<(), SslAlert>
2095            + 'static
2096            + Sync
2097            + Send,
2098    {
2099        let ret = unsafe {
2100            self.set_ex_data(SslContext::cached_ex_index::<AddFn>(), add_cb);
2101            self.set_ex_data(SslContext::cached_ex_index::<ParseFn>(), parse_cb);
2102
2103            ffi::SSL_CTX_add_custom_ext(
2104                self.as_ptr(),
2105                ext_type as c_uint,
2106                context.bits(),
2107                Some(raw_custom_ext_add::<AddFn, T>),
2108                Some(raw_custom_ext_free::<T>),
2109                ptr::null_mut(),
2110                Some(raw_custom_ext_parse::<ParseFn>),
2111                ptr::null_mut(),
2112            )
2113        };
2114        if ret == 1 {
2115            Ok(())
2116        } else {
2117            Err(ErrorStack::get())
2118        }
2119    }
2120
2121    /// Sets the maximum amount of early data that will be accepted on incoming connections.
2122    ///
2123    /// Defaults to 0.
2124    ///
2125    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
2126    #[corresponds(SSL_CTX_set_max_early_data)]
2127    #[cfg(any(ossl111, libressl340))]
2128    pub fn set_max_early_data(&mut self, bytes: u32) -> Result<(), ErrorStack> {
2129        if unsafe { ffi::SSL_CTX_set_max_early_data(self.as_ptr(), bytes) } == 1 {
2130            Ok(())
2131        } else {
2132            Err(ErrorStack::get())
2133        }
2134    }
2135
2136    /// Sets a callback that is called before most ClientHello processing and before the decision whether
2137    /// to resume a session is made. The callback may inspect the ClientHello and configure the
2138    /// connection.
2139    ///
2140    /// This corresponds to [`SSL_CTX_set_select_certificate_cb`].
2141    ///
2142    /// [`SSL_CTX_set_select_certificate_cb`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_CTX_set_select_certificate_cb
2143    ///
2144    /// Requires BoringSSL.
2145    #[cfg(any(boringssl, awslc))]
2146    pub fn set_select_certificate_callback<F>(&mut self, callback: F)
2147    where
2148        F: Fn(ClientHello<'_>) -> Result<(), SelectCertError> + Sync + Send + 'static,
2149    {
2150        unsafe {
2151            self.set_ex_data(SslContext::cached_ex_index::<F>(), callback);
2152            ffi::SSL_CTX_set_select_certificate_cb(
2153                self.as_ptr(),
2154                Some(callbacks::raw_select_cert::<F>),
2155            );
2156        }
2157    }
2158
2159    /// Sets a callback which will be invoked just after the client's hello message is received.
2160    ///
2161    /// Requires OpenSSL 1.1.1 or newer.
2162    #[corresponds(SSL_CTX_set_client_hello_cb)]
2163    #[cfg(ossl111)]
2164    pub fn set_client_hello_callback<F>(&mut self, callback: F)
2165    where
2166        F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), ClientHelloError> + 'static + Sync + Send,
2167    {
2168        unsafe {
2169            let ptr = self.set_ex_data_inner(SslContext::cached_ex_index::<F>(), callback);
2170            ffi::SSL_CTX_set_client_hello_cb(
2171                self.as_ptr(),
2172                Some(callbacks::raw_client_hello::<F>),
2173                ptr,
2174            );
2175        }
2176    }
2177
2178    /// Sets the context's session cache size limit, returning the previous limit.
2179    ///
2180    /// A value of 0 means that the cache size is unbounded.
2181    #[corresponds(SSL_CTX_sess_set_cache_size)]
2182    #[allow(clippy::useless_conversion)]
2183    pub fn set_session_cache_size(&mut self, size: i32) -> i64 {
2184        unsafe {
2185            ffi::SSL_CTX_sess_set_cache_size(self.as_ptr(), size as SslCacheSize) as SslCacheTy
2186        }
2187    }
2188
2189    /// Sets the context's supported signature algorithms.
2190    ///
2191    /// Requires OpenSSL 1.0.2 or newer.
2192    #[corresponds(SSL_CTX_set1_sigalgs_list)]
2193    #[cfg(ossl102)]
2194    pub fn set_sigalgs_list(&mut self, sigalgs: &str) -> Result<(), ErrorStack> {
2195        let sigalgs = CString::new(sigalgs).unwrap();
2196        unsafe {
2197            cvt(ffi::SSL_CTX_set1_sigalgs_list(self.as_ptr(), sigalgs.as_ptr()) as c_int)
2198                .map(|_| ())
2199        }
2200    }
2201
2202    /// Sets the context's supported elliptic curve groups.
2203    ///
2204    /// Requires AWS-LC or BoringSSL or OpenSSL 1.1.1 or LibreSSL 2.5.1 or newer.
2205    #[corresponds(SSL_CTX_set1_groups_list)]
2206    #[cfg(any(ossl111, boringssl, libressl251, awslc))]
2207    pub fn set_groups_list(&mut self, groups: &str) -> Result<(), ErrorStack> {
2208        let groups = CString::new(groups).unwrap();
2209        unsafe {
2210            cvt(ffi::SSL_CTX_set1_groups_list(self.as_ptr(), groups.as_ptr()) as c_int).map(|_| ())
2211        }
2212    }
2213
2214    /// Sets the number of TLS 1.3 session tickets that will be sent to a client after a full
2215    /// handshake.
2216    ///
2217    /// Requires OpenSSL 1.1.1 or newer.
2218    #[corresponds(SSL_CTX_set_num_tickets)]
2219    #[cfg(any(ossl111, boringssl, awslc))]
2220    pub fn set_num_tickets(&mut self, num_tickets: usize) -> Result<(), ErrorStack> {
2221        unsafe { cvt(ffi::SSL_CTX_set_num_tickets(self.as_ptr(), num_tickets)).map(|_| ()) }
2222    }
2223
2224    /// Set the context's security level to a value between 0 and 5, inclusive.
2225    /// A security value of 0 allows allows all parameters and algorithms.
2226    ///
2227    /// Requires OpenSSL 1.1.0 or newer.
2228    #[corresponds(SSL_CTX_set_security_level)]
2229    #[cfg(any(ossl110, libressl360))]
2230    pub fn set_security_level(&mut self, level: u32) {
2231        unsafe { ffi::SSL_CTX_set_security_level(self.as_ptr(), level as c_int) }
2232    }
2233
2234    /// Consumes the builder, returning a new `SslContext`.
2235    pub fn build(self) -> SslContext {
2236        self.0
2237    }
2238}
2239
2240foreign_type_and_impl_send_sync! {
2241    type CType = ffi::SSL_CTX;
2242    fn drop = ffi::SSL_CTX_free;
2243
2244    /// A context object for TLS streams.
2245    ///
2246    /// Applications commonly configure a single `SslContext` that is shared by all of its
2247    /// `SslStreams`.
2248    pub struct SslContext;
2249
2250    /// Reference to [`SslContext`]
2251    ///
2252    /// [`SslContext`]: struct.SslContext.html
2253    pub struct SslContextRef;
2254}
2255
2256impl Clone for SslContext {
2257    fn clone(&self) -> Self {
2258        (**self).to_owned()
2259    }
2260}
2261
2262impl ToOwned for SslContextRef {
2263    type Owned = SslContext;
2264
2265    fn to_owned(&self) -> Self::Owned {
2266        unsafe {
2267            SSL_CTX_up_ref(self.as_ptr());
2268            SslContext::from_ptr(self.as_ptr())
2269        }
2270    }
2271}
2272
2273// TODO: add useful info here
2274impl fmt::Debug for SslContext {
2275    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2276        write!(fmt, "SslContext")
2277    }
2278}
2279
2280impl SslContext {
2281    /// Creates a new builder object for an `SslContext`.
2282    pub fn builder(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> {
2283        SslContextBuilder::new(method)
2284    }
2285
2286    /// Returns a new extra data index.
2287    ///
2288    /// Each invocation of this function is guaranteed to return a distinct index. These can be used
2289    /// to store data in the context that can be retrieved later by callbacks, for example.
2290    #[corresponds(SSL_CTX_get_ex_new_index)]
2291    pub fn new_ex_index<T>() -> Result<Index<SslContext, T>, ErrorStack>
2292    where
2293        T: 'static + Sync + Send,
2294    {
2295        unsafe {
2296            ffi::init();
2297            let idx = cvt_n(get_new_idx(Some(free_data_box::<T>)))?;
2298            Ok(Index::from_raw(idx))
2299        }
2300    }
2301
2302    // FIXME should return a result?
2303    fn cached_ex_index<T>() -> Index<SslContext, T>
2304    where
2305        T: 'static + Sync + Send,
2306    {
2307        unsafe {
2308            let idx = *INDEXES
2309                .lock()
2310                .unwrap_or_else(|e| e.into_inner())
2311                .entry(TypeId::of::<T>())
2312                .or_insert_with(|| SslContext::new_ex_index::<T>().unwrap().as_raw());
2313            Index::from_raw(idx)
2314        }
2315    }
2316}
2317
2318impl SslContextRef {
2319    /// Returns the certificate associated with this `SslContext`, if present.
2320    ///
2321    /// Requires OpenSSL 1.0.2 or LibreSSL 2.7.0 or newer.
2322    #[corresponds(SSL_CTX_get0_certificate)]
2323    #[cfg(any(ossl102, libressl270))]
2324    pub fn certificate(&self) -> Option<&X509Ref> {
2325        unsafe {
2326            let ptr = ffi::SSL_CTX_get0_certificate(self.as_ptr());
2327            X509Ref::from_const_ptr_opt(ptr)
2328        }
2329    }
2330
2331    /// Returns the private key associated with this `SslContext`, if present.
2332    ///
2333    /// Requires OpenSSL 1.0.2 or LibreSSL 3.4.0 or newer.
2334    #[corresponds(SSL_CTX_get0_privatekey)]
2335    #[cfg(any(ossl102, libressl340))]
2336    pub fn private_key(&self) -> Option<&PKeyRef<Private>> {
2337        unsafe {
2338            let ptr = ffi::SSL_CTX_get0_privatekey(self.as_ptr());
2339            PKeyRef::from_const_ptr_opt(ptr)
2340        }
2341    }
2342
2343    /// Returns a shared reference to the certificate store used for verification.
2344    #[corresponds(SSL_CTX_get_cert_store)]
2345    pub fn cert_store(&self) -> &X509StoreRef {
2346        unsafe { X509StoreRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) }
2347    }
2348
2349    /// Returns a shared reference to the stack of certificates making up the chain from the leaf.
2350    #[corresponds(SSL_CTX_get_extra_chain_certs)]
2351    pub fn extra_chain_certs(&self) -> &StackRef<X509> {
2352        unsafe {
2353            let mut chain = ptr::null_mut();
2354            ffi::SSL_CTX_get_extra_chain_certs(self.as_ptr(), &mut chain);
2355            StackRef::from_const_ptr_opt(chain).expect("extra chain certs must not be null")
2356        }
2357    }
2358
2359    /// Returns a reference to the extra data at the specified index.
2360    #[corresponds(SSL_CTX_get_ex_data)]
2361    pub fn ex_data<T>(&self, index: Index<SslContext, T>) -> Option<&T> {
2362        unsafe {
2363            let data = ffi::SSL_CTX_get_ex_data(self.as_ptr(), index.as_raw());
2364            if data.is_null() {
2365                None
2366            } else {
2367                Some(&*(data as *const T))
2368            }
2369        }
2370    }
2371
2372    /// Gets the maximum amount of early data that will be accepted on incoming connections.
2373    ///
2374    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
2375    #[corresponds(SSL_CTX_get_max_early_data)]
2376    #[cfg(any(ossl111, libressl340))]
2377    pub fn max_early_data(&self) -> u32 {
2378        unsafe { ffi::SSL_CTX_get_max_early_data(self.as_ptr()) }
2379    }
2380
2381    /// Adds a session to the context's cache.
2382    ///
2383    /// Returns `true` if the session was successfully added to the cache, and `false` if it was already present.
2384    ///
2385    /// # Safety
2386    ///
2387    /// The caller of this method is responsible for ensuring that the session has never been used with another
2388    /// `SslContext` than this one.
2389    #[corresponds(SSL_CTX_add_session)]
2390    pub unsafe fn add_session(&self, session: &SslSessionRef) -> bool {
2391        ffi::SSL_CTX_add_session(self.as_ptr(), session.as_ptr()) != 0
2392    }
2393
2394    /// Removes a session from the context's cache and marks it as non-resumable.
2395    ///
2396    /// Returns `true` if the session was successfully found and removed, and `false` otherwise.
2397    ///
2398    /// # Safety
2399    ///
2400    /// The caller of this method is responsible for ensuring that the session has never been used with another
2401    /// `SslContext` than this one.
2402    #[corresponds(SSL_CTX_remove_session)]
2403    pub unsafe fn remove_session(&self, session: &SslSessionRef) -> bool {
2404        ffi::SSL_CTX_remove_session(self.as_ptr(), session.as_ptr()) != 0
2405    }
2406
2407    /// Returns the context's session cache size limit.
2408    ///
2409    /// A value of 0 means that the cache size is unbounded.
2410    #[corresponds(SSL_CTX_sess_get_cache_size)]
2411    #[allow(clippy::unnecessary_cast)]
2412    pub fn session_cache_size(&self) -> i64 {
2413        unsafe { ffi::SSL_CTX_sess_get_cache_size(self.as_ptr()) as i64 }
2414    }
2415
2416    /// Returns the verify mode that was set on this context from [`SslContextBuilder::set_verify`].
2417    ///
2418    /// [`SslContextBuilder::set_verify`]: struct.SslContextBuilder.html#method.set_verify
2419    #[corresponds(SSL_CTX_get_verify_mode)]
2420    pub fn verify_mode(&self) -> SslVerifyMode {
2421        let mode = unsafe { ffi::SSL_CTX_get_verify_mode(self.as_ptr()) };
2422        SslVerifyMode::from_bits(mode).expect("SSL_CTX_get_verify_mode returned invalid mode")
2423    }
2424
2425    /// Gets the number of TLS 1.3 session tickets that will be sent to a client after a full
2426    /// handshake.
2427    ///
2428    /// Requires OpenSSL 1.1.1 or newer.
2429    #[corresponds(SSL_CTX_get_num_tickets)]
2430    #[cfg(ossl111)]
2431    pub fn num_tickets(&self) -> usize {
2432        unsafe { ffi::SSL_CTX_get_num_tickets(self.as_ptr()) }
2433    }
2434
2435    /// Get the context's security level, which controls the allowed parameters
2436    /// and algorithms.
2437    ///
2438    /// Requires OpenSSL 1.1.0 or newer.
2439    #[corresponds(SSL_CTX_get_security_level)]
2440    #[cfg(any(ossl110, libressl360))]
2441    pub fn security_level(&self) -> u32 {
2442        unsafe { ffi::SSL_CTX_get_security_level(self.as_ptr()) as u32 }
2443    }
2444}
2445
2446/// Information about the state of a cipher.
2447pub struct CipherBits {
2448    /// The number of secret bits used for the cipher.
2449    pub secret: i32,
2450
2451    /// The number of bits processed by the chosen algorithm.
2452    pub algorithm: i32,
2453}
2454
2455/// Information about a cipher.
2456pub struct SslCipher(*mut ffi::SSL_CIPHER);
2457
2458impl ForeignType for SslCipher {
2459    type CType = ffi::SSL_CIPHER;
2460    type Ref = SslCipherRef;
2461
2462    #[inline]
2463    unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher {
2464        SslCipher(ptr)
2465    }
2466
2467    #[inline]
2468    fn as_ptr(&self) -> *mut ffi::SSL_CIPHER {
2469        self.0
2470    }
2471}
2472
2473impl Stackable for SslCipher {
2474    type StackType = ffi::stack_st_SSL_CIPHER;
2475}
2476
2477impl Deref for SslCipher {
2478    type Target = SslCipherRef;
2479
2480    fn deref(&self) -> &SslCipherRef {
2481        unsafe { SslCipherRef::from_ptr(self.0) }
2482    }
2483}
2484
2485impl DerefMut for SslCipher {
2486    fn deref_mut(&mut self) -> &mut SslCipherRef {
2487        unsafe { SslCipherRef::from_ptr_mut(self.0) }
2488    }
2489}
2490
2491/// Reference to an [`SslCipher`].
2492///
2493/// [`SslCipher`]: struct.SslCipher.html
2494pub struct SslCipherRef(Opaque);
2495
2496impl ForeignTypeRef for SslCipherRef {
2497    type CType = ffi::SSL_CIPHER;
2498}
2499
2500impl SslCipherRef {
2501    /// Returns the name of the cipher.
2502    #[corresponds(SSL_CIPHER_get_name)]
2503    pub fn name(&self) -> &'static str {
2504        unsafe {
2505            let ptr = ffi::SSL_CIPHER_get_name(self.as_ptr());
2506            CStr::from_ptr(ptr).to_str().unwrap()
2507        }
2508    }
2509
2510    /// Returns the RFC-standard name of the cipher, if one exists.
2511    ///
2512    /// Requires OpenSSL 1.1.1 or newer.
2513    #[corresponds(SSL_CIPHER_standard_name)]
2514    #[cfg(ossl111)]
2515    pub fn standard_name(&self) -> Option<&'static str> {
2516        unsafe {
2517            let ptr = ffi::SSL_CIPHER_standard_name(self.as_ptr());
2518            if ptr.is_null() {
2519                None
2520            } else {
2521                Some(CStr::from_ptr(ptr).to_str().unwrap())
2522            }
2523        }
2524    }
2525
2526    /// Returns the SSL/TLS protocol version that first defined the cipher.
2527    #[corresponds(SSL_CIPHER_get_version)]
2528    pub fn version(&self) -> &'static str {
2529        let version = unsafe {
2530            let ptr = ffi::SSL_CIPHER_get_version(self.as_ptr());
2531            CStr::from_ptr(ptr as *const _)
2532        };
2533
2534        str::from_utf8(version.to_bytes()).unwrap()
2535    }
2536
2537    /// Returns the number of bits used for the cipher.
2538    #[corresponds(SSL_CIPHER_get_bits)]
2539    #[allow(clippy::useless_conversion)]
2540    pub fn bits(&self) -> CipherBits {
2541        unsafe {
2542            let mut algo_bits = 0;
2543            let secret_bits = ffi::SSL_CIPHER_get_bits(self.as_ptr(), &mut algo_bits);
2544            CipherBits {
2545                secret: secret_bits.into(),
2546                algorithm: algo_bits.into(),
2547            }
2548        }
2549    }
2550
2551    /// Returns a textual description of the cipher.
2552    #[corresponds(SSL_CIPHER_description)]
2553    pub fn description(&self) -> String {
2554        unsafe {
2555            // SSL_CIPHER_description requires a buffer of at least 128 bytes.
2556            let mut buf = [0; 128];
2557            let ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128);
2558            String::from_utf8(CStr::from_ptr(ptr as *const _).to_bytes().to_vec()).unwrap()
2559        }
2560    }
2561
2562    /// Returns the handshake digest of the cipher.
2563    ///
2564    /// Requires OpenSSL 1.1.1 or newer.
2565    #[corresponds(SSL_CIPHER_get_handshake_digest)]
2566    #[cfg(ossl111)]
2567    pub fn handshake_digest(&self) -> Option<MessageDigest> {
2568        unsafe {
2569            let ptr = ffi::SSL_CIPHER_get_handshake_digest(self.as_ptr());
2570            if ptr.is_null() {
2571                None
2572            } else {
2573                Some(MessageDigest::from_ptr(ptr))
2574            }
2575        }
2576    }
2577
2578    /// Returns the NID corresponding to the cipher.
2579    ///
2580    /// Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.
2581    #[corresponds(SSL_CIPHER_get_cipher_nid)]
2582    #[cfg(any(ossl110, libressl270))]
2583    pub fn cipher_nid(&self) -> Option<Nid> {
2584        let n = unsafe { ffi::SSL_CIPHER_get_cipher_nid(self.as_ptr()) };
2585        if n == 0 {
2586            None
2587        } else {
2588            Some(Nid::from_raw(n))
2589        }
2590    }
2591}
2592
2593impl fmt::Debug for SslCipherRef {
2594    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2595        write!(fmt, "{}", self.name())
2596    }
2597}
2598
2599/// A stack of selected ciphers, and a stack of selected signalling cipher suites
2600#[derive(Debug)]
2601pub struct CipherLists {
2602    pub suites: Stack<SslCipher>,
2603    pub signalling_suites: Stack<SslCipher>,
2604}
2605
2606foreign_type_and_impl_send_sync! {
2607    type CType = ffi::SSL_SESSION;
2608    fn drop = ffi::SSL_SESSION_free;
2609
2610    /// An encoded SSL session.
2611    ///
2612    /// These can be cached to share sessions across connections.
2613    pub struct SslSession;
2614
2615    /// Reference to [`SslSession`].
2616    ///
2617    /// [`SslSession`]: struct.SslSession.html
2618    pub struct SslSessionRef;
2619}
2620
2621impl Clone for SslSession {
2622    fn clone(&self) -> SslSession {
2623        SslSessionRef::to_owned(self)
2624    }
2625}
2626
2627impl SslSession {
2628    from_der! {
2629        /// Deserializes a DER-encoded session structure.
2630        #[corresponds(d2i_SSL_SESSION)]
2631        from_der,
2632        SslSession,
2633        ffi::d2i_SSL_SESSION
2634    }
2635}
2636
2637impl ToOwned for SslSessionRef {
2638    type Owned = SslSession;
2639
2640    fn to_owned(&self) -> SslSession {
2641        unsafe {
2642            SSL_SESSION_up_ref(self.as_ptr());
2643            SslSession(self.as_ptr())
2644        }
2645    }
2646}
2647
2648impl SslSessionRef {
2649    /// Returns the SSL session ID.
2650    #[corresponds(SSL_SESSION_get_id)]
2651    pub fn id(&self) -> &[u8] {
2652        unsafe {
2653            let mut len = 0;
2654            let p = ffi::SSL_SESSION_get_id(self.as_ptr(), &mut len);
2655            #[allow(clippy::unnecessary_cast)]
2656            util::from_raw_parts(p as *const u8, len as usize)
2657        }
2658    }
2659
2660    /// Returns the length of the master key.
2661    #[corresponds(SSL_SESSION_get_master_key)]
2662    pub fn master_key_len(&self) -> usize {
2663        unsafe { SSL_SESSION_get_master_key(self.as_ptr(), ptr::null_mut(), 0) }
2664    }
2665
2666    /// Copies the master key into the provided buffer.
2667    ///
2668    /// Returns the number of bytes written, or the size of the master key if the buffer is empty.
2669    #[corresponds(SSL_SESSION_get_master_key)]
2670    pub fn master_key(&self, buf: &mut [u8]) -> usize {
2671        unsafe { SSL_SESSION_get_master_key(self.as_ptr(), buf.as_mut_ptr(), buf.len()) }
2672    }
2673
2674    /// Gets the maximum amount of early data that can be sent on this session.
2675    ///
2676    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
2677    #[corresponds(SSL_SESSION_get_max_early_data)]
2678    #[cfg(any(ossl111, libressl340))]
2679    pub fn max_early_data(&self) -> u32 {
2680        unsafe { ffi::SSL_SESSION_get_max_early_data(self.as_ptr()) }
2681    }
2682
2683    /// Returns the time at which the session was established, in seconds since the Unix epoch.
2684    #[corresponds(SSL_SESSION_get_time)]
2685    #[allow(clippy::useless_conversion)]
2686    pub fn time(&self) -> SslTimeTy {
2687        unsafe { ffi::SSL_SESSION_get_time(self.as_ptr()) }
2688    }
2689
2690    /// Returns the sessions timeout, in seconds.
2691    ///
2692    /// A session older than this time should not be used for session resumption.
2693    #[corresponds(SSL_SESSION_get_timeout)]
2694    #[allow(clippy::useless_conversion)]
2695    pub fn timeout(&self) -> i64 {
2696        unsafe { ffi::SSL_SESSION_get_timeout(self.as_ptr()).into() }
2697    }
2698
2699    /// Returns the session's TLS protocol version.
2700    ///
2701    /// Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.
2702    #[corresponds(SSL_SESSION_get_protocol_version)]
2703    #[cfg(any(ossl110, libressl270))]
2704    pub fn protocol_version(&self) -> SslVersion {
2705        unsafe {
2706            let version = ffi::SSL_SESSION_get_protocol_version(self.as_ptr());
2707            SslVersion(version)
2708        }
2709    }
2710
2711    /// Returns the session's TLS protocol version.
2712    #[corresponds(SSL_SESSION_get_protocol_version)]
2713    #[cfg(any(boringssl, awslc))]
2714    pub fn protocol_version(&self) -> SslVersion {
2715        unsafe {
2716            let version = ffi::SSL_SESSION_get_protocol_version(self.as_ptr());
2717            SslVersion(version as _)
2718        }
2719    }
2720
2721    to_der! {
2722        /// Serializes the session into a DER-encoded structure.
2723        #[corresponds(i2d_SSL_SESSION)]
2724        to_der,
2725        ffi::i2d_SSL_SESSION
2726    }
2727}
2728
2729foreign_type_and_impl_send_sync! {
2730    type CType = ffi::SSL;
2731    fn drop = ffi::SSL_free;
2732
2733    /// The state of an SSL/TLS session.
2734    ///
2735    /// `Ssl` objects are created from an [`SslContext`], which provides configuration defaults.
2736    /// These defaults can be overridden on a per-`Ssl` basis, however.
2737    ///
2738    /// [`SslContext`]: struct.SslContext.html
2739    pub struct Ssl;
2740
2741    /// Reference to an [`Ssl`].
2742    ///
2743    /// [`Ssl`]: struct.Ssl.html
2744    pub struct SslRef;
2745}
2746
2747impl fmt::Debug for Ssl {
2748    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2749        fmt::Debug::fmt(&**self, fmt)
2750    }
2751}
2752
2753impl Ssl {
2754    /// Returns a new extra data index.
2755    ///
2756    /// Each invocation of this function is guaranteed to return a distinct index. These can be used
2757    /// to store data in the context that can be retrieved later by callbacks, for example.
2758    #[corresponds(SSL_get_ex_new_index)]
2759    pub fn new_ex_index<T>() -> Result<Index<Ssl, T>, ErrorStack>
2760    where
2761        T: 'static + Sync + Send,
2762    {
2763        unsafe {
2764            ffi::init();
2765            let idx = cvt_n(get_new_ssl_idx(Some(free_data_box::<T>)))?;
2766            Ok(Index::from_raw(idx))
2767        }
2768    }
2769
2770    // FIXME should return a result?
2771    fn cached_ex_index<T>() -> Index<Ssl, T>
2772    where
2773        T: 'static + Sync + Send,
2774    {
2775        unsafe {
2776            let idx = *SSL_INDEXES
2777                .lock()
2778                .unwrap_or_else(|e| e.into_inner())
2779                .entry(TypeId::of::<T>())
2780                .or_insert_with(|| Ssl::new_ex_index::<T>().unwrap().as_raw());
2781            Index::from_raw(idx)
2782        }
2783    }
2784
2785    /// Creates a new `Ssl`.
2786    #[corresponds(SSL_new)]
2787    pub fn new(ctx: &SslContextRef) -> Result<Ssl, ErrorStack> {
2788        let session_ctx_index = try_get_session_ctx_index()?;
2789        unsafe {
2790            let ptr = cvt_p(ffi::SSL_new(ctx.as_ptr()))?;
2791            let mut ssl = Ssl::from_ptr(ptr);
2792            ssl.set_ex_data(*session_ctx_index, ctx.to_owned());
2793
2794            Ok(ssl)
2795        }
2796    }
2797
2798    /// Initiates a client-side TLS handshake.
2799    /// # Warning
2800    ///
2801    /// OpenSSL's default configuration is insecure. It is highly recommended to use
2802    /// `SslConnector` rather than `Ssl` directly, as it manages that configuration.
2803    #[corresponds(SSL_connect)]
2804    #[allow(deprecated)]
2805    pub fn connect<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
2806    where
2807        S: Read + Write,
2808    {
2809        SslStreamBuilder::new(self, stream).connect()
2810    }
2811
2812    /// Initiates a server-side TLS handshake.
2813    ///
2814    /// # Warning
2815    ///
2816    /// OpenSSL's default configuration is insecure. It is highly recommended to use
2817    /// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration.
2818    #[corresponds(SSL_accept)]
2819    #[allow(deprecated)]
2820    pub fn accept<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
2821    where
2822        S: Read + Write,
2823    {
2824        SslStreamBuilder::new(self, stream).accept()
2825    }
2826}
2827
2828impl fmt::Debug for SslRef {
2829    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2830        fmt.debug_struct("Ssl")
2831            .field("state", &self.state_string_long())
2832            .field("verify_result", &self.verify_result())
2833            .finish()
2834    }
2835}
2836
2837impl SslRef {
2838    #[cfg(not(feature = "tongsuo"))]
2839    fn get_raw_rbio(&self) -> *mut ffi::BIO {
2840        unsafe { ffi::SSL_get_rbio(self.as_ptr()) }
2841    }
2842
2843    #[cfg(feature = "tongsuo")]
2844    fn get_raw_rbio(&self) -> *mut ffi::BIO {
2845        unsafe {
2846            let bio = ffi::SSL_get_rbio(self.as_ptr());
2847            bio::find_correct_bio(bio)
2848        }
2849    }
2850
2851    fn get_error(&self, ret: c_int) -> ErrorCode {
2852        unsafe { ErrorCode::from_raw(ffi::SSL_get_error(self.as_ptr(), ret)) }
2853    }
2854
2855    /// Sets the mode used by the SSL, returning the new mode bit mask.
2856    ///
2857    /// Options already set before are not cleared.
2858    #[corresponds(SSL_set_mode)]
2859    pub fn set_mode(&mut self, mode: SslMode) -> SslMode {
2860        unsafe {
2861            let bits = ffi::SSL_set_mode(self.as_ptr(), mode.bits() as ModeTy) as SslBitType;
2862            SslMode::from_bits_retain(bits)
2863        }
2864    }
2865
2866    /// Clear the mode used by the SSL, returning the new mode bit mask.
2867    #[corresponds(SSL_clear_mode)]
2868    pub fn clear_mode(&mut self, mode: SslMode) -> SslMode {
2869        unsafe {
2870            let bits = ffi::SSL_clear_mode(self.as_ptr(), mode.bits() as ModeTy) as SslBitType;
2871            SslMode::from_bits_retain(bits)
2872        }
2873    }
2874
2875    /// Returns the mode set for the SSL.
2876    #[corresponds(SSL_get_mode)]
2877    pub fn mode(&self) -> SslMode {
2878        unsafe {
2879            let bits = ffi::SSL_get_mode(self.as_ptr()) as SslBitType;
2880            SslMode::from_bits_retain(bits)
2881        }
2882    }
2883
2884    /// Configure as an outgoing stream from a client.
2885    #[corresponds(SSL_set_connect_state)]
2886    pub fn set_connect_state(&mut self) {
2887        unsafe { ffi::SSL_set_connect_state(self.as_ptr()) }
2888    }
2889
2890    /// Configure as an incoming stream to a server.
2891    #[corresponds(SSL_set_accept_state)]
2892    pub fn set_accept_state(&mut self) {
2893        unsafe { ffi::SSL_set_accept_state(self.as_ptr()) }
2894    }
2895
2896    #[cfg(any(boringssl, awslc))]
2897    #[corresponds(SSL_ech_accepted)]
2898    pub fn ech_accepted(&self) -> bool {
2899        unsafe { ffi::SSL_ech_accepted(self.as_ptr()) != 0 }
2900    }
2901
2902    #[cfg(tongsuo)]
2903    #[corresponds(SSL_is_ntls)]
2904    pub fn is_ntls(&mut self) -> bool {
2905        unsafe { ffi::SSL_is_ntls(self.as_ptr()) != 0 }
2906    }
2907
2908    #[cfg(tongsuo)]
2909    #[corresponds(SSL_enable_ntls)]
2910    pub fn enable_ntls(&mut self) {
2911        unsafe { ffi::SSL_enable_ntls(self.as_ptr()) }
2912    }
2913
2914    #[cfg(tongsuo)]
2915    #[corresponds(SSL_disable_ntls)]
2916    pub fn disable_ntls(&mut self) {
2917        unsafe { ffi::SSL_disable_ntls(self.as_ptr()) }
2918    }
2919
2920    #[cfg(all(tongsuo, ossl300))]
2921    #[corresponds(SSL_enable_force_ntls)]
2922    pub fn enable_force_ntls(&mut self) {
2923        unsafe { ffi::SSL_enable_force_ntls(self.as_ptr()) }
2924    }
2925
2926    #[cfg(all(tongsuo, ossl300))]
2927    #[corresponds(SSL_disable_force_ntls)]
2928    pub fn disable_force_ntls(&mut self) {
2929        unsafe { ffi::SSL_disable_force_ntls(self.as_ptr()) }
2930    }
2931
2932    #[cfg(tongsuo)]
2933    #[corresponds(SSL_enable_sm_tls13_strict)]
2934    pub fn enable_sm_tls13_strict(&mut self) {
2935        unsafe { ffi::SSL_enable_sm_tls13_strict(self.as_ptr()) }
2936    }
2937
2938    #[cfg(tongsuo)]
2939    #[corresponds(SSL_disable_sm_tls13_strict)]
2940    pub fn disable_sm_tls13_strict(&mut self) {
2941        unsafe { ffi::SSL_disable_sm_tls13_strict(self.as_ptr()) }
2942    }
2943
2944    /// Like [`SslContextBuilder::set_verify`].
2945    ///
2946    /// [`SslContextBuilder::set_verify`]: struct.SslContextBuilder.html#method.set_verify
2947    #[corresponds(SSL_set_verify)]
2948    pub fn set_verify(&mut self, mode: SslVerifyMode) {
2949        unsafe { ffi::SSL_set_verify(self.as_ptr(), mode.bits() as c_int, None) }
2950    }
2951
2952    /// Returns the verify mode that was set using `set_verify`.
2953    #[corresponds(SSL_set_verify_mode)]
2954    pub fn verify_mode(&self) -> SslVerifyMode {
2955        let mode = unsafe { ffi::SSL_get_verify_mode(self.as_ptr()) };
2956        SslVerifyMode::from_bits(mode).expect("SSL_get_verify_mode returned invalid mode")
2957    }
2958
2959    /// Like [`SslContextBuilder::set_verify_callback`].
2960    ///
2961    /// [`SslContextBuilder::set_verify_callback`]: struct.SslContextBuilder.html#method.set_verify_callback
2962    #[corresponds(SSL_set_verify)]
2963    pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
2964    where
2965        F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
2966    {
2967        unsafe {
2968            // this needs to be in an Arc since the callback can register a new callback!
2969            self.set_ex_data(Ssl::cached_ex_index(), Arc::new(verify));
2970            ffi::SSL_set_verify(
2971                self.as_ptr(),
2972                mode.bits() as c_int,
2973                Some(ssl_raw_verify::<F>),
2974            );
2975        }
2976    }
2977
2978    /// Like [`SslContextBuilder::set_dh_auto`].
2979    ///
2980    /// [`SslContextBuilder::set_dh_auto`]: struct.SslContextBuilder.html#method.set_dh_auto
2981    #[corresponds(SSL_set_dh_auto)]
2982    #[cfg(ossl300)]
2983    pub fn set_dh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> {
2984        unsafe { cvt(ffi::SSL_set_dh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) }
2985    }
2986
2987    /// Like [`SslContextBuilder::set_tmp_dh`].
2988    ///
2989    /// [`SslContextBuilder::set_tmp_dh`]: struct.SslContextBuilder.html#method.set_tmp_dh
2990    #[corresponds(SSL_set_tmp_dh)]
2991    pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack> {
2992        unsafe { cvt(ffi::SSL_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) }
2993    }
2994
2995    /// Like [`SslContextBuilder::set_tmp_dh_callback`].
2996    ///
2997    /// [`SslContextBuilder::set_tmp_dh_callback`]: struct.SslContextBuilder.html#method.set_tmp_dh_callback
2998    #[corresponds(SSL_set_tmp_dh_callback)]
2999    pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
3000    where
3001        F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
3002    {
3003        unsafe {
3004            // this needs to be in an Arc since the callback can register a new callback!
3005            self.set_ex_data(Ssl::cached_ex_index(), Arc::new(callback));
3006            ffi::SSL_set_tmp_dh_callback(self.as_ptr(), Some(raw_tmp_dh_ssl::<F>));
3007        }
3008    }
3009
3010    /// Like [`SslContextBuilder::set_tmp_ecdh`].
3011    ///
3012    /// [`SslContextBuilder::set_tmp_ecdh`]: struct.SslContextBuilder.html#method.set_tmp_ecdh
3013    #[corresponds(SSL_set_tmp_ecdh)]
3014    pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack> {
3015        unsafe { cvt(ffi::SSL_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) }
3016    }
3017
3018    /// Like [`SslContextBuilder::set_ecdh_auto`].
3019    ///
3020    /// Requires OpenSSL 1.0.2 or LibreSSL.
3021    ///
3022    /// [`SslContextBuilder::set_tmp_ecdh`]: struct.SslContextBuilder.html#method.set_tmp_ecdh
3023    #[corresponds(SSL_set_ecdh_auto)]
3024    #[cfg(any(all(ossl102, not(ossl110)), libressl))]
3025    pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> {
3026        unsafe { cvt(ffi::SSL_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) }
3027    }
3028
3029    /// Like [`SslContextBuilder::set_alpn_protos`].
3030    ///
3031    /// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.
3032    ///
3033    /// [`SslContextBuilder::set_alpn_protos`]: struct.SslContextBuilder.html#method.set_alpn_protos
3034    #[corresponds(SSL_set_alpn_protos)]
3035    #[cfg(any(ossl102, libressl261, boringssl, awslc))]
3036    pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack> {
3037        unsafe {
3038            assert!(protocols.len() <= c_uint::MAX as usize);
3039            let r =
3040                ffi::SSL_set_alpn_protos(self.as_ptr(), protocols.as_ptr(), protocols.len() as _);
3041            // fun fact, SSL_set_alpn_protos has a reversed return code D:
3042            if r == 0 {
3043                Ok(())
3044            } else {
3045                Err(ErrorStack::get())
3046            }
3047        }
3048    }
3049
3050    /// Returns the current cipher if the session is active.
3051    #[corresponds(SSL_get_current_cipher)]
3052    pub fn current_cipher(&self) -> Option<&SslCipherRef> {
3053        unsafe {
3054            let ptr = ffi::SSL_get_current_cipher(self.as_ptr());
3055
3056            SslCipherRef::from_const_ptr_opt(ptr)
3057        }
3058    }
3059
3060    /// Returns a short string describing the state of the session.
3061    #[corresponds(SSL_state_string)]
3062    pub fn state_string(&self) -> &'static str {
3063        let state = unsafe {
3064            let ptr = ffi::SSL_state_string(self.as_ptr());
3065            CStr::from_ptr(ptr as *const _)
3066        };
3067
3068        str::from_utf8(state.to_bytes()).unwrap()
3069    }
3070
3071    /// Returns a longer string describing the state of the session.
3072    #[corresponds(SSL_state_string_long)]
3073    pub fn state_string_long(&self) -> &'static str {
3074        let state = unsafe {
3075            let ptr = ffi::SSL_state_string_long(self.as_ptr());
3076            CStr::from_ptr(ptr as *const _)
3077        };
3078
3079        str::from_utf8(state.to_bytes()).unwrap()
3080    }
3081
3082    /// Sets the host name to be sent to the server for Server Name Indication (SNI).
3083    ///
3084    /// It has no effect for a server-side connection.
3085    #[corresponds(SSL_set_tlsext_host_name)]
3086    pub fn set_hostname(&mut self, hostname: &str) -> Result<(), ErrorStack> {
3087        let cstr = CString::new(hostname).unwrap();
3088        unsafe {
3089            cvt(ffi::SSL_set_tlsext_host_name(self.as_ptr(), cstr.as_ptr() as *mut _) as c_int)
3090                .map(|_| ())
3091        }
3092    }
3093
3094    /// Returns the peer's certificate, if present.
3095    #[corresponds(SSL_get_peer_certificate)]
3096    pub fn peer_certificate(&self) -> Option<X509> {
3097        unsafe {
3098            let ptr = SSL_get1_peer_certificate(self.as_ptr());
3099            X509::from_ptr_opt(ptr)
3100        }
3101    }
3102
3103    /// Returns the certificate chain of the peer, if present.
3104    ///
3105    /// On the client side, the chain includes the leaf certificate, but on the server side it does
3106    /// not. Fun!
3107    #[corresponds(SSL_get_peer_cert_chain)]
3108    pub fn peer_cert_chain(&self) -> Option<&StackRef<X509>> {
3109        unsafe {
3110            let ptr = ffi::SSL_get_peer_cert_chain(self.as_ptr());
3111            StackRef::from_const_ptr_opt(ptr)
3112        }
3113    }
3114
3115    /// Returns the verified certificate chain of the peer, including the leaf certificate.
3116    ///
3117    /// If verification was not successful (i.e. [`verify_result`] does not return
3118    /// [`X509VerifyResult::OK`]), this chain may be incomplete or invalid.
3119    ///
3120    /// Requires OpenSSL 1.1.0 or newer.
3121    ///
3122    /// [`verify_result`]: #method.verify_result
3123    /// [`X509VerifyResult::OK`]: ../x509/struct.X509VerifyResult.html#associatedconstant.OK
3124    #[corresponds(SSL_get0_verified_chain)]
3125    #[cfg(ossl110)]
3126    pub fn verified_chain(&self) -> Option<&StackRef<X509>> {
3127        unsafe {
3128            let ptr = ffi::SSL_get0_verified_chain(self.as_ptr());
3129            StackRef::from_const_ptr_opt(ptr)
3130        }
3131    }
3132
3133    /// Like [`SslContext::certificate`].
3134    #[corresponds(SSL_get_certificate)]
3135    pub fn certificate(&self) -> Option<&X509Ref> {
3136        unsafe {
3137            let ptr = ffi::SSL_get_certificate(self.as_ptr());
3138            X509Ref::from_const_ptr_opt(ptr)
3139        }
3140    }
3141
3142    /// Like [`SslContext::private_key`].
3143    ///
3144    /// [`SslContext::private_key`]: struct.SslContext.html#method.private_key
3145    #[corresponds(SSL_get_privatekey)]
3146    pub fn private_key(&self) -> Option<&PKeyRef<Private>> {
3147        unsafe {
3148            let ptr = ffi::SSL_get_privatekey(self.as_ptr());
3149            PKeyRef::from_const_ptr_opt(ptr)
3150        }
3151    }
3152
3153    /// Returns the protocol version of the session.
3154    #[corresponds(SSL_version)]
3155    pub fn version2(&self) -> Option<SslVersion> {
3156        unsafe {
3157            let r = ffi::SSL_version(self.as_ptr());
3158            if r == 0 {
3159                None
3160            } else {
3161                Some(SslVersion(r))
3162            }
3163        }
3164    }
3165
3166    /// Returns a string describing the protocol version of the session.
3167    #[corresponds(SSL_get_version)]
3168    pub fn version_str(&self) -> &'static str {
3169        let version = unsafe {
3170            let ptr = ffi::SSL_get_version(self.as_ptr());
3171            CStr::from_ptr(ptr as *const _)
3172        };
3173
3174        str::from_utf8(version.to_bytes()).unwrap()
3175    }
3176
3177    /// Returns the protocol selected via Application Layer Protocol Negotiation (ALPN).
3178    ///
3179    /// The protocol's name is returned is an opaque sequence of bytes. It is up to the client
3180    /// to interpret it.
3181    ///
3182    /// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.
3183    #[corresponds(SSL_get0_alpn_selected)]
3184    #[cfg(any(ossl102, libressl261, boringssl, awslc))]
3185    pub fn selected_alpn_protocol(&self) -> Option<&[u8]> {
3186        unsafe {
3187            let mut data: *const c_uchar = ptr::null();
3188            let mut len: c_uint = 0;
3189            // Get the negotiated protocol from the SSL instance.
3190            // `data` will point at a `c_uchar` array; `len` will contain the length of this array.
3191            ffi::SSL_get0_alpn_selected(self.as_ptr(), &mut data, &mut len);
3192
3193            if data.is_null() {
3194                None
3195            } else {
3196                Some(util::from_raw_parts(data, len as usize))
3197            }
3198        }
3199    }
3200
3201    /// Enables the DTLS extension "use_srtp" as defined in RFC5764.
3202    #[corresponds(SSL_set_tlsext_use_srtp)]
3203    pub fn set_tlsext_use_srtp(&mut self, protocols: &str) -> Result<(), ErrorStack> {
3204        unsafe {
3205            let cstr = CString::new(protocols).unwrap();
3206
3207            let r = ffi::SSL_set_tlsext_use_srtp(self.as_ptr(), cstr.as_ptr());
3208            // fun fact, set_tlsext_use_srtp has a reversed return code D:
3209            if r == 0 {
3210                Ok(())
3211            } else {
3212                Err(ErrorStack::get())
3213            }
3214        }
3215    }
3216
3217    /// Gets all SRTP profiles that are enabled for handshake via set_tlsext_use_srtp
3218    ///
3219    /// DTLS extension "use_srtp" as defined in RFC5764 has to be enabled.
3220    #[corresponds(SSL_get_srtp_profiles)]
3221    pub fn srtp_profiles(&self) -> Option<&StackRef<SrtpProtectionProfile>> {
3222        unsafe {
3223            let chain = ffi::SSL_get_srtp_profiles(self.as_ptr());
3224
3225            StackRef::from_const_ptr_opt(chain)
3226        }
3227    }
3228
3229    /// Gets the SRTP profile selected by handshake.
3230    ///
3231    /// DTLS extension "use_srtp" as defined in RFC5764 has to be enabled.
3232    #[corresponds(SSL_get_selected_srtp_profile)]
3233    pub fn selected_srtp_profile(&self) -> Option<&SrtpProtectionProfileRef> {
3234        unsafe {
3235            let profile = ffi::SSL_get_selected_srtp_profile(self.as_ptr());
3236
3237            SrtpProtectionProfileRef::from_const_ptr_opt(profile)
3238        }
3239    }
3240
3241    /// Returns the number of bytes remaining in the currently processed TLS record.
3242    ///
3243    /// If this is greater than 0, the next call to `read` will not call down to the underlying
3244    /// stream.
3245    #[corresponds(SSL_pending)]
3246    pub fn pending(&self) -> usize {
3247        unsafe { ffi::SSL_pending(self.as_ptr()) as usize }
3248    }
3249
3250    /// Returns the servername sent by the client via Server Name Indication (SNI).
3251    ///
3252    /// It is only useful on the server side.
3253    ///
3254    /// # Note
3255    ///
3256    /// While the SNI specification requires that servernames be valid domain names (and therefore
3257    /// ASCII), OpenSSL does not enforce this restriction. If the servername provided by the client
3258    /// is not valid UTF-8, this function will return `None`. The `servername_raw` method returns
3259    /// the raw bytes and does not have this restriction.
3260    ///
3261    /// [`SSL_get_servername`]: https://www.openssl.org/docs/manmaster/man3/SSL_get_servername.html
3262    #[corresponds(SSL_get_servername)]
3263    // FIXME maybe rethink in 0.11?
3264    pub fn servername(&self, type_: NameType) -> Option<&str> {
3265        self.servername_raw(type_)
3266            .and_then(|b| str::from_utf8(b).ok())
3267    }
3268
3269    /// Returns the servername sent by the client via Server Name Indication (SNI).
3270    ///
3271    /// It is only useful on the server side.
3272    ///
3273    /// # Note
3274    ///
3275    /// Unlike `servername`, this method does not require the name be valid UTF-8.
3276    #[corresponds(SSL_get_servername)]
3277    pub fn servername_raw(&self, type_: NameType) -> Option<&[u8]> {
3278        unsafe {
3279            let name = ffi::SSL_get_servername(self.as_ptr(), type_.0);
3280            if name.is_null() {
3281                None
3282            } else {
3283                Some(CStr::from_ptr(name as *const _).to_bytes())
3284            }
3285        }
3286    }
3287
3288    /// Changes the context corresponding to the current connection.
3289    ///
3290    /// It is most commonly used in the Server Name Indication (SNI) callback.
3291    #[corresponds(SSL_set_SSL_CTX)]
3292    pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> {
3293        unsafe { cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) }
3294    }
3295
3296    /// Returns the context corresponding to the current connection.
3297    #[corresponds(SSL_get_SSL_CTX)]
3298    pub fn ssl_context(&self) -> &SslContextRef {
3299        unsafe {
3300            let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr());
3301            SslContextRef::from_ptr(ssl_ctx)
3302        }
3303    }
3304
3305    /// Returns a mutable reference to the X509 verification configuration.
3306    ///
3307    /// Requires AWS-LC or BoringSSL or OpenSSL 1.0.2 or newer.
3308    #[corresponds(SSL_get0_param)]
3309    #[cfg(any(ossl102, boringssl, libressl261, awslc))]
3310    pub fn param_mut(&mut self) -> &mut X509VerifyParamRef {
3311        unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) }
3312    }
3313
3314    /// Returns the certificate verification result.
3315    #[corresponds(SSL_get_verify_result)]
3316    pub fn verify_result(&self) -> X509VerifyResult {
3317        unsafe { X509VerifyResult::from_raw(ffi::SSL_get_verify_result(self.as_ptr()) as c_int) }
3318    }
3319
3320    /// Returns a shared reference to the SSL session.
3321    #[corresponds(SSL_get_session)]
3322    pub fn session(&self) -> Option<&SslSessionRef> {
3323        unsafe {
3324            let p = ffi::SSL_get_session(self.as_ptr());
3325            SslSessionRef::from_const_ptr_opt(p)
3326        }
3327    }
3328
3329    /// Copies the `client_random` value sent by the client in the TLS handshake into a buffer.
3330    ///
3331    /// Returns the number of bytes copied, or if the buffer is empty, the size of the `client_random`
3332    /// value.
3333    ///
3334    /// Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.
3335    #[corresponds(SSL_get_client_random)]
3336    #[cfg(any(ossl110, libressl270))]
3337    pub fn client_random(&self, buf: &mut [u8]) -> usize {
3338        unsafe {
3339            ffi::SSL_get_client_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len())
3340        }
3341    }
3342
3343    /// Copies the `server_random` value sent by the server in the TLS handshake into a buffer.
3344    ///
3345    /// Returns the number of bytes copied, or if the buffer is empty, the size of the `server_random`
3346    /// value.
3347    ///
3348    /// Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.
3349    #[corresponds(SSL_get_server_random)]
3350    #[cfg(any(ossl110, libressl270))]
3351    pub fn server_random(&self, buf: &mut [u8]) -> usize {
3352        unsafe {
3353            ffi::SSL_get_server_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len())
3354        }
3355    }
3356
3357    /// Derives keying material for application use in accordance to RFC 5705.
3358    #[corresponds(SSL_export_keying_material)]
3359    pub fn export_keying_material(
3360        &self,
3361        out: &mut [u8],
3362        label: &str,
3363        context: Option<&[u8]>,
3364    ) -> Result<(), ErrorStack> {
3365        unsafe {
3366            let (context, contextlen, use_context) = match context {
3367                Some(context) => (context.as_ptr() as *const c_uchar, context.len(), 1),
3368                None => (ptr::null(), 0, 0),
3369            };
3370            cvt(ffi::SSL_export_keying_material(
3371                self.as_ptr(),
3372                out.as_mut_ptr() as *mut c_uchar,
3373                out.len(),
3374                label.as_ptr() as *const c_char,
3375                label.len(),
3376                context,
3377                contextlen,
3378                use_context,
3379            ))
3380            .map(|_| ())
3381        }
3382    }
3383
3384    /// Derives keying material for application use in accordance to RFC 5705.
3385    ///
3386    /// This function is only usable with TLSv1.3, wherein there is no distinction between an empty context and no
3387    /// context. Therefore, unlike `export_keying_material`, `context` must always be supplied.
3388    ///
3389    /// Requires OpenSSL 1.1.1 or newer.
3390    #[corresponds(SSL_export_keying_material_early)]
3391    #[cfg(ossl111)]
3392    pub fn export_keying_material_early(
3393        &self,
3394        out: &mut [u8],
3395        label: &str,
3396        context: &[u8],
3397    ) -> Result<(), ErrorStack> {
3398        unsafe {
3399            cvt(ffi::SSL_export_keying_material_early(
3400                self.as_ptr(),
3401                out.as_mut_ptr() as *mut c_uchar,
3402                out.len(),
3403                label.as_ptr() as *const c_char,
3404                label.len(),
3405                context.as_ptr() as *const c_uchar,
3406                context.len(),
3407            ))
3408            .map(|_| ())
3409        }
3410    }
3411
3412    /// Sets the session to be used.
3413    ///
3414    /// This should be called before the handshake to attempt to reuse a previously established
3415    /// session. If the server is not willing to reuse the session, a new one will be transparently
3416    /// negotiated.
3417    ///
3418    /// # Safety
3419    ///
3420    /// The caller of this method is responsible for ensuring that the session is associated
3421    /// with the same `SslContext` as this `Ssl`.
3422    #[corresponds(SSL_set_session)]
3423    pub unsafe fn set_session(&mut self, session: &SslSessionRef) -> Result<(), ErrorStack> {
3424        cvt(ffi::SSL_set_session(self.as_ptr(), session.as_ptr())).map(|_| ())
3425    }
3426
3427    /// Determines if the session provided to `set_session` was successfully reused.
3428    #[corresponds(SSL_session_reused)]
3429    pub fn session_reused(&self) -> bool {
3430        unsafe { ffi::SSL_session_reused(self.as_ptr()) != 0 }
3431    }
3432
3433    /// Causes ssl (which must be the client end of a connection) to request a stapled OCSP response from the server
3434    ///
3435    /// This corresponds to [`SSL_enable_ocsp_stapling`].
3436    ///
3437    /// [`SSL_enable_ocsp_stapling`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_enable_ocsp_stapling
3438    ///
3439    /// Requires BoringSSL.
3440    #[cfg(any(boringssl, awslc))]
3441    pub fn enable_ocsp_stapling(&mut self) {
3442        unsafe { ffi::SSL_enable_ocsp_stapling(self.as_ptr()) }
3443    }
3444
3445    /// Causes ssl (which must be the client end of a connection) to request SCTs from the server
3446    ///
3447    /// This corresponds to [`SSL_enable_signed_cert_timestamps`].
3448    ///
3449    /// [`SSL_enable_signed_cert_timestamps`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_enable_signed_cert_timestamps
3450    ///
3451    /// Requires BoringSSL.
3452    #[cfg(any(boringssl, awslc))]
3453    pub fn enable_signed_cert_timestamps(&mut self) {
3454        unsafe { ffi::SSL_enable_signed_cert_timestamps(self.as_ptr()) }
3455    }
3456
3457    /// Configures whether sockets on ssl should permute extensions.
3458    ///
3459    /// This corresponds to [`SSL_set_permute_extensions`].
3460    ///
3461    /// [`SSL_set_permute_extensions`]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_set_permute_extensions
3462    ///
3463    /// Requires BoringSSL.
3464    #[cfg(any(boringssl, awslc))]
3465    pub fn set_permute_extensions(&mut self, enabled: bool) {
3466        unsafe { ffi::SSL_set_permute_extensions(self.as_ptr(), enabled as c_int) }
3467    }
3468
3469    /// Enable the processing of signed certificate timestamps (SCTs) for the given SSL connection.
3470    #[corresponds(SSL_enable_ct)]
3471    #[cfg(ossl111)]
3472    pub fn enable_ct(&mut self, validation_mode: SslCtValidationMode) -> Result<(), ErrorStack> {
3473        unsafe { cvt(ffi::SSL_enable_ct(self.as_ptr(), validation_mode.0)).map(|_| ()) }
3474    }
3475
3476    /// Check whether CT processing is enabled.
3477    #[corresponds(SSL_ct_is_enabled)]
3478    #[cfg(ossl111)]
3479    pub fn ct_is_enabled(&self) -> bool {
3480        unsafe { ffi::SSL_ct_is_enabled(self.as_ptr()) == 1 }
3481    }
3482
3483    /// Sets the status response a client wishes the server to reply with.
3484    #[corresponds(SSL_set_tlsext_status_type)]
3485    pub fn set_status_type(&mut self, type_: StatusType) -> Result<(), ErrorStack> {
3486        unsafe {
3487            cvt(ffi::SSL_set_tlsext_status_type(self.as_ptr(), type_.as_raw()) as c_int).map(|_| ())
3488        }
3489    }
3490
3491    /// Determines if current session used Extended Master Secret
3492    ///
3493    /// Returns `None` if the handshake is still in-progress.
3494    #[corresponds(SSL_get_extms_support)]
3495    #[cfg(ossl110)]
3496    pub fn extms_support(&self) -> Option<bool> {
3497        unsafe {
3498            match ffi::SSL_get_extms_support(self.as_ptr()) {
3499                -1 => None,
3500                ret => Some(ret != 0),
3501            }
3502        }
3503    }
3504
3505    /// Returns the server's OCSP response, if present.
3506    #[corresponds(SSL_get_tlsext_status_ocsp_resp)]
3507    #[cfg(not(any(boringssl, awslc)))]
3508    pub fn ocsp_status(&self) -> Option<&[u8]> {
3509        unsafe {
3510            let mut p = ptr::null_mut();
3511            let len = ffi::SSL_get_tlsext_status_ocsp_resp(self.as_ptr(), &mut p);
3512
3513            if len < 0 {
3514                None
3515            } else {
3516                Some(util::from_raw_parts(p as *const u8, len as usize))
3517            }
3518        }
3519    }
3520
3521    /// Returns the server's OCSP response, if present.
3522    #[corresponds(SSL_get0_ocsp_response)]
3523    #[cfg(any(boringssl, awslc))]
3524    pub fn ocsp_status(&self) -> Option<&[u8]> {
3525        unsafe {
3526            let mut p = ptr::null();
3527            let mut len: usize = 0;
3528            ffi::SSL_get0_ocsp_response(self.as_ptr(), &mut p, &mut len);
3529
3530            if len == 0 {
3531                None
3532            } else {
3533                Some(util::from_raw_parts(p as *const u8, len))
3534            }
3535        }
3536    }
3537
3538    /// Sets the OCSP response to be returned to the client.
3539    #[corresponds(SSL_set_tlsext_status_oscp_resp)]
3540    #[cfg(not(any(boringssl, awslc)))]
3541    pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack> {
3542        unsafe {
3543            assert!(response.len() <= c_int::MAX as usize);
3544            let p = cvt_p(ffi::OPENSSL_malloc(response.len() as _))?;
3545            ptr::copy_nonoverlapping(response.as_ptr(), p as *mut u8, response.len());
3546            cvt(ffi::SSL_set_tlsext_status_ocsp_resp(
3547                self.as_ptr(),
3548                p as *mut c_uchar,
3549                response.len() as c_long,
3550            ) as c_int)
3551            .map(|_| ())
3552            .map_err(|e| {
3553                ffi::OPENSSL_free(p);
3554                e
3555            })
3556        }
3557    }
3558
3559    /// Sets the OCSP response to be returned to the client.
3560    #[corresponds(SSL_set_ocsp_response)]
3561    #[cfg(any(boringssl, awslc))]
3562    pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack> {
3563        unsafe {
3564            cvt(ffi::SSL_set_ocsp_response(
3565                self.as_ptr(),
3566                response.as_ptr(),
3567                response.len(),
3568            ))
3569            .map(|_| ())
3570        }
3571    }
3572
3573    /// Determines if this `Ssl` is configured for server-side or client-side use.
3574    #[corresponds(SSL_is_server)]
3575    pub fn is_server(&self) -> bool {
3576        unsafe { SSL_is_server(self.as_ptr()) != 0 }
3577    }
3578
3579    /// Sets the extra data at the specified index.
3580    ///
3581    /// This can be used to provide data to callbacks registered with the context. Use the
3582    /// `Ssl::new_ex_index` method to create an `Index`.
3583    // FIXME should return a result
3584    #[corresponds(SSL_set_ex_data)]
3585    pub fn set_ex_data<T>(&mut self, index: Index<Ssl, T>, data: T) {
3586        match self.ex_data_mut(index) {
3587            Some(v) => *v = data,
3588            None => unsafe {
3589                let data = Box::new(data);
3590                ffi::SSL_set_ex_data(
3591                    self.as_ptr(),
3592                    index.as_raw(),
3593                    Box::into_raw(data) as *mut c_void,
3594                );
3595            },
3596        }
3597    }
3598
3599    /// Returns a reference to the extra data at the specified index.
3600    #[corresponds(SSL_get_ex_data)]
3601    pub fn ex_data<T>(&self, index: Index<Ssl, T>) -> Option<&T> {
3602        unsafe {
3603            let data = ffi::SSL_get_ex_data(self.as_ptr(), index.as_raw());
3604            if data.is_null() {
3605                None
3606            } else {
3607                Some(&*(data as *const T))
3608            }
3609        }
3610    }
3611
3612    /// Returns a mutable reference to the extra data at the specified index.
3613    #[corresponds(SSL_get_ex_data)]
3614    pub fn ex_data_mut<T>(&mut self, index: Index<Ssl, T>) -> Option<&mut T> {
3615        unsafe {
3616            let data = ffi::SSL_get_ex_data(self.as_ptr(), index.as_raw());
3617            if data.is_null() {
3618                None
3619            } else {
3620                Some(&mut *(data as *mut T))
3621            }
3622        }
3623    }
3624
3625    /// Sets the maximum amount of early data that will be accepted on this connection.
3626    ///
3627    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
3628    #[corresponds(SSL_set_max_early_data)]
3629    #[cfg(any(ossl111, libressl340))]
3630    pub fn set_max_early_data(&mut self, bytes: u32) -> Result<(), ErrorStack> {
3631        if unsafe { ffi::SSL_set_max_early_data(self.as_ptr(), bytes) } == 1 {
3632            Ok(())
3633        } else {
3634            Err(ErrorStack::get())
3635        }
3636    }
3637
3638    /// Gets the maximum amount of early data that can be sent on this connection.
3639    ///
3640    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
3641    #[corresponds(SSL_get_max_early_data)]
3642    #[cfg(any(ossl111, libressl340))]
3643    pub fn max_early_data(&self) -> u32 {
3644        unsafe { ffi::SSL_get_max_early_data(self.as_ptr()) }
3645    }
3646
3647    /// Copies the contents of the last Finished message sent to the peer into the provided buffer.
3648    ///
3649    /// The total size of the message is returned, so this can be used to determine the size of the
3650    /// buffer required.
3651    #[corresponds(SSL_get_finished)]
3652    pub fn finished(&self, buf: &mut [u8]) -> usize {
3653        unsafe { ffi::SSL_get_finished(self.as_ptr(), buf.as_mut_ptr() as *mut c_void, buf.len()) }
3654    }
3655
3656    /// Copies the contents of the last Finished message received from the peer into the provided
3657    /// buffer.
3658    ///
3659    /// The total size of the message is returned, so this can be used to determine the size of the
3660    /// buffer required.
3661    #[corresponds(SSL_get_peer_finished)]
3662    pub fn peer_finished(&self, buf: &mut [u8]) -> usize {
3663        unsafe {
3664            ffi::SSL_get_peer_finished(self.as_ptr(), buf.as_mut_ptr() as *mut c_void, buf.len())
3665        }
3666    }
3667
3668    /// Determines if the initial handshake has been completed.
3669    #[corresponds(SSL_is_init_finished)]
3670    #[cfg(ossl110)]
3671    pub fn is_init_finished(&self) -> bool {
3672        unsafe { ffi::SSL_is_init_finished(self.as_ptr()) != 0 }
3673    }
3674
3675    /// Determines if the client's hello message is in the SSLv2 format.
3676    ///
3677    /// This can only be used inside of the client hello callback. Otherwise, `false` is returned.
3678    ///
3679    /// Requires OpenSSL 1.1.1 or newer.
3680    #[corresponds(SSL_client_hello_isv2)]
3681    #[cfg(ossl111)]
3682    pub fn client_hello_isv2(&self) -> bool {
3683        unsafe { ffi::SSL_client_hello_isv2(self.as_ptr()) != 0 }
3684    }
3685
3686    /// Returns the legacy version field of the client's hello message.
3687    ///
3688    /// This can only be used inside of the client hello callback. Otherwise, `None` is returned.
3689    ///
3690    /// Requires OpenSSL 1.1.1 or newer.
3691    #[corresponds(SSL_client_hello_get0_legacy_version)]
3692    #[cfg(ossl111)]
3693    pub fn client_hello_legacy_version(&self) -> Option<SslVersion> {
3694        unsafe {
3695            let version = ffi::SSL_client_hello_get0_legacy_version(self.as_ptr());
3696            if version == 0 {
3697                None
3698            } else {
3699                Some(SslVersion(version as c_int))
3700            }
3701        }
3702    }
3703
3704    /// Returns the random field of the client's hello message.
3705    ///
3706    /// This can only be used inside of the client hello callback. Otherwise, `None` is returned.
3707    ///
3708    /// Requires OpenSSL 1.1.1 or newer.
3709    #[corresponds(SSL_client_hello_get0_random)]
3710    #[cfg(ossl111)]
3711    pub fn client_hello_random(&self) -> Option<&[u8]> {
3712        unsafe {
3713            let mut ptr = ptr::null();
3714            let len = ffi::SSL_client_hello_get0_random(self.as_ptr(), &mut ptr);
3715            if len == 0 {
3716                None
3717            } else {
3718                Some(util::from_raw_parts(ptr, len))
3719            }
3720        }
3721    }
3722
3723    /// Returns the session ID field of the client's hello message.
3724    ///
3725    /// This can only be used inside of the client hello callback. Otherwise, `None` is returned.
3726    ///
3727    /// Requires OpenSSL 1.1.1 or newer.
3728    #[corresponds(SSL_client_hello_get0_session_id)]
3729    #[cfg(ossl111)]
3730    pub fn client_hello_session_id(&self) -> Option<&[u8]> {
3731        unsafe {
3732            let mut ptr = ptr::null();
3733            let len = ffi::SSL_client_hello_get0_session_id(self.as_ptr(), &mut ptr);
3734            if len == 0 {
3735                None
3736            } else {
3737                Some(util::from_raw_parts(ptr, len))
3738            }
3739        }
3740    }
3741
3742    /// Returns the ciphers field of the client's hello message.
3743    ///
3744    /// This can only be used inside of the client hello callback. Otherwise, `None` is returned.
3745    ///
3746    /// Requires OpenSSL 1.1.1 or newer.
3747    #[corresponds(SSL_client_hello_get0_ciphers)]
3748    #[cfg(ossl111)]
3749    pub fn client_hello_ciphers(&self) -> Option<&[u8]> {
3750        unsafe {
3751            let mut ptr = ptr::null();
3752            let len = ffi::SSL_client_hello_get0_ciphers(self.as_ptr(), &mut ptr);
3753            if len == 0 {
3754                None
3755            } else {
3756                Some(util::from_raw_parts(ptr, len))
3757            }
3758        }
3759    }
3760
3761    /// Provides access to individual extensions from the ClientHello on a per-extension basis.
3762    ///
3763    /// This can only be used inside of the client hello callback. Otherwise, `None` is returned.
3764    ///
3765    /// Requires OpenSSL 1.1.1 or newer.
3766    #[cfg(ossl111)]
3767    pub fn client_hello_ext(&self, ext_type: TlsExtType) -> Option<&[u8]> {
3768        unsafe {
3769            let mut ptr = ptr::null();
3770            let mut len = 0usize;
3771            let r = ffi::SSL_client_hello_get0_ext(
3772                self.as_ptr(),
3773                ext_type.as_raw() as _,
3774                &mut ptr,
3775                &mut len,
3776            );
3777            if r == 0 {
3778                None
3779            } else {
3780                Some(util::from_raw_parts(ptr, len))
3781            }
3782        }
3783    }
3784
3785    /// Decodes a slice of wire-format cipher suite specification bytes. Unsupported cipher suites
3786    /// are ignored.
3787    ///
3788    /// Requires OpenSSL 1.1.1 or newer.
3789    #[corresponds(SSL_bytes_to_cipher_list)]
3790    #[cfg(ossl111)]
3791    pub fn bytes_to_cipher_list(
3792        &self,
3793        bytes: &[u8],
3794        isv2format: bool,
3795    ) -> Result<CipherLists, ErrorStack> {
3796        unsafe {
3797            let ptr = bytes.as_ptr();
3798            let len = bytes.len();
3799            let mut sk = ptr::null_mut();
3800            let mut scsvs = ptr::null_mut();
3801            let res = ffi::SSL_bytes_to_cipher_list(
3802                self.as_ptr(),
3803                ptr,
3804                len,
3805                isv2format as c_int,
3806                &mut sk,
3807                &mut scsvs,
3808            );
3809            if res == 1 {
3810                Ok(CipherLists {
3811                    suites: Stack::from_ptr(sk),
3812                    signalling_suites: Stack::from_ptr(scsvs),
3813                })
3814            } else {
3815                Err(ErrorStack::get())
3816            }
3817        }
3818    }
3819
3820    /// Returns the compression methods field of the client's hello message.
3821    ///
3822    /// This can only be used inside of the client hello callback. Otherwise, `None` is returned.
3823    ///
3824    /// Requires OpenSSL 1.1.1 or newer.
3825    #[corresponds(SSL_client_hello_get0_compression_methods)]
3826    #[cfg(ossl111)]
3827    pub fn client_hello_compression_methods(&self) -> Option<&[u8]> {
3828        unsafe {
3829            let mut ptr = ptr::null();
3830            let len = ffi::SSL_client_hello_get0_compression_methods(self.as_ptr(), &mut ptr);
3831            if len == 0 {
3832                None
3833            } else {
3834                Some(util::from_raw_parts(ptr, len))
3835            }
3836        }
3837    }
3838
3839    /// Sets the MTU used for DTLS connections.
3840    #[corresponds(SSL_set_mtu)]
3841    pub fn set_mtu(&mut self, mtu: u32) -> Result<(), ErrorStack> {
3842        unsafe { cvt(ffi::SSL_set_mtu(self.as_ptr(), mtu as MtuTy) as c_int).map(|_| ()) }
3843    }
3844
3845    /// Returns the PSK identity hint used during connection setup.
3846    ///
3847    /// May return `None` if no PSK identity hint was used during the connection setup.
3848    #[corresponds(SSL_get_psk_identity_hint)]
3849    #[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
3850    pub fn psk_identity_hint(&self) -> Option<&[u8]> {
3851        unsafe {
3852            let ptr = ffi::SSL_get_psk_identity_hint(self.as_ptr());
3853            if ptr.is_null() {
3854                None
3855            } else {
3856                Some(CStr::from_ptr(ptr).to_bytes())
3857            }
3858        }
3859    }
3860
3861    /// Returns the PSK identity used during connection setup.
3862    #[corresponds(SSL_get_psk_identity)]
3863    #[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
3864    pub fn psk_identity(&self) -> Option<&[u8]> {
3865        unsafe {
3866            let ptr = ffi::SSL_get_psk_identity(self.as_ptr());
3867            if ptr.is_null() {
3868                None
3869            } else {
3870                Some(CStr::from_ptr(ptr).to_bytes())
3871            }
3872        }
3873    }
3874
3875    #[corresponds(SSL_add0_chain_cert)]
3876    #[cfg(any(ossl102, boringssl, awslc))]
3877    pub fn add_chain_cert(&mut self, chain: X509) -> Result<(), ErrorStack> {
3878        unsafe {
3879            cvt(ffi::SSL_add0_chain_cert(self.as_ptr(), chain.as_ptr()) as c_int).map(|_| ())?;
3880            mem::forget(chain);
3881        }
3882        Ok(())
3883    }
3884
3885    /// Sets a new default TLS/SSL method for SSL objects
3886    #[cfg(not(any(boringssl, awslc)))]
3887    pub fn set_method(&mut self, method: SslMethod) -> Result<(), ErrorStack> {
3888        unsafe {
3889            cvt(ffi::SSL_set_ssl_method(self.as_ptr(), method.as_ptr()))?;
3890        };
3891        Ok(())
3892    }
3893
3894    /// Loads the private key from a file.
3895    #[corresponds(SSL_use_Private_Key_file)]
3896    pub fn set_private_key_file<P: AsRef<Path>>(
3897        &mut self,
3898        path: P,
3899        ssl_file_type: SslFiletype,
3900    ) -> Result<(), ErrorStack> {
3901        let p = path.as_ref().as_os_str().to_str().unwrap();
3902        let key_file = CString::new(p).unwrap();
3903        unsafe {
3904            cvt(ffi::SSL_use_PrivateKey_file(
3905                self.as_ptr(),
3906                key_file.as_ptr(),
3907                ssl_file_type.as_raw(),
3908            ))?;
3909        };
3910        Ok(())
3911    }
3912
3913    /// Sets the private key.
3914    #[corresponds(SSL_use_PrivateKey)]
3915    pub fn set_private_key(&mut self, pkey: &PKeyRef<Private>) -> Result<(), ErrorStack> {
3916        unsafe {
3917            cvt(ffi::SSL_use_PrivateKey(self.as_ptr(), pkey.as_ptr()))?;
3918        };
3919        Ok(())
3920    }
3921
3922    #[cfg(tongsuo)]
3923    #[corresponds(SSL_use_enc_Private_Key_file)]
3924    pub fn set_enc_private_key_file<P: AsRef<Path>>(
3925        &mut self,
3926        path: P,
3927        ssl_file_type: SslFiletype,
3928    ) -> Result<(), ErrorStack> {
3929        let p = path.as_ref().as_os_str().to_str().unwrap();
3930        let key_file = CString::new(p).unwrap();
3931        unsafe {
3932            cvt(ffi::SSL_use_enc_PrivateKey_file(
3933                self.as_ptr(),
3934                key_file.as_ptr(),
3935                ssl_file_type.as_raw(),
3936            ))?;
3937        };
3938        Ok(())
3939    }
3940
3941    #[cfg(tongsuo)]
3942    #[corresponds(SSL_use_enc_PrivateKey)]
3943    pub fn set_enc_private_key(&mut self, pkey: &PKeyRef<Private>) -> Result<(), ErrorStack> {
3944        unsafe {
3945            cvt(ffi::SSL_use_enc_PrivateKey(self.as_ptr(), pkey.as_ptr()))?;
3946        };
3947        Ok(())
3948    }
3949
3950    #[cfg(tongsuo)]
3951    #[corresponds(SSL_use_sign_Private_Key_file)]
3952    pub fn set_sign_private_key_file<P: AsRef<Path>>(
3953        &mut self,
3954        path: P,
3955        ssl_file_type: SslFiletype,
3956    ) -> Result<(), ErrorStack> {
3957        let p = path.as_ref().as_os_str().to_str().unwrap();
3958        let key_file = CString::new(p).unwrap();
3959        unsafe {
3960            cvt(ffi::SSL_use_sign_PrivateKey_file(
3961                self.as_ptr(),
3962                key_file.as_ptr(),
3963                ssl_file_type.as_raw(),
3964            ))?;
3965        };
3966        Ok(())
3967    }
3968
3969    #[cfg(tongsuo)]
3970    #[corresponds(SSL_use_sign_PrivateKey)]
3971    pub fn set_sign_private_key(&mut self, pkey: &PKeyRef<Private>) -> Result<(), ErrorStack> {
3972        unsafe {
3973            cvt(ffi::SSL_use_sign_PrivateKey(self.as_ptr(), pkey.as_ptr()))?;
3974        };
3975        Ok(())
3976    }
3977
3978    /// Sets the certificate
3979    #[corresponds(SSL_use_certificate)]
3980    pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
3981        unsafe {
3982            cvt(ffi::SSL_use_certificate(self.as_ptr(), cert.as_ptr()))?;
3983        };
3984        Ok(())
3985    }
3986
3987    #[cfg(tongsuo)]
3988    #[corresponds(SSL_use_enc_certificate)]
3989    pub fn set_enc_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
3990        unsafe {
3991            cvt(ffi::SSL_use_enc_certificate(self.as_ptr(), cert.as_ptr()))?;
3992        };
3993        Ok(())
3994    }
3995
3996    #[cfg(tongsuo)]
3997    #[corresponds(SSL_use_sign_certificate)]
3998    pub fn set_sign_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> {
3999        unsafe {
4000            cvt(ffi::SSL_use_sign_certificate(self.as_ptr(), cert.as_ptr()))?;
4001        };
4002        Ok(())
4003    }
4004
4005    /// Loads a certificate chain from a file.
4006    ///
4007    /// The file should contain a sequence of PEM-formatted certificates, the first being the leaf
4008    /// certificate, and the remainder forming the chain of certificates up to and including the
4009    /// trusted root certificate.
4010    #[corresponds(SSL_use_certificate_chain_file)]
4011    #[cfg(any(ossl110, libressl332))]
4012    pub fn set_certificate_chain_file<P: AsRef<Path>>(
4013        &mut self,
4014        path: P,
4015    ) -> Result<(), ErrorStack> {
4016        let p = path.as_ref().as_os_str().to_str().unwrap();
4017        let cert_file = CString::new(p).unwrap();
4018        unsafe {
4019            cvt(ffi::SSL_use_certificate_chain_file(
4020                self.as_ptr(),
4021                cert_file.as_ptr(),
4022            ))?;
4023        };
4024        Ok(())
4025    }
4026
4027    /// Sets ca certificate that client trusted
4028    #[corresponds(SSL_add_client_CA)]
4029    pub fn add_client_ca(&mut self, cacert: &X509Ref) -> Result<(), ErrorStack> {
4030        unsafe {
4031            cvt(ffi::SSL_add_client_CA(self.as_ptr(), cacert.as_ptr()))?;
4032        };
4033        Ok(())
4034    }
4035
4036    // Sets the list of CAs sent to the client when requesting a client certificate for the chosen ssl
4037    #[corresponds(SSL_set_client_CA_list)]
4038    pub fn set_client_ca_list(&mut self, list: Stack<X509Name>) {
4039        unsafe { ffi::SSL_set_client_CA_list(self.as_ptr(), list.as_ptr()) }
4040        mem::forget(list);
4041    }
4042
4043    /// Sets the minimum supported protocol version.
4044    ///
4045    /// A value of `None` will enable protocol versions down to the lowest version supported by
4046    /// OpenSSL.
4047    ///
4048    /// Requires AWS-LC or BoringSSL or OpenSSL 1.1.0 or LibreSSL 2.6.1 or newer.
4049    #[corresponds(SSL_set_min_proto_version)]
4050    #[cfg(any(ossl110, libressl261, boringssl, awslc))]
4051    pub fn set_min_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
4052        unsafe {
4053            cvt(ffi::SSL_set_min_proto_version(
4054                self.as_ptr(),
4055                version.map_or(0, |v| v.0 as _),
4056            ))
4057            .map(|_| ())
4058        }
4059    }
4060
4061    /// Sets the maximum supported protocol version.
4062    ///
4063    /// A value of `None` will enable protocol versions up to the highest version supported by
4064    /// OpenSSL.
4065    ///
4066    /// Requires AWS-LC or BoringSSL or OpenSSL 1.1.0 or or LibreSSL 2.6.1 or newer.
4067    #[corresponds(SSL_set_max_proto_version)]
4068    #[cfg(any(ossl110, libressl261, boringssl, awslc))]
4069    pub fn set_max_proto_version(&mut self, version: Option<SslVersion>) -> Result<(), ErrorStack> {
4070        unsafe {
4071            cvt(ffi::SSL_set_max_proto_version(
4072                self.as_ptr(),
4073                version.map_or(0, |v| v.0 as _),
4074            ))
4075            .map(|_| ())
4076        }
4077    }
4078
4079    /// Sets the list of supported ciphers for the TLSv1.3 protocol.
4080    ///
4081    /// The `set_cipher_list` method controls the cipher suites for protocols before TLSv1.3.
4082    ///
4083    /// The format consists of TLSv1.3 cipher suite names separated by `:` characters in order of
4084    /// preference.
4085    ///
4086    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
4087    #[corresponds(SSL_set_ciphersuites)]
4088    #[cfg(any(ossl111, libressl340))]
4089    pub fn set_ciphersuites(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
4090        let cipher_list = CString::new(cipher_list).unwrap();
4091        unsafe {
4092            cvt(ffi::SSL_set_ciphersuites(
4093                self.as_ptr(),
4094                cipher_list.as_ptr() as *const _,
4095            ))
4096            .map(|_| ())
4097        }
4098    }
4099
4100    /// Sets the list of supported ciphers for protocols before TLSv1.3.
4101    ///
4102    /// The `set_ciphersuites` method controls the cipher suites for TLSv1.3.
4103    ///
4104    /// See [`ciphers`] for details on the format.
4105    ///
4106    /// [`ciphers`]: https://www.openssl.org/docs/manmaster/apps/ciphers.html
4107    #[corresponds(SSL_set_cipher_list)]
4108    pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> {
4109        let cipher_list = CString::new(cipher_list).unwrap();
4110        unsafe {
4111            cvt(ffi::SSL_set_cipher_list(
4112                self.as_ptr(),
4113                cipher_list.as_ptr() as *const _,
4114            ))
4115            .map(|_| ())
4116        }
4117    }
4118
4119    /// Set the certificate store used for certificate verification
4120    #[corresponds(SSL_set_cert_store)]
4121    #[cfg(any(ossl102, boringssl, awslc))]
4122    pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> {
4123        unsafe {
4124            cvt(ffi::SSL_set0_verify_cert_store(self.as_ptr(), cert_store.as_ptr()) as c_int)?;
4125            mem::forget(cert_store);
4126            Ok(())
4127        }
4128    }
4129
4130    /// Sets the number of TLS 1.3 session tickets that will be sent to a client after a full
4131    /// handshake.
4132    ///
4133    /// Requires OpenSSL 1.1.1 or newer.
4134    #[corresponds(SSL_set_num_tickets)]
4135    #[cfg(ossl111)]
4136    pub fn set_num_tickets(&mut self, num_tickets: usize) -> Result<(), ErrorStack> {
4137        unsafe { cvt(ffi::SSL_set_num_tickets(self.as_ptr(), num_tickets)).map(|_| ()) }
4138    }
4139
4140    /// Gets the number of TLS 1.3 session tickets that will be sent to a client after a full
4141    /// handshake.
4142    ///
4143    /// Requires OpenSSL 1.1.1 or newer.
4144    #[corresponds(SSL_get_num_tickets)]
4145    #[cfg(ossl111)]
4146    pub fn num_tickets(&self) -> usize {
4147        unsafe { ffi::SSL_get_num_tickets(self.as_ptr()) }
4148    }
4149
4150    /// Set the context's security level to a value between 0 and 5, inclusive.
4151    /// A security value of 0 allows allows all parameters and algorithms.
4152    ///
4153    /// Requires OpenSSL 1.1.0 or newer.
4154    #[corresponds(SSL_set_security_level)]
4155    #[cfg(any(ossl110, libressl360))]
4156    pub fn set_security_level(&mut self, level: u32) {
4157        unsafe { ffi::SSL_set_security_level(self.as_ptr(), level as c_int) }
4158    }
4159
4160    /// Get the connection's security level, which controls the allowed parameters
4161    /// and algorithms.
4162    ///
4163    /// Requires OpenSSL 1.1.0 or newer.
4164    #[corresponds(SSL_get_security_level)]
4165    #[cfg(any(ossl110, libressl360))]
4166    pub fn security_level(&self) -> u32 {
4167        unsafe { ffi::SSL_get_security_level(self.as_ptr()) as u32 }
4168    }
4169
4170    /// Get the temporary key provided by the peer that is used during key
4171    /// exchange.
4172    // We use an owned value because EVP_KEY free need to be called when it is
4173    // dropped
4174    #[corresponds(SSL_get_peer_tmp_key)]
4175    #[cfg(ossl300)]
4176    pub fn peer_tmp_key(&self) -> Result<PKey<Public>, ErrorStack> {
4177        unsafe {
4178            let mut key = ptr::null_mut();
4179            match cvt_long(ffi::SSL_get_peer_tmp_key(self.as_ptr(), &mut key)) {
4180                Ok(_) => Ok(PKey::<Public>::from_ptr(key)),
4181                Err(e) => Err(e),
4182            }
4183        }
4184    }
4185
4186    /// Returns the temporary key from the local end of the connection that is
4187    /// used during key exchange.
4188    // We use an owned value because EVP_KEY free need to be called when it is
4189    // dropped
4190    #[corresponds(SSL_get_tmp_key)]
4191    #[cfg(ossl300)]
4192    pub fn tmp_key(&self) -> Result<PKey<Private>, ErrorStack> {
4193        unsafe {
4194            let mut key = ptr::null_mut();
4195            match cvt_long(ffi::SSL_get_tmp_key(self.as_ptr(), &mut key)) {
4196                Ok(_) => Ok(PKey::<Private>::from_ptr(key)),
4197                Err(e) => Err(e),
4198            }
4199        }
4200    }
4201}
4202
4203/// An SSL stream midway through the handshake process.
4204#[derive(Debug)]
4205pub struct MidHandshakeSslStream<S> {
4206    stream: SslStream<S>,
4207    error: Error,
4208}
4209
4210impl<S> MidHandshakeSslStream<S> {
4211    /// Returns a shared reference to the inner stream.
4212    pub fn get_ref(&self) -> &S {
4213        self.stream.get_ref()
4214    }
4215
4216    /// Returns a mutable reference to the inner stream.
4217    pub fn get_mut(&mut self) -> &mut S {
4218        self.stream.get_mut()
4219    }
4220
4221    /// Returns a shared reference to the `Ssl` of the stream.
4222    pub fn ssl(&self) -> &SslRef {
4223        self.stream.ssl()
4224    }
4225
4226    /// Returns a mutable reference to the `Ssl` of the stream.
4227    pub fn ssl_mut(&mut self) -> &mut SslRef {
4228        self.stream.ssl_mut()
4229    }
4230
4231    /// Returns the underlying error which interrupted this handshake.
4232    pub fn error(&self) -> &Error {
4233        &self.error
4234    }
4235
4236    /// Consumes `self`, returning its error.
4237    pub fn into_error(self) -> Error {
4238        self.error
4239    }
4240}
4241
4242impl<S> MidHandshakeSslStream<S>
4243where
4244    S: Read + Write,
4245{
4246    /// Restarts the handshake process.
4247    ///
4248    #[corresponds(SSL_do_handshake)]
4249    pub fn handshake(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
4250        match self.stream.do_handshake() {
4251            Ok(()) => Ok(self.stream),
4252            Err(error) => {
4253                self.error = error;
4254                match self.error.code() {
4255                    ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
4256                        Err(HandshakeError::WouldBlock(self))
4257                    }
4258                    _ => Err(HandshakeError::Failure(self)),
4259                }
4260            }
4261        }
4262    }
4263}
4264
4265/// A TLS session over a stream.
4266pub struct SslStream<S> {
4267    ssl: ManuallyDrop<Ssl>,
4268    method: ManuallyDrop<BioMethod>,
4269    _p: PhantomData<S>,
4270}
4271
4272impl<S> Drop for SslStream<S> {
4273    fn drop(&mut self) {
4274        // ssl holds a reference to method internally so it has to drop first
4275        unsafe {
4276            ManuallyDrop::drop(&mut self.ssl);
4277            ManuallyDrop::drop(&mut self.method);
4278        }
4279    }
4280}
4281
4282impl<S> fmt::Debug for SslStream<S>
4283where
4284    S: fmt::Debug,
4285{
4286    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4287        fmt.debug_struct("SslStream")
4288            .field("stream", &self.get_ref())
4289            .field("ssl", &self.ssl())
4290            .finish()
4291    }
4292}
4293
4294impl<S: Read + Write> SslStream<S> {
4295    /// Creates a new `SslStream`.
4296    ///
4297    /// This function performs no IO; the stream will not have performed any part of the handshake
4298    /// with the peer. If the `Ssl` was configured with [`SslRef::set_connect_state`] or
4299    /// [`SslRef::set_accept_state`], the handshake can be performed automatically during the first
4300    /// call to read or write. Otherwise the `connect` and `accept` methods can be used to
4301    /// explicitly perform the handshake.
4302    #[corresponds(SSL_set_bio)]
4303    pub fn new(ssl: Ssl, stream: S) -> Result<Self, ErrorStack> {
4304        let (bio, method) = bio::new(stream)?;
4305        unsafe {
4306            ffi::SSL_set_bio(ssl.as_ptr(), bio, bio);
4307        }
4308
4309        Ok(SslStream {
4310            ssl: ManuallyDrop::new(ssl),
4311            method: ManuallyDrop::new(method),
4312            _p: PhantomData,
4313        })
4314    }
4315
4316    /// Read application data transmitted by a client before handshake completion.
4317    ///
4318    /// Useful for reducing latency, but vulnerable to replay attacks. Call
4319    /// [`SslRef::set_accept_state`] first.
4320    ///
4321    /// Returns `Ok(0)` if all early data has been read.
4322    ///
4323    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
4324    #[corresponds(SSL_read_early_data)]
4325    #[cfg(any(ossl111, libressl340))]
4326    pub fn read_early_data(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
4327        let mut read = 0;
4328        let ret = unsafe {
4329            ffi::SSL_read_early_data(
4330                self.ssl.as_ptr(),
4331                buf.as_ptr() as *mut c_void,
4332                buf.len(),
4333                &mut read,
4334            )
4335        };
4336        match ret {
4337            ffi::SSL_READ_EARLY_DATA_ERROR => Err(self.make_error(ret)),
4338            ffi::SSL_READ_EARLY_DATA_SUCCESS => Ok(read),
4339            ffi::SSL_READ_EARLY_DATA_FINISH => Ok(0),
4340            _ => unreachable!(),
4341        }
4342    }
4343
4344    /// Send data to the server without blocking on handshake completion.
4345    ///
4346    /// Useful for reducing latency, but vulnerable to replay attacks. Call
4347    /// [`SslRef::set_connect_state`] first.
4348    ///
4349    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
4350    #[corresponds(SSL_write_early_data)]
4351    #[cfg(any(ossl111, libressl340))]
4352    pub fn write_early_data(&mut self, buf: &[u8]) -> Result<usize, Error> {
4353        let mut written = 0;
4354        let ret = unsafe {
4355            ffi::SSL_write_early_data(
4356                self.ssl.as_ptr(),
4357                buf.as_ptr() as *const c_void,
4358                buf.len(),
4359                &mut written,
4360            )
4361        };
4362        if ret > 0 {
4363            Ok(written)
4364        } else {
4365            Err(self.make_error(ret))
4366        }
4367    }
4368
4369    /// Initiates a client-side TLS handshake.
4370    ///
4371    /// # Warning
4372    ///
4373    /// OpenSSL's default configuration is insecure. It is highly recommended to use
4374    /// `SslConnector` rather than `Ssl` directly, as it manages that configuration.
4375    #[corresponds(SSL_connect)]
4376    pub fn connect(&mut self) -> Result<(), Error> {
4377        let ret = unsafe { ffi::SSL_connect(self.ssl.as_ptr()) };
4378        if ret > 0 {
4379            Ok(())
4380        } else {
4381            Err(self.make_error(ret))
4382        }
4383    }
4384
4385    /// Initiates a server-side TLS handshake.
4386    ///
4387    /// # Warning
4388    ///
4389    /// OpenSSL's default configuration is insecure. It is highly recommended to use
4390    /// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration.
4391    #[corresponds(SSL_accept)]
4392    pub fn accept(&mut self) -> Result<(), Error> {
4393        let ret = unsafe { ffi::SSL_accept(self.ssl.as_ptr()) };
4394        if ret > 0 {
4395            Ok(())
4396        } else {
4397            Err(self.make_error(ret))
4398        }
4399    }
4400
4401    /// Initiates the handshake.
4402    ///
4403    /// This will fail if `set_accept_state` or `set_connect_state` was not called first.
4404    #[corresponds(SSL_do_handshake)]
4405    pub fn do_handshake(&mut self) -> Result<(), Error> {
4406        let ret = unsafe { ffi::SSL_do_handshake(self.ssl.as_ptr()) };
4407        if ret > 0 {
4408            Ok(())
4409        } else {
4410            Err(self.make_error(ret))
4411        }
4412    }
4413
4414    /// Perform a stateless server-side handshake.
4415    ///
4416    /// Requires that cookie generation and verification callbacks were
4417    /// set on the SSL context.
4418    ///
4419    /// Returns `Ok(true)` if a complete ClientHello containing a valid cookie
4420    /// was read, in which case the handshake should be continued via
4421    /// `accept`. If a HelloRetryRequest containing a fresh cookie was
4422    /// transmitted, `Ok(false)` is returned instead. If the handshake cannot
4423    /// proceed at all, `Err` is returned.
4424    #[corresponds(SSL_stateless)]
4425    #[cfg(ossl111)]
4426    pub fn stateless(&mut self) -> Result<bool, ErrorStack> {
4427        match unsafe { ffi::SSL_stateless(self.ssl.as_ptr()) } {
4428            1 => Ok(true),
4429            0 => Ok(false),
4430            -1 => Err(ErrorStack::get()),
4431            _ => unreachable!(),
4432        }
4433    }
4434
4435    /// Like `read`, but takes a possibly-uninitialized slice.
4436    ///
4437    /// # Safety
4438    ///
4439    /// No portion of `buf` will be de-initialized by this method. If the method returns `Ok(n)`,
4440    /// then the first `n` bytes of `buf` are guaranteed to be initialized.
4441    #[corresponds(SSL_read_ex)]
4442    pub fn read_uninit(&mut self, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
4443        loop {
4444            match self.ssl_read_uninit(buf) {
4445                Ok(n) => return Ok(n),
4446                Err(ref e) if e.code() == ErrorCode::ZERO_RETURN => return Ok(0),
4447                Err(ref e) if e.code() == ErrorCode::SYSCALL && e.io_error().is_none() => {
4448                    return Ok(0);
4449                }
4450                Err(ref e) if e.code() == ErrorCode::WANT_READ && e.io_error().is_none() => {}
4451                Err(e) => {
4452                    return Err(e
4453                        .into_io_error()
4454                        .unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e)));
4455                }
4456            }
4457        }
4458    }
4459
4460    /// Like `read`, but returns an `ssl::Error` rather than an `io::Error`.
4461    ///
4462    /// It is particularly useful with a non-blocking socket, where the error value will identify if
4463    /// OpenSSL is waiting on read or write readiness.
4464    #[corresponds(SSL_read_ex)]
4465    pub fn ssl_read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
4466        // SAFETY: `ssl_read_uninit` does not de-initialize the buffer.
4467        unsafe {
4468            self.ssl_read_uninit(util::from_raw_parts_mut(
4469                buf.as_mut_ptr().cast::<MaybeUninit<u8>>(),
4470                buf.len(),
4471            ))
4472        }
4473    }
4474
4475    /// Like `read_ssl`, but takes a possibly-uninitialized slice.
4476    ///
4477    /// # Safety
4478    ///
4479    /// No portion of `buf` will be de-initialized by this method. If the method returns `Ok(n)`,
4480    /// then the first `n` bytes of `buf` are guaranteed to be initialized.
4481    #[corresponds(SSL_read_ex)]
4482    pub fn ssl_read_uninit(&mut self, buf: &mut [MaybeUninit<u8>]) -> Result<usize, Error> {
4483        cfg_if! {
4484            if #[cfg(any(ossl111, libressl350))] {
4485                let mut readbytes = 0;
4486                let ret = unsafe {
4487                    ffi::SSL_read_ex(
4488                        self.ssl().as_ptr(),
4489                        buf.as_mut_ptr().cast(),
4490                        buf.len(),
4491                        &mut readbytes,
4492                    )
4493                };
4494
4495                if ret > 0 {
4496                    Ok(readbytes)
4497                } else {
4498                    Err(self.make_error(ret))
4499                }
4500            } else {
4501                if buf.is_empty() {
4502                    return Ok(0);
4503                }
4504
4505                let len = usize::min(c_int::MAX as usize, buf.len()) as c_int;
4506                let ret = unsafe {
4507                    ffi::SSL_read(self.ssl().as_ptr(), buf.as_mut_ptr().cast(), len)
4508                };
4509                if ret > 0 {
4510                    Ok(ret as usize)
4511                } else {
4512                    Err(self.make_error(ret))
4513                }
4514            }
4515        }
4516    }
4517
4518    /// Like `write`, but returns an `ssl::Error` rather than an `io::Error`.
4519    ///
4520    /// It is particularly useful with a non-blocking socket, where the error value will identify if
4521    /// OpenSSL is waiting on read or write readiness.
4522    #[corresponds(SSL_write_ex)]
4523    pub fn ssl_write(&mut self, buf: &[u8]) -> Result<usize, Error> {
4524        cfg_if! {
4525            if #[cfg(any(ossl111, libressl350))] {
4526                let mut written = 0;
4527                let ret = unsafe {
4528                    ffi::SSL_write_ex(
4529                        self.ssl().as_ptr(),
4530                        buf.as_ptr().cast(),
4531                        buf.len(),
4532                        &mut written,
4533                    )
4534                };
4535
4536                if ret > 0 {
4537                    Ok(written)
4538                } else {
4539                    Err(self.make_error(ret))
4540                }
4541            } else {
4542                if buf.is_empty() {
4543                    return Ok(0);
4544                }
4545
4546                let len = usize::min(c_int::MAX as usize, buf.len()) as c_int;
4547                let ret = unsafe {
4548                    ffi::SSL_write(self.ssl().as_ptr(), buf.as_ptr().cast(), len)
4549                };
4550                if ret > 0 {
4551                    Ok(ret as usize)
4552                } else {
4553                    Err(self.make_error(ret))
4554                }
4555            }
4556        }
4557    }
4558
4559    /// Reads data from the stream, without removing it from the queue.
4560    #[corresponds(SSL_peek_ex)]
4561    pub fn ssl_peek(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
4562        cfg_if! {
4563            if #[cfg(any(ossl111, libressl350))] {
4564                let mut readbytes = 0;
4565                let ret = unsafe {
4566                    ffi::SSL_peek_ex(
4567                        self.ssl().as_ptr(),
4568                        buf.as_mut_ptr().cast(),
4569                        buf.len(),
4570                        &mut readbytes,
4571                    )
4572                };
4573
4574                if ret > 0 {
4575                    Ok(readbytes)
4576                } else {
4577                    Err(self.make_error(ret))
4578                }
4579            } else {
4580                if buf.is_empty() {
4581                    return Ok(0);
4582                }
4583
4584                let len = usize::min(c_int::MAX as usize, buf.len()) as c_int;
4585                let ret = unsafe {
4586                    ffi::SSL_peek(self.ssl().as_ptr(), buf.as_mut_ptr().cast(), len)
4587                };
4588                if ret > 0 {
4589                    Ok(ret as usize)
4590                } else {
4591                    Err(self.make_error(ret))
4592                }
4593            }
4594        }
4595    }
4596
4597    /// Shuts down the session.
4598    ///
4599    /// The shutdown process consists of two steps. The first step sends a close notify message to
4600    /// the peer, after which `ShutdownResult::Sent` is returned. The second step awaits the receipt
4601    /// of a close notify message from the peer, after which `ShutdownResult::Received` is returned.
4602    ///
4603    /// While the connection may be closed after the first step, it is recommended to fully shut the
4604    /// session down. In particular, it must be fully shut down if the connection is to be used for
4605    /// further communication in the future.
4606    #[corresponds(SSL_shutdown)]
4607    pub fn shutdown(&mut self) -> Result<ShutdownResult, Error> {
4608        match unsafe { ffi::SSL_shutdown(self.ssl.as_ptr()) } {
4609            0 => Ok(ShutdownResult::Sent),
4610            1 => Ok(ShutdownResult::Received),
4611            n => Err(self.make_error(n)),
4612        }
4613    }
4614
4615    /// Returns the session's shutdown state.
4616    #[corresponds(SSL_get_shutdown)]
4617    pub fn get_shutdown(&mut self) -> ShutdownState {
4618        unsafe {
4619            let bits = ffi::SSL_get_shutdown(self.ssl.as_ptr());
4620            ShutdownState::from_bits_retain(bits)
4621        }
4622    }
4623
4624    /// Sets the session's shutdown state.
4625    ///
4626    /// This can be used to tell OpenSSL that the session should be cached even if a full two-way
4627    /// shutdown was not completed.
4628    #[corresponds(SSL_set_shutdown)]
4629    pub fn set_shutdown(&mut self, state: ShutdownState) {
4630        unsafe { ffi::SSL_set_shutdown(self.ssl.as_ptr(), state.bits()) }
4631    }
4632}
4633
4634impl<S> SslStream<S> {
4635    fn make_error(&mut self, ret: c_int) -> Error {
4636        self.check_panic();
4637
4638        let code = self.ssl.get_error(ret);
4639
4640        let cause = match code {
4641            ErrorCode::SSL => Some(InnerError::Ssl(ErrorStack::get())),
4642            ErrorCode::SYSCALL => {
4643                let errs = ErrorStack::get();
4644                if errs.errors().is_empty() {
4645                    self.get_bio_error().map(InnerError::Io)
4646                } else {
4647                    Some(InnerError::Ssl(errs))
4648                }
4649            }
4650            ErrorCode::ZERO_RETURN => None,
4651            ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
4652                self.get_bio_error().map(InnerError::Io)
4653            }
4654            _ => None,
4655        };
4656
4657        Error { code, cause }
4658    }
4659
4660    fn check_panic(&mut self) {
4661        if let Some(err) = unsafe { bio::take_panic::<S>(self.ssl.get_raw_rbio()) } {
4662            resume_unwind(err)
4663        }
4664    }
4665
4666    fn get_bio_error(&mut self) -> Option<io::Error> {
4667        unsafe { bio::take_error::<S>(self.ssl.get_raw_rbio()) }
4668    }
4669
4670    /// Returns a shared reference to the underlying stream.
4671    pub fn get_ref(&self) -> &S {
4672        unsafe {
4673            let bio = self.ssl.get_raw_rbio();
4674            bio::get_ref(bio)
4675        }
4676    }
4677
4678    /// Returns a mutable reference to the underlying stream.
4679    ///
4680    /// # Warning
4681    ///
4682    /// It is inadvisable to read from or write to the underlying stream as it
4683    /// will most likely corrupt the SSL session.
4684    pub fn get_mut(&mut self) -> &mut S {
4685        unsafe {
4686            let bio = self.ssl.get_raw_rbio();
4687            bio::get_mut(bio)
4688        }
4689    }
4690
4691    /// Returns a shared reference to the `Ssl` object associated with this stream.
4692    pub fn ssl(&self) -> &SslRef {
4693        &self.ssl
4694    }
4695
4696    /// Returns a mutable reference to the `Ssl` object associated with this stream.
4697    pub fn ssl_mut(&mut self) -> &mut SslRef {
4698        &mut self.ssl
4699    }
4700}
4701
4702impl<S: Read + Write> Read for SslStream<S> {
4703    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4704        // SAFETY: `read_uninit` does not de-initialize the buffer
4705        unsafe {
4706            self.read_uninit(util::from_raw_parts_mut(
4707                buf.as_mut_ptr().cast::<MaybeUninit<u8>>(),
4708                buf.len(),
4709            ))
4710        }
4711    }
4712}
4713
4714impl<S: Read + Write> Write for SslStream<S> {
4715    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
4716        loop {
4717            match self.ssl_write(buf) {
4718                Ok(n) => return Ok(n),
4719                Err(ref e) if e.code() == ErrorCode::WANT_READ && e.io_error().is_none() => {}
4720                Err(e) => {
4721                    return Err(e
4722                        .into_io_error()
4723                        .unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e)));
4724                }
4725            }
4726        }
4727    }
4728
4729    fn flush(&mut self) -> io::Result<()> {
4730        self.get_mut().flush()
4731    }
4732}
4733
4734/// A partially constructed `SslStream`, useful for unusual handshakes.
4735#[deprecated(
4736    since = "0.10.32",
4737    note = "use the methods directly on Ssl/SslStream instead"
4738)]
4739pub struct SslStreamBuilder<S> {
4740    inner: SslStream<S>,
4741}
4742
4743#[allow(deprecated)]
4744impl<S> SslStreamBuilder<S>
4745where
4746    S: Read + Write,
4747{
4748    /// Begin creating an `SslStream` atop `stream`
4749    pub fn new(ssl: Ssl, stream: S) -> Self {
4750        Self {
4751            inner: SslStream::new(ssl, stream).unwrap(),
4752        }
4753    }
4754
4755    /// Perform a stateless server-side handshake
4756    ///
4757    /// Requires that cookie generation and verification callbacks were
4758    /// set on the SSL context.
4759    ///
4760    /// Returns `Ok(true)` if a complete ClientHello containing a valid cookie
4761    /// was read, in which case the handshake should be continued via
4762    /// `accept`. If a HelloRetryRequest containing a fresh cookie was
4763    /// transmitted, `Ok(false)` is returned instead. If the handshake cannot
4764    /// proceed at all, `Err` is returned.
4765    #[corresponds(SSL_stateless)]
4766    #[cfg(ossl111)]
4767    pub fn stateless(&mut self) -> Result<bool, ErrorStack> {
4768        match unsafe { ffi::SSL_stateless(self.inner.ssl.as_ptr()) } {
4769            1 => Ok(true),
4770            0 => Ok(false),
4771            -1 => Err(ErrorStack::get()),
4772            _ => unreachable!(),
4773        }
4774    }
4775
4776    /// Configure as an outgoing stream from a client.
4777    #[corresponds(SSL_set_connect_state)]
4778    pub fn set_connect_state(&mut self) {
4779        unsafe { ffi::SSL_set_connect_state(self.inner.ssl.as_ptr()) }
4780    }
4781
4782    /// Configure as an incoming stream to a server.
4783    #[corresponds(SSL_set_accept_state)]
4784    pub fn set_accept_state(&mut self) {
4785        unsafe { ffi::SSL_set_accept_state(self.inner.ssl.as_ptr()) }
4786    }
4787
4788    /// See `Ssl::connect`
4789    pub fn connect(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
4790        match self.inner.connect() {
4791            Ok(()) => Ok(self.inner),
4792            Err(error) => match error.code() {
4793                ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
4794                    Err(HandshakeError::WouldBlock(MidHandshakeSslStream {
4795                        stream: self.inner,
4796                        error,
4797                    }))
4798                }
4799                _ => Err(HandshakeError::Failure(MidHandshakeSslStream {
4800                    stream: self.inner,
4801                    error,
4802                })),
4803            },
4804        }
4805    }
4806
4807    /// See `Ssl::accept`
4808    pub fn accept(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
4809        match self.inner.accept() {
4810            Ok(()) => Ok(self.inner),
4811            Err(error) => match error.code() {
4812                ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
4813                    Err(HandshakeError::WouldBlock(MidHandshakeSslStream {
4814                        stream: self.inner,
4815                        error,
4816                    }))
4817                }
4818                _ => Err(HandshakeError::Failure(MidHandshakeSslStream {
4819                    stream: self.inner,
4820                    error,
4821                })),
4822            },
4823        }
4824    }
4825
4826    /// Initiates the handshake.
4827    ///
4828    /// This will fail if `set_accept_state` or `set_connect_state` was not called first.
4829    #[corresponds(SSL_do_handshake)]
4830    pub fn handshake(mut self) -> Result<SslStream<S>, HandshakeError<S>> {
4831        match self.inner.do_handshake() {
4832            Ok(()) => Ok(self.inner),
4833            Err(error) => match error.code() {
4834                ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => {
4835                    Err(HandshakeError::WouldBlock(MidHandshakeSslStream {
4836                        stream: self.inner,
4837                        error,
4838                    }))
4839                }
4840                _ => Err(HandshakeError::Failure(MidHandshakeSslStream {
4841                    stream: self.inner,
4842                    error,
4843                })),
4844            },
4845        }
4846    }
4847
4848    /// Read application data transmitted by a client before handshake
4849    /// completion.
4850    ///
4851    /// Useful for reducing latency, but vulnerable to replay attacks. Call
4852    /// `set_accept_state` first.
4853    ///
4854    /// Returns `Ok(0)` if all early data has been read.
4855    ///
4856    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
4857    #[corresponds(SSL_read_early_data)]
4858    #[cfg(any(ossl111, libressl340))]
4859    pub fn read_early_data(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
4860        self.inner.read_early_data(buf)
4861    }
4862
4863    /// Send data to the server without blocking on handshake completion.
4864    ///
4865    /// Useful for reducing latency, but vulnerable to replay attacks. Call
4866    /// `set_connect_state` first.
4867    ///
4868    /// Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.
4869    #[corresponds(SSL_write_early_data)]
4870    #[cfg(any(ossl111, libressl340))]
4871    pub fn write_early_data(&mut self, buf: &[u8]) -> Result<usize, Error> {
4872        self.inner.write_early_data(buf)
4873    }
4874}
4875
4876#[allow(deprecated)]
4877impl<S> SslStreamBuilder<S> {
4878    /// Returns a shared reference to the underlying stream.
4879    pub fn get_ref(&self) -> &S {
4880        unsafe {
4881            let bio = self.inner.ssl.get_raw_rbio();
4882            bio::get_ref(bio)
4883        }
4884    }
4885
4886    /// Returns a mutable reference to the underlying stream.
4887    ///
4888    /// # Warning
4889    ///
4890    /// It is inadvisable to read from or write to the underlying stream as it
4891    /// will most likely corrupt the SSL session.
4892    pub fn get_mut(&mut self) -> &mut S {
4893        unsafe {
4894            let bio = self.inner.ssl.get_raw_rbio();
4895            bio::get_mut(bio)
4896        }
4897    }
4898
4899    /// Returns a shared reference to the `Ssl` object associated with this builder.
4900    pub fn ssl(&self) -> &SslRef {
4901        &self.inner.ssl
4902    }
4903
4904    /// Returns a mutable reference to the `Ssl` object associated with this builder.
4905    pub fn ssl_mut(&mut self) -> &mut SslRef {
4906        &mut self.inner.ssl
4907    }
4908}
4909
4910/// The result of a shutdown request.
4911#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4912pub enum ShutdownResult {
4913    /// A close notify message has been sent to the peer.
4914    Sent,
4915
4916    /// A close notify response message has been received from the peer.
4917    Received,
4918}
4919
4920bitflags! {
4921    /// The shutdown state of a session.
4922    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
4923    #[repr(transparent)]
4924    pub struct ShutdownState: c_int {
4925        /// A close notify message has been sent to the peer.
4926        const SENT = ffi::SSL_SENT_SHUTDOWN;
4927        /// A close notify message has been received from the peer.
4928        const RECEIVED = ffi::SSL_RECEIVED_SHUTDOWN;
4929    }
4930}
4931
4932cfg_if! {
4933    if #[cfg(any(boringssl, ossl110, libressl273, awslc))] {
4934        use ffi::{SSL_CTX_up_ref, SSL_SESSION_get_master_key, SSL_SESSION_up_ref, SSL_is_server};
4935    } else {
4936        #[allow(bad_style)]
4937        pub unsafe fn SSL_CTX_up_ref(ssl: *mut ffi::SSL_CTX) -> c_int {
4938            ffi::CRYPTO_add_lock(
4939                &mut (*ssl).references,
4940                1,
4941                ffi::CRYPTO_LOCK_SSL_CTX,
4942                "mod.rs\0".as_ptr() as *const _,
4943                line!() as c_int,
4944            );
4945            0
4946        }
4947
4948        #[allow(bad_style)]
4949        pub unsafe fn SSL_SESSION_get_master_key(
4950            session: *const ffi::SSL_SESSION,
4951            out: *mut c_uchar,
4952            mut outlen: usize,
4953        ) -> usize {
4954            if outlen == 0 {
4955                return (*session).master_key_length as usize;
4956            }
4957            if outlen > (*session).master_key_length as usize {
4958                outlen = (*session).master_key_length as usize;
4959            }
4960            ptr::copy_nonoverlapping((*session).master_key.as_ptr(), out, outlen);
4961            outlen
4962        }
4963
4964        #[allow(bad_style)]
4965        pub unsafe fn SSL_is_server(s: *mut ffi::SSL) -> c_int {
4966            (*s).server
4967        }
4968
4969        #[allow(bad_style)]
4970        pub unsafe fn SSL_SESSION_up_ref(ses: *mut ffi::SSL_SESSION) -> c_int {
4971            ffi::CRYPTO_add_lock(
4972                &mut (*ses).references,
4973                1,
4974                ffi::CRYPTO_LOCK_SSL_CTX,
4975                "mod.rs\0".as_ptr() as *const _,
4976                line!() as c_int,
4977            );
4978            0
4979        }
4980    }
4981}
4982
4983cfg_if! {
4984    if #[cfg(ossl300)] {
4985        use ffi::SSL_get1_peer_certificate;
4986    } else {
4987        use ffi::SSL_get_peer_certificate as SSL_get1_peer_certificate;
4988    }
4989}
4990cfg_if! {
4991    if #[cfg(any(boringssl, ossl110, libressl291, awslc))] {
4992        use ffi::{TLS_method, DTLS_method, TLS_client_method, TLS_server_method, DTLS_server_method, DTLS_client_method};
4993    } else {
4994        use ffi::{
4995            SSLv23_method as TLS_method, DTLSv1_method as DTLS_method, SSLv23_client_method as TLS_client_method,
4996            SSLv23_server_method as TLS_server_method,
4997        };
4998    }
4999}
5000cfg_if! {
5001    if #[cfg(ossl110)] {
5002        unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int {
5003            ffi::CRYPTO_get_ex_new_index(
5004                ffi::CRYPTO_EX_INDEX_SSL_CTX,
5005                0,
5006                ptr::null_mut(),
5007                None,
5008                None,
5009                f,
5010            )
5011        }
5012
5013        unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int {
5014            ffi::CRYPTO_get_ex_new_index(
5015                ffi::CRYPTO_EX_INDEX_SSL,
5016                0,
5017                ptr::null_mut(),
5018                None,
5019                None,
5020                f,
5021            )
5022        }
5023    } else {
5024        use std::sync::Once;
5025
5026        unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int {
5027            // hack around https://rt.openssl.org/Ticket/Display.html?id=3710&user=guest&pass=guest
5028            static ONCE: Once = Once::new();
5029            ONCE.call_once(|| {
5030                cfg_if! {
5031                    if #[cfg(not(any(boringssl, awslc)))] {
5032                        ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), None, None, None);
5033                    } else {
5034                        ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, None);
5035                    }
5036                }
5037            });
5038
5039            cfg_if! {
5040                if #[cfg(not(any(boringssl, awslc)))] {
5041                    ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), None, None, f)
5042                } else {
5043                    ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, f)
5044                }
5045            }
5046        }
5047
5048        unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int {
5049            // hack around https://rt.openssl.org/Ticket/Display.html?id=3710&user=guest&pass=guest
5050            static ONCE: Once = Once::new();
5051            ONCE.call_once(|| {
5052                #[cfg(not(any(boringssl, awslc)))]
5053                ffi::SSL_get_ex_new_index(0, ptr::null_mut(), None, None, None);
5054                #[cfg(any(boringssl, awslc))]
5055                ffi::SSL_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, None);
5056            });
5057
5058            #[cfg(not(any(boringssl, awslc)))]
5059            return ffi::SSL_get_ex_new_index(0, ptr::null_mut(), None, None, f);
5060            #[cfg(any(boringssl, awslc))]
5061            return ffi::SSL_get_ex_new_index(0, ptr::null_mut(), ptr::null_mut(), None, f);
5062        }
5063    }
5064}