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
57 run()
58 {
59 auto self = shared_from_this();
60
61 // We need to be executing within a strand to perform async operations
62 // on the I/O objects in this session.
63 boost::asio::dispatch(m_stream.get_executor(), [self](){
64 // Set the timeout.
65 boost::beast::get_lowest_layer(self->m_stream).expires_after(std::chrono::seconds(30));
66
67 // Perform the SSL handshake
68 // Note, this is the buffered version of the handshake.
69 self->m_stream.async_handshake(
70 boost::asio::ssl::stream_base::server,
71 self->m_buffer.data(),
72 boost::beast::bind_front_handler(
73 &connection_tls::on_handshake,
74 self
75 )
76 );
77 });
78 }
79
80 void
81 on_handshake(boost::beast::error_code ec, const std::size_t bytes_used)
82 {
83 if (ec) {
84 // ToDO
85 return report_err(ec, "on_handshake()");
86 }
87
88 // Consume the portion of the buffer used by the handshake
89 m_buffer.consume(bytes_used);
90
91 do_read();
92 }
93
94 void
95 do_close()
96 {
97 // Set the timeout.
98 boost::beast::get_lowest_layer(m_stream).expires_after(std::chrono::seconds(30));
99
100 // Perform the SSL shutdown
101 m_stream.async_shutdown(
102 boost::beast::bind_front_handler(
103 &connection_tls::on_shutdown,
104 shared_from_this()
105 )
106 );
107 }
108
109 void
110 on_shutdown([[maybe_unused]] boost::beast::error_code ec)
111 {
112 // At this point the connection is closed gracefully
113 }
114
115 private:
116 std::shared_ptr<boost::asio::ssl::context> m_ctx; // Keep the context alive
117 boost::beast::ssl_stream<malloy::tcp::stream<>> m_stream;
118 };
119
120}
Definition: connection_tls.hpp:17
Definition: connection.hpp:41
std::shared_ptr< spdlog::logger > logger() const noexcept
Definition: connection.hpp:184
Definition: router.hpp:103