0.00% Lines (0/4) 0.00% Functions (0/2)
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 + // Copyright (c) 2026 Steve Gerbino
4   // 5   //
5   // Distributed under the Boost Software License, Version 1.0. (See accompanying 6   // 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) 7   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7   // 8   //
8   // Official repository: https://github.com/cppalliance/corosio 9   // Official repository: https://github.com/cppalliance/corosio
9   // 10   //
10   11  
11   #ifndef BOOST_COROSIO_TLS_STREAM_HPP 12   #ifndef BOOST_COROSIO_TLS_STREAM_HPP
12   #define BOOST_COROSIO_TLS_STREAM_HPP 13   #define BOOST_COROSIO_TLS_STREAM_HPP
13   14  
14   #include <boost/corosio/detail/config.hpp> 15   #include <boost/corosio/detail/config.hpp>
15   #include <boost/capy/buffers.hpp> 16   #include <boost/capy/buffers.hpp>
16   #include <boost/capy/detail/buffer_array.hpp> 17   #include <boost/capy/detail/buffer_array.hpp>
17   #include <boost/capy/io/any_stream.hpp> 18   #include <boost/capy/io/any_stream.hpp>
18   #include <boost/capy/io_task.hpp> 19   #include <boost/capy/io_task.hpp>
19   20  
20   #include <cstddef> 21   #include <cstddef>
21   #include <string_view> 22   #include <string_view>
22   23  
23   namespace boost::corosio { 24   namespace boost::corosio {
24   25  
25   /** TLS handshake role. 26   /** TLS handshake role.
26   27  
27   Specifies whether to perform the TLS handshake as a client or server. 28   Specifies whether to perform the TLS handshake as a client or server.
28   29  
29   @see tls_stream::handshake 30   @see tls_stream::handshake
30   */ 31   */
31   enum class tls_role 32   enum class tls_role
32   { 33   {
33   /// Perform handshake as the connecting client. 34   /// Perform handshake as the connecting client.
34   client, 35   client,
35   36  
36   /// Perform handshake as the accepting server. 37   /// Perform handshake as the accepting server.
37   server 38   server
38   }; 39   };
39   40  
40   /** Abstract base class for TLS streams. 41   /** Abstract base class for TLS streams.
41   42  
42   This class provides a runtime-polymorphic interface for TLS 43   This class provides a runtime-polymorphic interface for TLS
43   implementations. Derived classes (openssl_stream, wolfssl_stream) 44   implementations. Derived classes (openssl_stream, wolfssl_stream)
44   implement the virtual functions to provide backend-specific 45   implement the virtual functions to provide backend-specific
45   TLS functionality. 46   TLS functionality.
46   47  
47   Unlike @ref io_stream which represents OS-level I/O completed 48   Unlike @ref io_stream which represents OS-level I/O completed
48   by the kernel, TLS streams are coroutine-based: their operations 49   by the kernel, TLS streams are coroutine-based: their operations
49   are implemented as coroutines that orchestrate sub-operations 50   are implemented as coroutines that orchestrate sub-operations
50   on the underlying stream. 51   on the underlying stream.
51   52  
52   The non-virtual template wrappers (`read_some`, `write_some`) 53   The non-virtual template wrappers (`read_some`, `write_some`)
53   satisfy the `capy::Stream` concept, enabling TLS streams to 54   satisfy the `capy::Stream` concept, enabling TLS streams to
54   be used anywhere a Stream is expected. 55   be used anywhere a Stream is expected.
55   56  
56   @par Thread Safety 57   @par Thread Safety
57   Distinct objects: Safe.@n 58   Distinct objects: Safe.@n
58 - Shared objects: Unsafe. 59 + Shared objects: Unsafe, with one exception: one read operation and
  60 + one write operation may be in flight simultaneously. `shutdown()`
  61 + may overlap a pending read. When the execution context runs on
  62 + multiple threads, all operations on one stream must be performed
  63 + within the same `capy::strand` (or otherwise never run
  64 + concurrently); a single-threaded context needs no strand.
59   65  
60   @see openssl_stream, wolfssl_stream 66   @see openssl_stream, wolfssl_stream
61   */ 67   */
62   class BOOST_COROSIO_DECL tls_stream 68   class BOOST_COROSIO_DECL tls_stream
63   { 69   {
64   public: 70   public:
65   /// Destroy the TLS stream. 71   /// Destroy the TLS stream.
66   virtual ~tls_stream() = default; 72   virtual ~tls_stream() = default;
67   73  
68   tls_stream(tls_stream const&) = delete; 74   tls_stream(tls_stream const&) = delete;
69   tls_stream& operator=(tls_stream const&) = delete; 75   tls_stream& operator=(tls_stream const&) = delete;
70   76  
71   /** Initiate an asynchronous read operation. 77   /** Initiate an asynchronous read operation.
72   78  
73   Reads decrypted data into the provided buffer sequence. The 79   Reads decrypted data into the provided buffer sequence. The
74   operation completes when at least one byte has been read, 80   operation completes when at least one byte has been read,
75   or an error occurs. 81   or an error occurs.
76   82  
77   This non-virtual template wrapper satisfies the `capy::Stream` 83   This non-virtual template wrapper satisfies the `capy::Stream`
78   concept by delegating to the virtual `do_read_some`. 84   concept by delegating to the virtual `do_read_some`.
79   85  
  86 + @par Thread Safety
  87 + May run concurrently with one operation in the other
  88 + direction, subject to the class-level threading contract.
  89 + Two concurrent operations in the same direction are
  90 + undefined.
  91 +
80   @param buffers The buffer sequence to read data into. 92   @param buffers The buffer sequence to read data into.
81   93  
82   @return An awaitable yielding `(error_code,std::size_t)`. 94   @return An awaitable yielding `(error_code,std::size_t)`.
83   */ 95   */
84   template<capy::MutableBufferSequence Buffers> 96   template<capy::MutableBufferSequence Buffers>
MISUBC 85   auto read_some(Buffers const& buffers) 97   auto read_some(Buffers const& buffers)
86   { 98   {
MISUBC 87   return do_read_some(buffers); 99   return do_read_some(buffers);
88   } 100   }
89   101  
90   /** Initiate an asynchronous write operation. 102   /** Initiate an asynchronous write operation.
91   103  
92   Encrypts and writes data from the provided buffer sequence. 104   Encrypts and writes data from the provided buffer sequence.
93   The operation completes when at least one byte has been 105   The operation completes when at least one byte has been
94   written, or an error occurs. 106   written, or an error occurs.
95   107  
96   This non-virtual template wrapper satisfies the `capy::Stream` 108   This non-virtual template wrapper satisfies the `capy::Stream`
97   concept by delegating to the virtual `do_write_some`. 109   concept by delegating to the virtual `do_write_some`.
98   110  
  111 + @par Thread Safety
  112 + May run concurrently with one operation in the other
  113 + direction, subject to the class-level threading contract.
  114 + Two concurrent operations in the same direction are
  115 + undefined.
  116 +
99   @param buffers The buffer sequence containing data to write. 117   @param buffers The buffer sequence containing data to write.
100   118  
101   @return An awaitable yielding `(error_code,std::size_t)`. 119   @return An awaitable yielding `(error_code,std::size_t)`.
102   */ 120   */
103   template<capy::ConstBufferSequence Buffers> 121   template<capy::ConstBufferSequence Buffers>
MISUBC 104   auto write_some(Buffers const& buffers) 122   auto write_some(Buffers const& buffers)
105   { 123   {
MISUBC 106   return do_write_some(buffers); 124   return do_write_some(buffers);
107   } 125   }
108   126  
109 - /** Perform the TLS handshake asynchronously. 127 + /** Asynchronously perform the TLS handshake.
110   128  
111   Initiates the TLS handshake process. For client connections, 129   Initiates the TLS handshake process. For client connections,
112   this sends the ClientHello and processes the server's response. 130   this sends the ClientHello and processes the server's response.
113   For server connections, this waits for the ClientHello and 131   For server connections, this waits for the ClientHello and
114   sends the server's response. 132   sends the server's response.
115   133  
116   A handshake attempt, successful or not, consumes the stream 134   A handshake attempt, successful or not, consumes the stream
117   state: a subsequent call behaves as if `reset()` had been 135   state: a subsequent call behaves as if `reset()` had been
118   called first and performs a fresh handshake using the 136   called first and performs a fresh handshake using the
119   current configuration. 137   current configuration.
120   138  
  139 + @par Preconditions
  140 + The underlying stream must be connected. No other TLS
  141 + operation may be in progress on this stream.
  142 +
121   @param role The handshake role, client or server. 143   @param role The handshake role, client or server.
122   144  
123   @return An awaitable yielding `(error_code)`. 145   @return An awaitable yielding `(error_code)`.
124   */ 146   */
125   virtual capy::io_task<> handshake(tls_role role) = 0; 147   virtual capy::io_task<> handshake(tls_role role) = 0;
126   148  
127 - /** Perform a graceful TLS shutdown asynchronously. 149 + /** Asynchronously perform a graceful TLS shutdown.
128   150  
129   Initiates the TLS shutdown sequence by sending a close_notify 151   Initiates the TLS shutdown sequence by sending a close_notify
130   alert and waiting for the peer's close_notify response. 152   alert and waiting for the peer's close_notify response.
131   153  
  154 + @par Preconditions
  155 + A handshake must have completed successfully. May overlap
  156 + a pending read. No concurrent write may be in progress.
  157 +
  158 + @par Postconditions
  159 + If the transport ends before the peer's close_notify is
  160 + received, the result is `capy::error::stream_truncated`, not
  161 + success: an unannounced close is indistinguishable from a
  162 + truncation attack and must not be reported as a clean
  163 + shutdown. A shutdown stopped mid-flight reports canceled;
  164 + any other transport error propagates unchanged.
  165 +
132   @return An awaitable yielding `(error_code)`. 166   @return An awaitable yielding `(error_code)`.
133   */ 167   */
134   virtual capy::io_task<> shutdown() = 0; 168   virtual capy::io_task<> shutdown() = 0;
135   169  
136   /** Reset TLS session state for reuse. 170   /** Reset TLS session state for reuse.
137   171  
138   Releases TLS session state including session keys and peer 172   Releases TLS session state including session keys and peer
139   certificates, returning the stream to a state where 173   certificates, returning the stream to a state where
140   `handshake()` can be called again. Internal memory 174   `handshake()` can be called again. Internal memory
141   allocations (I/O buffers) are preserved. 175   allocations (I/O buffers) are preserved.
142   176  
143   Calling `handshake()` on a previously-used stream 177   Calling `handshake()` on a previously-used stream
144   implicitly performs a reset first, so explicit calls 178   implicitly performs a reset first, so explicit calls
145   are only needed to eagerly release session state. 179   are only needed to eagerly release session state.
146   180  
147   @par Preconditions 181   @par Preconditions
148   No TLS operation (handshake, read, write, shutdown) is 182   No TLS operation (handshake, read, write, shutdown) is
149   in progress. 183   in progress.
150   184  
151   @par Thread Safety 185   @par Thread Safety
152   Not thread safe. The caller must ensure no concurrent 186   Not thread safe. The caller must ensure no concurrent
153   operations are in progress on this stream. 187   operations are in progress on this stream.
154   188  
155   @note If called mid-session before `shutdown()`, pending 189   @note If called mid-session before `shutdown()`, pending
156   TLS data is discarded and the peer will observe a 190   TLS data is discarded and the peer will observe a
157   truncated stream. 191   truncated stream.
158   */ 192   */
159   virtual void reset() = 0; 193   virtual void reset() = 0;
160   194  
161   /** Set the peer hostname for SNI and certificate verification. 195   /** Set the peer hostname for SNI and certificate verification.
162   196  
163   Configures the hostname sent in the TLS Server Name 197   Configures the hostname sent in the TLS Server Name
164   Indication extension and matched against the peer 198   Indication extension and matched against the peer
165   certificate during verification. The value takes effect 199   certificate during verification. The value takes effect
166   at the next `handshake()`; an established session is not 200   at the next `handshake()`; an established session is not
167   affected. It persists across `reset()`, so a stream reused 201   affected. It persists across `reset()`, so a stream reused
168   to reach a different host must set the new name before 202   to reach a different host must set the new name before
169   handshaking again. 203   handshaking again.
170   204  
171   An empty hostname (the default) disables SNI and hostname 205   An empty hostname (the default) disables SNI and hostname
172   verification. 206   verification.
173   207  
174   If `hostname` is an IP literal (IPv4 or IPv6), it is matched 208   If `hostname` is an IP literal (IPv4 or IPv6), it is matched
175   against the certificate's iPAddress entries instead of its 209   against the certificate's iPAddress entries instead of its
176   DNS names, and no SNI is sent (RFC 6066 excludes literals). 210   DNS names, and no SNI is sent (RFC 6066 excludes literals).
177   A backend build that cannot match iPAddress entries fails the 211   A backend build that cannot match iPAddress entries fails the
178   handshake with `std::errc::function_not_supported` rather 212   handshake with `std::errc::function_not_supported` rather
179   than skip verification. 213   than skip verification.
180   214  
181   @par Postconditions 215   @par Postconditions
182   The next `handshake()` uses `hostname` for SNI and 216   The next `handshake()` uses `hostname` for SNI and
183   certificate verification, or neither if it is empty. 217   certificate verification, or neither if it is empty.
184   218  
185   @note The hostname is used for client handshakes only; 219   @note The hostname is used for client handshakes only;
186   it is ignored when handshaking as a server. 220   it is ignored when handshaking as a server.
187   221  
188   @param hostname The peer hostname, or empty to disable. 222   @param hostname The peer hostname, or empty to disable.
189   */ 223   */
190   virtual void set_hostname(std::string_view hostname) = 0; 224   virtual void set_hostname(std::string_view hostname) = 0;
191   225  
192 - /** Returns a reference to the underlying stream. 226 + /** Return a reference to the underlying stream.
193   227  
194   Provides access to the type-erased underlying stream for 228   Provides access to the type-erased underlying stream for
195   operations like cancellation or accessing native handles. 229   operations like cancellation or accessing native handles.
196   230  
197   @warning Do not reseat (assign to) the returned reference. 231   @warning Do not reseat (assign to) the returned reference.
198   The TLS implementation holds internal state bound to 232   The TLS implementation holds internal state bound to
199   the original stream. Replacing it causes undefined 233   the original stream. Replacing it causes undefined
200   behavior. 234   behavior.
201   235  
202   @return Reference to the wrapped stream. 236   @return Reference to the wrapped stream.
203   */ 237   */
204   virtual capy::any_stream& next_layer() noexcept = 0; 238   virtual capy::any_stream& next_layer() noexcept = 0;
205   239  
206 - /** Returns a const reference to the underlying stream. 240 + /** Return a const reference to the underlying stream.
207   241  
208   @return Const reference to the wrapped stream. 242   @return Const reference to the wrapped stream.
209   */ 243   */
210   virtual capy::any_stream const& next_layer() const noexcept = 0; 244   virtual capy::any_stream const& next_layer() const noexcept = 0;
211   245  
212 - /** Returns the name of the TLS backend. 246 + /** Return the name of the TLS backend.
213   247  
214   @return A string identifying the TLS implementation, 248   @return A string identifying the TLS implementation,
215   such as "openssl" or "wolfssl". 249   such as "openssl" or "wolfssl".
216   */ 250   */
217   virtual std::string_view name() const noexcept = 0; 251   virtual std::string_view name() const noexcept = 0;
218   252  
219 - /** Returns the ALPN protocol negotiated during the handshake. 253 + /** Return the ALPN protocol negotiated during the handshake.
220   254  
221   Application-Layer Protocol Negotiation selects a single 255   Application-Layer Protocol Negotiation selects a single
222   application protocol (for example `"h2"` or `"http/1.1"`) 256   application protocol (for example `"h2"` or `"http/1.1"`)
223   during the TLS handshake, from the list supplied via 257   during the TLS handshake, from the list supplied via
224   @ref tls_context::set_alpn. 258   @ref tls_context::set_alpn.
225   259  
226   @return The negotiated protocol, or an empty view if no 260   @return The negotiated protocol, or an empty view if no
227   protocol was negotiated, ALPN was not offered, the 261   protocol was negotiated, ALPN was not offered, the
228   handshake has not completed, or the backend/build does 262   handshake has not completed, or the backend/build does
229   not support ALPN. 263   not support ALPN.
230   264  
231   @par Thread Safety 265   @par Thread Safety
232   Safe to call after the handshake completes; not safe to call 266   Safe to call after the handshake completes; not safe to call
233   concurrently with a handshake or reset. 267   concurrently with a handshake or reset.
234   */ 268   */
235   virtual std::string_view alpn_protocol() const noexcept { return {}; } 269   virtual std::string_view alpn_protocol() const noexcept { return {}; }
236   270  
237   protected: 271   protected:
238   tls_stream() = default; 272   tls_stream() = default;
239   273  
240   /** Virtual read implementation. 274   /** Virtual read implementation.
241   275  
242   Derived classes override this to perform TLS decryption 276   Derived classes override this to perform TLS decryption
243   and read operations. 277   and read operations.
244   278  
245   @param buffers Buffer sequence to read into. 279   @param buffers Buffer sequence to read into.
246   280  
247   @return An awaitable yielding `(error_code,std::size_t)`. 281   @return An awaitable yielding `(error_code,std::size_t)`.
248   */ 282   */
249   virtual capy::io_task<std::size_t> do_read_some( 283   virtual capy::io_task<std::size_t> do_read_some(
250   capy::detail::mutable_buffer_array<capy::detail::max_iovec_> buffers) = 0; 284   capy::detail::mutable_buffer_array<capy::detail::max_iovec_> buffers) = 0;
251   285  
252   /** Virtual write implementation. 286   /** Virtual write implementation.
253   287  
254   Derived classes override this to perform TLS encryption 288   Derived classes override this to perform TLS encryption
255   and write operations. 289   and write operations.
256   290  
257   @param buffers Buffer sequence to write from. 291   @param buffers Buffer sequence to write from.
258   292  
259   @return An awaitable yielding `(error_code,std::size_t)`. 293   @return An awaitable yielding `(error_code,std::size_t)`.
260   */ 294   */
261   virtual capy::io_task<std::size_t> do_write_some( 295   virtual capy::io_task<std::size_t> do_write_some(
262   capy::detail::const_buffer_array<capy::detail::max_iovec_> buffers) = 0; 296   capy::detail::const_buffer_array<capy::detail::max_iovec_> buffers) = 0;
263   }; 297   };
264   298  
265   } // namespace boost::corosio 299   } // namespace boost::corosio
266   300  
267   #endif 301   #endif