blob: d232c023303cd116d1bfacb1d45b2afdc2daf90f [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 Tanous1abe55e2018-09-05 08:30:59 -07009
Gunnar Mills1214b7e2020-06-04 10:11:30 -050010#include <array>
11#include <functional>
Ed Tanous1b0044b2018-08-03 14:30:05 -070012
13#ifdef BMCWEB_ENABLE_SSL
14#include <boost/beast/websocket/ssl.hpp>
15#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -070016
Ed Tanous1abe55e2018-09-05 08:30:59 -070017namespace crow
18{
19namespace websocket
20{
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020021
Ed Tanous863c1c22022-02-21 21:33:06 -080022enum class MessageType
23{
24 Binary,
25 Text,
26};
27
Ed Tanous1abe55e2018-09-05 08:30:59 -070028struct Connection : std::enable_shared_from_this<Connection>
29{
30 public:
Ed Tanous5ebb9d32023-02-27 18:20:47 -080031 Connection() = default;
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +010032
Ed Tanousecd6a3a2022-01-07 09:18:40 -080033 Connection(const Connection&) = delete;
34 Connection(Connection&&) = delete;
35 Connection& operator=(const Connection&) = delete;
36 Connection& operator=(const Connection&&) = delete;
37
Ed Tanous9eb808c2022-01-25 10:19:23 -080038 virtual void sendBinary(std::string_view msg) = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -070039 virtual void sendBinary(std::string&& msg) = 0;
Ed Tanous863c1c22022-02-21 21:33:06 -080040 virtual void sendEx(MessageType type, std::string_view msg,
41 std::function<void()>&& onDone) = 0;
Ed Tanous9eb808c2022-01-25 10:19:23 -080042 virtual void sendText(std::string_view msg) = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -070043 virtual void sendText(std::string&& msg) = 0;
Ed Tanous9eb808c2022-01-25 10:19:23 -080044 virtual void close(std::string_view msg = "quit") = 0;
Ed Tanous863c1c22022-02-21 21:33:06 -080045 virtual void deferRead() = 0;
46 virtual void resumeRead() = 0;
Ed Tanous2c70f802020-09-28 14:29:23 -070047 virtual boost::asio::io_context& getIoContext() = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -070048 virtual ~Connection() = default;
Ninad Palsule052bcbf2023-05-30 11:10:58 -050049 virtual boost::urls::url_view url() = 0;
Ed Tanous7045c8d2017-04-03 10:04:37 -070050};
51
Gunnar Mills1214b7e2020-06-04 10:11:30 -050052template <typename Adaptor>
53class ConnectionImpl : public Connection
Ed Tanous1abe55e2018-09-05 08:30:59 -070054{
Ed Tanous5ebb9d32023-02-27 18:20:47 -080055 using self_t = ConnectionImpl<Adaptor>;
56
Ed Tanous1abe55e2018-09-05 08:30:59 -070057 public:
58 ConnectionImpl(
Ed Tanous5ebb9d32023-02-27 18:20:47 -080059 const boost::urls::url_view& urlViewIn,
60 const std::shared_ptr<persistent_data::UserSession>& sessionIn,
Ninad Palsule052bcbf2023-05-30 11:10:58 -050061 Adaptor adaptorIn, std::function<void(Connection&)> openHandlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070062 std::function<void(Connection&, const std::string&, bool)>
Ed Tanous8a592812022-06-04 09:06:59 -070063 messageHandlerIn,
Ed Tanous863c1c22022-02-21 21:33:06 -080064 std::function<void(crow::websocket::Connection&, std::string_view,
65 crow::websocket::MessageType type,
66 std::function<void()>&& whenComplete)>
67 messageExHandlerIn,
Ed Tanous8a592812022-06-04 09:06:59 -070068 std::function<void(Connection&, const std::string&)> closeHandlerIn,
69 std::function<void(Connection&)> errorHandlerIn) :
Ed Tanous5ebb9d32023-02-27 18:20:47 -080070 uri(urlViewIn),
71 ws(std::move(adaptorIn)), inBuffer(inString, 131088),
Ed Tanous8a592812022-06-04 09:06:59 -070072 openHandler(std::move(openHandlerIn)),
73 messageHandler(std::move(messageHandlerIn)),
Ed Tanous863c1c22022-02-21 21:33:06 -080074 messageExHandler(std::move(messageExHandlerIn)),
Ed Tanous8a592812022-06-04 09:06:59 -070075 closeHandler(std::move(closeHandlerIn)),
Ed Tanous5ebb9d32023-02-27 18:20:47 -080076 errorHandler(std::move(errorHandlerIn)), session(sessionIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070077 {
dhineskumare02bdd962021-07-08 16:06:49 +053078 /* Turn on the timeouts on websocket stream to server role */
79 ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(
80 boost::beast::role_type::server));
Ed Tanous62598e32023-07-17 17:06:25 -070081 BMCWEB_LOG_DEBUG("Creating new connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070082 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070083
Ed Tanous2c70f802020-09-28 14:29:23 -070084 boost::asio::io_context& getIoContext() override
Ed Tanous1abe55e2018-09-05 08:30:59 -070085 {
Ed Tanous271584a2019-07-09 16:24:22 -070086 return static_cast<boost::asio::io_context&>(
87 ws.get_executor().context());
Ed Tanous911ac312017-08-15 09:37:42 -070088 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070089
Ed Tanous5ebb9d32023-02-27 18:20:47 -080090 void start(const crow::Request& req)
Ed Tanous1abe55e2018-09-05 08:30:59 -070091 {
Ed Tanous62598e32023-07-17 17:06:25 -070092 BMCWEB_LOG_DEBUG("starting connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070093
Ed Tanousfe5b2162019-05-22 14:28:16 -070094 using bf = boost::beast::http::field;
Ed Tanous5ebb9d32023-02-27 18:20:47 -080095 std::string protocolHeader = req.req[bf::sec_websocket_protocol];
Ed Tanous7045c8d2017-04-03 10:04:37 -070096
Ed Tanousd4d77e32020-08-18 00:07:28 -070097 ws.set_option(boost::beast::websocket::stream_base::decorator(
Ed Tanous5ebb9d32023-02-27 18:20:47 -080098 [session{session},
99 protocolHeader](boost::beast::websocket::response_type& m) {
James Feistf8aa3d22020-04-08 18:32:33 -0700100
101#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
Ed Tanous002d39b2022-05-31 08:59:27 -0700102 if (session != nullptr)
103 {
104 // use protocol for csrf checking
Ed Tanous7e9c08e2023-06-16 11:29:37 -0700105 if (session->cookieAuth &&
106 !crow::utility::constantTimeStringCompare(
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800107 protocolHeader, session->csrfToken))
James Feistf8aa3d22020-04-08 18:32:33 -0700108 {
Ed Tanous62598e32023-07-17 17:06:25 -0700109 BMCWEB_LOG_ERROR("Websocket CSRF error");
Ed Tanous002d39b2022-05-31 08:59:27 -0700110 m.result(boost::beast::http::status::unauthorized);
111 return;
James Feistf8aa3d22020-04-08 18:32:33 -0700112 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700113 }
James Feistf8aa3d22020-04-08 18:32:33 -0700114#endif
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800115 if (!protocolHeader.empty())
Ed Tanous002d39b2022-05-31 08:59:27 -0700116 {
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800117 m.insert(bf::sec_websocket_protocol, protocolHeader);
Ed Tanous002d39b2022-05-31 08:59:27 -0700118 }
Ed Tanousfe5b2162019-05-22 14:28:16 -0700119
Ed Tanous002d39b2022-05-31 08:59:27 -0700120 m.insert(bf::strict_transport_security, "max-age=31536000; "
121 "includeSubdomains; "
122 "preload");
123 m.insert(bf::pragma, "no-cache");
124 m.insert(bf::cache_control, "no-Store,no-Cache");
125 m.insert("Content-Security-Policy", "default-src 'self'");
126 m.insert("X-XSS-Protection", "1; "
127 "mode=block");
128 m.insert("X-Content-Type-Options", "nosniff");
129 }));
Ed Tanousd4d77e32020-08-18 00:07:28 -0700130
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800131 // Make a pointer to keep the req alive while we accept it.
Ed Tanousb2896142024-01-31 15:25:47 -0800132 using Body = boost::beast::http::request<bmcweb::HttpBody>;
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800133 std::unique_ptr<Body> mobile = std::make_unique<Body>(req.req);
134 Body* ptr = mobile.get();
Ed Tanousd4d77e32020-08-18 00:07:28 -0700135 // Perform the websocket upgrade
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800136 ws.async_accept(*ptr,
137 std::bind_front(&self_t::acceptDone, this,
138 shared_from_this(), std::move(mobile)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700139 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700140
Ed Tanous26ccae32023-02-16 10:28:44 -0800141 void sendBinary(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700142 {
143 ws.binary(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800144 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
145 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700146 doWrite();
147 }
148
Ed Tanous863c1c22022-02-21 21:33:06 -0800149 void sendEx(MessageType type, std::string_view msg,
150 std::function<void()>&& onDone) override
151 {
152 if (doingWrite)
153 {
Ed Tanous62598e32023-07-17 17:06:25 -0700154 BMCWEB_LOG_CRITICAL(
155 "Cannot mix sendEx usage with sendBinary or sendText");
Ed Tanous863c1c22022-02-21 21:33:06 -0800156 onDone();
157 return;
158 }
159 ws.binary(type == MessageType::Binary);
160
161 ws.async_write(boost::asio::buffer(msg),
162 [weak(weak_from_this()), onDone{std::move(onDone)}](
163 const boost::beast::error_code& ec, size_t) {
164 std::shared_ptr<Connection> self = weak.lock();
zhaogang.0108a8894202023-12-22 08:53:40 +0000165 if (!self)
166 {
167 BMCWEB_LOG_ERROR("Connection went away");
168 return;
169 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800170
171 // Call the done handler regardless of whether we
172 // errored, but before we close things out
173 onDone();
174
175 if (ec)
176 {
Ed Tanous62598e32023-07-17 17:06:25 -0700177 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous863c1c22022-02-21 21:33:06 -0800178 self->close("write error");
179 }
180 });
181 }
182
Ed Tanous1abe55e2018-09-05 08:30:59 -0700183 void sendBinary(std::string&& msg) override
184 {
185 ws.binary(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800186 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
187 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700188 doWrite();
189 }
190
Ed Tanous26ccae32023-02-16 10:28:44 -0800191 void sendText(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700192 {
193 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800194 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
195 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700196 doWrite();
197 }
198
199 void sendText(std::string&& msg) override
200 {
201 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800202 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
203 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700204 doWrite();
205 }
206
Ed Tanous26ccae32023-02-16 10:28:44 -0800207 void close(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700208 {
209 ws.async_close(
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200210 {boost::beast::websocket::close_code::normal, msg},
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800211 [self(shared_from_this())](const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700212 if (ec == boost::asio::error::operation_aborted)
213 {
214 return;
215 }
216 if (ec)
217 {
Ed Tanous62598e32023-07-17 17:06:25 -0700218 BMCWEB_LOG_ERROR("Error closing websocket {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700219 return;
220 }
Patrick Williams5a39f772023-10-20 11:20:21 -0500221 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700222 }
223
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500224 boost::urls::url_view url() override
225 {
226 return uri;
227 }
228
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800229 void acceptDone(const std::shared_ptr<Connection>& /*self*/,
Ed Tanous52e31622024-01-23 16:31:11 -0800230 const std::unique_ptr<
Ed Tanousb2896142024-01-31 15:25:47 -0800231 boost::beast::http::request<bmcweb::HttpBody>>& /*req*/,
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800232 const boost::system::error_code& ec)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700233 {
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800234 if (ec)
235 {
236 BMCWEB_LOG_ERROR("Error in ws.async_accept {}", ec);
237 return;
238 }
Ed Tanous62598e32023-07-17 17:06:25 -0700239 BMCWEB_LOG_DEBUG("Websocket accepted connection");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700240
241 if (openHandler)
242 {
zhanghch0577726382021-10-21 14:07:57 +0800243 openHandler(*this);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700244 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800245 doRead();
246 }
247
248 void deferRead() override
249 {
250 readingDefered = true;
251
252 // If we're not actively reading, we need to take ownership of
253 // ourselves for a small portion of time, do that, and clear when we
254 // resume.
255 selfOwned = shared_from_this();
256 }
257
258 void resumeRead() override
259 {
260 readingDefered = false;
261 doRead();
262
263 // No longer need to keep ourselves alive now that read is active.
264 selfOwned.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700265 }
266
267 void doRead()
268 {
Ed Tanous863c1c22022-02-21 21:33:06 -0800269 if (readingDefered)
270 {
271 return;
272 }
273 ws.async_read(inBuffer, [this, self(shared_from_this())](
274 const boost::beast::error_code& ec,
275 size_t bytesRead) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700276 if (ec)
277 {
278 if (ec != boost::beast::websocket::error::closed)
279 {
Ed Tanous62598e32023-07-17 17:06:25 -0700280 BMCWEB_LOG_ERROR("doRead error {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700281 }
282 if (closeHandler)
283 {
Ed Tanous079360a2022-06-29 10:05:19 -0700284 std::string reason{ws.reason().reason.c_str()};
285 closeHandler(*this, reason);
Ed Tanous002d39b2022-05-31 08:59:27 -0700286 }
287 return;
288 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800289
290 handleMessage(bytesRead);
Ed Tanous002d39b2022-05-31 08:59:27 -0700291 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700292 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700293 void doWrite()
294 {
295 // If we're already doing a write, ignore the request, it will be picked
296 // up when the current write is complete
297 if (doingWrite)
298 {
299 return;
300 }
301
Ed Tanous863c1c22022-02-21 21:33:06 -0800302 if (outBuffer.size() == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700303 {
304 // Done for now
305 return;
306 }
307 doingWrite = true;
Ed Tanous863c1c22022-02-21 21:33:06 -0800308 ws.async_write(outBuffer.data(), [this, self(shared_from_this())](
309 const boost::beast::error_code& ec,
310 size_t bytesSent) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700311 doingWrite = false;
Ed Tanous863c1c22022-02-21 21:33:06 -0800312 outBuffer.consume(bytesSent);
Ed Tanous002d39b2022-05-31 08:59:27 -0700313 if (ec == boost::beast::websocket::error::closed)
314 {
315 // Do nothing here. doRead handler will call the
316 // closeHandler.
317 close("Write error");
318 return;
319 }
320 if (ec)
321 {
Ed Tanous62598e32023-07-17 17:06:25 -0700322 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700323 return;
324 }
325 doWrite();
326 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 }
328
329 private:
Ed Tanous863c1c22022-02-21 21:33:06 -0800330 void handleMessage(size_t bytesRead)
331 {
332 if (messageExHandler)
333 {
334 // Note, because of the interactions with the read buffers,
335 // this message handler overrides the normal message handler
336 messageExHandler(*this, inString, MessageType::Binary,
337 [this, self(shared_from_this()), bytesRead]() {
338 if (self == nullptr)
339 {
340 return;
341 }
342
343 inBuffer.consume(bytesRead);
344 inString.clear();
345
346 doRead();
347 });
348 return;
349 }
350
351 if (messageHandler)
352 {
353 messageHandler(*this, inString, ws.got_text());
354 }
355 inBuffer.consume(bytesRead);
356 inString.clear();
357 doRead();
358 }
359
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500360 boost::urls::url uri;
361
Ed Tanous2aee6ca2021-02-01 09:52:17 -0800362 boost::beast::websocket::stream<Adaptor, false> ws;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700363
Ed Tanous863c1c22022-02-21 21:33:06 -0800364 bool readingDefered = false;
Ed Tanous609145a2018-09-05 16:27:36 -0700365 std::string inString;
366 boost::asio::dynamic_string_buffer<std::string::value_type,
367 std::string::traits_type,
368 std::string::allocator_type>
369 inBuffer;
Ed Tanous863c1c22022-02-21 21:33:06 -0800370
371 boost::beast::multi_buffer outBuffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700372 bool doingWrite = false;
373
zhanghch0577726382021-10-21 14:07:57 +0800374 std::function<void(Connection&)> openHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700375 std::function<void(Connection&, const std::string&, bool)> messageHandler;
Ed Tanous863c1c22022-02-21 21:33:06 -0800376 std::function<void(crow::websocket::Connection&, std::string_view,
377 crow::websocket::MessageType type,
378 std::function<void()>&& whenComplete)>
379 messageExHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700380 std::function<void(Connection&, const std::string&)> closeHandler;
381 std::function<void(Connection&)> errorHandler;
Ed Tanous52cc1122020-07-18 13:51:21 -0700382 std::shared_ptr<persistent_data::UserSession> session;
Ed Tanous863c1c22022-02-21 21:33:06 -0800383
384 std::shared_ptr<Connection> selfOwned;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700385};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700386} // namespace websocket
387} // namespace crow