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::client::http
9{
10
14 template<typename... ConnArgs>
16 public connection<connection_tls<ConnArgs...>, ConnArgs...>,
17 public std::enable_shared_from_this<connection_tls<ConnArgs...>>
18 {
19 using parent_t = connection<connection_tls<ConnArgs...>, ConnArgs...>;
20
21 public:
23 std::shared_ptr<spdlog::logger> logger,
24 boost::asio::io_context& io_ctx,
25 boost::asio::ssl::context& tls_ctx,
26 const std::uint64_t body_limit
27 ) :
28 parent_t(std::move(logger), body_limit),
29 m_stream(boost::asio::make_strand(io_ctx), tls_ctx) // ToDo: make_strand() necessary since we're using coroutines?
30 {
31 }
32
33 // Called by base class
34 [[nodiscard]]
35 boost::beast::ssl_stream<malloy::tcp::stream<>>&
36 stream()
37 {
38 return m_stream;
39 }
40
41 // Called by base class
42 // ToDo: Return error code!
43 boost::asio::awaitable<void>
44 hook_connected()
45 {
46 // Perform the TLS handshake
47 parent_t::set_stream_timeout(std::chrono::seconds(30)); // ToDo: Do not hard-code!
48 co_await m_stream.async_handshake(boost::asio::ssl::stream_base::client);
49 }
50
59 set_hostname(const std::string_view hostname)
60 {
61 // Note: We copy the std::string_view into an std::string as the underlying OpenSSL API expects C-strings.
62 const std::string str{ hostname };
63
64 // Specify SNI hostname (This is used by many hosts to figure out to which host we actually want to talk to)
65 if (!SSL_set_tlsext_host_name(m_stream.native_handle(), str.c_str()))
66 return {static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};
67
68 // Specify the expected hostname for the peer certificate verification
69 if (!SSL_set1_host(m_stream.native_handle(), str.c_str())) {
70 return {static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};
71 }
72
73 return { };
74 }
75
76 private:
77 boost::beast::ssl_stream<malloy::tcp::stream<>> m_stream;
78 };
79}
Definition: connection_tls.hpp:18
malloy::error_code set_hostname(const std::string_view hostname)
Definition: connection_tls.hpp:59
Definition: connection.hpp:34
boost::beast::error_code error_code
Error code used to signify errors without throwing. Truthy means it holds an error.
Definition: error.hpp:9