blob: 87742008ceb27169b0ba62adb0136ee7ba36f771 [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:
Ed Tanouse551b5f2023-02-27 14:19:07 -080030 explicit Connection(const crow::Request& reqIn) : req(reqIn.req)
Ed Tanous23a21a12020-07-25 04:45:05 +000031 {}
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;
Ed Tanous7045c8d2017-04-03 10:04:37 -070049
Jan Sowinskiee52ae12020-01-09 16:28:32 +000050 boost::beast::http::request<boost::beast::http::string_body> req;
Ed Tanous7045c8d2017-04-03 10:04:37 -070051};
52
Gunnar Mills1214b7e2020-06-04 10:11:30 -050053template <typename Adaptor>
54class ConnectionImpl : public Connection
Ed Tanous1abe55e2018-09-05 08:30:59 -070055{
56 public:
57 ConnectionImpl(
Jan Sowinskiee52ae12020-01-09 16:28:32 +000058 const crow::Request& reqIn, Adaptor adaptorIn,
Ed Tanous8a592812022-06-04 09:06:59 -070059 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 Tanouse551b5f2023-02-27 14:19:07 -080068 Connection(reqIn),
Ed Tanouse05aec52022-01-25 10:28:56 -080069 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)),
74 errorHandler(std::move(errorHandlerIn)), session(reqIn.session)
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 Tanous1abe55e2018-09-05 08:30:59 -070079 BMCWEB_LOG_DEBUG << "Creating new connection " << 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 Tanous1abe55e2018-09-05 08:30:59 -070088 void start()
89 {
90 BMCWEB_LOG_DEBUG << "starting connection " << this;
Ed Tanous7045c8d2017-04-03 10:04:37 -070091
Ed Tanousfe5b2162019-05-22 14:28:16 -070092 using bf = boost::beast::http::field;
93
Jan Sowinskiee52ae12020-01-09 16:28:32 +000094 std::string_view protocol = req[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(
James Feistf8aa3d22020-04-08 18:32:33 -070097 [session{session}, protocol{std::string(protocol)}](
Ed Tanous1abe55e2018-09-05 08:30:59 -070098 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
Gunnar Millse628df82023-04-04 10:15:42 -0500104 if (!crow::utility::constantTimeStringCompare(
Ed Tanous002d39b2022-05-31 08:59:27 -0700105 protocol, session->csrfToken))
James Feistf8aa3d22020-04-08 18:32:33 -0700106 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700107 BMCWEB_LOG_ERROR << "Websocket CSRF error";
108 m.result(boost::beast::http::status::unauthorized);
109 return;
James Feistf8aa3d22020-04-08 18:32:33 -0700110 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700111 }
James Feistf8aa3d22020-04-08 18:32:33 -0700112#endif
Ed Tanous002d39b2022-05-31 08:59:27 -0700113 if (!protocol.empty())
114 {
115 m.insert(bf::sec_websocket_protocol, protocol);
116 }
Ed Tanousfe5b2162019-05-22 14:28:16 -0700117
Ed Tanous002d39b2022-05-31 08:59:27 -0700118 m.insert(bf::strict_transport_security, "max-age=31536000; "
119 "includeSubdomains; "
120 "preload");
121 m.insert(bf::pragma, "no-cache");
122 m.insert(bf::cache_control, "no-Store,no-Cache");
123 m.insert("Content-Security-Policy", "default-src 'self'");
124 m.insert("X-XSS-Protection", "1; "
125 "mode=block");
126 m.insert("X-Content-Type-Options", "nosniff");
127 }));
Ed Tanousd4d77e32020-08-18 00:07:28 -0700128
129 // Perform the websocket upgrade
130 ws.async_accept(req, [this, self(shared_from_this())](
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800131 const boost::system::error_code& ec) {
Ed Tanousd4d77e32020-08-18 00:07:28 -0700132 if (ec)
133 {
134 BMCWEB_LOG_ERROR << "Error in ws.async_accept " << ec;
135 return;
136 }
137 acceptDone();
138 });
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 {
154 BMCWEB_LOG_CRITICAL
155 << "Cannot mix sendEx usage with sendBinary or sendText";
156 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();
165
166 // Call the done handler regardless of whether we
167 // errored, but before we close things out
168 onDone();
169
170 if (ec)
171 {
172 BMCWEB_LOG_ERROR << "Error in ws.async_write " << ec;
173 self->close("write error");
174 }
175 });
176 }
177
Ed Tanous1abe55e2018-09-05 08:30:59 -0700178 void sendBinary(std::string&& msg) override
179 {
180 ws.binary(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800181 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
182 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700183 doWrite();
184 }
185
Ed Tanous26ccae32023-02-16 10:28:44 -0800186 void sendText(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700187 {
188 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800189 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
190 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700191 doWrite();
192 }
193
194 void sendText(std::string&& msg) override
195 {
196 ws.text(true);
Ed Tanous863c1c22022-02-21 21:33:06 -0800197 outBuffer.commit(boost::asio::buffer_copy(outBuffer.prepare(msg.size()),
198 boost::asio::buffer(msg)));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700199 doWrite();
200 }
201
Ed Tanous26ccae32023-02-16 10:28:44 -0800202 void close(std::string_view msg) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700203 {
204 ws.async_close(
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200205 {boost::beast::websocket::close_code::normal, msg},
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800206 [self(shared_from_this())](const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700207 if (ec == boost::asio::error::operation_aborted)
208 {
209 return;
210 }
211 if (ec)
212 {
213 BMCWEB_LOG_ERROR << "Error closing websocket " << ec;
214 return;
215 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700216 });
217 }
218
219 void acceptDone()
220 {
221 BMCWEB_LOG_DEBUG << "Websocket accepted connection";
222
223 if (openHandler)
224 {
zhanghch0577726382021-10-21 14:07:57 +0800225 openHandler(*this);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700226 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800227 doRead();
228 }
229
230 void deferRead() override
231 {
232 readingDefered = true;
233
234 // If we're not actively reading, we need to take ownership of
235 // ourselves for a small portion of time, do that, and clear when we
236 // resume.
237 selfOwned = shared_from_this();
238 }
239
240 void resumeRead() override
241 {
242 readingDefered = false;
243 doRead();
244
245 // No longer need to keep ourselves alive now that read is active.
246 selfOwned.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700247 }
248
249 void doRead()
250 {
Ed Tanous863c1c22022-02-21 21:33:06 -0800251 if (readingDefered)
252 {
253 return;
254 }
255 ws.async_read(inBuffer, [this, self(shared_from_this())](
256 const boost::beast::error_code& ec,
257 size_t bytesRead) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700258 if (ec)
259 {
260 if (ec != boost::beast::websocket::error::closed)
261 {
262 BMCWEB_LOG_ERROR << "doRead error " << ec;
263 }
264 if (closeHandler)
265 {
Ed Tanous079360a2022-06-29 10:05:19 -0700266 std::string reason{ws.reason().reason.c_str()};
267 closeHandler(*this, reason);
Ed Tanous002d39b2022-05-31 08:59:27 -0700268 }
269 return;
270 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800271
272 handleMessage(bytesRead);
Ed Tanous002d39b2022-05-31 08:59:27 -0700273 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700274 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700275 void doWrite()
276 {
277 // If we're already doing a write, ignore the request, it will be picked
278 // up when the current write is complete
279 if (doingWrite)
280 {
281 return;
282 }
283
Ed Tanous863c1c22022-02-21 21:33:06 -0800284 if (outBuffer.size() == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700285 {
286 // Done for now
287 return;
288 }
289 doingWrite = true;
Ed Tanous863c1c22022-02-21 21:33:06 -0800290 ws.async_write(outBuffer.data(), [this, self(shared_from_this())](
291 const boost::beast::error_code& ec,
292 size_t bytesSent) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700293 doingWrite = false;
Ed Tanous863c1c22022-02-21 21:33:06 -0800294 outBuffer.consume(bytesSent);
Ed Tanous002d39b2022-05-31 08:59:27 -0700295 if (ec == boost::beast::websocket::error::closed)
296 {
297 // Do nothing here. doRead handler will call the
298 // closeHandler.
299 close("Write error");
300 return;
301 }
302 if (ec)
303 {
304 BMCWEB_LOG_ERROR << "Error in ws.async_write " << ec;
305 return;
306 }
307 doWrite();
308 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700309 }
310
311 private:
Ed Tanous863c1c22022-02-21 21:33:06 -0800312 void handleMessage(size_t bytesRead)
313 {
314 if (messageExHandler)
315 {
316 // Note, because of the interactions with the read buffers,
317 // this message handler overrides the normal message handler
318 messageExHandler(*this, inString, MessageType::Binary,
319 [this, self(shared_from_this()), bytesRead]() {
320 if (self == nullptr)
321 {
322 return;
323 }
324
325 inBuffer.consume(bytesRead);
326 inString.clear();
327
328 doRead();
329 });
330 return;
331 }
332
333 if (messageHandler)
334 {
335 messageHandler(*this, inString, ws.got_text());
336 }
337 inBuffer.consume(bytesRead);
338 inString.clear();
339 doRead();
340 }
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