87.50% Lines (14/16) 88.89% Functions (8/9)
TLA Baseline Branch
Line Hits Code Line Hits Code
1   // 1   //
2   // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com) 2   // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3   // Copyright (c) 2026 Michael Vandeberg 3   // Copyright (c) 2026 Michael Vandeberg
4   // 4   //
5   // Distributed under the Boost Software License, Version 1.0. (See accompanying 5   // Distributed under the Boost Software License, Version 1.0. (See accompanying
6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7   // 7   //
8   // Official repository: https://github.com/cppalliance/corosio 8   // Official repository: https://github.com/cppalliance/corosio
9   // 9   //
10   10  
11   #ifndef BOOST_COROSIO_TLS_CONTEXT_HPP 11   #ifndef BOOST_COROSIO_TLS_CONTEXT_HPP
12   #define BOOST_COROSIO_TLS_CONTEXT_HPP 12   #define BOOST_COROSIO_TLS_CONTEXT_HPP
13   13  
14   #include <boost/corosio/detail/config.hpp> 14   #include <boost/corosio/detail/config.hpp>
15   15  
16   #include <cstddef> 16   #include <cstddef>
17   #include <functional> 17   #include <functional>
18   #include <span> 18   #include <span>
19   #include <system_error> 19   #include <system_error>
20   #include <memory> 20   #include <memory>
21   #include <string_view> 21   #include <string_view>
22   22  
23   namespace boost::corosio { 23   namespace boost::corosio {
24   24  
25   // 25   //
26   // Enumerations 26   // Enumerations
27   // 27   //
28   28  
29   /** TLS protocol version. 29   /** TLS protocol version.
30   30  
31   Specifies the minimum or maximum TLS protocol version to use 31   Specifies the minimum or maximum TLS protocol version to use
32   for connections. Only modern, secure versions are supported. 32   for connections. Only modern, secure versions are supported.
33   33  
34   @see tls_context::set_min_protocol_version 34   @see tls_context::set_min_protocol_version
35   @see tls_context::set_max_protocol_version 35   @see tls_context::set_max_protocol_version
36   */ 36   */
37   enum class tls_version 37   enum class tls_version
38   { 38   {
39   /// TLS 1.2 (RFC 5246). 39   /// TLS 1.2 (RFC 5246).
40   tls_1_2, 40   tls_1_2,
41   41  
42   /// TLS 1.3 (RFC 8446). 42   /// TLS 1.3 (RFC 8446).
43   tls_1_3 43   tls_1_3
44   }; 44   };
45   45  
46   /** Certificate and key file format. 46   /** Certificate and key file format.
47   47  
48   Specifies the encoding format for certificate and key data. 48   Specifies the encoding format for certificate and key data.
49   49  
50   @see tls_context::use_certificate 50   @see tls_context::use_certificate
51   @see tls_context::use_private_key 51   @see tls_context::use_private_key
52   */ 52   */
53   enum class tls_file_format 53   enum class tls_file_format
54   { 54   {
55   /// PEM format (Base64-encoded with header/footer lines). 55   /// PEM format (Base64-encoded with header/footer lines).
56   pem, 56   pem,
57   57  
58   /// DER format (raw ASN.1 binary encoding). 58   /// DER format (raw ASN.1 binary encoding).
59   der 59   der
60   }; 60   };
61   61  
62   /** Peer certificate verification mode. 62   /** Peer certificate verification mode.
63   63  
64   Controls how the TLS implementation verifies the peer's 64   Controls how the TLS implementation verifies the peer's
65   certificate during the handshake. 65   certificate during the handshake.
66   66  
67   @see tls_context::set_verify_mode 67   @see tls_context::set_verify_mode
68   */ 68   */
69   enum class tls_verify_mode 69   enum class tls_verify_mode
70   { 70   {
71   /// Do not request or verify the peer certificate. 71   /// Do not request or verify the peer certificate.
72   none, 72   none,
73   73  
74   /// Request and verify the peer certificate if presented. 74   /// Request and verify the peer certificate if presented.
75   peer, 75   peer,
76   76  
77   /// Require and verify the peer certificate (fail if not presented). 77   /// Require and verify the peer certificate (fail if not presented).
78   require_peer 78   require_peer
79   }; 79   };
80   80  
81   /** Certificate revocation checking policy. 81   /** Certificate revocation checking policy.
82   82  
83   Controls how certificate revocation status is checked during 83   Controls how certificate revocation status is checked during
84   verification. 84   verification.
85   85  
86   @see tls_context::set_revocation_policy 86   @see tls_context::set_revocation_policy
87   */ 87   */
88   enum class tls_revocation_policy 88   enum class tls_revocation_policy
89   { 89   {
90   /// Do not check revocation status. 90   /// Do not check revocation status.
91   disabled, 91   disabled,
92   92  
93   /// Check revocation but allow connection if status is unknown. 93   /// Check revocation but allow connection if status is unknown.
94   soft_fail, 94   soft_fail,
95   95  
96   /// Require successful revocation check (fail if status is unknown). 96   /// Require successful revocation check (fail if status is unknown).
97   hard_fail 97   hard_fail
98   }; 98   };
99   99  
100   /** Purpose for password callback invocation. 100   /** Purpose for password callback invocation.
101   101  
102   Indicates whether the password is needed for reading (decrypting) 102   Indicates whether the password is needed for reading (decrypting)
103   or writing (encrypting) key material. 103   or writing (encrypting) key material.
104   104  
105   @see tls_context::set_password_callback 105   @see tls_context::set_password_callback
106   */ 106   */
107   enum class tls_password_purpose 107   enum class tls_password_purpose
108   { 108   {
109   /// Password needed to decrypt/read protected key material. 109   /// Password needed to decrypt/read protected key material.
110   for_reading, 110   for_reading,
111   111  
112   /// Password needed to encrypt/write protected key material. 112   /// Password needed to encrypt/write protected key material.
113   for_writing 113   for_writing
114   }; 114   };
115   115  
116   class tls_context; 116   class tls_context;
117   117  
118   /** A non-owning view of certificate verification state. 118   /** A non-owning view of certificate verification state.
119   119  
120   An instance is passed to the callback installed via 120   An instance is passed to the callback installed via
121   tls_context::set_verify_callback during the TLS handshake. It 121   tls_context::set_verify_callback during the TLS handshake. It
122   exposes the backend's native verification handle so the callback 122   exposes the backend's native verification handle so the callback
123   can inspect the certificate and chain currently being verified. 123   can inspect the certificate and chain currently being verified.
124   124  
125   The value returned by native_handle() is, for the OpenSSL and 125   The value returned by native_handle() is, for the OpenSSL and
126   WolfSSL backends, an `X509_STORE_CTX*`. For portable inspection that 126   WolfSSL backends, an `X509_STORE_CTX*`. For portable inspection that
127   works across backends (for example certificate pinning), prefer 127   works across backends (for example certificate pinning), prefer
128   certificate(), which returns the DER encoding of the certificate 128   certificate(), which returns the DER encoding of the certificate
129   currently being verified. 129   currently being verified.
130   130  
131   @par Lifetime 131   @par Lifetime
132   132  
133   The wrapped handle and the certificate() bytes are owned by the TLS 133   The wrapped handle and the certificate() bytes are owned by the TLS
134   backend and are valid only for the duration of a single callback 134   backend and are valid only for the duration of a single callback
135   invocation. Do not retain them beyond the call. 135   invocation. Do not retain them beyond the call.
136   136  
137   @see tls_context::set_verify_callback 137   @see tls_context::set_verify_callback
138   */ 138   */
139   class verify_context 139   class verify_context
140   { 140   {
141   void* handle_; 141   void* handle_;
142   unsigned char const* der_; 142   unsigned char const* der_;
143   std::size_t der_len_; 143   std::size_t der_len_;
144   144  
145   public: 145   public:
146   /** Construct from a native handle and the current certificate. 146   /** Construct from a native handle and the current certificate.
147   147  
148   @param handle The backend verification handle (for OpenSSL and 148   @param handle The backend verification handle (for OpenSSL and
149   WolfSSL, an `X509_STORE_CTX*`). 149   WolfSSL, an `X509_STORE_CTX*`).
150   @param der Pointer to the DER encoding of the certificate under 150   @param der Pointer to the DER encoding of the certificate under
151   verification, or `nullptr` if unavailable. 151   verification, or `nullptr` if unavailable.
152   @param der_len Length of the DER encoding in bytes. 152   @param der_len Length of the DER encoding in bytes.
153   */ 153   */
154   verify_context( 154   verify_context(
155   void* handle, unsigned char const* der, std::size_t der_len) noexcept 155   void* handle, unsigned char const* der, std::size_t der_len) noexcept
156   : handle_(handle), der_(der), der_len_(der_len) 156   : handle_(handle), der_(der), der_len_(der_len)
157   { 157   {
158   } 158   }
159   159  
160   /** Return the native verification handle. 160   /** Return the native verification handle.
161   161  
162   Cast the result to the backend's verification context type 162   Cast the result to the backend's verification context type
163   (e.g. `X509_STORE_CTX*`) to inspect the certificate chain using 163   (e.g. `X509_STORE_CTX*`) to inspect the certificate chain using
164   backend-specific APIs. 164   backend-specific APIs.
165   165  
166   @return The native handle, or `nullptr` if none is available. 166   @return The native handle, or `nullptr` if none is available.
167   */ 167   */
168   void* native_handle() const noexcept { return handle_; } 168   void* native_handle() const noexcept { return handle_; }
169   169  
170   /** Return the DER encoding of the certificate being verified. 170   /** Return the DER encoding of the certificate being verified.
171   171  
172   This is the portable way to inspect the peer certificate from a 172   This is the portable way to inspect the peer certificate from a
173   verification callback: it works identically on every backend, 173   verification callback: it works identically on every backend,
174   without depending on backend-specific build options. A DER 174   without depending on backend-specific build options. A DER
175   certificate is an ASN.1 `SEQUENCE`, so the first byte is `0x30`. 175   certificate is an ASN.1 `SEQUENCE`, so the first byte is `0x30`.
176   176  
177   @return A view of the certificate's DER bytes, valid only for the 177   @return A view of the certificate's DER bytes, valid only for the
178   duration of the callback. Empty if the certificate is not 178   duration of the callback. Empty if the certificate is not
179   available. 179   available.
180   */ 180   */
MISUBC 181   std::span<unsigned char const> certificate() const noexcept 181   std::span<unsigned char const> certificate() const noexcept
182   { 182   {
MISUBC 183   return {der_, der_len_}; 183   return {der_, der_len_};
184   } 184   }
185   }; 185   };
186   186  
187   namespace detail { 187   namespace detail {
188   struct tls_context_data; 188   struct tls_context_data;
189   tls_context_data const& get_tls_context_data(tls_context const&) noexcept; 189   tls_context_data const& get_tls_context_data(tls_context const&) noexcept;
190   } // namespace detail 190   } // namespace detail
191   191  
  192 + #ifdef _MSC_VER
  193 + #pragma warning(push)
  194 + #pragma warning(disable : 4251) // shared_ptr needs dll-interface
  195 + #endif
  196 +
192   /** A portable TLS context for certificate and settings storage. 197   /** A portable TLS context for certificate and settings storage.
193   198  
194   The `tls_context` class provides a backend-agnostic interface for 199   The `tls_context` class provides a backend-agnostic interface for
195   configuring TLS connections. It stores credentials (certificates and 200   configuring TLS connections. It stores credentials (certificates and
196   private keys), trust anchors, protocol settings, and verification 201   private keys), trust anchors, protocol settings, and verification
197   options that are used when establishing TLS connections. 202   options that are used when establishing TLS connections.
198   203  
199   This class is a shared handle to an opaque implementation. Copies 204   This class is a shared handle to an opaque implementation. Copies
200   share the same underlying state. This allows contexts to be passed 205   share the same underlying state. This allows contexts to be passed
201   by value and shared across multiple TLS streams. 206   by value and shared across multiple TLS streams.
202   207  
203   This class abstracts the configuration phase of TLS across multiple 208   This class abstracts the configuration phase of TLS across multiple
204   backend implementations (OpenSSL, WolfSSL, mbedTLS, Schannel, etc.), 209   backend implementations (OpenSSL, WolfSSL, mbedTLS, Schannel, etc.),
205   allowing portable code that works regardless of which TLS library 210   allowing portable code that works regardless of which TLS library
206   is linked. 211   is linked.
207   212  
208   @par Modification After Stream Creation 213   @par Modification After Stream Creation
209   214  
210   Modifying a context after a TLS stream has been created from it 215   Modifying a context after a TLS stream has been created from it
211   results in undefined behavior. The context's configuration is 216   results in undefined behavior. The context's configuration is
212   captured when the first stream is constructed, and subsequent 217   captured when the first stream is constructed, and subsequent
213   modifications are not reflected in existing or new streams 218   modifications are not reflected in existing or new streams
214   sharing the context. 219   sharing the context.
215   220  
216   If different configurations are needed, create separate context 221   If different configurations are needed, create separate context
217   objects. 222   objects.
218   223  
219   @par Thread Safety 224   @par Thread Safety
220   225  
221   Distinct objects: Safe. 226   Distinct objects: Safe.
222   227  
223   Shared objects: Unsafe. A context must not be modified while 228   Shared objects: Unsafe. A context must not be modified while
224   any thread is creating streams from it. 229   any thread is creating streams from it.
225   230  
226   @par Example 231   @par Example
227 - @code 232 + @par !example tls_context
228 - // Create a client context with system trust anchors  
229 - corosio::tls_context ctx;  
230 - if (auto ec = ctx.set_default_verify_paths())  
231 - co_return;  
232 - if (auto ec = ctx.set_verify_mode( corosio::tls_verify_mode::peer ))  
233 - co_return;  
234 -  
235 - // Use with a TLS stream  
236 - corosio::openssl_stream secure( &sock, ctx );  
237 - secure.set_hostname( "example.com" );  
238 - if (auto [ec] = co_await secure.handshake( corosio::tls_role::client ); ec)  
239 - co_return;  
240 - @endcode  
241   233  
242   @see tls_role 234   @see tls_role
243 - #ifdef _MSC_VER  
244 - #pragma warning(push)  
245 - #pragma warning(disable : 4251) // shared_ptr needs dll-interface  
246 - #endif  
247   */ 235   */
248   class BOOST_COROSIO_DECL tls_context 236   class BOOST_COROSIO_DECL tls_context
249   { 237   {
250   struct implementation; 238   struct implementation;
251   std::shared_ptr<implementation> impl_; 239   std::shared_ptr<implementation> impl_;
252   240  
253   friend detail::tls_context_data const& 241   friend detail::tls_context_data const&
254   detail::get_tls_context_data(tls_context const&) noexcept; 242   detail::get_tls_context_data(tls_context const&) noexcept;
255   243  
256   public: 244   public:
257   /** Construct a default TLS context. 245   /** Construct a default TLS context.
258   246  
259   Creates a context with default settings suitable for TLS 1.2 247   Creates a context with default settings suitable for TLS 1.2
260   and TLS 1.3 connections. No certificates or trust anchors are 248   and TLS 1.3 connections. No certificates or trust anchors are
261   loaded; call the appropriate methods to configure credentials 249   loaded; call the appropriate methods to configure credentials
262   and verification. 250   and verification.
263   251  
264   @par Example 252   @par Example
265 - @code 253 + @par !example tls_context
266 - corosio::tls_context ctx;  
267 - @endcode  
268   */ 254   */
269   tls_context(); 255   tls_context();
270   256  
271   /** Copy constructor. 257   /** Copy constructor.
272   258  
273   Creates a new handle that shares ownership of the underlying 259   Creates a new handle that shares ownership of the underlying
274   TLS context state with `other`. 260   TLS context state with `other`.
275   261  
276   @param other The context to copy from. 262   @param other The context to copy from.
277   */ 263   */
HITCBC 278   2 tls_context(tls_context const& other) = default; 264   2 tls_context(tls_context const& other) = default;
279   265  
280   /** Copy assignment operator. 266   /** Copy assignment operator.
281   267  
282   Releases the current context's shared ownership and acquires 268   Releases the current context's shared ownership and acquires
283   shared ownership of `other`'s underlying state. 269   shared ownership of `other`'s underlying state.
284   270  
285   @param other The context to copy from. 271   @param other The context to copy from.
286   272  
287   @return Reference to this context. 273   @return Reference to this context.
288   */ 274   */
HITCBC 289   1 tls_context& operator=(tls_context const& other) = default; 275   1 tls_context& operator=(tls_context const& other) = default;
290   276  
291   /** Move constructor. 277   /** Move constructor.
292   278  
293   Transfers ownership of the TLS context from another instance. 279   Transfers ownership of the TLS context from another instance.
294   After the move, `other` is in a valid but empty state. 280   After the move, `other` is in a valid but empty state.
295   281  
296   @param other The context to move from. 282   @param other The context to move from.
297   */ 283   */
HITCBC 298   2 tls_context(tls_context&& other) noexcept = default; 284   2 tls_context(tls_context&& other) noexcept = default;
299   285  
300   /** Move assignment operator. 286   /** Move assignment operator.
301   287  
302   Releases the current context's shared ownership and transfers 288   Releases the current context's shared ownership and transfers
303   ownership from another instance. After the move, `other` is 289   ownership from another instance. After the move, `other` is
304   in a valid but empty state. 290   in a valid but empty state.
305   291  
306   @param other The context to move from. 292   @param other The context to move from.
307   293  
308   @return Reference to this context. 294   @return Reference to this context.
309   */ 295   */
HITCBC 310   1 tls_context& operator=(tls_context&& other) noexcept = default; 296   1 tls_context& operator=(tls_context&& other) noexcept = default;
311   297  
312   /** Destructor. 298   /** Destructor.
313   299  
314   Releases this handle's shared ownership of the underlying 300   Releases this handle's shared ownership of the underlying
315   context. The context state is destroyed when the last handle 301   context. The context state is destroyed when the last handle
316   is released. 302   is released.
317   */ 303   */
HITCBC 318   55 ~tls_context() = default; 304   55 ~tls_context() = default;
319   305  
320   // 306   //
321   // Credential Loading 307   // Credential Loading
322   // 308   //
323   309  
324   /** Load the entity certificate from a memory buffer. 310   /** Load the entity certificate from a memory buffer.
325   311  
326   Sets the certificate that identifies this endpoint to the peer. 312   Sets the certificate that identifies this endpoint to the peer.
327   For servers, this is the server certificate. For clients using 313   For servers, this is the server certificate. For clients using
328   mutual TLS, this is the client certificate. 314   mutual TLS, this is the client certificate.
329   315  
330   The certificate must match the private key loaded via 316   The certificate must match the private key loaded via
331   `use_private_key()` or `use_private_key_file()`. 317   `use_private_key()` or `use_private_key_file()`.
332   318  
333   @param certificate The certificate data. 319   @param certificate The certificate data.
334   320  
335   @param format The encoding format of the certificate data. 321   @param format The encoding format of the certificate data.
336   322  
337   @return Success. The certificate is recorded and decoded when the 323   @return Success. The certificate is recorded and decoded when the
338   native context is first built; a malformed certificate surfaces 324   native context is first built; a malformed certificate surfaces
339   as a handshake failure. 325   as a handshake failure.
340   326  
341   @see use_certificate_file 327   @see use_certificate_file
342   @see use_private_key 328   @see use_private_key
343   */ 329   */
344   [[nodiscard]] std::error_code 330   [[nodiscard]] std::error_code
345   use_certificate(std::string_view certificate, tls_file_format format); 331   use_certificate(std::string_view certificate, tls_file_format format);
346   332  
347   /** Load the entity certificate from a file. 333   /** Load the entity certificate from a file.
348   334  
349   Sets the certificate that identifies this endpoint to the peer. 335   Sets the certificate that identifies this endpoint to the peer.
350   For servers, this is the server certificate. For clients using 336   For servers, this is the server certificate. For clients using
351   mutual TLS, this is the client certificate. 337   mutual TLS, this is the client certificate.
352   338  
353   @param filename Path to the certificate file. 339   @param filename Path to the certificate file.
354   340  
355   @param format The encoding format of the file. 341   @param format The encoding format of the file.
356   342  
357   @return Success, or an error if the file could not be read. The 343   @return Success, or an error if the file could not be read. The
358   certificate is decoded when the native context is first built; 344   certificate is decoded when the native context is first built;
359   a malformed certificate surfaces as a handshake failure. 345   a malformed certificate surfaces as a handshake failure.
360   346  
361   @par Example 347   @par Example
362 - @code 348 + @par !example use_certificate_file
363 - if (auto ec = ctx.use_certificate_file(  
364 - "server.crt", tls_file_format::pem ))  
365 - return;  
366 - @endcode  
367   349  
368   @see use_certificate 350   @see use_certificate
369   @see use_private_key_file 351   @see use_private_key_file
370   */ 352   */
371   [[nodiscard]] std::error_code 353   [[nodiscard]] std::error_code
372   use_certificate_file(std::string_view filename, tls_file_format format); 354   use_certificate_file(std::string_view filename, tls_file_format format);
373   355  
374   /** Load a certificate chain from a memory buffer. 356   /** Load a certificate chain from a memory buffer.
375   357  
376   Loads the entity certificate followed by intermediate CA certificates. 358   Loads the entity certificate followed by intermediate CA certificates.
377   The chain should be ordered from leaf to root (excluding the root). 359   The chain should be ordered from leaf to root (excluding the root).
378   This is the typical format for PEM certificate bundles. 360   This is the typical format for PEM certificate bundles.
379   361  
380   @param chain The certificate chain data in PEM format (concatenated 362   @param chain The certificate chain data in PEM format (concatenated
381   certificates). 363   certificates).
382   364  
383   @return Success. The chain is recorded and decoded when the native 365   @return Success. The chain is recorded and decoded when the native
384   context is first built; a malformed chain surfaces as a 366   context is first built; a malformed chain surfaces as a
385   handshake failure. 367   handshake failure.
386   368  
387   @see use_certificate_chain_file 369   @see use_certificate_chain_file
388   */ 370   */
389   [[nodiscard]] std::error_code use_certificate_chain(std::string_view chain); 371   [[nodiscard]] std::error_code use_certificate_chain(std::string_view chain);
390   372  
391   /** Load a certificate chain from a file. 373   /** Load a certificate chain from a file.
392   374  
393   Loads the entity certificate followed by intermediate CA certificates 375   Loads the entity certificate followed by intermediate CA certificates
394   from a PEM file. The file should contain concatenated PEM certificates 376   from a PEM file. The file should contain concatenated PEM certificates
395   ordered from leaf to root (excluding the root). 377   ordered from leaf to root (excluding the root).
396   378  
397   @param filename Path to the certificate chain file. 379   @param filename Path to the certificate chain file.
398   380  
399   @return Success, or an error if the file could not be read. The 381   @return Success, or an error if the file could not be read. The
400   chain is decoded when the native context is first built; a 382   chain is decoded when the native context is first built; a
401   malformed chain surfaces as a handshake failure. 383   malformed chain surfaces as a handshake failure.
402   384  
403   @par Example 385   @par Example
404 - @code 386 + @par !example use_certificate_chain_file
405 - if (auto ec = ctx.use_certificate_chain_file( "fullchain.pem" ))  
406 - return;  
407 - @endcode  
408   387  
409   @see use_certificate_chain 388   @see use_certificate_chain
410   */ 389   */
411   [[nodiscard]] std::error_code use_certificate_chain_file(std::string_view filename); 390   [[nodiscard]] std::error_code use_certificate_chain_file(std::string_view filename);
412   391  
413   /** Load the private key from a memory buffer. 392   /** Load the private key from a memory buffer.
414   393  
415   Sets the private key corresponding to the entity certificate. 394   Sets the private key corresponding to the entity certificate.
416   The key must match the certificate loaded via `use_certificate()` 395   The key must match the certificate loaded via `use_certificate()`
417   or `use_certificate_chain()`. 396   or `use_certificate_chain()`.
418   397  
419   If the key is encrypted, set a password callback via 398   If the key is encrypted, set a password callback via
420   `set_password_callback()` before calling this function. 399   `set_password_callback()` before calling this function.
421   400  
422   @param private_key The private key data. 401   @param private_key The private key data.
423   402  
424   @param format The encoding format of the key data. 403   @param format The encoding format of the key data.
425   404  
426   @return Success. The key is recorded and decoded when the native 405   @return Success. The key is recorded and decoded when the native
427   context is first built; a malformed key, a missing password 406   context is first built; a malformed key, a missing password
428   callback for an encrypted key, or a certificate mismatch 407   callback for an encrypted key, or a certificate mismatch
429   surfaces as a handshake failure. 408   surfaces as a handshake failure.
430   409  
431   @see use_private_key_file 410   @see use_private_key_file
432   @see set_password_callback 411   @see set_password_callback
433   */ 412   */
434   [[nodiscard]] std::error_code 413   [[nodiscard]] std::error_code
435   use_private_key(std::string_view private_key, tls_file_format format); 414   use_private_key(std::string_view private_key, tls_file_format format);
436   415  
437   /** Load the private key from a file. 416   /** Load the private key from a file.
438   417  
439   Sets the private key corresponding to the entity certificate. 418   Sets the private key corresponding to the entity certificate.
440   The key must match the certificate loaded via `use_certificate_file()` 419   The key must match the certificate loaded via `use_certificate_file()`
441   or `use_certificate_chain_file()`. 420   or `use_certificate_chain_file()`.
442   421  
443   If the key file is encrypted, set a password callback via 422   If the key file is encrypted, set a password callback via
444   `set_password_callback()` before calling this function. 423   `set_password_callback()` before calling this function.
445   424  
446   @param filename Path to the private key file. 425   @param filename Path to the private key file.
447   426  
448   @param format The encoding format of the file. 427   @param format The encoding format of the file.
449   428  
450   @return Success, or an error if the file could not be read. The 429   @return Success, or an error if the file could not be read. The
451   key is decoded when the native context is first built; a 430   key is decoded when the native context is first built; a
452   malformed key or a certificate mismatch surfaces as a 431   malformed key or a certificate mismatch surfaces as a
453   handshake failure. 432   handshake failure.
454   433  
455   @par Example 434   @par Example
456 - @code 435 + @par !example use_private_key_file
457 - if (auto ec = ctx.use_private_key_file(  
458 - "server.key", tls_file_format::pem ))  
459 - return;  
460 - @endcode  
461   436  
462   @see use_private_key 437   @see use_private_key
463   @see set_password_callback 438   @see set_password_callback
464   */ 439   */
465   [[nodiscard]] std::error_code 440   [[nodiscard]] std::error_code
466   use_private_key_file(std::string_view filename, tls_file_format format); 441   use_private_key_file(std::string_view filename, tls_file_format format);
467   442  
468   /** Load credentials from a PKCS#12 bundle in memory. 443   /** Load credentials from a PKCS#12 bundle in memory.
469   444  
470   PKCS#12 (also known as PFX) is a binary format that bundles a 445   PKCS#12 (also known as PFX) is a binary format that bundles a
471   certificate, private key, and optionally intermediate certificates 446   certificate, private key, and optionally intermediate certificates
472   into a single password-protected file. 447   into a single password-protected file.
473   448  
474   @param data The PKCS#12 bundle data. 449   @param data The PKCS#12 bundle data.
475   450  
476   @param passphrase The password protecting the bundle. 451   @param passphrase The password protecting the bundle.
477   452  
478   @return Success. The bundle is recorded and decoded into the 453   @return Success. The bundle is recorded and decoded into the
479   certificate, private key, and chain when the native context is 454   certificate, private key, and chain when the native context is
480   first built; a malformed bundle or wrong passphrase surfaces as 455   first built; a malformed bundle or wrong passphrase surfaces as
481   a handshake failure. 456   a handshake failure.
482   457  
483   @note Intermediate certificates inside the bundle are loaded and 458   @note Intermediate certificates inside the bundle are loaded and
484   sent during the handshake on both backends. 459   sent during the handshake on both backends.
485   460  
486   @see use_pkcs12_file 461   @see use_pkcs12_file
487   */ 462   */
488   [[nodiscard]] std::error_code 463   [[nodiscard]] std::error_code
489   use_pkcs12(std::string_view data, std::string_view passphrase); 464   use_pkcs12(std::string_view data, std::string_view passphrase);
490   465  
491   /** Load credentials from a PKCS#12 file. 466   /** Load credentials from a PKCS#12 file.
492   467  
493   PKCS#12 (also known as PFX) is a binary format that bundles a 468   PKCS#12 (also known as PFX) is a binary format that bundles a
494   certificate, private key, and optionally intermediate certificates 469   certificate, private key, and optionally intermediate certificates
495   into a single password-protected file. This is common on Windows 470   into a single password-protected file. This is common on Windows
496   and for certificates exported from browsers. 471   and for certificates exported from browsers.
497   472  
498   @param filename Path to the PKCS#12 file. 473   @param filename Path to the PKCS#12 file.
499   474  
500   @param passphrase The password protecting the file. 475   @param passphrase The password protecting the file.
501   476  
502   @return Success, or an error if the file could not be read. The 477   @return Success, or an error if the file could not be read. The
503   bundle is decoded when the native context is first built; a 478   bundle is decoded when the native context is first built; a
504   malformed bundle or wrong passphrase surfaces as a handshake 479   malformed bundle or wrong passphrase surfaces as a handshake
505   failure. 480   failure.
506   481  
507   @note Intermediate certificates inside the bundle are loaded and 482   @note Intermediate certificates inside the bundle are loaded and
508   sent during the handshake on both backends. 483   sent during the handshake on both backends.
509   484  
510   @par Example 485   @par Example
511 - @code 486 + @par !example use_pkcs12_file
512 - if (auto ec = ctx.use_pkcs12_file( "credentials.pfx", "secret" ))  
513 - return;  
514 - @endcode  
515   487  
516   @see use_pkcs12 488   @see use_pkcs12
517   */ 489   */
518   [[nodiscard]] std::error_code 490   [[nodiscard]] std::error_code
519   use_pkcs12_file(std::string_view filename, std::string_view passphrase); 491   use_pkcs12_file(std::string_view filename, std::string_view passphrase);
520   492  
521   // 493   //
522   // Trust Anchors 494   // Trust Anchors
523   // 495   //
524   496  
525   /** Add a certificate authority for peer verification. 497   /** Add a certificate authority for peer verification.
526   498  
527   Adds a single CA certificate to the trust store used for verifying 499   Adds a single CA certificate to the trust store used for verifying
528   peer certificates. Call this multiple times to add multiple CAs, 500   peer certificates. Call this multiple times to add multiple CAs,
529   or use `load_verify_file()` for a bundle. 501   or use `load_verify_file()` for a bundle.
530   502  
531   @param ca The CA certificate data in PEM format. 503   @param ca The CA certificate data in PEM format.
532   504  
533   @return Success. The certificate is recorded and decoded when the 505   @return Success. The certificate is recorded and decoded when the
534   native context is first built; a malformed certificate 506   native context is first built; a malformed certificate
535   surfaces as a handshake failure. 507   surfaces as a handshake failure.
536   508  
537   @see load_verify_file 509   @see load_verify_file
538   @see set_default_verify_paths 510   @see set_default_verify_paths
539   */ 511   */
540   [[nodiscard]] std::error_code add_certificate_authority(std::string_view ca); 512   [[nodiscard]] std::error_code add_certificate_authority(std::string_view ca);
541   513  
542   /** Load CA certificates from a file. 514   /** Load CA certificates from a file.
543   515  
544   Loads one or more CA certificates from a PEM file. The file may 516   Loads one or more CA certificates from a PEM file. The file may
545   contain multiple concatenated PEM certificates. 517   contain multiple concatenated PEM certificates.
546   518  
547   @param filename Path to a PEM file containing CA certificates. 519   @param filename Path to a PEM file containing CA certificates.
548   520  
549   @return Success, or an error if the file could not be read. The 521   @return Success, or an error if the file could not be read. The
550   certificates are decoded when the native context is first 522   certificates are decoded when the native context is first
551   built; malformed certificates surface as a handshake failure. 523   built; malformed certificates surface as a handshake failure.
552   524  
553   @par Example 525   @par Example
554 - @code 526 + @par !example load_verify_file
555 - if (auto ec = ctx.load_verify_file(  
556 - "/etc/ssl/certs/ca-certificates.crt" ))  
557 - return;  
558 - @endcode  
559   527  
560   @see add_certificate_authority 528   @see add_certificate_authority
561   @see add_verify_path 529   @see add_verify_path
562   */ 530   */
563   [[nodiscard]] std::error_code load_verify_file(std::string_view filename); 531   [[nodiscard]] std::error_code load_verify_file(std::string_view filename);
564   532  
565   /** Add a directory of CA certificates for verification. 533   /** Add a directory of CA certificates for verification.
566   534  
567   Adds a directory of CA certificates to the trust store. The 535   Adds a directory of CA certificates to the trust store. The
568   directory is applied when the native context is first built from 536   directory is applied when the native context is first built from
569   this context. 537   this context.
570   538  
571   The expected directory layout depends on the backend. OpenSSL 539   The expected directory layout depends on the backend. OpenSSL
572   performs on-demand lookups and requires each certificate file to 540   performs on-demand lookups and requires each certificate file to
573   be named by its subject-name hash (as generated by 541   be named by its subject-name hash (as generated by
574   `openssl rehash` or `c_rehash`); WolfSSL loads every certificate 542   `openssl rehash` or `c_rehash`); WolfSSL loads every certificate
575   file in the directory. 543   file in the directory.
576   544  
577   @param path Path to the directory of CA certificates. 545   @param path Path to the directory of CA certificates.
578   546  
579   @return Success. The path is recorded and applied when the native 547   @return Success. The path is recorded and applied when the native
580   context is built; a directory that cannot be read at that time 548   context is built; a directory that cannot be read at that time
581   is skipped rather than reported here. 549   is skipped rather than reported here.
582   550  
583   @par Example 551   @par Example
584 - @code 552 + @par !example add_verify_path
585 - if (auto ec = ctx.add_verify_path( "/etc/ssl/certs" ))  
586 - return;  
587 - @endcode  
588   553  
589   @see load_verify_file 554   @see load_verify_file
590   @see set_default_verify_paths 555   @see set_default_verify_paths
591   */ 556   */
592   [[nodiscard]] std::error_code add_verify_path(std::string_view path); 557   [[nodiscard]] std::error_code add_verify_path(std::string_view path);
593   558  
594   /** Use the system default CA certificate store. 559   /** Use the system default CA certificate store.
595   560  
596   Configures the context to use the operating system's default 561   Configures the context to use the operating system's default
597   trust store for peer certificate verification. This is the 562   trust store for peer certificate verification. This is the
598   recommended approach for HTTPS clients connecting to public 563   recommended approach for HTTPS clients connecting to public
599   servers. 564   servers.
600   565  
601   The system store is loaded when the native context is first built 566   The system store is loaded when the native context is first built
602   from this context. For a verified-safe client, combine this with 567   from this context. For a verified-safe client, combine this with
603   `set_verify_mode( tls_verify_mode::peer )` and, when connecting by 568   `set_verify_mode( tls_verify_mode::peer )` and, when connecting by
604   name, `tls_stream::set_hostname()`. 569   name, `tls_stream::set_hostname()`.
605   570  
606   @return Success. The request is recorded and applied when the 571   @return Success. The request is recorded and applied when the
607   native context is built; if the system store cannot be loaded 572   native context is built; if the system store cannot be loaded
608   at that time it is skipped rather than reported here, so a 573   at that time it is skipped rather than reported here, so a
609   context that must reject unverified peers should also use 574   context that must reject unverified peers should also use
610   `set_verify_mode( tls_verify_mode::peer )`. 575   `set_verify_mode( tls_verify_mode::peer )`.
611   576  
612   @note The OpenSSL backend honors the `SSL_CERT_FILE` and 577   @note The OpenSSL backend honors the `SSL_CERT_FILE` and
613   `SSL_CERT_DIR` environment variables. The WolfSSL backend 578   `SSL_CERT_DIR` environment variables. The WolfSSL backend
614   requires a build with `WOLFSSL_SYS_CA_CERTS`; without it the 579   requires a build with `WOLFSSL_SYS_CA_CERTS`; without it the
615   system store is unavailable and this call has no effect. 580   system store is unavailable and this call has no effect.
616   581  
617   @par Example 582   @par Example
618 - @code 583 + @par !example set_default_verify_paths
619 - // Trust the same CAs as the system  
620 - if (auto ec = ctx.set_default_verify_paths())  
621 - return;  
622 - if (auto ec = ctx.set_verify_mode( tls_verify_mode::peer ))  
623 - return;  
624 - @endcode  
625   584  
626   @see load_verify_file 585   @see load_verify_file
627   @see add_verify_path 586   @see add_verify_path
628   @see set_verify_mode 587   @see set_verify_mode
629   */ 588   */
630   [[nodiscard]] std::error_code set_default_verify_paths(); 589   [[nodiscard]] std::error_code set_default_verify_paths();
631   590  
632   // 591   //
633   // Protocol Configuration 592   // Protocol Configuration
634   // 593   //
635   594  
636   /** Set the minimum TLS protocol version. 595   /** Set the minimum TLS protocol version.
637   596  
638   Connections will reject protocol versions older than this. 597   Connections will reject protocol versions older than this.
639   The default allows TLS 1.2 and newer. 598   The default allows TLS 1.2 and newer.
640   599  
641   @param v The minimum protocol version to accept. 600   @param v The minimum protocol version to accept.
642   601  
643   @return Success. The version is recorded and applied when the 602   @return Success. The version is recorded and applied when the
644   native context is first built. 603   native context is first built.
645   604  
646   @par Example 605   @par Example
647 - @code 606 + @par !example set_min_protocol_version
648 - // Require TLS 1.3 minimum  
649 - if (auto ec = ctx.set_min_protocol_version( tls_version::tls_1_3 ))  
650 - return;  
651 - @endcode  
652   607  
653   @see set_max_protocol_version 608   @see set_max_protocol_version
654   */ 609   */
655   [[nodiscard]] std::error_code set_min_protocol_version(tls_version v); 610   [[nodiscard]] std::error_code set_min_protocol_version(tls_version v);
656   611  
657   /** Set the maximum TLS protocol version. 612   /** Set the maximum TLS protocol version.
658   613  
659   Connections will not negotiate protocol versions newer than this. 614   Connections will not negotiate protocol versions newer than this.
660   The default allows the newest supported version. 615   The default allows the newest supported version.
661   616  
662   @param v The maximum protocol version to accept. 617   @param v The maximum protocol version to accept.
663   618  
664   @return Success. The version is recorded and applied when the 619   @return Success. The version is recorded and applied when the
665   native context is first built. 620   native context is first built.
666   621  
667   @note On WolfSSL the ceiling is applied by selecting a 622   @note On WolfSSL the ceiling is applied by selecting a
668   version-specific method (no native set-max API exists); an 623   version-specific method (no native set-max API exists); an
669   invalid window where the minimum exceeds the maximum yields a 624   invalid window where the minimum exceeds the maximum yields a
670   context that fails the handshake. 625   context that fails the handshake.
671   626  
672   @see set_min_protocol_version 627   @see set_min_protocol_version
673   */ 628   */
674   [[nodiscard]] std::error_code set_max_protocol_version(tls_version v); 629   [[nodiscard]] std::error_code set_max_protocol_version(tls_version v);
675   630  
676   /** Set the allowed cipher suites. 631   /** Set the allowed cipher suites.
677   632  
678   Configures which cipher suites may be used for connections. 633   Configures which cipher suites may be used for connections.
679   The format is backend-specific but typically follows OpenSSL 634   The format is backend-specific but typically follows OpenSSL
680   cipher list syntax. 635   cipher list syntax.
681   636  
682   @param ciphers The cipher suite specification string. 637   @param ciphers The cipher suite specification string.
683   638  
684   @return Success. The string is recorded and applied when the 639   @return Success. The string is recorded and applied when the
685   native context is first built; an invalid cipher string 640   native context is first built; an invalid cipher string
686   surfaces as a handshake failure. 641   surfaces as a handshake failure.
687   642  
688   @par Example 643   @par Example
689 - @code 644 + @par !example set_ciphersuites
690 - // TLS 1.2 cipher suites (OpenSSL format)  
691 - if (auto ec = ctx.set_ciphersuites( "ECDHE+AESGCM:ECDHE+CHACHA20" ))  
692 - return;  
693 - @endcode  
694   645  
695   @note This configures cipher suites for TLS 1.2 and below. For 646   @note This configures cipher suites for TLS 1.2 and below. For
696   TLS 1.3, use @ref set_ciphersuites_tls13. 647   TLS 1.3, use @ref set_ciphersuites_tls13.
697   */ 648   */
698   [[nodiscard]] std::error_code set_ciphersuites(std::string_view ciphers); 649   [[nodiscard]] std::error_code set_ciphersuites(std::string_view ciphers);
699   650  
700   /** Set the allowed TLS 1.3 cipher suites. 651   /** Set the allowed TLS 1.3 cipher suites.
701   652  
702   TLS 1.3 uses a distinct, fixed set of cipher suites configured 653   TLS 1.3 uses a distinct, fixed set of cipher suites configured
703   separately from earlier versions. The format is a colon-separated 654   separately from earlier versions. The format is a colon-separated
704   list of TLS 1.3 suite names. 655   list of TLS 1.3 suite names.
705   656  
706   @param ciphers The TLS 1.3 cipher suite list. 657   @param ciphers The TLS 1.3 cipher suite list.
707   658  
708   @return Success. The string is recorded and applied when the 659   @return Success. The string is recorded and applied when the
709   native context is first built; an invalid cipher string 660   native context is first built; an invalid cipher string
710   surfaces as a handshake failure. 661   surfaces as a handshake failure.
711   662  
712   @par Example 663   @par Example
713 - @code 664 + @par !example set_ciphersuites_tls13
714 - if (auto ec = ctx.set_ciphersuites_tls13(  
715 - "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256" ))  
716 - return;  
717 - @endcode  
718   665  
719   @note On the WolfSSL backend, TLS 1.2 and TLS 1.3 suites share a 666   @note On the WolfSSL backend, TLS 1.2 and TLS 1.3 suites share a
720   single cipher list; this call and @ref set_ciphersuites are 667   single cipher list; this call and @ref set_ciphersuites are
721   merged into one list. 668   merged into one list.
722   669  
723   @see set_ciphersuites 670   @see set_ciphersuites
724   */ 671   */
725   [[nodiscard]] std::error_code set_ciphersuites_tls13(std::string_view ciphers); 672   [[nodiscard]] std::error_code set_ciphersuites_tls13(std::string_view ciphers);
726   673  
727   /** Set the ALPN protocol list. 674   /** Set the ALPN protocol list.
728   675  
729   Configures Application-Layer Protocol Negotiation (ALPN) for 676   Configures Application-Layer Protocol Negotiation (ALPN) for
730   the connection. ALPN is used to negotiate which application 677   the connection. ALPN is used to negotiate which application
731   protocol to use over the TLS connection (e.g., "h2" for HTTP/2, 678   protocol to use over the TLS connection (e.g., "h2" for HTTP/2,
732   "http/1.1" for HTTP/1.1). 679   "http/1.1" for HTTP/1.1).
733   680  
734   The protocols are tried in preference order (first = highest). 681   The protocols are tried in preference order (first = highest).
735   682  
736   @param protocols Ordered list of protocol identifiers. 683   @param protocols Ordered list of protocol identifiers.
737   684  
738   @return Success, or an error if ALPN configuration fails. 685   @return Success, or an error if ALPN configuration fails.
739   686  
740   @note Read the negotiated protocol after the handshake via 687   @note Read the negotiated protocol after the handshake via
741   @ref tls_stream::alpn_protocol. On WolfSSL, ALPN requires a 688   @ref tls_stream::alpn_protocol. On WolfSSL, ALPN requires a
742   build with `HAVE_ALPN`; without it, offering protocols fails 689   build with `HAVE_ALPN`; without it, offering protocols fails
743   the handshake with `std::errc::function_not_supported` rather 690   the handshake with `std::errc::function_not_supported` rather
744   than negotiate nothing silently. 691   than negotiate nothing silently.
745   692  
746   @par Example 693   @par Example
747 - @code 694 + @par !example set_alpn
748 - // Prefer HTTP/2, fall back to HTTP/1.1  
749 - if (auto ec = ctx.set_alpn( { "h2", "http/1.1" } ))  
750 - return;  
751 - @endcode  
752   */ 695   */
753   [[nodiscard]] std::error_code set_alpn(std::initializer_list<std::string_view> protocols); 696   [[nodiscard]] std::error_code set_alpn(std::initializer_list<std::string_view> protocols);
754   697  
755   // 698   //
756   // Certificate Verification 699   // Certificate Verification
757   // 700   //
758   701  
759   /** Set the peer certificate verification mode. 702   /** Set the peer certificate verification mode.
760   703  
761   Controls whether and how peer certificates are verified during 704   Controls whether and how peer certificates are verified during
762   the TLS handshake. 705   the TLS handshake.
763   706  
764   @param mode The verification mode to use. 707   @param mode The verification mode to use.
765   708  
766   @return Success. The mode is recorded and applied when the native 709   @return Success. The mode is recorded and applied when the native
767   context is first built. 710   context is first built.
768   711  
769   @par Example 712   @par Example
770 - @code 713 + @par !example set_verify_mode
771 - // Verify peer certificate (typical for clients; servers doing  
772 - // mTLS use tls_verify_mode::require_peer instead)  
773 - if (auto ec = ctx.set_verify_mode( tls_verify_mode::peer ))  
774 - return;  
775 - @endcode  
776   714  
777   @see tls_verify_mode 715   @see tls_verify_mode
778   */ 716   */
779   [[nodiscard]] std::error_code set_verify_mode(tls_verify_mode mode); 717   [[nodiscard]] std::error_code set_verify_mode(tls_verify_mode mode);
780   718  
781   /** Set the maximum certificate chain verification depth. 719   /** Set the maximum certificate chain verification depth.
782   720  
783   Limits how many intermediate certificates can appear between 721   Limits how many intermediate certificates can appear between
784   the peer certificate and a trusted root. The default is 722   the peer certificate and a trusted root. The default is
785   typically 100, which is sufficient for most certificate chains. 723   typically 100, which is sufficient for most certificate chains.
786   724  
787   @param depth Maximum number of intermediate certificates allowed. 725   @param depth Maximum number of intermediate certificates allowed.
788   726  
789   @return Success. The depth is recorded and applied when the native 727   @return Success. The depth is recorded and applied when the native
790   context is first built. 728   context is first built.
791   */ 729   */
792   [[nodiscard]] std::error_code set_verify_depth(int depth); 730   [[nodiscard]] std::error_code set_verify_depth(int depth);
793   731  
794   /** Set a custom certificate verification callback. 732   /** Set a custom certificate verification callback.
795   733  
796   Installs a callback that is invoked during certificate chain 734   Installs a callback that is invoked during certificate chain
797   verification. The callback can perform additional validation 735   verification. The callback can perform additional validation
798   beyond the standard checks and can override verification 736   beyond the standard checks and can override verification
799   results. 737   results.
800   738  
801   The callback receives the built-in verification result so far and 739   The callback receives the built-in verification result so far and
802   a verify_context describing the certificate being verified. Return 740   a verify_context describing the certificate being verified. Return
803   `true` to accept the certificate, `false` to reject. Inspect the 741   `true` to accept the certificate, `false` to reject. Inspect the
804   certificate portably via `verify_context::certificate()` (its DER 742   certificate portably via `verify_context::certificate()` (its DER
805   encoding) — for example to pin a specific certificate. 743   encoding) — for example to pin a specific certificate.
806   744  
807   @par Backend Support 745   @par Backend Support
808   746  
809   The exact set of certificates the callback sees differs by backend: 747   The exact set of certificates the callback sees differs by backend:
810   748  
811   - OpenSSL: the callback runs once per certificate in the chain, 749   - OpenSSL: the callback runs once per certificate in the chain,
812   including certificates that passed the built-in checks. It can 750   including certificates that passed the built-in checks. It can
813   therefore both relax verification (return `true` for a 751   therefore both relax verification (return `true` for a
814   certificate the library rejected) and tighten it (return `false` 752   certificate the library rejected) and tighten it (return `false`
815   for a certificate the library accepted, e.g. pinning). 753   for a certificate the library accepted, e.g. pinning).
816   - WolfSSL built with `WOLFSSL_ALWAYS_VERIFY_CB` (implied by 754   - WolfSSL built with `WOLFSSL_ALWAYS_VERIFY_CB` (implied by
817   `--enable-opensslextra`): same as OpenSSL. 755   `--enable-opensslextra`): same as OpenSSL.
818   - WolfSSL without that option: the library invokes the callback 756   - WolfSSL without that option: the library invokes the callback
819   only on verification *failure*, so it cannot be honored on a 757   only on verification *failure*, so it cannot be honored on a
820   successful handshake. To avoid silently ignoring a 758   successful handshake. To avoid silently ignoring a
821   verification-tightening callback (which would fail open), a 759   verification-tightening callback (which would fail open), a
822   context that carries a callback instead **fails the handshake** 760   context that carries a callback instead **fails the handshake**
823   with `std::errc::function_not_supported` on such a build. Rebuild 761   with `std::errc::function_not_supported` on such a build. Rebuild
824   WolfSSL with `WOLFSSL_ALWAYS_VERIFY_CB`, or omit the callback. 762   WolfSSL with `WOLFSSL_ALWAYS_VERIFY_CB`, or omit the callback.
825   763  
826   @tparam Callback A callable with signature 764   @tparam Callback A callable with signature
827   `bool( bool preverified, verify_context& ctx )`. 765   `bool( bool preverified, verify_context& ctx )`.
828   766  
829   @param callback The verification callback. Recorded here and 767   @param callback The verification callback. Recorded here and
830   applied during the handshake; on a WolfSSL build that 768   applied during the handshake; on a WolfSSL build that
831   cannot honor it, the handshake fails with 769   cannot honor it, the handshake fails with
832   `std::errc::function_not_supported` (see Backend Support). 770   `std::errc::function_not_supported` (see Backend Support).
833   771  
834   @par Example 772   @par Example
835 - @code 773 + @par !example set_verify_callback
836 - if (auto ec = ctx.set_verify_mode( tls_verify_mode::peer ))  
837 - return;  
838 - ctx.set_verify_callback(  
839 - []( bool preverified, verify_context& ctx ) -> bool  
840 - {  
841 - if( ! preverified )  
842 - return false;  
843 - // Pin: accept only a certificate whose DER matches.  
844 - auto der = ctx.certificate();  
845 - return der.size() == expected_pin.size() &&  
846 - std::equal( der.begin(), der.end(), expected_pin.begin() );  
847 - });  
848 - @endcode  
849   774  
850   @see verify_context 775   @see verify_context
851   @see set_verify_mode 776   @see set_verify_mode
852   */ 777   */
853   template<typename Callback> 778   template<typename Callback>
854   void set_verify_callback(Callback callback); 779   void set_verify_callback(Callback callback);
855   780  
856   /** Set a callback for Server Name Indication (SNI). 781   /** Set a callback for Server Name Indication (SNI).
857   782  
858   For server connections, this callback is invoked during the TLS 783   For server connections, this callback is invoked during the TLS
859   handshake when a client sends an SNI extension. The callback 784   handshake when a client sends an SNI extension. The callback
860   receives the requested hostname and can accept or reject the 785   receives the requested hostname and can accept or reject the
861   connection. 786   connection.
862   787  
863   @tparam Callback A callable with signature 788   @tparam Callback A callable with signature
864   `bool( std::string_view hostname )`. 789   `bool( std::string_view hostname )`.
865   790  
866   @param callback The SNI callback. Return `true` to accept the 791   @param callback The SNI callback. Return `true` to accept the
867   connection or `false` to reject it with an alert. 792   connection or `false` to reject it with an alert.
868   793  
869   @par Example 794   @par Example
870 - @code 795 + @par !example set_servername_callback
871 - // Accept connections for specific domains only  
872 - ctx.set_servername_callback(  
873 - []( std::string_view hostname ) -> bool  
874 - {  
875 - return hostname == "api.example.com" ||  
876 - hostname == "www.example.com";  
877 - });  
878 - @endcode  
879   796  
880   @note For virtual hosting with different certificates per hostname, 797   @note For virtual hosting with different certificates per hostname,
881   create separate contexts and select the appropriate one before 798   create separate contexts and select the appropriate one before
882   creating the TLS stream. 799   creating the TLS stream.
883   800  
884   @see tls_stream::set_hostname 801   @see tls_stream::set_hostname
885   */ 802   */
886   template<typename Callback> 803   template<typename Callback>
887   void set_servername_callback(Callback callback); 804   void set_servername_callback(Callback callback);
888   805  
889   private: 806   private:
890   void set_servername_callback_impl( 807   void set_servername_callback_impl(
891   std::function<bool(std::string_view)> callback); 808   std::function<bool(std::string_view)> callback);
892   809  
893   void set_password_callback_impl( 810   void set_password_callback_impl(
894   std::function<std::string(std::size_t, tls_password_purpose)> callback); 811   std::function<std::string(std::size_t, tls_password_purpose)> callback);
895   812  
896   void set_verify_callback_impl( 813   void set_verify_callback_impl(
897   std::function<bool(bool, verify_context&)> callback); 814   std::function<bool(bool, verify_context&)> callback);
898   815  
899   public: 816   public:
900   // 817   //
901   // Revocation Checking 818   // Revocation Checking
902   // 819   //
903   820  
904   /** Add a Certificate Revocation List from memory. 821   /** Add a Certificate Revocation List from memory.
905   822  
906   Adds a CRL to the verification store for checking whether 823   Adds a CRL to the verification store for checking whether
907   certificates have been revoked. CRLs are typically fetched 824   certificates have been revoked. CRLs are typically fetched
908   from the URLs in a certificate's CRL Distribution Points 825   from the URLs in a certificate's CRL Distribution Points
909   extension. 826   extension.
910   827  
911   @param crl The CRL data in DER or PEM format. 828   @param crl The CRL data in DER or PEM format.
912   829  
913   @return Success. The CRL is recorded and decoded when the native 830   @return Success. The CRL is recorded and decoded when the native
914   context is first built; a malformed CRL surfaces as a 831   context is first built; a malformed CRL surfaces as a
915   handshake failure. 832   handshake failure.
916   833  
917   @note CRLs are consulted only when a revocation policy is set via 834   @note CRLs are consulted only when a revocation policy is set via
918   @ref set_revocation_policy. On WolfSSL, CRL checking requires a 835   @ref set_revocation_policy. On WolfSSL, CRL checking requires a
919   build with `HAVE_CRL`; without it, supplying a CRL or a 836   build with `HAVE_CRL`; without it, supplying a CRL or a
920   revocation policy fails the handshake with 837   revocation policy fails the handshake with
921   `std::errc::function_not_supported`. 838   `std::errc::function_not_supported`.
922   839  
923   @see add_crl_file 840   @see add_crl_file
924   @see set_revocation_policy 841   @see set_revocation_policy
925   */ 842   */
926   [[nodiscard]] std::error_code add_crl(std::string_view crl); 843   [[nodiscard]] std::error_code add_crl(std::string_view crl);
927   844  
928   /** Add a Certificate Revocation List from a file. 845   /** Add a Certificate Revocation List from a file.
929   846  
930   Adds a CRL to the verification store for checking whether 847   Adds a CRL to the verification store for checking whether
931   certificates have been revoked. 848   certificates have been revoked.
932   849  
933   @param filename Path to a CRL file (DER or PEM format). 850   @param filename Path to a CRL file (DER or PEM format).
934   851  
935   @return Success, or an error if the file could not be read. The 852   @return Success, or an error if the file could not be read. The
936   CRL is decoded when the native context is first built; a 853   CRL is decoded when the native context is first built; a
937   malformed CRL surfaces as a handshake failure. 854   malformed CRL surfaces as a handshake failure.
938   855  
939   @note CRLs are consulted only when a revocation policy is set via 856   @note CRLs are consulted only when a revocation policy is set via
940   @ref set_revocation_policy (WolfSSL requires a `HAVE_CRL` 857   @ref set_revocation_policy (WolfSSL requires a `HAVE_CRL`
941   build). 858   build).
942   859  
943   @par Example 860   @par Example
944 - @code 861 + @par !example add_crl_file
945 - if (auto ec = ctx.add_crl_file( "issuer.crl" ))  
946 - return;  
947 - @endcode  
948   862  
949   @see add_crl 863   @see add_crl
950   @see set_revocation_policy 864   @see set_revocation_policy
951   */ 865   */
952   [[nodiscard]] std::error_code add_crl_file(std::string_view filename); 866   [[nodiscard]] std::error_code add_crl_file(std::string_view filename);
953   867  
954   /** Set the certificate revocation checking policy. 868   /** Set the certificate revocation checking policy.
955   869  
956   Controls how certificate revocation status is checked during 870   Controls how certificate revocation status is checked during
957   verification via CRLs. 871   verification via CRLs.
958   872  
959   @param policy The revocation checking policy. 873   @param policy The revocation checking policy.
960   874  
961   @par Example 875   @par Example
962 - @code 876 + @par !example set_revocation_policy
963 - // Require successful revocation check  
964 - ctx.set_revocation_policy( tls_revocation_policy::hard_fail );  
965 -  
966 - // Check but allow unknown status  
967 - ctx.set_revocation_policy( tls_revocation_policy::soft_fail );  
968 - @endcode  
969   877  
970   @note Revocation is checked via CRLs supplied with @ref add_crl / 878   @note Revocation is checked via CRLs supplied with @ref add_crl /
971   @ref add_crl_file. `soft_fail` accepts a certificate whose 879   @ref add_crl_file. `soft_fail` accepts a certificate whose
972   status cannot be determined (missing/expired CRL) but rejects 880   status cannot be determined (missing/expired CRL) but rejects
973   one that is actually revoked; `hard_fail` also rejects unknown 881   one that is actually revoked; `hard_fail` also rejects unknown
974   status. OCSP-based revocation is not available (see the TLS 882   status. OCSP-based revocation is not available (see the TLS
975   guide). On WolfSSL a non-disabled policy requires a `HAVE_CRL` 883   guide). On WolfSSL a non-disabled policy requires a `HAVE_CRL`
976   build, else the handshake fails with 884   build, else the handshake fails with
977   `std::errc::function_not_supported`. 885   `std::errc::function_not_supported`.
978   886  
979   @see tls_revocation_policy 887   @see tls_revocation_policy
980   @see add_crl 888   @see add_crl
981   */ 889   */
982   void set_revocation_policy(tls_revocation_policy policy); 890   void set_revocation_policy(tls_revocation_policy policy);
983   891  
984   // 892   //
985   // Password Handling 893   // Password Handling
986   // 894   //
987   895  
988   /** Set the password callback for encrypted keys. 896   /** Set the password callback for encrypted keys.
989   897  
990   Installs a callback that provides passwords for encrypted 898   Installs a callback that provides passwords for encrypted
991   private keys and PKCS#12 files. The callback is invoked when 899   private keys and PKCS#12 files. The callback is invoked when
992   loading encrypted key material. 900   loading encrypted key material.
993   901  
994   @tparam Callback A callable with signature 902   @tparam Callback A callable with signature
995   `std::string( std::size_t max_length, password_purpose purpose )`. 903   `std::string( std::size_t max_length, password_purpose purpose )`.
996   904  
997   @param callback The password callback. It receives the maximum 905   @param callback The password callback. It receives the maximum
998   password length and the purpose (reading or writing), and 906   password length and the purpose (reading or writing), and
999   returns the password string. 907   returns the password string.
1000   908  
1001   @par Example 909   @par Example
1002 - @code 910 + @par !example set_password_callback
1003 - ctx.set_password_callback(  
1004 - []( std::size_t max_len, tls_password_purpose purpose )  
1005 - {  
1006 - // In practice, prompt user or read from secure storage  
1007 - return std::string( "my-key-password" );  
1008 - });  
1009 -  
1010 - // Now load encrypted key  
1011 - if (auto ec = ctx.use_private_key_file(  
1012 - "encrypted.key", tls_file_format::pem ))  
1013 - return;  
1014 - @endcode  
1015   911  
1016   @see tls_password_purpose 912   @see tls_password_purpose
1017   */ 913   */
1018   template<typename Callback> 914   template<typename Callback>
1019   void set_password_callback(Callback callback); 915   void set_password_callback(Callback callback);
1020   }; 916   };
1021   #ifdef _MSC_VER 917   #ifdef _MSC_VER
1022   #pragma warning(pop) 918   #pragma warning(pop)
1023   #endif 919   #endif
1024   920  
1025   template<typename Callback> 921   template<typename Callback>
1026   void 922   void
HITCBC 1027   1 tls_context::set_servername_callback(Callback callback) 923   1 tls_context::set_servername_callback(Callback callback)
1028   { 924   {
HITCBC 1029   1 set_servername_callback_impl(std::move(callback)); 925   1 set_servername_callback_impl(std::move(callback));
HITCBC 1030   1 } 926   1 }
1031   927  
1032   template<typename Callback> 928   template<typename Callback>
1033   void 929   void
HITCBC 1034   4 tls_context::set_password_callback(Callback callback) 930   4 tls_context::set_password_callback(Callback callback)
1035   { 931   {
HITCBC 1036   4 set_password_callback_impl(std::move(callback)); 932   4 set_password_callback_impl(std::move(callback));
HITCBC 1037   4 } 933   4 }
1038   934  
1039   template<typename Callback> 935   template<typename Callback>
1040   void 936   void
HITCBC 1041   2 tls_context::set_verify_callback(Callback callback) 937   2 tls_context::set_verify_callback(Callback callback)
1042   { 938   {
HITCBC 1043   2 set_verify_callback_impl(std::move(callback)); 939   2 set_verify_callback_impl(std::move(callback));
HITCBC 1044   2 } 940   2 }
1045   941  
1046   } // namespace boost::corosio 942   } // namespace boost::corosio
1047   943  
1048   #endif 944   #endif