|
7 | 7 | #include "base/logger.hpp"
|
8 | 8 | #include "base/configuration.hpp"
|
9 | 9 | #include "base/convert.hpp"
|
| 10 | +#include "base/io-engine.hpp" |
10 | 11 | #include <boost/asio/ssl/context.hpp>
|
11 | 12 | #include <boost/asio/ssl/verify_context.hpp>
|
12 | 13 | #include <boost/asio/ssl/verify_mode.hpp>
|
@@ -103,3 +104,45 @@ void UnbufferedAsioTlsStream::BeforeHandshake(handshake_type type)
|
103 | 104 | }
|
104 | 105 | #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
|
105 | 106 | }
|
| 107 | + |
| 108 | +/** |
| 109 | + * Forcefully close the connection, typically (details are up to the operating system) using a TCP RST. |
| 110 | + */ |
| 111 | +void AsioTlsStream::ForceDisconnect() |
| 112 | +{ |
| 113 | + boost::system::error_code ec; |
| 114 | + |
| 115 | + // Close the socket. In case the connection wasn't shut down cleanly by GracefulDisconnect(), the operating system |
| 116 | + // will typically terminate the connection with a TCP RST. Otherwise, this just releases the file descriptor. |
| 117 | + lowest_layer().close(ec); |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Try to cleanly shut down the connection. This involves sending a TLS close_notify shutdown alert and terminating the |
| 122 | + * underlying TCP connection. Sending these additional messages can block, hence the method takes a yield context and |
| 123 | + * internally implements a timeout of 10 seconds for the operation after which the connection is forcefully terminated |
| 124 | + * using ForceDisconnect(). |
| 125 | + * |
| 126 | + * @param strand Asio strand used for other operations on this connection. |
| 127 | + * @param yc Yield context for Asio coroutines |
| 128 | + */ |
| 129 | +void AsioTlsStream::GracefulDisconnect(boost::asio::io_context::strand strand, boost::asio::yield_context yc) |
| 130 | +{ |
| 131 | + boost::system::error_code ec; |
| 132 | + |
| 133 | + Timeout::Ptr shutdownTimeout(new Timeout(strand.context(), strand, boost::posix_time::seconds(10), |
| 134 | + [this, keepAlive = AsioTlsStream::Ptr(this)](boost::asio::yield_context yc) { |
| 135 | + // Forcefully terminate the connection if async_shutdown() blocked more than 10 seconds. |
| 136 | + ForceDisconnect(); |
| 137 | + } |
| 138 | + )); |
| 139 | + // Close the TLS connection, effectively uses SSL_shutdown() to send a close_notify shutdown alert to the peer. |
| 140 | + next_layer().async_shutdown(yc[ec]); |
| 141 | + shutdownTimeout->Cancel(); |
| 142 | + |
| 143 | + // Shut down the TCP connection. |
| 144 | + lowest_layer().shutdown(lowest_layer_type::shutdown_both, ec); |
| 145 | + |
| 146 | + // Clean up the connection (closes the file descriptor). |
| 147 | + ForceDisconnect(); |
| 148 | +} |
0 commit comments