blob: 027ab246428ea06cea38f27f54f090eabe7f6160 [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 Tanous5ebb9d32023-02-27 18:20:47 -080030 Connection() = default;
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;
Ed Tanous7045c8d2017-04-03 10:04:37 -070049};
50
Gunnar Mills1214b7e2020-06-04 10:11:30 -050051template <typename Adaptor>
52class ConnectionImpl : public Connection
Ed Tanous1abe55e2018-09-05 08:30:59 -070053{
Ed Tanous5ebb9d32023-02-27 18:20:47 -080054 using self_t = ConnectionImpl<Adaptor>;
55
Ed Tanous1abe55e2018-09-05 08:30:59 -070056 public:
57 ConnectionImpl(
Ed Tanous5ebb9d32023-02-27 18:20:47 -080058 const boost::urls::url_view& urlViewIn,
59 const std::shared_ptr<persistent_data::UserSession>& sessionIn,
Ninad Palsule052bcbf2023-05-30 11:10:58 -050060 Adaptor adaptorIn, std::function<void(Connection&)> openHandlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 std::function<void(Connection&, const std::string&, bool)>
Ed Tanous8a592812022-06-04 09:06:59 -070062 messageHandlerIn,
Ed Tanous863c1c22022-02-21 21:33:06 -080063 std::function<void(crow::websocket::Connection&, std::string_view,
64 crow::websocket::MessageType type,
65 std::function<void()>&& whenComplete)>
66 messageExHandlerIn,
Ed Tanous8a592812022-06-04 09:06:59 -070067 std::function<void(Connection&, const std::string&)> closeHandlerIn,
68 std::function<void(Connection&)> errorHandlerIn) :
Ed Tanous5ebb9d32023-02-27 18:20:47 -080069 uri(urlViewIn),
70 ws(std::move(adaptorIn)), inBuffer(inString, 131088),
Ed Tanous8a592812022-06-04 09:06:59 -070071 openHandler(std::move(openHandlerIn)),
72 messageHandler(std::move(messageHandlerIn)),
Ed Tanous863c1c22022-02-21 21:33:06 -080073 messageExHandler(std::move(messageExHandlerIn)),
Ed Tanous8a592812022-06-04 09:06:59 -070074 closeHandler(std::move(closeHandlerIn)),
Ed Tanous5ebb9d32023-02-27 18:20:47 -080075 errorHandler(std::move(errorHandlerIn)), session(sessionIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070076 {
dhineskumare02bdd962021-07-08 16:06:49 +053077 /* Turn on the timeouts on websocket stream to server role */
78 ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(
79 boost::beast::role_type::server));
Ed Tanous62598e32023-07-17 17:06:25 -070080 BMCWEB_LOG_DEBUG("Creating new connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070081 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070082
Ed Tanous2c70f802020-09-28 14:29:23 -070083 boost::asio::io_context& getIoContext() override
Ed Tanous1abe55e2018-09-05 08:30:59 -070084 {
Ed Tanous271584a2019-07-09 16:24:22 -070085 return static_cast<boost::asio::io_context&>(
86 ws.get_executor().context());
Ed Tanous911ac312017-08-15 09:37:42 -070087 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070088
Ed Tanous5ebb9d32023-02-27 18:20:47 -080089 void start(const crow::Request& req)
Ed Tanous1abe55e2018-09-05 08:30:59 -070090 {
Ed Tanous62598e32023-07-17 17:06:25 -070091 BMCWEB_LOG_DEBUG("starting connection {}", logPtr(this));
Ed Tanous7045c8d2017-04-03 10:04:37 -070092
Ed Tanousfe5b2162019-05-22 14:28:16 -070093 using bf = boost::beast::http::field;
Ed Tanous5ebb9d32023-02-27 18:20:47 -080094 std::string protocolHeader = req.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(
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.
131 using Body =
132 boost::beast::http::request<boost::beast::http::string_body>;
133 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();
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 {
Ed Tanous62598e32023-07-17 17:06:25 -0700172 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous863c1c22022-02-21 21:33:06 -0800173 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 {
Ed Tanous62598e32023-07-17 17:06:25 -0700213 BMCWEB_LOG_ERROR("Error closing websocket {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700214 return;
215 }
Patrick Williams5a39f772023-10-20 11:20:21 -0500216 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700217 }
218
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500219 boost::urls::url_view url() override
220 {
221 return uri;
222 }
223
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800224 void acceptDone(const std::shared_ptr<Connection>& /*self*/,
225 const std::unique_ptr<boost::beast::http::request<
226 boost::beast::http::string_body>>& /*req*/,
227 const boost::system::error_code& ec)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700228 {
Ed Tanous5ebb9d32023-02-27 18:20:47 -0800229 if (ec)
230 {
231 BMCWEB_LOG_ERROR("Error in ws.async_accept {}", ec);
232 return;
233 }
Ed Tanous62598e32023-07-17 17:06:25 -0700234 BMCWEB_LOG_DEBUG("Websocket accepted connection");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700235
236 if (openHandler)
237 {
zhanghch0577726382021-10-21 14:07:57 +0800238 openHandler(*this);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700239 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800240 doRead();
241 }
242
243 void deferRead() override
244 {
245 readingDefered = true;
246
247 // If we're not actively reading, we need to take ownership of
248 // ourselves for a small portion of time, do that, and clear when we
249 // resume.
250 selfOwned = shared_from_this();
251 }
252
253 void resumeRead() override
254 {
255 readingDefered = false;
256 doRead();
257
258 // No longer need to keep ourselves alive now that read is active.
259 selfOwned.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 }
261
262 void doRead()
263 {
Ed Tanous863c1c22022-02-21 21:33:06 -0800264 if (readingDefered)
265 {
266 return;
267 }
268 ws.async_read(inBuffer, [this, self(shared_from_this())](
269 const boost::beast::error_code& ec,
270 size_t bytesRead) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700271 if (ec)
272 {
273 if (ec != boost::beast::websocket::error::closed)
274 {
Ed Tanous62598e32023-07-17 17:06:25 -0700275 BMCWEB_LOG_ERROR("doRead error {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700276 }
277 if (closeHandler)
278 {
Ed Tanous079360a2022-06-29 10:05:19 -0700279 std::string reason{ws.reason().reason.c_str()};
280 closeHandler(*this, reason);
Ed Tanous002d39b2022-05-31 08:59:27 -0700281 }
282 return;
283 }
Ed Tanous863c1c22022-02-21 21:33:06 -0800284
285 handleMessage(bytesRead);
Ed Tanous002d39b2022-05-31 08:59:27 -0700286 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700287 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700288 void doWrite()
289 {
290 // If we're already doing a write, ignore the request, it will be picked
291 // up when the current write is complete
292 if (doingWrite)
293 {
294 return;
295 }
296
Ed Tanous863c1c22022-02-21 21:33:06 -0800297 if (outBuffer.size() == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700298 {
299 // Done for now
300 return;
301 }
302 doingWrite = true;
Ed Tanous863c1c22022-02-21 21:33:06 -0800303 ws.async_write(outBuffer.data(), [this, self(shared_from_this())](
304 const boost::beast::error_code& ec,
305 size_t bytesSent) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700306 doingWrite = false;
Ed Tanous863c1c22022-02-21 21:33:06 -0800307 outBuffer.consume(bytesSent);
Ed Tanous002d39b2022-05-31 08:59:27 -0700308 if (ec == boost::beast::websocket::error::closed)
309 {
310 // Do nothing here. doRead handler will call the
311 // closeHandler.
312 close("Write error");
313 return;
314 }
315 if (ec)
316 {
Ed Tanous62598e32023-07-17 17:06:25 -0700317 BMCWEB_LOG_ERROR("Error in ws.async_write {}", ec);
Ed Tanous002d39b2022-05-31 08:59:27 -0700318 return;
319 }
320 doWrite();
321 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700322 }
323
324 private:
Ed Tanous863c1c22022-02-21 21:33:06 -0800325 void handleMessage(size_t bytesRead)
326 {
327 if (messageExHandler)
328 {
329 // Note, because of the interactions with the read buffers,
330 // this message handler overrides the normal message handler
331 messageExHandler(*this, inString, MessageType::Binary,
332 [this, self(shared_from_this()), bytesRead]() {
333 if (self == nullptr)
334 {
335 return;
336 }
337
338 inBuffer.consume(bytesRead);
339 inString.clear();
340
341 doRead();
342 });
343 return;
344 }
345
346 if (messageHandler)
347 {
348 messageHandler(*this, inString, ws.got_text());
349 }
350 inBuffer.consume(bytesRead);
351 inString.clear();
352 doRead();
353 }
354
Ninad Palsule052bcbf2023-05-30 11:10:58 -0500355 boost::urls::url uri;
356
Ed Tanous2aee6ca2021-02-01 09:52:17 -0800357 boost::beast::websocket::stream<Adaptor, false> ws;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358
Ed Tanous863c1c22022-02-21 21:33:06 -0800359 bool readingDefered = false;
Ed Tanous609145a2018-09-05 16:27:36 -0700360 std::string inString;
361 boost::asio::dynamic_string_buffer<std::string::value_type,
362 std::string::traits_type,
363 std::string::allocator_type>
364 inBuffer;
Ed Tanous863c1c22022-02-21 21:33:06 -0800365
366 boost::beast::multi_buffer outBuffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700367 bool doingWrite = false;
368
zhanghch0577726382021-10-21 14:07:57 +0800369 std::function<void(Connection&)> openHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700370 std::function<void(Connection&, const std::string&, bool)> messageHandler;
Ed Tanous863c1c22022-02-21 21:33:06 -0800371 std::function<void(crow::websocket::Connection&, std::string_view,
372 crow::websocket::MessageType type,
373 std::function<void()>&& whenComplete)>
374 messageExHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700375 std::function<void(Connection&, const std::string&)> closeHandler;
376 std::function<void(Connection&)> errorHandler;
Ed Tanous52cc1122020-07-18 13:51:21 -0700377 std::shared_ptr<persistent_data::UserSession> session;
Ed Tanous863c1c22022-02-21 21:33:06 -0800378
379 std::shared_ptr<Connection> selfOwned;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700380};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700381} // namespace websocket
382} // namespace crow