Malloy
Loading...
Searching...
No Matches
connection_tls.hpp
1#pragma once
2
3#include "connection.hpp"
4#include "../../core/tcp/stream.hpp"
5
6#include <boost/beast/ssl/ssl_stream.hpp>
7
8namespace malloy::server::http
9{
10
15 public connection<connection_tls>,
16 public std::enable_shared_from_this<connection_tls>
17 {
18 friend connection;
19
20 public:
22 std::shared_ptr<spdlog::logger> logger,
23 boost::asio::ip::tcp::socket&& socket,
24 std::shared_ptr<boost::asio::ssl::context> ctx,
25 boost::beast::flat_buffer buffer,
26 std::shared_ptr<const std::filesystem::path> doc_root,
27 std::shared_ptr<handler> router
28 ) :
30 logger,
31 std::move(buffer),
32 std::move(router),
33 std::move(doc_root)
34 ),
35 m_ctx(std::move(ctx)),
36 m_stream(std::move(socket), *m_ctx)
37 {
38 }
39
40 // Called by the base class
41 [[nodiscard]]
42 boost::beast::ssl_stream<malloy::tcp::stream<>>&
43 stream()
44 {
45 return m_stream;
46 }
47
48 [[nodiscard]]
49 boost::beast::ssl_stream<malloy::tcp::stream<>>
50 release_stream()
51 {
52 return std::move(m_stream);
53 }
54
55 // Start the asynchronous operation
56 void run()
57 {
58 auto self = shared_from_this();
59
60 // We need to be executing within a strand to perform async operations
61 // on the I/O objects in this session.
62 boost::asio::dispatch(m_stream.get_executor(), [self](){
63 // Set the timeout.
64 boost::beast::get_lowest_layer(self->m_stream).expires_after(std::chrono::seconds(30));
65
66 // Perform the SSL handshake
67 // Note, this is the buffered version of the handshake.
68 self->m_stream.async_handshake(
69 boost::asio::ssl::stream_base::server,
70 self->m_buffer.data(),
71 boost::beast::bind_front_handler(
72 &connection_tls::on_handshake,
73 self
74 )
75 );
76 });
77 }
78
79 void on_handshake(boost::beast::error_code ec, const std::size_t bytes_used)
80 {
81 if (ec) {
82 // ToDO
83 return report_err(ec, "on_handshake()");
84 }
85
86 // Consume the portion of the buffer used by the handshake
87 m_buffer.consume(bytes_used);
88
89 do_read();
90 }
91
92 void do_close()
93 {
94 // Set the timeout.
95 boost::beast::get_lowest_layer(m_stream).expires_after(std::chrono::seconds(30));
96
97 // Perform the SSL shutdown
98 m_stream.async_shutdown(
99 boost::beast::bind_front_handler(
100 &connection_tls::on_shutdown,
101 shared_from_this()
102 )
103 );
104 }
105
106 void on_shutdown([[maybe_unused]] boost::beast::error_code ec)
107 {
108 // At this point the connection is closed gracefully
109 }
110
111 private:
112 std::shared_ptr<boost::asio::ssl::context> m_ctx; // Keep the context alive
113 boost::beast::ssl_stream<malloy::tcp::stream<>> m_stream;
114 };
115
116}
Definition: connection_tls.hpp:17
Definition: connection.hpp:41
std::shared_ptr< spdlog::logger > logger() const noexcept
Definition: connection.hpp:184
Definition: router.hpp:104