blob: 72d0684d6e2d6a95712334f46678d1c4cbef7bb7 [file] [log] [blame]
V-Sanjana88ada3b2023-04-13 15:18:31 +05301#pragma once
Ed Tanous41fe81c2024-09-02 15:08:41 -07002#include "boost_formatters.hpp"
Ed Tanousb2896142024-01-31 15:25:47 -08003#include "http_body.hpp"
V-Sanjana88ada3b2023-04-13 15:18:31 +05304#include "http_request.hpp"
5#include "http_response.hpp"
6
V-Sanjana88ada3b2023-04-13 15:18:31 +05307#include <boost/asio/buffer.hpp>
8#include <boost/asio/steady_timer.hpp>
9#include <boost/beast/core/multi_buffer.hpp>
V-Sanjana88ada3b2023-04-13 15:18:31 +053010#include <boost/beast/websocket.hpp>
11
12#include <array>
Ed Tanous8f79c5b2024-01-30 15:56:37 -080013#include <cstddef>
V-Sanjana88ada3b2023-04-13 15:18:31 +053014#include <functional>
Ed Tanous8f79c5b2024-01-30 15:56:37 -080015#include <optional>
V-Sanjana88ada3b2023-04-13 15:18:31 +053016
17namespace crow
18{
19
20namespace sse_socket
21{
Ed Tanous93cf0ac2024-03-28 00:35:13 -070022struct Connection : public std::enable_shared_from_this<Connection>
V-Sanjana88ada3b2023-04-13 15:18:31 +053023{
24 public:
Ed Tanous6fde95f2023-06-01 07:33:34 -070025 Connection() = default;
V-Sanjana88ada3b2023-04-13 15:18:31 +053026
27 Connection(const Connection&) = delete;
28 Connection(Connection&&) = delete;
29 Connection& operator=(const Connection&) = delete;
30 Connection& operator=(const Connection&&) = delete;
31 virtual ~Connection() = default;
32
33 virtual boost::asio::io_context& getIoContext() = 0;
V-Sanjana88ada3b2023-04-13 15:18:31 +053034 virtual void close(std::string_view msg = "quit") = 0;
Ed Tanous6d799e12024-09-11 14:33:37 -070035 virtual void sendSseEvent(std::string_view id, std::string_view msg) = 0;
V-Sanjana88ada3b2023-04-13 15:18:31 +053036};
37
38template <typename Adaptor>
39class ConnectionImpl : public Connection
40{
41 public:
Ed Tanousf80a87f2024-06-16 12:10:33 -070042 ConnectionImpl(
43 Adaptor&& adaptorIn,
44 std::function<void(Connection&, const Request&)> openHandlerIn,
45 std::function<void(Connection&)> closeHandlerIn) :
Ed Tanous6fde95f2023-06-01 07:33:34 -070046 adaptor(std::move(adaptorIn)),
Ed Tanous93cf0ac2024-03-28 00:35:13 -070047 timer(static_cast<boost::asio::io_context&>(
48 adaptor.get_executor().context())),
49 openHandler(std::move(openHandlerIn)),
V-Sanjana88ada3b2023-04-13 15:18:31 +053050 closeHandler(std::move(closeHandlerIn))
Ed Tanous8f79c5b2024-01-30 15:56:37 -080051
V-Sanjana88ada3b2023-04-13 15:18:31 +053052 {
Ed Tanous62598e32023-07-17 17:06:25 -070053 BMCWEB_LOG_DEBUG("SseConnectionImpl: SSE constructor {}", logPtr(this));
V-Sanjana88ada3b2023-04-13 15:18:31 +053054 }
55
56 ConnectionImpl(const ConnectionImpl&) = delete;
57 ConnectionImpl(const ConnectionImpl&&) = delete;
58 ConnectionImpl& operator=(const ConnectionImpl&) = delete;
59 ConnectionImpl& operator=(const ConnectionImpl&&) = delete;
60
61 ~ConnectionImpl() override
62 {
Ed Tanous62598e32023-07-17 17:06:25 -070063 BMCWEB_LOG_DEBUG("SSE ConnectionImpl: SSE destructor {}", logPtr(this));
V-Sanjana88ada3b2023-04-13 15:18:31 +053064 }
65
66 boost::asio::io_context& getIoContext() override
67 {
68 return static_cast<boost::asio::io_context&>(
69 adaptor.get_executor().context());
70 }
71
Ed Tanousf80a87f2024-06-16 12:10:33 -070072 void start(const Request& req)
V-Sanjana88ada3b2023-04-13 15:18:31 +053073 {
Ed Tanous464924c2024-12-20 14:49:45 -080074 BMCWEB_LOG_DEBUG("Starting SSE connection");
75
76 res.set(boost::beast::http::field::content_type, "text/event-stream");
77 boost::beast::http::response_serializer<BodyType>& serial =
78 serializer.emplace(res);
79
80 boost::beast::http::async_write_header(
81 adaptor, serial,
82 std::bind_front(&ConnectionImpl::sendSSEHeaderCallback, this,
83 shared_from_this(), req));
V-Sanjana88ada3b2023-04-13 15:18:31 +053084 }
85
86 void close(const std::string_view msg) override
87 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -080088 BMCWEB_LOG_DEBUG("Closing connection with reason {}", msg);
V-Sanjana88ada3b2023-04-13 15:18:31 +053089 // send notification to handler for cleanup
90 if (closeHandler)
91 {
Ed Tanous6fde95f2023-06-01 07:33:34 -070092 closeHandler(*this);
V-Sanjana88ada3b2023-04-13 15:18:31 +053093 }
Ed Tanous62598e32023-07-17 17:06:25 -070094 BMCWEB_LOG_DEBUG("Closing SSE connection {} - {}", logPtr(this), msg);
Ed Tanous6fde95f2023-06-01 07:33:34 -070095 boost::beast::get_lowest_layer(adaptor).close();
V-Sanjana88ada3b2023-04-13 15:18:31 +053096 }
97
V-Sanjana88ada3b2023-04-13 15:18:31 +053098 void sendSSEHeaderCallback(const std::shared_ptr<Connection>& /*self*/,
Ed Tanous464924c2024-12-20 14:49:45 -080099 const Request& req,
Ed Tanous6fde95f2023-06-01 07:33:34 -0700100 const boost::system::error_code& ec,
101 size_t /*bytesSent*/)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530102 {
Ed Tanous6fde95f2023-06-01 07:33:34 -0700103 serializer.reset();
V-Sanjana88ada3b2023-04-13 15:18:31 +0530104 if (ec)
105 {
Ed Tanous62598e32023-07-17 17:06:25 -0700106 BMCWEB_LOG_ERROR("Error sending header{}", ec);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530107 close("async_write_header failed");
108 return;
109 }
Ed Tanous62598e32023-07-17 17:06:25 -0700110 BMCWEB_LOG_DEBUG("SSE header sent - Connection established");
Ed Tanous464924c2024-12-20 14:49:45 -0800111 if (!openHandler)
112 {
113 BMCWEB_LOG_CRITICAL("No open handler???");
114 return;
115 }
116 openHandler(*this, req);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530117
V-Sanjana88ada3b2023-04-13 15:18:31 +0530118 // SSE stream header sent, So let us setup monitor.
119 // Any read data on this stream will be error in case of SSE.
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800120 adaptor.async_read_some(boost::asio::buffer(buffer),
121 std::bind_front(&ConnectionImpl::afterReadError,
122 this, shared_from_this()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530123 }
124
Ed Tanous6fde95f2023-06-01 07:33:34 -0700125 void afterReadError(const std::shared_ptr<Connection>& /*self*/,
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800126 const boost::system::error_code& ec, size_t bytesRead)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530127 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800128 BMCWEB_LOG_DEBUG("Read {}", bytesRead);
Ed Tanous6fde95f2023-06-01 07:33:34 -0700129 if (ec == boost::asio::error::operation_aborted)
130 {
131 return;
132 }
V-Sanjana88ada3b2023-04-13 15:18:31 +0530133 if (ec)
134 {
Ed Tanous62598e32023-07-17 17:06:25 -0700135 BMCWEB_LOG_ERROR("Read error: {}", ec);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530136 }
137
Ed Tanous6fde95f2023-06-01 07:33:34 -0700138 close("Close SSE connection");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530139 }
140
141 void doWrite()
142 {
V-Sanjana88ada3b2023-04-13 15:18:31 +0530143 if (doingWrite)
144 {
145 return;
146 }
147 if (inputBuffer.size() == 0)
148 {
Ed Tanous62598e32023-07-17 17:06:25 -0700149 BMCWEB_LOG_DEBUG("inputBuffer is empty... Bailing out");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530150 return;
151 }
Ed Tanous6fde95f2023-06-01 07:33:34 -0700152 startTimeout();
V-Sanjana88ada3b2023-04-13 15:18:31 +0530153 doingWrite = true;
154
155 adaptor.async_write_some(
156 inputBuffer.data(),
157 std::bind_front(&ConnectionImpl::doWriteCallback, this,
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800158 shared_from_this()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530159 }
160
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800161 void doWriteCallback(const std::shared_ptr<Connection>& /*self*/,
V-Sanjana88ada3b2023-04-13 15:18:31 +0530162 const boost::beast::error_code& ec,
Ed Tanous6fde95f2023-06-01 07:33:34 -0700163 size_t bytesTransferred)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530164 {
Ed Tanous6fde95f2023-06-01 07:33:34 -0700165 timer.cancel();
V-Sanjana88ada3b2023-04-13 15:18:31 +0530166 doingWrite = false;
167 inputBuffer.consume(bytesTransferred);
168
169 if (ec == boost::asio::error::eof)
170 {
Ed Tanous62598e32023-07-17 17:06:25 -0700171 BMCWEB_LOG_ERROR("async_write_some() SSE stream closed");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530172 close("SSE stream closed");
173 return;
174 }
175
176 if (ec)
177 {
Ed Tanous62598e32023-07-17 17:06:25 -0700178 BMCWEB_LOG_ERROR("async_write_some() failed: {}", ec.message());
V-Sanjana88ada3b2023-04-13 15:18:31 +0530179 close("async_write_some failed");
180 return;
181 }
Ed Tanous62598e32023-07-17 17:06:25 -0700182 BMCWEB_LOG_DEBUG("async_write_some() bytes transferred: {}",
183 bytesTransferred);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530184
185 doWrite();
186 }
187
Ed Tanous6d799e12024-09-11 14:33:37 -0700188 void sendSseEvent(std::string_view id, std::string_view msg) override
V-Sanjana88ada3b2023-04-13 15:18:31 +0530189 {
190 if (msg.empty())
191 {
Ed Tanous62598e32023-07-17 17:06:25 -0700192 BMCWEB_LOG_DEBUG("Empty data, bailing out.");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530193 return;
194 }
195
Ed Tanous6fde95f2023-06-01 07:33:34 -0700196 dataFormat(id, msg);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530197
198 doWrite();
199 }
200
Ed Tanous6fde95f2023-06-01 07:33:34 -0700201 void dataFormat(std::string_view id, std::string_view msg)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530202 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800203 constexpr size_t bufferLimit = 10485760U; // 10MB
204 if (id.size() + msg.size() + inputBuffer.size() >= bufferLimit)
205 {
206 BMCWEB_LOG_ERROR("SSE Buffer overflow while waiting for client");
207 close("Buffer overflow");
208 return;
209 }
V-Sanjana88ada3b2023-04-13 15:18:31 +0530210 std::string rawData;
211 if (!id.empty())
212 {
213 rawData += "id: ";
Ed Tanous6fde95f2023-06-01 07:33:34 -0700214 rawData.append(id);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530215 rawData += "\n";
216 }
217
218 rawData += "data: ";
219 for (char character : msg)
220 {
221 rawData += character;
222 if (character == '\n')
223 {
224 rawData += "data: ";
225 }
226 }
227 rawData += "\n\n";
228
Ed Tanous44106f32024-04-06 13:48:50 -0700229 size_t copied = boost::asio::buffer_copy(
230 inputBuffer.prepare(rawData.size()), boost::asio::buffer(rawData));
231 inputBuffer.commit(copied);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530232 }
233
Ed Tanous6fde95f2023-06-01 07:33:34 -0700234 void startTimeout()
V-Sanjana88ada3b2023-04-13 15:18:31 +0530235 {
V-Sanjana88ada3b2023-04-13 15:18:31 +0530236 std::weak_ptr<Connection> weakSelf = weak_from_this();
237 timer.expires_after(std::chrono::seconds(30));
238 timer.async_wait(std::bind_front(&ConnectionImpl::onTimeoutCallback,
239 this, weak_from_this()));
240 }
241
242 void onTimeoutCallback(const std::weak_ptr<Connection>& weakSelf,
Ed Tanous6fde95f2023-06-01 07:33:34 -0700243 const boost::system::error_code& ec)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530244 {
245 std::shared_ptr<Connection> self = weakSelf.lock();
246 if (!self)
247 {
Ed Tanous62598e32023-07-17 17:06:25 -0700248 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
249 logPtr(self.get()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530250 return;
251 }
252
253 if (ec == boost::asio::error::operation_aborted)
254 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800255 BMCWEB_LOG_DEBUG("Timer operation aborted");
Ed Tanous8ece0e42024-01-02 13:16:50 -0800256 // Canceled wait means the path succeeded.
V-Sanjana88ada3b2023-04-13 15:18:31 +0530257 return;
258 }
259 if (ec)
260 {
Ed Tanous62598e32023-07-17 17:06:25 -0700261 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()), ec);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530262 }
263
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800264 BMCWEB_LOG_WARNING("{} Connection timed out, closing",
Ed Tanous62598e32023-07-17 17:06:25 -0700265 logPtr(self.get()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530266
267 self->close("closing connection");
268 }
269
270 private:
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800271 std::array<char, 1> buffer{};
V-Sanjana88ada3b2023-04-13 15:18:31 +0530272 boost::beast::multi_buffer inputBuffer;
273
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800274 Adaptor adaptor;
275
Ed Tanousb2896142024-01-31 15:25:47 -0800276 using BodyType = bmcweb::HttpBody;
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800277 boost::beast::http::response<BodyType> res;
278 std::optional<boost::beast::http::response_serializer<BodyType>> serializer;
Ed Tanous6fde95f2023-06-01 07:33:34 -0700279 boost::asio::steady_timer timer;
V-Sanjana88ada3b2023-04-13 15:18:31 +0530280 bool doingWrite = false;
V-Sanjana88ada3b2023-04-13 15:18:31 +0530281
Ed Tanousf80a87f2024-06-16 12:10:33 -0700282 std::function<void(Connection&, const Request&)> openHandler;
Ed Tanous6fde95f2023-06-01 07:33:34 -0700283 std::function<void(Connection&)> closeHandler;
V-Sanjana88ada3b2023-04-13 15:18:31 +0530284};
285} // namespace sse_socket
286} // namespace crow