blob: 0faa8c60c7f433f612398ac122dd203f715d385b [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 Tanous04e438c2020-10-03 08:06:26 -07003#include "http_request.hpp"
Gunnar Mills1214b7e2020-06-04 10:11:30 -05004
Ed Tanous609145a2018-09-05 16:27:36 -07005#include <boost/asio/buffer.hpp>
Ed Tanous863c1c22022-02-21 21:33:06 -08006#include <boost/beast/core/multi_buffer.hpp>
Ed Tanous1b0044b2018-08-03 14:30:05 -07007#include <boost/beast/websocket.hpp>
Ed Tanous1abe55e2018-09-05 08:30:59 -07008
Gunnar Mills1214b7e2020-06-04 10:11:30 -05009#include <array>
10#include <functional>
Ed Tanous1b0044b2018-08-03 14:30:05 -070011
12#ifdef BMCWEB_ENABLE_SSL
13#include <boost/beast/websocket/ssl.hpp>
14#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -070015
Ed Tanous1abe55e2018-09-05 08:30:59 -070016namespace crow
17{
18namespace websocket
19{
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020020
Ed Tanous863c1c22022-02-21 21:33:06 -080021enum class MessageType
22{
23 Binary,
24 Text,
25};
26
Ed Tanous1abe55e2018-09-05 08:30:59 -070027struct Connection : std::enable_shared_from_this<Connection>
28{
29 public:
Patrick Williams89492a12023-05-10 07:51:34 -050030 explicit Connection(const crow::Request& reqIn) : req(reqIn.req) {}
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +010031
Ed Tanousecd6a3a2022-01-07 09:18:40 -080032 Connection(const Connection&) = delete;
33 Connection(Connection&&) = delete;
34 Connection& operator=(const Connection&) = delete;
35 Connection& operator=(const Connection&&) = delete;
36
Ed Tanous9eb808c2022-01-25 10:19:23 -080037 virtual void sendBinary(std::string_view msg) = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -070038 virtual void sendBinary(std::string&& 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 Tanous1abe55e2018-09-05 08:30:59 -070042 virtual void sendText(std::string&& msg) = 0;
Ed Tanous9eb808c2022-01-25 10:19:23 -080043 virtual void close(std::string_view msg = "quit") = 0;
Ed Tanous863c1c22022-02-21 21:33:06 -080044 virtual void deferRead() = 0;
45 virtual void resumeRead() = 0;
Ed Tanous2c70f802020-09-28 14:29:23 -070046 virtual boost::asio::io_context& getIoContext() = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -070047 virtual ~Connection() = default;
Ninad Palsule052bcbf2023-05-30 11:10:58 -050048 virtual boost::urls::url_view url() = 0;
Jan Sowinskiee52ae12020-01-09 16:28:32 +000049 boost::beast::http::request<boost::beast::http::string_body> req;
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{
55 public:
56 ConnectionImpl(
Ninad Palsule052bcbf2023-05-30 11:10:58 -050057 const crow::Request& reqIn, boost::urls::url_view urlViewIn,
58 Adaptor adaptorIn, std::function<void(Connection&)> openHandlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070059 std::function<void(Connection&, const std::string&, bool)>
Ed Tanous8a592812022-06-04 09:06:59 -070060 messageHandlerIn,
Ed Tanous863c1c22022-02-21 21:33:06 -080061 std::function<void(crow::websocket::Connection&, std::string_view,
62 crow::websocket::MessageType type,
63 std::function<void()>&& whenComplete)>
64 messageExHandlerIn,
Ed Tanous8a592812022-06-04 09:06:59 -070065 std::function<void(Connection&, const std::string&)> closeHandlerIn,
66 std::function<void(Connection&)> errorHandlerIn) :
Ed Tanouse551b5f2023-02-27 14:19:07 -080067 Connection(reqIn),
Ninad Palsule052bcbf2023-05-30 11:10:58 -050068 uri(urlViewIn), ws(std::move(adaptorIn)), inBuffer(inString, 131088),
Ed Tanous8a592812022-06-04 09:06:59 -070069 openHandler(std::move(openHandlerIn)),
70 messageHandler(std::move(messageHandlerIn)),
Ed Tanous863c1c22022-02-21 21:33:06 -080071 messageExHandler(std::move(messageExHandlerIn)),
Ed Tanous8a592812022-06-04 09:06:59 -070072 closeHandler(std::move(closeHandlerIn)),
73 errorHandler(std::move(errorHandlerIn)), session(reqIn.session)
Ed Tanous1abe55e2018-09-05 08:30:59 -070074 {
dhineskumare02bdd962021-07-08 16:06:49 +053075 /* Turn on the timeouts on websocket stream to server role */
76 ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(
77 boost::beast::role_type::server));
Ed Tanous1abe55e2018-09-05 08:30:59 -070078 BMCWEB_LOG_DEBUG << "Creating new connection " << this;
Ed Tanous7045c8d2017-04-03 10:04:37 -070079 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070080
Ed Tanous2c70f802020-09-28 14:29:23 -070081 boost::asio::io_context& getIoContext() override
Ed Tanous1abe55e2018-09-05 08:30:59 -070082 {
Ed Tanous271584a2019-07-09 16:24:22 -070083 return static_cast<boost::asio::io_context&>(
84 ws.get_executor().context());
Ed Tanous911ac312017-08-15 09:37:42 -070085 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070086
Ed Tanous1abe55e2018-09-05 08:30:59 -070087 void start()
88 {
89 BMCWEB_LOG_DEBUG << "starting connection " << this;
Ed Tanous7045c8d2017-04-03 10:04:37 -070090
Ed Tanousfe5b2162019-05-22 14:28:16 -070091 using bf = boost::beast::http::field;
92
Jan Sowinskiee52ae12020-01-09 16:28:32 +000093 std::string_view protocol = req[bf::sec_websocket_protocol];
Ed Tanous7045c8d2017-04-03 10:04:37 -070094
Ed Tanousd4d77e32020-08-18 00:07:28 -070095 ws.set_option(boost::beast::websocket::stream_base::decorator(
James Feistf8aa3d22020-04-08 18:32:33 -070096 [session{session}, protocol{std::string(protocol)}](
Ed Tanous1abe55e2018-09-05 08:30:59 -070097 boost::beast::websocket::response_type& m) {
James Feistf8aa3d22020-04-08 18:32:33 -070098
99#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
Ed Tanous002d39b2022-05-31 08:59:27 -0700100 if (session != nullptr)
101 {
102 // use protocol for csrf checking
Gunnar Millse628df82023-04-04 10:15:42 -0500103 if (!crow::utility::constantTimeStringCompare(
Ed Tanous002d39b2022-05-31 08:59:27 -0700104 protocol, session->csrfToken))
James Feistf8aa3d22020-04-08 18:32:33 -0700105 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700106 BMCWEB_LOG_ERROR << "Websocket CSRF error";
107 m.result(boost::beast::http::status::unauthorized);
108 return;
James Feistf8aa3d22020-04-08 18:32:33 -0700109 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700110 }
James Feistf8aa3d22020-04-08 18:32:33 -0700111#endif
Ed Tanous002d39b2022-05-31 08:59:27 -0700112 if (!protocol.empty())
113 {
114 m.insert(bf::sec_websocket_protocol, protocol);
115 }
Ed Tanousfe5b2162019-05-22 14:28:16 -0700116
Ed Tanous002d39b2022-05-31 08:59:27 -0700117 m.insert(bf::strict_transport_security, "max-age=31536000; "
118 "includeSubdomains; "
119 "preload");
120 m.insert(bf::pragma, "no-cache");
121 m.insert(bf::cache_control, "no-Store,no-Cache");
122 m.insert("Content-Security-Policy", "default-src 'self'");
123 m.insert("X-XSS-Protection", "1; "
124 "mode=block");
125 m.insert("X-Content-Type-Options", "nosniff");
126 }));
Ed Tanousd4d77e32020-08-18 00:07:28 -0700127
128 // Perform the websocket upgrade
129 ws.async_accept(req, [this, self(shared_from_this())](
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800130 const boost::system::error_code& ec) {
Ed Tanousd4d77e32020-08-18 00:07:28 -0700131 if (ec)
132 {
133 BMCWEB_LOG_ERROR << "Error in ws.async_accept " << ec;
134 return;
135 }
136 acceptDone();
137 });
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 {
153 BMCWEB_LOG_CRITICAL
154 << "Cannot mix sendEx usage with sendBinary or sendText";
155 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();
164
165 // Call the done handler regardless of whether we
166 // errored, but before we close things out
167 onDone();
168
169 if (ec)
170 {
171 BMCWEB_LOG_ERROR << "Error in ws.async_write " << ec;
172 self->close("write error");
173 }
174 });
175 }
176
Ed Tanous1abe55e2018-09-05 08:30:59 -0700177 void sendBinary(std::string&& msg) override
178 {
179 ws.binary(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800180 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
181 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700182 doWrite();
183 }
184
Ed Tanous26ccae32023-02-16 10:28:44 -0800185 void sendText(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700186 {
187 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800188 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
189 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700190 doWrite();
191 }
192
193 void sendText(std::string&& msg) override
194 {
195 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800196 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
197 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700198 doWrite();
199 }
200
Ed Tanous26ccae32023-02-16 10:28:44 -0800201 void close(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700202 {
203 ws.async_close(
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200204 {boost::beast::websocket::close_code::normal, msg},
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800205 [self(shared_from_this())](const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700206 if (ec == boost::asio::error::operation_aborted)
207 {
208 return;
209 }
210 if (ec)
211 {
212 BMCWEB_LOG_ERROR << "Error closing websocket " << ec;
213 return;
214 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700215 });
216 }
217
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500218 boost::urls::url_view url() override
219 {
220 return uri;
221 }
222
Ed Tanous1abe55e2018-09-05 08:30:59 -0700223 void acceptDone()
224 {
225 BMCWEB_LOG_DEBUG << "Websocket accepted connection";
226
227 if (openHandler)
228 {
zhanghch0577726382021-10-21 14:07:57 +0800229 openHandler(*this);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700230 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800231 doRead();
232 }
233
234 void deferRead() override
235 {
236 readingDefered = true;
237
238 // If we're not actively reading, we need to take ownership of
239 // ourselves for a small portion of time, do that, and clear when we
240 // resume.
241 selfOwned = shared_from_this();
242 }
243
244 void resumeRead() override
245 {
246 readingDefered = false;
247 doRead();
248
249 // No longer need to keep ourselves alive now that read is active.
250 selfOwned.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700251 }
252
253 void doRead()
254 {
Ed Tanous863c1c22022-02-21 21:33:06 -0800255 if (readingDefered)
256 {
257 return;
258 }
259 ws.async_read(inBuffer, [this, self(shared_from_this())](
260 const boost::beast::error_code& ec,
261 size_t bytesRead) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700262 if (ec)
263 {
264 if (ec != boost::beast::websocket::error::closed)
265 {
266 BMCWEB_LOG_ERROR << "doRead error " << ec;
267 }
268 if (closeHandler)
269 {
Ed Tanous079360a2022-06-29 10:05:19 -0700270 std::string reason{ws.reason().reason.c_str()};
271 closeHandler(*this, reason);
Ed Tanous002d39b2022-05-31 08:59:27 -0700272 }
273 return;
274 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800275
276 handleMessage(bytesRead);
Ed Tanous002d39b2022-05-31 08:59:27 -0700277 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700278 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 void doWrite()
280 {
281 // If we're already doing a write, ignore the request, it will be picked
282 // up when the current write is complete
283 if (doingWrite)
284 {
285 return;
286 }
287
Ed Tanous863c1c22022-02-21 21:33:06 -0800288 if (outBuffer.size() == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700289 {
290 // Done for now
291 return;
292 }
293 doingWrite = true;
Ed Tanous863c1c22022-02-21 21:33:06 -0800294 ws.async_write(outBuffer.data(), [this, self(shared_from_this())](
295 const boost::beast::error_code& ec,
296 size_t bytesSent) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700297 doingWrite = false;
Ed Tanous863c1c22022-02-21 21:33:06 -0800298 outBuffer.consume(bytesSent);
Ed Tanous002d39b2022-05-31 08:59:27 -0700299 if (ec == boost::beast::websocket::error::closed)
300 {
301 // Do nothing here. doRead handler will call the
302 // closeHandler.
303 close("Write error");
304 return;
305 }
306 if (ec)
307 {
308 BMCWEB_LOG_ERROR << "Error in ws.async_write " << ec;
309 return;
310 }
311 doWrite();
312 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700313 }
314
315 private:
Ed Tanous863c1c22022-02-21 21:33:06 -0800316 void handleMessage(size_t bytesRead)
317 {
318 if (messageExHandler)
319 {
320 // Note, because of the interactions with the read buffers,
321 // this message handler overrides the normal message handler
322 messageExHandler(*this, inString, MessageType::Binary,
323 [this, self(shared_from_this()), bytesRead]() {
324 if (self == nullptr)
325 {
326 return;
327 }
328
329 inBuffer.consume(bytesRead);
330 inString.clear();
331
332 doRead();
333 });
334 return;
335 }
336
337 if (messageHandler)
338 {
339 messageHandler(*this, inString, ws.got_text());
340 }
341 inBuffer.consume(bytesRead);
342 inString.clear();
343 doRead();
344 }
345
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500346 boost::urls::url uri;
347
Ed Tanous2aee6ca2021-02-01 09:52:17 -0800348 boost::beast::websocket::stream<Adaptor, false> ws;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700349
Ed Tanous863c1c22022-02-21 21:33:06 -0800350 bool readingDefered = false;
Ed Tanous609145a2018-09-05 16:27:36 -0700351 std::string inString;
352 boost::asio::dynamic_string_buffer<std::string::value_type,
353 std::string::traits_type,
354 std::string::allocator_type>
355 inBuffer;
Ed Tanous863c1c22022-02-21 21:33:06 -0800356
357 boost::beast::multi_buffer outBuffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 bool doingWrite = false;
359
zhanghch0577726382021-10-21 14:07:57 +0800360 std::function<void(Connection&)> openHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700361 std::function<void(Connection&, const std::string&, bool)> messageHandler;
Ed Tanous863c1c22022-02-21 21:33:06 -0800362 std::function<void(crow::websocket::Connection&, std::string_view,
363 crow::websocket::MessageType type,
364 std::function<void()>&& whenComplete)>
365 messageExHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700366 std::function<void(Connection&, const std::string&)> closeHandler;
367 std::function<void(Connection&)> errorHandler;
Ed Tanous52cc1122020-07-18 13:51:21 -0700368 std::shared_ptr<persistent_data::UserSession> session;
Ed Tanous863c1c22022-02-21 21:33:06 -0800369
370 std::shared_ptr<Connection> selfOwned;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700371};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700372} // namespace websocket
373} // namespace crow