blob: e8d7b1259ed06d621fa6394bdf4182da874442ab [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08002#include "async_resp.hpp"
Ed Tanousb2896142024-01-31 15:25:47 -08003#include "http_body.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07004#include "http_request.hpp"
Gunnar Mills1214b7e2020-06-04 10:11:30 -05005
Ed Tanous609145a2018-09-05 16:27:36 -07006#include <boost/asio/buffer.hpp>
Ed Tanous863c1c22022-02-21 21:33:06 -08007#include <boost/beast/core/multi_buffer.hpp>
Ed Tanous1b0044b2018-08-03 14:30:05 -07008#include <boost/beast/websocket.hpp>
Ed Tanous8db83742024-04-13 09:11:15 -07009#include <boost/beast/websocket/ssl.hpp>
Ed Tanous1abe55e2018-09-05 08:30:59 -070010
Gunnar Mills1214b7e2020-06-04 10:11:30 -050011#include <array>
12#include <functional>
Ed Tanous1b0044b2018-08-03 14:30:05 -070013
Ed Tanous1abe55e2018-09-05 08:30:59 -070014namespace crow
15{
16namespace websocket
17{
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020018
Ed Tanous863c1c22022-02-21 21:33:06 -080019enum class MessageType
20{
21 Binary,
22 Text,
23};
24
Ed Tanous1abe55e2018-09-05 08:30:59 -070025struct Connection : std::enable_shared_from_this<Connection>
26{
27 public:
Ed Tanous5ebb9d32023-02-27 18:20:47 -080028 Connection() = default;
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +010029
Ed Tanousecd6a3a2022-01-07 09:18:40 -080030 Connection(const Connection&) = delete;
31 Connection(Connection&&) = delete;
32 Connection& operator=(const Connection&) = delete;
33 Connection& operator=(const Connection&&) = delete;
34
Ed Tanous9eb808c2022-01-25 10:19:23 -080035 virtual void sendBinary(std::string_view msg) = 0;
Ed Tanous863c1c22022-02-21 21:33:06 -080036 virtual void sendEx(MessageType type, std::string_view msg,
37 std::function<void()>&& onDone) = 0;
Ed Tanous9eb808c2022-01-25 10:19:23 -080038 virtual void sendText(std::string_view msg) = 0;
Ed Tanous9eb808c2022-01-25 10:19:23 -080039 virtual void close(std::string_view msg = "quit") = 0;
Ed Tanous863c1c22022-02-21 21:33:06 -080040 virtual void deferRead() = 0;
41 virtual void resumeRead() = 0;
Ed Tanous2c70f802020-09-28 14:29:23 -070042 virtual boost::asio::io_context& getIoContext() = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -070043 virtual ~Connection() = default;
Ninad Palsule052bcbf2023-05-30 11:10:58 -050044 virtual boost::urls::url_view url() = 0;
Ed Tanous7045c8d2017-04-03 10:04:37 -070045};
46
Gunnar Mills1214b7e2020-06-04 10:11:30 -050047template <typename Adaptor>
48class ConnectionImpl : public Connection
Ed Tanous1abe55e2018-09-05 08:30:59 -070049{
Ed Tanous5ebb9d32023-02-27 18:20:47 -080050 using self_t = ConnectionImpl<Adaptor>;
51
Ed Tanous1abe55e2018-09-05 08:30:59 -070052 public:
53 ConnectionImpl(
Ed Tanous5ebb9d32023-02-27 18:20:47 -080054 const boost::urls::url_view& urlViewIn,
55 const std::shared_ptr<persistent_data::UserSession>& sessionIn,
Ninad Palsule052bcbf2023-05-30 11:10:58 -050056 Adaptor adaptorIn, std::function<void(Connection&)> openHandlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070057 std::function<void(Connection&, const std::string&, bool)>
Ed Tanous8a592812022-06-04 09:06:59 -070058 messageHandlerIn,
Ed Tanous863c1c22022-02-21 21:33:06 -080059 std::function<void(crow::websocket::Connection&, std::string_view,
60 crow::websocket::MessageType type,
61 std::function<void()>&& whenComplete)>
62 messageExHandlerIn,
Ed Tanous8a592812022-06-04 09:06:59 -070063 std::function<void(Connection&, const std::string&)> closeHandlerIn,
64 std::function<void(Connection&)> errorHandlerIn) :
Ed Tanous5ebb9d32023-02-27 18:20:47 -080065 uri(urlViewIn),
66 ws(std::move(adaptorIn)), inBuffer(inString, 131088),
Ed Tanous8a592812022-06-04 09:06:59 -070067 openHandler(std::move(openHandlerIn)),
68 messageHandler(std::move(messageHandlerIn)),
Ed Tanous863c1c22022-02-21 21:33:06 -080069 messageExHandler(std::move(messageExHandlerIn)),
Ed Tanous8a592812022-06-04 09:06:59 -070070 closeHandler(std::move(closeHandlerIn)),
Ed Tanous5ebb9d32023-02-27 18:20:47 -080071 errorHandler(std::move(errorHandlerIn)), session(sessionIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070072 {
dhineskumare02bdd962021-07-08 16:06:49 +053073 /* Turn on the timeouts on websocket stream to server role */
74 ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(
75 boost::beast::role_type::server));
Ed Tanous62598e32023-07-17 17:06:25 -070076 BMCWEB_LOG_DEBUG("Creating new connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070077 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070078
Ed Tanous2c70f802020-09-28 14:29:23 -070079 boost::asio::io_context& getIoContext() override
Ed Tanous1abe55e2018-09-05 08:30:59 -070080 {
Ed Tanous271584a2019-07-09 16:24:22 -070081 return static_cast<boost::asio::io_context&>(
82 ws.get_executor().context());
Ed Tanous911ac312017-08-15 09:37:42 -070083 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070084
Ed Tanous5ebb9d32023-02-27 18:20:47 -080085 void start(const crow::Request& req)
Ed Tanous1abe55e2018-09-05 08:30:59 -070086 {
Ed Tanous62598e32023-07-17 17:06:25 -070087 BMCWEB_LOG_DEBUG("starting connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070088
Ed Tanousfe5b2162019-05-22 14:28:16 -070089 using bf = boost::beast::http::field;
Myung Bae1873a042024-04-01 09:27:39 -050090 std::string protocolHeader{
91 req.getHeaderValue(bf::sec_websocket_protocol)};
Ed Tanous7045c8d2017-04-03 10:04:37 -070092
Ed Tanousd4d77e32020-08-18 00:07:28 -070093 ws.set_option(boost::beast::websocket::stream_base::decorator(
Ed Tanous5ebb9d32023-02-27 18:20:47 -080094 [session{session},
95 protocolHeader](boost::beast::websocket::response_type& m) {
Ed Tanous83328312024-05-09 15:48:09 -070096 if constexpr (!BMCWEB_INSECURE_DISABLE_CSRF)
Ed Tanous002d39b2022-05-31 08:59:27 -070097 {
Ed Tanous83328312024-05-09 15:48:09 -070098 if (session != nullptr)
James Feistf8aa3d22020-04-08 18:32:33 -070099 {
Ed Tanous83328312024-05-09 15:48:09 -0700100 // use protocol for csrf checking
101 if (session->cookieAuth &&
102 !crow::utility::constantTimeStringCompare(
103 protocolHeader, session->csrfToken))
104 {
105 BMCWEB_LOG_ERROR("Websocket CSRF error");
106 m.result(boost::beast::http::status::unauthorized);
107 return;
108 }
James Feistf8aa3d22020-04-08 18:32:33 -0700109 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700110 }
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800111 if (!protocolHeader.empty())
Ed Tanous002d39b2022-05-31 08:59:27 -0700112 {
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800113 m.insert(bf::sec_websocket_protocol, protocolHeader);
Ed Tanous002d39b2022-05-31 08:59:27 -0700114 }
Ed Tanousfe5b2162019-05-22 14:28:16 -0700115
Ed Tanous002d39b2022-05-31 08:59:27 -0700116 m.insert(bf::strict_transport_security, "max-age=31536000; "
117 "includeSubdomains; "
118 "preload");
119 m.insert(bf::pragma, "no-cache");
120 m.insert(bf::cache_control, "no-Store,no-Cache");
121 m.insert("Content-Security-Policy", "default-src 'self'");
122 m.insert("X-XSS-Protection", "1; "
123 "mode=block");
124 m.insert("X-Content-Type-Options", "nosniff");
125 }));
Ed Tanousd4d77e32020-08-18 00:07:28 -0700126
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800127 // Make a pointer to keep the req alive while we accept it.
Ed Tanousb2896142024-01-31 15:25:47 -0800128 using Body = boost::beast::http::request<bmcweb::HttpBody>;
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800129 std::unique_ptr<Body> mobile = std::make_unique<Body>(req.req);
130 Body* ptr = mobile.get();
Ed Tanousd4d77e32020-08-18 00:07:28 -0700131 // Perform the websocket upgrade
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800132 ws.async_accept(*ptr,
133 std::bind_front(&self_t::acceptDone, this,
134 shared_from_this(), std::move(mobile)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700135 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700136
Ed Tanous26ccae32023-02-16 10:28:44 -0800137 void sendBinary(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700138 {
139 ws.binary(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800140 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
141 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700142 doWrite();
143 }
144
Ed Tanous863c1c22022-02-21 21:33:06 -0800145 void sendEx(MessageType type, std::string_view msg,
146 std::function<void()>&& onDone) override
147 {
148 if (doingWrite)
149 {
Ed Tanous62598e32023-07-17 17:06:25 -0700150 BMCWEB_LOG_CRITICAL(
151 "Cannot mix sendEx usage with sendBinary or sendText");
Ed Tanous863c1c22022-02-21 21:33:06 -0800152 onDone();
153 return;
154 }
155 ws.binary(type == MessageType::Binary);
156
157 ws.async_write(boost::asio::buffer(msg),
158 [weak(weak_from_this()), onDone{std::move(onDone)}](
159 const boost::beast::error_code& ec, size_t) {
160 std::shared_ptr<Connection> self = weak.lock();
zhaogang.0108a8894202023-12-22 08:53:40 +0000161 if (!self)
162 {
163 BMCWEB_LOG_ERROR("Connection went away");
164 return;
165 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800166
167 // Call the done handler regardless of whether we
168 // errored, but before we close things out
169 onDone();
170
171 if (ec)
172 {
Ed Tanous62598e32023-07-17 17:06:25 -0700173 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous863c1c22022-02-21 21:33:06 -0800174 self->close("write error");
175 }
176 });
177 }
178
Ed Tanous26ccae32023-02-16 10:28:44 -0800179 void sendText(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700180 {
181 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800182 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
183 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700184 doWrite();
185 }
186
Ed Tanous26ccae32023-02-16 10:28:44 -0800187 void close(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700188 {
189 ws.async_close(
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200190 {boost::beast::websocket::close_code::normal, msg},
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800191 [self(shared_from_this())](const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700192 if (ec == boost::asio::error::operation_aborted)
193 {
194 return;
195 }
196 if (ec)
197 {
Ed Tanous62598e32023-07-17 17:06:25 -0700198 BMCWEB_LOG_ERROR("Error closing websocket {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700199 return;
200 }
Patrick Williams5a39f772023-10-20 11:20:21 -0500201 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700202 }
203
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500204 boost::urls::url_view url() override
205 {
206 return uri;
207 }
208
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800209 void acceptDone(const std::shared_ptr<Connection>& /*self*/,
Ed Tanous52e31622024-01-23 16:31:11 -0800210 const std::unique_ptr<
Ed Tanousb2896142024-01-31 15:25:47 -0800211 boost::beast::http::request<bmcweb::HttpBody>>& /*req*/,
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800212 const boost::system::error_code& ec)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700213 {
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800214 if (ec)
215 {
216 BMCWEB_LOG_ERROR("Error in ws.async_accept {}", ec);
217 return;
218 }
Ed Tanous62598e32023-07-17 17:06:25 -0700219 BMCWEB_LOG_DEBUG("Websocket accepted connection");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700220
221 if (openHandler)
222 {
zhanghch0577726382021-10-21 14:07:57 +0800223 openHandler(*this);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700224 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800225 doRead();
226 }
227
228 void deferRead() override
229 {
230 readingDefered = true;
231
232 // If we're not actively reading, we need to take ownership of
233 // ourselves for a small portion of time, do that, and clear when we
234 // resume.
235 selfOwned = shared_from_this();
236 }
237
238 void resumeRead() override
239 {
240 readingDefered = false;
241 doRead();
242
243 // No longer need to keep ourselves alive now that read is active.
244 selfOwned.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700245 }
246
247 void doRead()
248 {
Ed Tanous863c1c22022-02-21 21:33:06 -0800249 if (readingDefered)
250 {
251 return;
252 }
253 ws.async_read(inBuffer, [this, self(shared_from_this())](
254 const boost::beast::error_code& ec,
255 size_t bytesRead) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700256 if (ec)
257 {
258 if (ec != boost::beast::websocket::error::closed)
259 {
Ed Tanous62598e32023-07-17 17:06:25 -0700260 BMCWEB_LOG_ERROR("doRead error {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700261 }
262 if (closeHandler)
263 {
Ed Tanous079360a2022-06-29 10:05:19 -0700264 std::string reason{ws.reason().reason.c_str()};
265 closeHandler(*this, reason);
Ed Tanous002d39b2022-05-31 08:59:27 -0700266 }
267 return;
268 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800269
270 handleMessage(bytesRead);
Ed Tanous002d39b2022-05-31 08:59:27 -0700271 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700272 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700273 void doWrite()
274 {
275 // If we're already doing a write, ignore the request, it will be picked
276 // up when the current write is complete
277 if (doingWrite)
278 {
279 return;
280 }
281
Ed Tanous863c1c22022-02-21 21:33:06 -0800282 if (outBuffer.size() == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 {
284 // Done for now
285 return;
286 }
287 doingWrite = true;
Ed Tanous863c1c22022-02-21 21:33:06 -0800288 ws.async_write(outBuffer.data(), [this, self(shared_from_this())](
289 const boost::beast::error_code& ec,
290 size_t bytesSent) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700291 doingWrite = false;
Ed Tanous863c1c22022-02-21 21:33:06 -0800292 outBuffer.consume(bytesSent);
Ed Tanous002d39b2022-05-31 08:59:27 -0700293 if (ec == boost::beast::websocket::error::closed)
294 {
295 // Do nothing here. doRead handler will call the
296 // closeHandler.
297 close("Write error");
298 return;
299 }
300 if (ec)
301 {
Ed Tanous62598e32023-07-17 17:06:25 -0700302 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700303 return;
304 }
305 doWrite();
306 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700307 }
308
309 private:
Ed Tanous863c1c22022-02-21 21:33:06 -0800310 void handleMessage(size_t bytesRead)
311 {
312 if (messageExHandler)
313 {
314 // Note, because of the interactions with the read buffers,
315 // this message handler overrides the normal message handler
316 messageExHandler(*this, inString, MessageType::Binary,
317 [this, self(shared_from_this()), bytesRead]() {
318 if (self == nullptr)
319 {
320 return;
321 }
322
323 inBuffer.consume(bytesRead);
324 inString.clear();
325
326 doRead();
327 });
328 return;
329 }
330
331 if (messageHandler)
332 {
333 messageHandler(*this, inString, ws.got_text());
334 }
335 inBuffer.consume(bytesRead);
336 inString.clear();
337 doRead();
338 }
339
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500340 boost::urls::url uri;
341
Ed Tanous2aee6ca2021-02-01 09:52:17 -0800342 boost::beast::websocket::stream<Adaptor, false> ws;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343
Ed Tanous863c1c22022-02-21 21:33:06 -0800344 bool readingDefered = false;
Ed Tanous609145a2018-09-05 16:27:36 -0700345 std::string inString;
346 boost::asio::dynamic_string_buffer<std::string::value_type,
347 std::string::traits_type,
348 std::string::allocator_type>
349 inBuffer;
Ed Tanous863c1c22022-02-21 21:33:06 -0800350
351 boost::beast::multi_buffer outBuffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 bool doingWrite = false;
353
zhanghch0577726382021-10-21 14:07:57 +0800354 std::function<void(Connection&)> openHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 std::function<void(Connection&, const std::string&, bool)> messageHandler;
Ed Tanous863c1c22022-02-21 21:33:06 -0800356 std::function<void(crow::websocket::Connection&, std::string_view,
357 crow::websocket::MessageType type,
358 std::function<void()>&& whenComplete)>
359 messageExHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700360 std::function<void(Connection&, const std::string&)> closeHandler;
361 std::function<void(Connection&)> errorHandler;
Ed Tanous52cc1122020-07-18 13:51:21 -0700362 std::shared_ptr<persistent_data::UserSession> session;
Ed Tanous863c1c22022-02-21 21:33:06 -0800363
364 std::shared_ptr<Connection> selfOwned;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700365};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700366} // namespace websocket
367} // namespace crow