Clio develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
WsConnection.hpp
1//------------------------------------------------------------------------------
2/*
3 This file is part of clio: https://github.com/XRPLF/clio
4 Copyright (c) 2024, the clio developers.
5
6 Permission to use, copy, modify, and distribute this software for any
7 purpose with or without fee is hereby granted, provided that the above
8 copyright notice and this permission notice appear in all copies.
9
10 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17*/
18//==============================================================================
19
20#pragma once
21
22#include "util/Taggable.hpp"
23#include "util/build/Build.hpp"
24#include "web/ng/Connection.hpp"
25#include "web/ng/Error.hpp"
26#include "web/ng/Request.hpp"
27#include "web/ng/Response.hpp"
28#include "web/ng/impl/Concepts.hpp"
29
30#include <boost/asio/buffer.hpp>
31#include <boost/asio/ip/tcp.hpp>
32#include <boost/asio/spawn.hpp>
33#include <boost/asio/ssl/context.hpp>
34#include <boost/asio/ssl/stream.hpp>
35#include <boost/beast/core/buffers_to_string.hpp>
36#include <boost/beast/core/flat_buffer.hpp>
37#include <boost/beast/core/role.hpp>
38#include <boost/beast/core/tcp_stream.hpp>
39#include <boost/beast/http/field.hpp>
40#include <boost/beast/http/message.hpp>
41#include <boost/beast/http/string_body.hpp>
42#include <boost/beast/ssl.hpp>
43#include <boost/beast/websocket/rfc6455.hpp>
44#include <boost/beast/websocket/stream.hpp>
45#include <boost/beast/websocket/stream_base.hpp>
46
47#include <chrono>
48#include <memory>
49#include <optional>
50#include <string>
51#include <utility>
52
53namespace web::ng::impl {
54
56public:
58
59 virtual std::optional<Error>
60 sendBuffer(boost::asio::const_buffer buffer, boost::asio::yield_context yield) = 0;
61};
62
63template <typename StreamType>
65 boost::beast::websocket::stream<StreamType> stream_;
66 boost::beast::http::request<boost::beast::http::string_body> initialRequest_;
67 bool closed_{false};
68
69public:
71 boost::asio::ip::tcp::socket socket,
72 std::string ip,
73 boost::beast::flat_buffer buffer,
74 boost::beast::http::request<boost::beast::http::string_body> initialRequest,
75 util::TagDecoratorFactory const& tagDecoratorFactory
76 )
78 : WsConnectionBase(std::move(ip), std::move(buffer), tagDecoratorFactory)
79 , stream_(std::move(socket))
80 , initialRequest_(std::move(initialRequest))
81 {
82 setupWsStream();
83 }
84
86 boost::asio::ip::tcp::socket socket,
87 std::string ip,
88 boost::beast::flat_buffer buffer,
89 boost::asio::ssl::context& sslContext,
90 boost::beast::http::request<boost::beast::http::string_body> initialRequest,
91 util::TagDecoratorFactory const& tagDecoratorFactory
92 )
94 : WsConnectionBase(std::move(ip), std::move(buffer), tagDecoratorFactory)
95 , stream_(std::move(socket), sslContext)
96 , initialRequest_(std::move(initialRequest))
97 {
98 setupWsStream();
99 }
100
101 std::optional<Error>
102 performHandshake(boost::asio::yield_context yield)
103 {
104 Error error;
105 stream_.async_accept(initialRequest_, yield[error]);
106 if (error)
107 return error;
108 return std::nullopt;
109 }
110
111 bool
112 wasUpgraded() const override
113 {
114 return true;
115 }
116
117 std::optional<Error>
118 sendBuffer(boost::asio::const_buffer buffer, boost::asio::yield_context yield) override
119 {
120 boost::beast::websocket::stream_base::timeout timeoutOption{};
121 stream_.get_option(timeoutOption);
122
123 boost::system::error_code error;
124 stream_.async_write(buffer, yield[error]);
125 if (error)
126 return error;
127 return std::nullopt;
128 }
129
130 void
131 setTimeout(std::chrono::steady_clock::duration newTimeout) override
132 {
133 boost::beast::websocket::stream_base::timeout wsTimeout =
134 boost::beast::websocket::stream_base::timeout::suggested(boost::beast::role_type::server);
135 wsTimeout.idle_timeout = newTimeout;
136 wsTimeout.handshake_timeout = newTimeout;
137 stream_.set_option(wsTimeout);
138 }
139
140 std::optional<Error>
141 send(Response response, boost::asio::yield_context yield) override
142 {
143 return sendBuffer(response.asWsResponse(), yield);
144 }
145
146 std::expected<Request, Error>
147 receive(boost::asio::yield_context yield) override
148 {
149 Error error;
150 stream_.async_read(buffer_, yield[error]);
151 if (error)
152 return std::unexpected{error};
153
154 auto request = boost::beast::buffers_to_string(buffer_.data());
155 buffer_.consume(buffer_.size());
156
157 return Request{std::move(request), initialRequest_};
158 }
159
160 void
161 close(boost::asio::yield_context yield) override
162 {
163 if (closed_)
164 return;
165
166 // This should be set before the async_close(). Otherwise there is a possibility to have multiple coroutines
167 // waiting on async_close(), but only one will be woken up after the actual close happened, others will hang.
168 closed_ = true;
169
170 boost::system::error_code error; // unused
171 stream_.async_close(boost::beast::websocket::close_code::normal, yield[error]);
172 }
173
174private:
175 void
176 setupWsStream()
177 {
178 // Disable the timeout. The websocket::stream uses its own timeout settings.
179 boost::beast::get_lowest_layer(stream_).expires_never();
181 stream_.set_option(
182 boost::beast::websocket::stream_base::decorator([](boost::beast::websocket::response_type& res) {
183 res.set(boost::beast::http::field::server, util::build::getClioFullVersionString());
184 })
185 );
186 }
187};
188
189using PlainWsConnection = WsConnection<boost::beast::tcp_stream>;
190using SslWsConnection = WsConnection<boost::asio::ssl::stream<boost::beast::tcp_stream>>;
191
192std::expected<std::unique_ptr<PlainWsConnection>, Error>
193makePlainWsConnection(
194 boost::asio::ip::tcp::socket socket,
195 std::string ip,
196 boost::beast::flat_buffer buffer,
197 boost::beast::http::request<boost::beast::http::string_body> request,
198 util::TagDecoratorFactory const& tagDecoratorFactory,
199 boost::asio::yield_context yield
200);
201
202std::expected<std::unique_ptr<SslWsConnection>, Error>
203makeSslWsConnection(
204 boost::asio::ip::tcp::socket socket,
205 std::string ip,
206 boost::beast::flat_buffer buffer,
207 boost::beast::http::request<boost::beast::http::string_body> request,
208 boost::asio::ssl::context& sslContext,
209 util::TagDecoratorFactory const& tagDecoratorFactory,
210 boost::asio::yield_context yield
211);
212
213} // namespace web::ng::impl
A factory for TagDecorator instantiation.
Definition Taggable.hpp:169
std::string const & ip() const
Get the ip of the client.
Definition Connection.cpp:37
A class representing a connection to a client.
Definition Connection.hpp:100
Connection(std::string ip, boost::beast::flat_buffer buffer, util::TagDecoratorFactory const &tagDecoratorFactory)
Construct a new Connection object.
Definition Connection.cpp:48
static constexpr std::chrono::steady_clock::duration kDEFAULT_TIMEOUT
The default timeout for send, receive, and close operations.
Definition Connection.hpp:109
Represents an HTTP or WebSocket request.
Definition Request.hpp:37
Represents an HTTP or Websocket response.
Definition Response.hpp:40
boost::asio::const_buffer asWsResponse() const &
Get the message of the response as a const buffer.
Definition Response.cpp:188
Definition WsConnection.hpp:55
Definition WsConnection.hpp:64
std::optional< Error > send(Response response, boost::asio::yield_context yield) override
Send a response to the client.
Definition WsConnection.hpp:141
std::expected< Request, Error > receive(boost::asio::yield_context yield) override
Receive a request from the client.
Definition WsConnection.hpp:147
void close(boost::asio::yield_context yield) override
Gracefully close the connection.
Definition WsConnection.hpp:161
void setTimeout(std::chrono::steady_clock::duration newTimeout) override
Get the timeout for send, receive, and close operations. For WebSocket connections,...
Definition WsConnection.hpp:131
bool wasUpgraded() const override
Whether the connection was upgraded. Upgraded connections are websocket connections.
Definition WsConnection.hpp:112
Definition Concepts.hpp:33
Definition Concepts.hpp:30