blob: dd2870545303daa7e85a18d78dc9a18cf53bfaef [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
V-Sanjana88ada3b2023-04-13 15:18:31 +05303#pragma once
Ed Tanous41fe81c2024-09-02 15:08:41 -07004#include "boost_formatters.hpp"
Ed Tanousb2896142024-01-31 15:25:47 -08005#include "http_body.hpp"
V-Sanjana88ada3b2023-04-13 15:18:31 +05306#include "http_request.hpp"
7#include "http_response.hpp"
8
V-Sanjana88ada3b2023-04-13 15:18:31 +05309#include <boost/asio/buffer.hpp>
10#include <boost/asio/steady_timer.hpp>
11#include <boost/beast/core/multi_buffer.hpp>
V-Sanjana88ada3b2023-04-13 15:18:31 +053012#include <boost/beast/websocket.hpp>
13
14#include <array>
Ed Tanous8f79c5b2024-01-30 15:56:37 -080015#include <cstddef>
V-Sanjana88ada3b2023-04-13 15:18:31 +053016#include <functional>
Ed Tanous8f79c5b2024-01-30 15:56:37 -080017#include <optional>
V-Sanjana88ada3b2023-04-13 15:18:31 +053018
19namespace crow
20{
21
22namespace sse_socket
23{
Ed Tanous93cf0ac2024-03-28 00:35:13 -070024struct Connection : public std::enable_shared_from_this<Connection>
V-Sanjana88ada3b2023-04-13 15:18:31 +053025{
26 public:
Ed Tanous6fde95f2023-06-01 07:33:34 -070027 Connection() = default;
V-Sanjana88ada3b2023-04-13 15:18:31 +053028
29 Connection(const Connection&) = delete;
30 Connection(Connection&&) = delete;
31 Connection& operator=(const Connection&) = delete;
32 Connection& operator=(const Connection&&) = delete;
33 virtual ~Connection() = default;
34
35 virtual boost::asio::io_context& getIoContext() = 0;
V-Sanjana88ada3b2023-04-13 15:18:31 +053036 virtual void close(std::string_view msg = "quit") = 0;
Ed Tanous6d799e12024-09-11 14:33:37 -070037 virtual void sendSseEvent(std::string_view id, std::string_view msg) = 0;
V-Sanjana88ada3b2023-04-13 15:18:31 +053038};
39
40template <typename Adaptor>
41class ConnectionImpl : public Connection
42{
43 public:
Ed Tanousf80a87f2024-06-16 12:10:33 -070044 ConnectionImpl(
45 Adaptor&& adaptorIn,
46 std::function<void(Connection&, const Request&)> openHandlerIn,
47 std::function<void(Connection&)> closeHandlerIn) :
Ed Tanous6fde95f2023-06-01 07:33:34 -070048 adaptor(std::move(adaptorIn)),
Ed Tanous93cf0ac2024-03-28 00:35:13 -070049 timer(static_cast<boost::asio::io_context&>(
50 adaptor.get_executor().context())),
51 openHandler(std::move(openHandlerIn)),
V-Sanjana88ada3b2023-04-13 15:18:31 +053052 closeHandler(std::move(closeHandlerIn))
Ed Tanous8f79c5b2024-01-30 15:56:37 -080053
V-Sanjana88ada3b2023-04-13 15:18:31 +053054 {
Ed Tanous62598e32023-07-17 17:06:25 -070055 BMCWEB_LOG_DEBUG("SseConnectionImpl: SSE constructor {}", logPtr(this));
V-Sanjana88ada3b2023-04-13 15:18:31 +053056 }
57
58 ConnectionImpl(const ConnectionImpl&) = delete;
59 ConnectionImpl(const ConnectionImpl&&) = delete;
60 ConnectionImpl& operator=(const ConnectionImpl&) = delete;
61 ConnectionImpl& operator=(const ConnectionImpl&&) = delete;
62
63 ~ConnectionImpl() override
64 {
Ed Tanous62598e32023-07-17 17:06:25 -070065 BMCWEB_LOG_DEBUG("SSE ConnectionImpl: SSE destructor {}", logPtr(this));
V-Sanjana88ada3b2023-04-13 15:18:31 +053066 }
67
68 boost::asio::io_context& getIoContext() override
69 {
70 return static_cast<boost::asio::io_context&>(
71 adaptor.get_executor().context());
72 }
73
Ed Tanousf80a87f2024-06-16 12:10:33 -070074 void start(const Request& req)
V-Sanjana88ada3b2023-04-13 15:18:31 +053075 {
Ed Tanous464924c2024-12-20 14:49:45 -080076 BMCWEB_LOG_DEBUG("Starting SSE connection");
77
78 res.set(boost::beast::http::field::content_type, "text/event-stream");
79 boost::beast::http::response_serializer<BodyType>& serial =
80 serializer.emplace(res);
81
82 boost::beast::http::async_write_header(
83 adaptor, serial,
84 std::bind_front(&ConnectionImpl::sendSSEHeaderCallback, this,
85 shared_from_this(), req));
V-Sanjana88ada3b2023-04-13 15:18:31 +053086 }
87
88 void close(const std::string_view msg) override
89 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -080090 BMCWEB_LOG_DEBUG("Closing connection with reason {}", msg);
V-Sanjana88ada3b2023-04-13 15:18:31 +053091 // send notification to handler for cleanup
92 if (closeHandler)
93 {
Ed Tanous6fde95f2023-06-01 07:33:34 -070094 closeHandler(*this);
V-Sanjana88ada3b2023-04-13 15:18:31 +053095 }
Ed Tanous62598e32023-07-17 17:06:25 -070096 BMCWEB_LOG_DEBUG("Closing SSE connection {} - {}", logPtr(this), msg);
Ed Tanous6fde95f2023-06-01 07:33:34 -070097 boost::beast::get_lowest_layer(adaptor).close();
V-Sanjana88ada3b2023-04-13 15:18:31 +053098 }
99
V-Sanjana88ada3b2023-04-13 15:18:31 +0530100 void sendSSEHeaderCallback(const std::shared_ptr<Connection>& /*self*/,
Ed Tanous464924c2024-12-20 14:49:45 -0800101 const Request& req,
Ed Tanous6fde95f2023-06-01 07:33:34 -0700102 const boost::system::error_code& ec,
103 size_t /*bytesSent*/)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530104 {
Ed Tanous6fde95f2023-06-01 07:33:34 -0700105 serializer.reset();
V-Sanjana88ada3b2023-04-13 15:18:31 +0530106 if (ec)
107 {
Ed Tanous62598e32023-07-17 17:06:25 -0700108 BMCWEB_LOG_ERROR("Error sending header{}", ec);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530109 close("async_write_header failed");
110 return;
111 }
Ed Tanous62598e32023-07-17 17:06:25 -0700112 BMCWEB_LOG_DEBUG("SSE header sent - Connection established");
Ed Tanous464924c2024-12-20 14:49:45 -0800113 if (!openHandler)
114 {
115 BMCWEB_LOG_CRITICAL("No open handler???");
116 return;
117 }
118 openHandler(*this, req);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530119
V-Sanjana88ada3b2023-04-13 15:18:31 +0530120 // SSE stream header sent, So let us setup monitor.
121 // Any read data on this stream will be error in case of SSE.
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800122 adaptor.async_read_some(boost::asio::buffer(buffer),
123 std::bind_front(&ConnectionImpl::afterReadError,
124 this, shared_from_this()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530125 }
126
Ed Tanous6fde95f2023-06-01 07:33:34 -0700127 void afterReadError(const std::shared_ptr<Connection>& /*self*/,
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800128 const boost::system::error_code& ec, size_t bytesRead)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530129 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800130 BMCWEB_LOG_DEBUG("Read {}", bytesRead);
Ed Tanous6fde95f2023-06-01 07:33:34 -0700131 if (ec == boost::asio::error::operation_aborted)
132 {
133 return;
134 }
V-Sanjana88ada3b2023-04-13 15:18:31 +0530135 if (ec)
136 {
Ed Tanous62598e32023-07-17 17:06:25 -0700137 BMCWEB_LOG_ERROR("Read error: {}", ec);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530138 }
139
Ed Tanous6fde95f2023-06-01 07:33:34 -0700140 close("Close SSE connection");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530141 }
142
143 void doWrite()
144 {
V-Sanjana88ada3b2023-04-13 15:18:31 +0530145 if (doingWrite)
146 {
147 return;
148 }
149 if (inputBuffer.size() == 0)
150 {
Ed Tanous62598e32023-07-17 17:06:25 -0700151 BMCWEB_LOG_DEBUG("inputBuffer is empty... Bailing out");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530152 return;
153 }
Ed Tanous6fde95f2023-06-01 07:33:34 -0700154 startTimeout();
V-Sanjana88ada3b2023-04-13 15:18:31 +0530155 doingWrite = true;
156
157 adaptor.async_write_some(
158 inputBuffer.data(),
159 std::bind_front(&ConnectionImpl::doWriteCallback, this,
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800160 shared_from_this()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530161 }
162
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800163 void doWriteCallback(const std::shared_ptr<Connection>& /*self*/,
V-Sanjana88ada3b2023-04-13 15:18:31 +0530164 const boost::beast::error_code& ec,
Ed Tanous6fde95f2023-06-01 07:33:34 -0700165 size_t bytesTransferred)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530166 {
Ed Tanous6fde95f2023-06-01 07:33:34 -0700167 timer.cancel();
V-Sanjana88ada3b2023-04-13 15:18:31 +0530168 doingWrite = false;
169 inputBuffer.consume(bytesTransferred);
170
171 if (ec == boost::asio::error::eof)
172 {
Ed Tanous62598e32023-07-17 17:06:25 -0700173 BMCWEB_LOG_ERROR("async_write_some() SSE stream closed");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530174 close("SSE stream closed");
175 return;
176 }
177
178 if (ec)
179 {
Ed Tanous62598e32023-07-17 17:06:25 -0700180 BMCWEB_LOG_ERROR("async_write_some() failed: {}", ec.message());
V-Sanjana88ada3b2023-04-13 15:18:31 +0530181 close("async_write_some failed");
182 return;
183 }
Ed Tanous62598e32023-07-17 17:06:25 -0700184 BMCWEB_LOG_DEBUG("async_write_some() bytes transferred: {}",
185 bytesTransferred);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530186
187 doWrite();
188 }
189
Ed Tanous6d799e12024-09-11 14:33:37 -0700190 void sendSseEvent(std::string_view id, std::string_view msg) override
V-Sanjana88ada3b2023-04-13 15:18:31 +0530191 {
192 if (msg.empty())
193 {
Ed Tanous62598e32023-07-17 17:06:25 -0700194 BMCWEB_LOG_DEBUG("Empty data, bailing out.");
V-Sanjana88ada3b2023-04-13 15:18:31 +0530195 return;
196 }
197
Ed Tanous6fde95f2023-06-01 07:33:34 -0700198 dataFormat(id, msg);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530199
200 doWrite();
201 }
202
Ed Tanous6fde95f2023-06-01 07:33:34 -0700203 void dataFormat(std::string_view id, std::string_view msg)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530204 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800205 constexpr size_t bufferLimit = 10485760U; // 10MB
206 if (id.size() + msg.size() + inputBuffer.size() >= bufferLimit)
207 {
208 BMCWEB_LOG_ERROR("SSE Buffer overflow while waiting for client");
209 close("Buffer overflow");
210 return;
211 }
V-Sanjana88ada3b2023-04-13 15:18:31 +0530212 std::string rawData;
213 if (!id.empty())
214 {
215 rawData += "id: ";
Ed Tanous6fde95f2023-06-01 07:33:34 -0700216 rawData.append(id);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530217 rawData += "\n";
218 }
219
220 rawData += "data: ";
221 for (char character : msg)
222 {
223 rawData += character;
224 if (character == '\n')
225 {
226 rawData += "data: ";
227 }
228 }
229 rawData += "\n\n";
230
Ed Tanous44106f32024-04-06 13:48:50 -0700231 size_t copied = boost::asio::buffer_copy(
232 inputBuffer.prepare(rawData.size()), boost::asio::buffer(rawData));
233 inputBuffer.commit(copied);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530234 }
235
Ed Tanous6fde95f2023-06-01 07:33:34 -0700236 void startTimeout()
V-Sanjana88ada3b2023-04-13 15:18:31 +0530237 {
V-Sanjana88ada3b2023-04-13 15:18:31 +0530238 std::weak_ptr<Connection> weakSelf = weak_from_this();
239 timer.expires_after(std::chrono::seconds(30));
240 timer.async_wait(std::bind_front(&ConnectionImpl::onTimeoutCallback,
241 this, weak_from_this()));
242 }
243
244 void onTimeoutCallback(const std::weak_ptr<Connection>& weakSelf,
Ed Tanous6fde95f2023-06-01 07:33:34 -0700245 const boost::system::error_code& ec)
V-Sanjana88ada3b2023-04-13 15:18:31 +0530246 {
247 std::shared_ptr<Connection> self = weakSelf.lock();
248 if (!self)
249 {
Ed Tanous62598e32023-07-17 17:06:25 -0700250 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
251 logPtr(self.get()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530252 return;
253 }
254
255 if (ec == boost::asio::error::operation_aborted)
256 {
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800257 BMCWEB_LOG_DEBUG("Timer operation aborted");
Ed Tanous8ece0e42024-01-02 13:16:50 -0800258 // Canceled wait means the path succeeded.
V-Sanjana88ada3b2023-04-13 15:18:31 +0530259 return;
260 }
261 if (ec)
262 {
Ed Tanous62598e32023-07-17 17:06:25 -0700263 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()), ec);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530264 }
265
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800266 BMCWEB_LOG_WARNING("{} Connection timed out, closing",
Ed Tanous62598e32023-07-17 17:06:25 -0700267 logPtr(self.get()));
V-Sanjana88ada3b2023-04-13 15:18:31 +0530268
269 self->close("closing connection");
270 }
271
272 private:
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800273 std::array<char, 1> buffer{};
V-Sanjana88ada3b2023-04-13 15:18:31 +0530274 boost::beast::multi_buffer inputBuffer;
275
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800276 Adaptor adaptor;
277
Ed Tanousb2896142024-01-31 15:25:47 -0800278 using BodyType = bmcweb::HttpBody;
Ed Tanous8f79c5b2024-01-30 15:56:37 -0800279 boost::beast::http::response<BodyType> res;
280 std::optional<boost::beast::http::response_serializer<BodyType>> serializer;
Ed Tanous6fde95f2023-06-01 07:33:34 -0700281 boost::asio::steady_timer timer;
V-Sanjana88ada3b2023-04-13 15:18:31 +0530282 bool doingWrite = false;
V-Sanjana88ada3b2023-04-13 15:18:31 +0530283
Ed Tanousf80a87f2024-06-16 12:10:33 -0700284 std::function<void(Connection&, const Request&)> openHandler;
Ed Tanous6fde95f2023-06-01 07:33:34 -0700285 std::function<void(Connection&)> closeHandler;
V-Sanjana88ada3b2023-04-13 15:18:31 +0530286};
287} // namespace sse_socket
288} // namespace crow