blob: 4262c70a5c5d87897ae989b9a79f645ce7c37c21 [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 Tanous863c1c22022-02-21 21:33:06 -080039 virtual void sendEx(MessageType type, std::string_view msg,
40 std::function<void()>&& onDone) = 0;
Ed Tanous9eb808c2022-01-25 10:19:23 -080041 virtual void sendText(std::string_view msg) = 0;
Ed Tanous9eb808c2022-01-25 10:19:23 -080042 virtual void close(std::string_view msg = "quit") = 0;
Ed Tanous863c1c22022-02-21 21:33:06 -080043 virtual void deferRead() = 0;
44 virtual void resumeRead() = 0;
Ed Tanous2c70f802020-09-28 14:29:23 -070045 virtual boost::asio::io_context& getIoContext() = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -070046 virtual ~Connection() = default;
Ninad Palsule052bcbf2023-05-30 11:10:58 -050047 virtual boost::urls::url_view url() = 0;
Ed Tanous7045c8d2017-04-03 10:04:37 -070048};
49
Gunnar Mills1214b7e2020-06-04 10:11:30 -050050template <typename Adaptor>
51class ConnectionImpl : public Connection
Ed Tanous1abe55e2018-09-05 08:30:59 -070052{
Ed Tanous5ebb9d32023-02-27 18:20:47 -080053 using self_t = ConnectionImpl<Adaptor>;
54
Ed Tanous1abe55e2018-09-05 08:30:59 -070055 public:
56 ConnectionImpl(
Ed Tanous5ebb9d32023-02-27 18:20:47 -080057 const boost::urls::url_view& urlViewIn,
58 const std::shared_ptr<persistent_data::UserSession>& sessionIn,
Ninad Palsule052bcbf2023-05-30 11:10:58 -050059 Adaptor adaptorIn, std::function<void(Connection&)> openHandlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070060 std::function<void(Connection&, const std::string&, bool)>
Ed Tanous8a592812022-06-04 09:06:59 -070061 messageHandlerIn,
Ed Tanous863c1c22022-02-21 21:33:06 -080062 std::function<void(crow::websocket::Connection&, std::string_view,
63 crow::websocket::MessageType type,
64 std::function<void()>&& whenComplete)>
65 messageExHandlerIn,
Ed Tanous8a592812022-06-04 09:06:59 -070066 std::function<void(Connection&, const std::string&)> closeHandlerIn,
67 std::function<void(Connection&)> errorHandlerIn) :
Ed Tanous5ebb9d32023-02-27 18:20:47 -080068 uri(urlViewIn),
69 ws(std::move(adaptorIn)), inBuffer(inString, 131088),
Ed Tanous8a592812022-06-04 09:06:59 -070070 openHandler(std::move(openHandlerIn)),
71 messageHandler(std::move(messageHandlerIn)),
Ed Tanous863c1c22022-02-21 21:33:06 -080072 messageExHandler(std::move(messageExHandlerIn)),
Ed Tanous8a592812022-06-04 09:06:59 -070073 closeHandler(std::move(closeHandlerIn)),
Ed Tanous5ebb9d32023-02-27 18:20:47 -080074 errorHandler(std::move(errorHandlerIn)), session(sessionIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070075 {
dhineskumare02bdd962021-07-08 16:06:49 +053076 /* Turn on the timeouts on websocket stream to server role */
77 ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(
78 boost::beast::role_type::server));
Ed Tanous62598e32023-07-17 17:06:25 -070079 BMCWEB_LOG_DEBUG("Creating new connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070080 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070081
Ed Tanous2c70f802020-09-28 14:29:23 -070082 boost::asio::io_context& getIoContext() override
Ed Tanous1abe55e2018-09-05 08:30:59 -070083 {
Ed Tanous271584a2019-07-09 16:24:22 -070084 return static_cast<boost::asio::io_context&>(
85 ws.get_executor().context());
Ed Tanous911ac312017-08-15 09:37:42 -070086 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070087
Ed Tanous5ebb9d32023-02-27 18:20:47 -080088 void start(const crow::Request& req)
Ed Tanous1abe55e2018-09-05 08:30:59 -070089 {
Ed Tanous62598e32023-07-17 17:06:25 -070090 BMCWEB_LOG_DEBUG("starting connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070091
Ed Tanousfe5b2162019-05-22 14:28:16 -070092 using bf = boost::beast::http::field;
Myung Bae1873a042024-04-01 09:27:39 -050093 std::string protocolHeader{
94 req.getHeaderValue(bf::sec_websocket_protocol)};
Ed Tanous7045c8d2017-04-03 10:04:37 -070095
Ed Tanousd4d77e32020-08-18 00:07:28 -070096 ws.set_option(boost::beast::websocket::stream_base::decorator(
Ed Tanous5ebb9d32023-02-27 18:20:47 -080097 [session{session},
98 protocolHeader](boost::beast::websocket::response_type& m) {
James Feistf8aa3d22020-04-08 18:32:33 -070099
100#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
Ed Tanous002d39b2022-05-31 08:59:27 -0700101 if (session != nullptr)
102 {
103 // use protocol for csrf checking
Ed Tanous7e9c08e2023-06-16 11:29:37 -0700104 if (session->cookieAuth &&
105 !crow::utility::constantTimeStringCompare(
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800106 protocolHeader, session->csrfToken))
James Feistf8aa3d22020-04-08 18:32:33 -0700107 {
Ed Tanous62598e32023-07-17 17:06:25 -0700108 BMCWEB_LOG_ERROR("Websocket CSRF error");
Ed Tanous002d39b2022-05-31 08:59:27 -0700109 m.result(boost::beast::http::status::unauthorized);
110 return;
James Feistf8aa3d22020-04-08 18:32:33 -0700111 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700112 }
James Feistf8aa3d22020-04-08 18:32:33 -0700113#endif
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800114 if (!protocolHeader.empty())
Ed Tanous002d39b2022-05-31 08:59:27 -0700115 {
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800116 m.insert(bf::sec_websocket_protocol, protocolHeader);
Ed Tanous002d39b2022-05-31 08:59:27 -0700117 }
Ed Tanousfe5b2162019-05-22 14:28:16 -0700118
Ed Tanous002d39b2022-05-31 08:59:27 -0700119 m.insert(bf::strict_transport_security, "max-age=31536000; "
120 "includeSubdomains; "
121 "preload");
122 m.insert(bf::pragma, "no-cache");
123 m.insert(bf::cache_control, "no-Store,no-Cache");
124 m.insert("Content-Security-Policy", "default-src 'self'");
125 m.insert("X-XSS-Protection", "1; "
126 "mode=block");
127 m.insert("X-Content-Type-Options", "nosniff");
128 }));
Ed Tanousd4d77e32020-08-18 00:07:28 -0700129
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800130 // Make a pointer to keep the req alive while we accept it.
Ed Tanousb2896142024-01-31 15:25:47 -0800131 using Body = boost::beast::http::request<bmcweb::HttpBody>;
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800132 std::unique_ptr<Body> mobile = std::make_unique<Body>(req.req);
133 Body* ptr = mobile.get();
Ed Tanousd4d77e32020-08-18 00:07:28 -0700134 // Perform the websocket upgrade
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800135 ws.async_accept(*ptr,
136 std::bind_front(&self_t::acceptDone, this,
137 shared_from_this(), std::move(mobile)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700138 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700139
Ed Tanous26ccae32023-02-16 10:28:44 -0800140 void sendBinary(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700141 {
142 ws.binary(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800143 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
144 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700145 doWrite();
146 }
147
Ed Tanous863c1c22022-02-21 21:33:06 -0800148 void sendEx(MessageType type, std::string_view msg,
149 std::function<void()>&& onDone) override
150 {
151 if (doingWrite)
152 {
Ed Tanous62598e32023-07-17 17:06:25 -0700153 BMCWEB_LOG_CRITICAL(
154 "Cannot mix sendEx usage with sendBinary or sendText");
Ed Tanous863c1c22022-02-21 21:33:06 -0800155 onDone();
156 return;
157 }
158 ws.binary(type == MessageType::Binary);
159
160 ws.async_write(boost::asio::buffer(msg),
161 [weak(weak_from_this()), onDone{std::move(onDone)}](
162 const boost::beast::error_code& ec, size_t) {
163 std::shared_ptr<Connection> self = weak.lock();
zhaogang.0108a8894202023-12-22 08:53:40 +0000164 if (!self)
165 {
166 BMCWEB_LOG_ERROR("Connection went away");
167 return;
168 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800169
170 // Call the done handler regardless of whether we
171 // errored, but before we close things out
172 onDone();
173
174 if (ec)
175 {
Ed Tanous62598e32023-07-17 17:06:25 -0700176 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous863c1c22022-02-21 21:33:06 -0800177 self->close("write error");
178 }
179 });
180 }
181
Ed Tanous26ccae32023-02-16 10:28:44 -0800182 void sendText(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700183 {
184 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800185 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
186 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700187 doWrite();
188 }
189
Ed Tanous26ccae32023-02-16 10:28:44 -0800190 void close(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700191 {
192 ws.async_close(
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200193 {boost::beast::websocket::close_code::normal, msg},
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800194 [self(shared_from_this())](const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700195 if (ec == boost::asio::error::operation_aborted)
196 {
197 return;
198 }
199 if (ec)
200 {
Ed Tanous62598e32023-07-17 17:06:25 -0700201 BMCWEB_LOG_ERROR("Error closing websocket {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700202 return;
203 }
Patrick Williams5a39f772023-10-20 11:20:21 -0500204 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700205 }
206
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500207 boost::urls::url_view url() override
208 {
209 return uri;
210 }
211
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800212 void acceptDone(const std::shared_ptr<Connection>& /*self*/,
Ed Tanous52e31622024-01-23 16:31:11 -0800213 const std::unique_ptr<
Ed Tanousb2896142024-01-31 15:25:47 -0800214 boost::beast::http::request<bmcweb::HttpBody>>& /*req*/,
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800215 const boost::system::error_code& ec)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700216 {
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800217 if (ec)
218 {
219 BMCWEB_LOG_ERROR("Error in ws.async_accept {}", ec);
220 return;
221 }
Ed Tanous62598e32023-07-17 17:06:25 -0700222 BMCWEB_LOG_DEBUG("Websocket accepted connection");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700223
224 if (openHandler)
225 {
zhanghch0577726382021-10-21 14:07:57 +0800226 openHandler(*this);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700227 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800228 doRead();
229 }
230
231 void deferRead() override
232 {
233 readingDefered = true;
234
235 // If we're not actively reading, we need to take ownership of
236 // ourselves for a small portion of time, do that, and clear when we
237 // resume.
238 selfOwned = shared_from_this();
239 }
240
241 void resumeRead() override
242 {
243 readingDefered = false;
244 doRead();
245
246 // No longer need to keep ourselves alive now that read is active.
247 selfOwned.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248 }
249
250 void doRead()
251 {
Ed Tanous863c1c22022-02-21 21:33:06 -0800252 if (readingDefered)
253 {
254 return;
255 }
256 ws.async_read(inBuffer, [this, self(shared_from_this())](
257 const boost::beast::error_code& ec,
258 size_t bytesRead) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700259 if (ec)
260 {
261 if (ec != boost::beast::websocket::error::closed)
262 {
Ed Tanous62598e32023-07-17 17:06:25 -0700263 BMCWEB_LOG_ERROR("doRead error {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700264 }
265 if (closeHandler)
266 {
Ed Tanous079360a2022-06-29 10:05:19 -0700267 std::string reason{ws.reason().reason.c_str()};
268 closeHandler(*this, reason);
Ed Tanous002d39b2022-05-31 08:59:27 -0700269 }
270 return;
271 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800272
273 handleMessage(bytesRead);
Ed Tanous002d39b2022-05-31 08:59:27 -0700274 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700275 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700276 void doWrite()
277 {
278 // If we're already doing a write, ignore the request, it will be picked
279 // up when the current write is complete
280 if (doingWrite)
281 {
282 return;
283 }
284
Ed Tanous863c1c22022-02-21 21:33:06 -0800285 if (outBuffer.size() == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700286 {
287 // Done for now
288 return;
289 }
290 doingWrite = true;
Ed Tanous863c1c22022-02-21 21:33:06 -0800291 ws.async_write(outBuffer.data(), [this, self(shared_from_this())](
292 const boost::beast::error_code& ec,
293 size_t bytesSent) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700294 doingWrite = false;
Ed Tanous863c1c22022-02-21 21:33:06 -0800295 outBuffer.consume(bytesSent);
Ed Tanous002d39b2022-05-31 08:59:27 -0700296 if (ec == boost::beast::websocket::error::closed)
297 {
298 // Do nothing here. doRead handler will call the
299 // closeHandler.
300 close("Write error");
301 return;
302 }
303 if (ec)
304 {
Ed Tanous62598e32023-07-17 17:06:25 -0700305 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700306 return;
307 }
308 doWrite();
309 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700310 }
311
312 private:
Ed Tanous863c1c22022-02-21 21:33:06 -0800313 void handleMessage(size_t bytesRead)
314 {
315 if (messageExHandler)
316 {
317 // Note, because of the interactions with the read buffers,
318 // this message handler overrides the normal message handler
319 messageExHandler(*this, inString, MessageType::Binary,
320 [this, self(shared_from_this()), bytesRead]() {
321 if (self == nullptr)
322 {
323 return;
324 }
325
326 inBuffer.consume(bytesRead);
327 inString.clear();
328
329 doRead();
330 });
331 return;
332 }
333
334 if (messageHandler)
335 {
336 messageHandler(*this, inString, ws.got_text());
337 }
338 inBuffer.consume(bytesRead);
339 inString.clear();
340 doRead();
341 }
342
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500343 boost::urls::url uri;
344
Ed Tanous2aee6ca2021-02-01 09:52:17 -0800345 boost::beast::websocket::stream<Adaptor, false> ws;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346
Ed Tanous863c1c22022-02-21 21:33:06 -0800347 bool readingDefered = false;
Ed Tanous609145a2018-09-05 16:27:36 -0700348 std::string inString;
349 boost::asio::dynamic_string_buffer<std::string::value_type,
350 std::string::traits_type,
351 std::string::allocator_type>
352 inBuffer;
Ed Tanous863c1c22022-02-21 21:33:06 -0800353
354 boost::beast::multi_buffer outBuffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 bool doingWrite = false;
356
zhanghch0577726382021-10-21 14:07:57 +0800357 std::function<void(Connection&)> openHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 std::function<void(Connection&, const std::string&, bool)> messageHandler;
Ed Tanous863c1c22022-02-21 21:33:06 -0800359 std::function<void(crow::websocket::Connection&, std::string_view,
360 crow::websocket::MessageType type,
361 std::function<void()>&& whenComplete)>
362 messageExHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700363 std::function<void(Connection&, const std::string&)> closeHandler;
364 std::function<void(Connection&)> errorHandler;
Ed Tanous52cc1122020-07-18 13:51:21 -0700365 std::shared_ptr<persistent_data::UserSession> session;
Ed Tanous863c1c22022-02-21 21:33:06 -0800366
367 std::shared_ptr<Connection> selfOwned;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700368};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700369} // namespace websocket
370} // namespace crow