10#ifndef BOTAN_ASIO_STREAM_H_
11#define BOTAN_ASIO_STREAM_H_
13#include <botan/asio_compat.h>
14#if !defined(BOTAN_FOUND_COMPATIBLE_BOOST_ASIO_VERSION)
15 #error Available boost headers are too old for the boost asio stream.
18 #include <botan/asio_async_ops.h>
19 #include <botan/asio_context.h>
20 #include <botan/asio_error.h>
22 #include <botan/tls_callbacks.h>
23 #include <botan/tls_channel.h>
24 #include <botan/tls_client.h>
25 #include <botan/tls_magic.h>
26 #include <botan/tls_server.h>
30 #define BOOST_ASIO_DISABLE_SERIAL_PORT
31 #include <boost/asio.hpp>
32 #include <boost/beast/core.hpp>
36 #include <type_traits>
40template <
class SL,
class C>
58class StreamCallbacks :
public Callbacks {
62 void tls_emit_data(std::span<const uint8_t> data)
final {
63 m_send_buffer.commit(boost::asio::buffer_copy(m_send_buffer.prepare(data.size()),
64 boost::asio::buffer(data.data(), data.size())));
67 void tls_record_received(uint64_t, std::span<const uint8_t> data)
final {
68 m_receive_buffer.commit(boost::asio::buffer_copy(m_receive_buffer.prepare(data.size()),
69 boost::asio::const_buffer(data.data(), data.size())));
72 bool tls_peer_closed_connection()
final {
86 void tls_alert(TLS::Alert alert)
final {
87 if(alert.is_fatal() || alert.type() == TLS::AlertType::CloseNotify) {
92 m_alert_from_peer = alert;
96 void tls_verify_cert_chain(
const std::vector<X509_Certificate>& cert_chain,
97 const std::vector<std::optional<OCSP::Response>>& ocsp_responses,
98 const std::vector<Certificate_Store*>& trusted_roots,
100 std::string_view hostname,
101 const TLS::Policy& policy)
override {
102 auto ctx = m_context.lock();
104 if(ctx && ctx->has_verify_callback()) {
105 ctx->get_verify_callback()(cert_chain, ocsp_responses, trusted_roots, usage, hostname, policy);
107 Callbacks::tls_verify_cert_chain(cert_chain, ocsp_responses, trusted_roots, usage, hostname, policy);
113 template <
class SL,
class C>
116 void set_context(std::weak_ptr<Botan::TLS::Context> context) { m_context = std::move(context); }
118 void consume_send_buffer() { m_send_buffer.consume(m_send_buffer.size()); }
120 boost::beast::flat_buffer& send_buffer() {
return m_send_buffer; }
122 const boost::beast::flat_buffer& send_buffer()
const {
return m_send_buffer; }
124 boost::beast::flat_buffer& receive_buffer() {
return m_receive_buffer; }
126 const boost::beast::flat_buffer& receive_buffer()
const {
return m_receive_buffer; }
128 bool shutdown_received()
const {
129 return m_alert_from_peer && m_alert_from_peer->type() == AlertType::CloseNotify;
132 std::optional<Alert> alert_from_peer()
const {
return m_alert_from_peer; }
135 std::optional<Alert> m_alert_from_peer;
136 boost::beast::flat_buffer m_receive_buffer;
137 boost::beast::flat_buffer m_send_buffer;
139 std::weak_ptr<TLS::Context> m_context;
145concept basic_completion_token = boost::asio::completion_token_for<
T, void(boost::system::error_code)>;
148concept byte_size_completion_token = boost::asio::completion_token_for<
T, void(boost::system::error_code,
size_t)>;
158template <
class StreamLayer,
class ChannelT = Channel>
161 using default_completion_token =
162 boost::asio::default_completion_token_t<boost::beast::executor_type<StreamLayer>>;
180 template <
typename... Args>
181 explicit Stream(std::shared_ptr<Context> context, std::shared_ptr<StreamCallbacks> callbacks, Args&&... args) :
182 m_context(std::move(context)),
183 m_nextLayer(std::forward<Args>(args)...),
184 m_core(std::move(callbacks)),
186 m_input_buffer(m_input_buffer_space.data(), m_input_buffer_space.size()) {
187 m_core->set_context(m_context);
196 template <
typename... Args>
197 explicit Stream(std::shared_ptr<Context> context, Args&&... args) :
198 Stream(std::move(context), std::make_shared<StreamCallbacks>(), std::forward<Args>(args)...) {}
211 template <
typename Arg>
212 explicit Stream(Arg&& arg,
213 std::shared_ptr<Context> context,
214 std::shared_ptr<StreamCallbacks> callbacks = std::make_shared<StreamCallbacks>()) :
215 Stream(std::move(context), std::move(callbacks), std::forward<Arg>(arg)) {}
217 #if defined(BOTAN_HAS_HAS_DEFAULT_TLS_CONTEXT)
228 template <
typename... Args>
229 explicit Stream(Server_Information server_info, Args&&... args) :
230 Stream(std::make_shared<Context>(std::move(server_info)), std::forward<Args>(args)...) {}
233 virtual ~Stream() =
default;
235 Stream(Stream&& other) =
default;
236 Stream& operator=(Stream&& other) =
default;
238 Stream(
const Stream& other) =
delete;
239 Stream& operator=(
const Stream& other) =
delete;
245 using next_layer_type =
typename std::remove_reference<StreamLayer>::type;
247 const next_layer_type& next_layer()
const {
return m_nextLayer; }
249 next_layer_type& next_layer() {
return m_nextLayer; }
251 using lowest_layer_type =
typename boost::beast::lowest_layer_type<StreamLayer>;
253 lowest_layer_type& lowest_layer() {
return boost::beast::get_lowest_layer(m_nextLayer); }
255 const lowest_layer_type& lowest_layer()
const {
return boost::beast::get_lowest_layer(m_nextLayer); }
257 using executor_type =
typename next_layer_type::executor_type;
259 executor_type get_executor() noexcept {
return m_nextLayer.get_executor(); }
261 using native_handle_type =
typename std::add_pointer<ChannelT>::type;
263 native_handle_type native_handle() {
265 return m_native_handle.get();
281 void set_verify_callback(Context::Verify_Callback callback) {
282 m_context->set_verify_callback(std::move(callback));
291 void set_verify_callback(Context::Verify_Callback callback, boost::system::error_code& ec) {
293 m_context->set_verify_callback(std::move(callback));
297 void set_verify_depth(
int depth) {
299 throw Not_Implemented(
"set_verify_depth is not implemented");
307 void set_verify_depth(
int depth, boost::system::error_code& ec) {
309 ec = ErrorType::NotImplemented;
313 template <
typename verify_mode>
314 void set_verify_mode(verify_mode v) {
316 throw Not_Implemented(
"set_verify_mode is not implemented");
324 template <
typename verify_mode>
325 void set_verify_mode(verify_mode v, boost::system::error_code& ec) {
327 ec = ErrorType::NotImplemented;
342 void handshake(Connection_Side side) {
343 boost::system::error_code ec;
345 boost::asio::detail::throw_error(ec,
"handshake");
356 void handshake(Connection_Side side, boost::system::error_code& ec) {
357 setup_native_handle(side, ec);
366 if(has_data_to_send()) {
367 send_pending_encrypted_data(ec);
372 if(native_handle()->is_handshake_complete()) {
380 handle_tls_protocol_errors(ec);
386 read_and_process_encrypted_data_from_peer(ec);
401 template <detail::basic_completion_token CompletionToken = default_completion_token>
403 CompletionToken&& completion_token = default_completion_token{}) {
404 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>(
405 [
this](
auto&& completion_handler, TLS::Connection_Side connection_side) {
406 using completion_handler_t = std::decay_t<
decltype(completion_handler)>;
408 boost::system::error_code ec;
409 setup_native_handle(connection_side, ec);
411 detail::AsyncHandshakeOperation<completion_handler_t, Stream> op{
412 std::forward<completion_handler_t>(completion_handler), *
this, ec};
419 template <
typename ConstBufferSequence, detail::basic_completion_token BufferedHandshakeHandler>
420 auto async_handshake(Connection_Side side,
421 const ConstBufferSequence& buffers,
422 BufferedHandshakeHandler&& handler) {
424 throw Not_Implemented(
"buffered async handshake is not implemented");
441 void shutdown(boost::system::error_code& ec) {
442 try_with_error_code([&] { native_handle()->close(); }, ec);
444 send_pending_encrypted_data(ec);
458 boost::system::error_code ec;
460 boost::asio::detail::throw_error(ec,
"shutdown");
471 template <
typename Handler,
typename Executor>
473 void operator()(boost::system::error_code ec, std::size_t) { handler(ec); }
475 using executor_type = boost::asio::associated_executor_t<Handler, Executor>;
477 executor_type get_executor() const noexcept {
478 return boost::asio::get_associated_executor(handler, io_executor);
481 using allocator_type = boost::asio::associated_allocator_t<Handler>;
483 allocator_type get_allocator() const noexcept {
return boost::asio::get_associated_allocator(handler); }
486 Executor io_executor;
500 template <detail::basic_completion_token CompletionToken = default_completion_token>
501 auto async_shutdown(CompletionToken&& completion_token = default_completion_token{}) {
502 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>(
503 [
this](
auto&& completion_handler) {
504 using completion_handler_t = std::decay_t<
decltype(completion_handler)>;
506 boost::system::error_code ec;
507 try_with_error_code([&] { native_handle()->close(); }, ec);
509 using write_handler_t = Wrapper<completion_handler_t, typename Stream::executor_type>;
511 TLS::detail::AsyncWriteOperation<write_handler_t, Stream> op{
512 write_handler_t{std::forward<completion_handler_t>(completion_handler), get_executor()},
514 boost::asio::buffer_size(send_buffer()),
535 template <
typename MutableBufferSequence>
536 std::size_t read_some(
const MutableBufferSequence& buffers, boost::system::error_code& ec) {
542 if(has_received_data()) {
543 return copy_received_data(buffers);
552 handle_tls_protocol_errors(ec);
559 read_and_process_encrypted_data_from_peer(ec);
576 template <
typename MutableBufferSequence>
577 std::size_t read_some(
const MutableBufferSequence& buffers) {
578 boost::system::error_code ec;
579 const auto n = read_some(buffers, ec);
580 boost::asio::detail::throw_error(ec,
"read_some");
594 template <
typename ConstBufferSequence>
595 std::size_t write_some(
const ConstBufferSequence& buffers, boost::system::error_code& ec) {
596 tls_encrypt(buffers, ec);
597 send_pending_encrypted_data(ec);
598 return !ec ? boost::asio::buffer_size(buffers) : 0;
611 template <
typename ConstBufferSequence>
612 std::size_t write_some(
const ConstBufferSequence& buffers) {
613 boost::system::error_code ec;
614 const auto n = write_some(buffers, ec);
615 boost::asio::detail::throw_error(ec,
"write_some");
627 template <
typename ConstBufferSequence,
628 detail::byte_size_completion_token CompletionToken = default_completion_token>
629 auto async_write_some(
const ConstBufferSequence& buffers,
630 CompletionToken&& completion_token = default_completion_token{}) {
631 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::size_t)>(
632 [
this](
auto&& completion_handler,
const auto& bufs) {
633 using completion_handler_t = std::decay_t<
decltype(completion_handler)>;
635 boost::system::error_code ec;
636 tls_encrypt(bufs, ec);
641 m_core->send_buffer().consume(m_core->send_buffer().size());
644 detail::AsyncWriteOperation<completion_handler_t, Stream> op{
645 std::forward<completion_handler_t>(completion_handler),
647 ec ? 0 : boost::asio::buffer_size(bufs),
663 template <
typename MutableBufferSequence,
664 detail::byte_size_completion_token CompletionToken = default_completion_token>
665 auto async_read_some(
const MutableBufferSequence& buffers,
666 CompletionToken&& completion_token = default_completion_token{}) {
667 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::size_t)>(
668 [
this](
auto&& completion_handler,
const auto& bufs) {
669 using completion_handler_t = std::decay_t<
decltype(completion_handler)>;
671 detail::AsyncReadOperation<completion_handler_t, Stream, MutableBufferSequence> op{
672 std::forward<completion_handler_t>(completion_handler), *
this, bufs};
684 bool shutdown_received()
const {
return m_core->shutdown_received(); }
687 template <
class H,
class S,
class M,
class A>
688 friend class detail::AsyncReadOperation;
689 template <
class H,
class S,
class A>
690 friend class detail::AsyncWriteOperation;
691 template <
class H,
class S,
class A>
692 friend class detail::AsyncHandshakeOperation;
694 const boost::asio::mutable_buffer& input_buffer() {
return m_input_buffer; }
696 boost::asio::const_buffer send_buffer()
const {
return m_core->send_buffer().data(); }
699 bool has_received_data()
const {
return m_core->receive_buffer().size() > 0; }
702 template <
typename MutableBufferSequence>
703 std::size_t copy_received_data(MutableBufferSequence buffers) {
708 const auto copiedBytes = boost::asio::buffer_copy(buffers, m_core->receive_buffer().data());
709 m_core->receive_buffer().consume(copiedBytes);
714 bool has_data_to_send()
const {
return m_core->send_buffer().size() > 0; }
717 void consume_send_buffer(std::size_t bytesConsumed) { m_core->send_buffer().consume(bytesConsumed); }
728 void setup_native_handle(Connection_Side side, boost::system::error_code& ec) {
731 if constexpr(std::is_same<ChannelT, Channel>::value) {
736 if(side == Connection_Side::Client) {
737 m_native_handle = std::unique_ptr<Client>(
739 m_context->m_session_manager,
740 m_context->m_credentials_manager,
743 m_context->m_server_info,
744 m_context->m_policy->latest_supported_version(
false )));
746 m_native_handle = std::unique_ptr<Server>(
new Server(m_core,
747 m_context->m_session_manager,
748 m_context->m_credentials_manager,
774 void handle_tls_protocol_errors(boost::system::error_code& ec) {
783 else if(
auto error = error_from_us()) {
795 else if(
auto alert = alert_from_peer()) {
796 if(alert->type() == AlertType::CloseNotify) {
797 ec = boost::asio::error::eof;
813 void read_and_process_encrypted_data_from_peer(boost::system::error_code& ec) {
821 BOTAN_ASSERT(!has_received_data(),
"receive buffer is empty");
822 BOTAN_ASSERT(!error_from_us() && !alert_from_peer(),
"TLS session is healthy");
828 boost::asio::const_buffer read_buffer{input_buffer().data(), m_nextLayer.read_some(input_buffer(), ec)};
830 process_encrypted_data(read_buffer);
831 }
else if(ec == boost::asio::error::eof) {
832 ec = StreamError::StreamTruncated;
844 size_t send_pending_encrypted_data(boost::system::error_code& ec) {
849 auto writtenBytes = boost::asio::write(m_nextLayer, send_buffer(), ec);
850 consume_send_buffer(writtenBytes);
852 if(ec == boost::asio::error::eof && !shutdown_received()) {
854 ec = StreamError::StreamTruncated;
865 template <
typename ConstBufferSequence>
866 void tls_encrypt(
const ConstBufferSequence& buffers, boost::system::error_code& ec) {
870 std::vector<uint8_t> copy_buffer;
871 auto unpack = [©_buffer](
const auto& bufs) -> std::span<const uint8_t> {
872 const auto buffers_in_sequence =
873 std::distance(boost::asio::buffer_sequence_begin(bufs), boost::asio::buffer_sequence_end(bufs));
875 if(buffers_in_sequence == 0) {
877 }
else if(buffers_in_sequence == 1) {
878 const boost::asio::const_buffer buf = *boost::asio::buffer_sequence_begin(bufs);
879 return {
static_cast<const uint8_t*
>(buf.data()), buf.size()};
881 copy_buffer.resize(boost::asio::buffer_size(bufs));
882 boost::asio::buffer_copy(boost::asio::buffer(copy_buffer), bufs);
890 try_with_error_code([&] { native_handle()->send(
unpack(buffers)); }, ec);
904 void process_encrypted_data(
const boost::asio::const_buffer& read_buffer) {
906 "no one sent an alert before (no data allowed after that)");
914 native_handle()->received_data({
static_cast<const uint8_t*
>(read_buffer.data()), read_buffer.size()});
916 m_ec_from_last_read);
920 template <
typename Fun>
921 void try_with_error_code(Fun f, boost::system::error_code& ec) {
924 }
catch(
const TLS_Exception& e) {
926 }
catch(
const Exception& e) {
928 }
catch(
const std::exception&) {
929 ec = ErrorType::Unknown;
939 std::optional<Alert> alert_from_peer()
const {
return m_core->alert_from_peer(); }
947 boost::system::error_code error_from_us()
const {
return m_ec_from_last_read; }
950 std::shared_ptr<Context> m_context;
951 StreamLayer m_nextLayer;
953 std::shared_ptr<StreamCallbacks> m_core;
954 std::unique_ptr<ChannelT> m_native_handle;
955 boost::system::error_code m_ec_from_last_read;
958 std::vector<uint8_t> m_input_buffer_space;
959 const boost::asio::mutable_buffer m_input_buffer;
965Stream(Server_Information,
T) -> Stream<T>;
967Stream(std::shared_ptr<Context>, std::shared_ptr<StreamCallbacks>,
T) -> Stream<T>;
969Stream(std::shared_ptr<Context>,
T) -> Stream<T>;
971Stream(
T, std::shared_ptr<Context>) -> Stream<T>;
#define BOTAN_ASSERT_NOMSG(expr)
#define BOTAN_STATE_CHECK(expr)
#define BOTAN_ASSERT(expr, assertion_made)
int(* final)(unsigned char *, CTX *)
constexpr void unpack(Polynomial< PolyTrait, D > &p, ByteSourceT &byte_source, UnmapFnT unmap)