Crow  1.1
A C++ microframework for the web
 
Loading...
Searching...
No Matches
websocket.h
1#pragma once
2#include <array>
3#include <cstring>
4#include <memory>
5#include <optional>
6#include <string>
7#include <thread>
8#include "crow/http_response.h"
9#include "crow/logging.h"
10#include "crow/socket_adaptors.h"
11#include "crow/http_request.h"
12#include "crow/tcp_socket_options.h"
13#include "crow/TinySHA1.hpp"
14#include "crow/utility.h"
15
16namespace crow // NOTE: Already documented in "crow/app.h"
17{
18#ifdef CROW_USE_BOOST
19 namespace asio = boost::asio;
20 using error_code = boost::system::error_code;
21#else
22 using error_code = asio::error_code;
23#endif
24
25 /**
26 * \namespace crow::websocket
27 * \brief Namespace that includes the \ref Connection class
28 * and \ref connection struct. Useful for WebSockets connection.
29 *
30 * Used specially in crow/websocket.h, crow/app.h and crow/routing.h
31 */
32 namespace websocket
33 {
34 enum class WebSocketReadState
35 {
36 MiniHeader,
37 Len16,
38 Len64,
39 Mask,
40 Payload,
41 };
42
43 // Codes taken from https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1
44 enum CloseStatusCode : uint16_t {
45 NormalClosure = 1000,
46 EndpointGoingAway = 1001,
47 ProtocolError = 1002,
48 UnacceptableData = 1003,
49 InconsistentData = 1007,
50 PolicyViolated = 1008,
51 MessageTooBig = 1009,
52 ExtensionsNotNegotiated = 1010,
53 UnexpectedCondition = 1011,
54
55 // Reserved for applications only, should not send/receive these to/from clients
56 NoStatusCodePresent = 1005,
57 ClosedAbnormally = 1006,
58 TLSHandshakeFailure = 1015,
59
60 StartStatusCodesForLibraries = 3000,
61 StartStatusCodesForPrivateUse = 4000,
62 // Status code should be between 1000 and 4999 inclusive
63 StartStatusCodes = NormalClosure,
64 EndStatusCodes = 4999,
65 };
66
67 /// A base class for websocket connection.
69 {
70 virtual void send_binary(std::string msg) = 0;
71 virtual void send_text(std::string msg) = 0;
72 virtual void send_ping(std::string msg) = 0;
73 virtual void send_pong(std::string msg) = 0;
74 virtual void close(std::string const& msg = "quit", uint16_t status_code = CloseStatusCode::NormalClosure) = 0;
75 virtual std::string get_remote_ip() = 0;
76 virtual uint16_t get_remote_port() = 0;
77 virtual std::string get_subprotocol() const = 0;
78 virtual ~connection() = default;
79
80 void userdata(void* u) { userdata_ = u; }
81 void* userdata() { return userdata_; }
82
83 private:
84 void* userdata_{nullptr};
85 };
86
87 // Modified version of the illustration in RFC6455 Section-5.2
88 //
89 //
90 // 0 1 2 3 -byte
91 // 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 -bit
92 // +-+-+-+-+-------+-+-------------+-------------------------------+
93 // |F|R|R|R| opcode|M| Payload len | Extended payload length |
94 // |I|S|S|S| (4) |A| (7) | (16/64) |
95 // |N|V|V|V| |S| | (if payload len==126/127) |
96 // | |1|2|3| |K| | |
97 // +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
98 // | Extended payload length continued, if payload len == 127 |
99 // + - - - - - - - - - - - - - - - +-------------------------------+
100 // | |Masking-key, if MASK set to 1 |
101 // +-------------------------------+-------------------------------+
102 // | Masking-key (continued) | Payload Data |
103 // +-------------------------------- - - - - - - - - - - - - - - - +
104 // : Payload Data continued ... :
105 // + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
106 // | Payload Data continued ... |
107 // +---------------------------------------------------------------+
108 //
109
110 /// A websocket connection.
111
112 template<typename Adaptor, typename Handler>
113 class Connection : public connection, public std::enable_shared_from_this<Connection<Adaptor, Handler>>
114 {
115 public:
116 /// Factory for a connection.
117 ///
118 /// Requires a request with an "Upgrade: websocket" header.<br>
119 /// Automatically handles the handshake.
120 static void create(const crow::request& req, Adaptor adaptor, Handler* handler,
121 uint64_t max_payload, const std::vector<std::string>& subprotocols,
122 std::function<void(crow::websocket::connection&)> open_handler,
123 std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler,
124 std::function<void(crow::websocket::connection&, const std::string&, uint16_t)> close_handler,
125 std::function<void(crow::websocket::connection&, const std::string&)> error_handler,
126 std::function<void(const crow::request&, std::optional<crow::response>&, void**)> accept_handler,
127 bool mirror_protocols,
128 const detail::socket::tcp_socket_options& tcp_options = {})
129 {
130 auto conn = std::shared_ptr<Connection>(new Connection(std::move(adaptor),
131 handler, max_payload,
132 std::move(open_handler),
133 std::move(message_handler),
134 std::move(close_handler),
135 std::move(error_handler),
136 std::move(accept_handler)));
137
138 // Apply TCP socket options to WebSocket connection
139 detail::socket::apply_tcp_socket_options(conn->adaptor_.socket(), tcp_options);
140
141 // Kept for get_remote_ip(), which must still answer once the socket is closed (e.g. in onclose)
142 conn->remote_ip_ = req.remote_ip_address;
143
144 // Perform handshake validation
145 if (!utility::string_equals(req.get_header_value("upgrade"), "websocket"))
146 {
147 conn->adaptor_.close();
148 return;
149 }
150
151 std::string requested_subprotocols_header = req.get_header_value("Sec-WebSocket-Protocol");
152 if (!subprotocols.empty() || !requested_subprotocols_header.empty())
153 {
154 auto requested_subprotocols = utility::split(requested_subprotocols_header, ", ");
155 auto subprotocol = utility::find_first_of(subprotocols.begin(), subprotocols.end(), requested_subprotocols.begin(), requested_subprotocols.end());
156 if (subprotocol != subprotocols.end())
157 {
158 conn->subprotocol_ = *subprotocol;
159 }
160 }
161
162 if (mirror_protocols & !requested_subprotocols_header.empty())
163 {
164 conn->subprotocol_ = requested_subprotocols_header;
165 }
166
167 if (conn->accept_handler_)
168 {
169 void* ud = nullptr;
170 std::optional<crow::response> res;
171 conn->accept_handler_(req, res, &ud);
172 if (res)
173 {
174 std::vector<asio::const_buffer> buffers;
175 auto server_name = "";
176 std::string content_length_buffer;
177 res->write_header_into_buffer(buffers, content_length_buffer, req.keep_alive, server_name);
178 buffers.emplace_back(res->body.data(), res->body.size());
179 error_code ec;
180 asio::write(conn->adaptor_.socket(), buffers, ec);
181 conn->adaptor_.close();
182 return;
183 }
184 conn->userdata(ud);
185 }
186
187 // Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
188 // Sec-WebSocket-Version: 13
189 std::string magic = req.get_header_value("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
190 sha1::SHA1 s;
191 s.processBytes(magic.data(), magic.size());
192 uint8_t digest[20];
193 s.getDigestBytes(digest);
194
195 conn->handler_->add_websocket(conn);
196 conn->start(crow::utility::base64encode((unsigned char*)digest, 20));
197 }
198
199 ~Connection() noexcept override = default;
200
201 template<typename Callable>
203 {
204 Callable callable;
205 std::weak_ptr<void> watch;
206
207 void operator()()
208 {
209 if (auto anchor = watch.lock())
210 {
211 std::move(callable)();
212 }
213 }
214 };
215
216 /// Send data through the socket.
217 template<typename CompletionHandler>
218 void dispatch(CompletionHandler&& handler)
219 {
220 asio::dispatch(adaptor_.get_io_context(),
221 WeakWrappedMessage<typename std::decay<CompletionHandler>::type>{
222 std::forward<CompletionHandler>(handler), anchor_});
223 }
224
225 /// Send data through the socket and return immediately.
226 template<typename CompletionHandler>
227 void post(CompletionHandler&& handler)
228 {
229 asio::post(adaptor_.get_io_context(),
230 WeakWrappedMessage<typename std::decay<CompletionHandler>::type>{
231 std::forward<CompletionHandler>(handler), anchor_});
232 }
233
234 /// Send a "Ping" message.
235
236 ///
237 /// Usually invoked to check if the other point is still online.
238 void send_ping(std::string msg) override
239 {
240 send_data(0x9, std::move(msg));
241 }
242
243 /// Send a "Pong" message.
244
245 ///
246 /// Usually automatically invoked as a response to a "Ping" message.
247 void send_pong(std::string msg) override
248 {
249 send_data(0xA, std::move(msg));
250 }
251
252 /// Send a binary encoded message.
253 void send_binary(std::string msg) override
254 {
255 send_data(0x2, std::move(msg));
256 }
257
258 /// Send a plaintext message.
259 void send_text(std::string msg) override
260 {
261 send_data(0x1, std::move(msg));
262 }
263
264 /// Send a close signal.
265
266 ///
267 /// Sets a flag to destroy the object once the message is sent.
268 void close(std::string const& msg, uint16_t status_code) override
269 {
270 dispatch([shared_this = this->shared_from_this(), msg, status_code]() mutable {
271 shared_this->has_sent_close_ = true;
272 if (shared_this->has_recv_close_ && !shared_this->is_close_handler_called_)
273 {
274 shared_this->is_close_handler_called_ = true;
275 if (shared_this->close_handler_)
276 shared_this->close_handler_(*shared_this, msg, status_code);
277 }
278
279 switch(status_code) {
280
281 case NoStatusCodePresent:
282 case ClosedAbnormally:
283 case TLSHandshakeFailure:
284 // These codes only report that no status code was received and must not
285 // be sent in a Close frame (RFC 6455 Section 7.4.1), so send none at all.
286 {
287 shared_this->write_buffers_.emplace_back(shared_this->build_header(0x8, 0));
288 }
289 break;
290 default:
291 {
292 auto header = shared_this->build_header(0x8, msg.size() + 2);
293 char status_buf[2];
294 uint16_t network_status_code = htons(status_code);
295 std::memcpy(status_buf, &network_status_code, sizeof(network_status_code));
296
297 shared_this->write_buffers_.emplace_back(std::move(header));
298 shared_this->write_buffers_.emplace_back(std::string(status_buf, 2));
299 shared_this->write_buffers_.emplace_back(msg);
300 }
301 }
302 shared_this->do_write();
303 });
304 }
305
306 /// Returns the IP address the connection was opened from, also once the socket is closed (empty for a Unix domain socket).
307 std::string get_remote_ip() override
308 {
309 return remote_ip_;
310 }
311
312 /// Returns the TCP port of the remote endpoint, 0 when unavailable (Unix domain socket or socket already closed).
313 uint16_t get_remote_port() override
314 {
315 return adaptor_.remote_port();
316 }
317
318 void set_max_payload_size(uint64_t payload)
319 {
320 max_payload_bytes_ = payload;
321 }
322
323 /// Returns the matching client/server subprotocol, empty string if none matched.
324 std::string get_subprotocol() const override
325 {
326 return subprotocol_;
327 }
328
329 protected:
330 /// Generate the websocket headers using an opcode and the message size (in bytes).
331 std::string build_header(int opcode, size_t size)
332 {
333 char buf[2 + 8] = "\x80\x00";
334 buf[0] += opcode;
335 if (size < 126)
336 {
337 buf[1] += static_cast<char>(size);
338 return {buf, buf + 2};
339 }
340 else if (size < 0x10000)
341 {
342 buf[1] += 126;
343 uint16_t len = htons(static_cast<uint16_t>(size));
344 std::memcpy(buf + 2, &len, sizeof(len));
345 return {buf, buf + 4};
346 }
347 else
348 {
349 buf[1] += 127;
350 uint64_t len = ((1 == htonl(1)) ? static_cast<uint64_t>(size) : (static_cast<uint64_t>(htonl((size) & 0xFFFFFFFF)) << 32) | htonl(static_cast<uint64_t>(size) >> 32));
351 std::memcpy(buf + 2, &len, sizeof(len));
352 return {buf, buf + 10};
353 }
354 }
355
356 /// Send the HTTP upgrade response.
357
358 ///
359 /// Finishes the handshake process, then starts reading messages from the socket.
360 void start(std::string&& hello)
361 {
362 static const std::string header =
363 "HTTP/1.1 101 Switching Protocols\r\n"
364 "Upgrade: websocket\r\n"
365 "Connection: Upgrade\r\n"
366 "Sec-WebSocket-Accept: ";
367 write_buffers_.emplace_back(header);
368 write_buffers_.emplace_back(std::move(hello));
369 write_buffers_.emplace_back(crlf);
370 if (!subprotocol_.empty())
371 {
372 write_buffers_.emplace_back("Sec-WebSocket-Protocol: ");
373 write_buffers_.emplace_back(subprotocol_);
374 write_buffers_.emplace_back(crlf);
375 }
376 write_buffers_.emplace_back(crlf);
377 do_write();
378 if (open_handler_ && !call_handler([this] { open_handler_(*this); }))
379 return;
380 do_read();
381 }
382
383 /// Read a websocket message.
384
385 ///
386 /// Involves:<br>
387 /// Handling headers (opcodes, size).<br>
388 /// Unmasking the payload.<br>
389 /// Reading the actual payload.<br>
390 void do_read()
391 {
392 if (has_sent_close_ && has_recv_close_)
393 {
394 close_connection_ = true;
395 adaptor_.shutdown_readwrite();
396 adaptor_.close();
397 check_destroy();
398 return;
399 }
400
401 is_reading = true;
402 switch (state_)
403 {
404 case WebSocketReadState::MiniHeader:
405 {
406 mini_header_ = 0;
407 asio::async_read(
408 adaptor_.socket(), asio::buffer(&mini_header_, 2),
409 [shared_this = this->shared_from_this()](const error_code& ec, std::size_t
410#ifdef CROW_ENABLE_DEBUG
411 bytes_transferred
412#endif
413 )
414
415 {
416 shared_this->is_reading = false;
417 shared_this->mini_header_ = ntohs(shared_this->mini_header_);
418#ifdef CROW_ENABLE_DEBUG
419
420 if (!ec && bytes_transferred != 2)
421 {
422 throw std::runtime_error("WebSocket:MiniHeader:async_read fail:asio bug?");
423 }
424#endif
425
426 if (!ec)
427 {
428 if ((shared_this->mini_header_ & 0x80) == 0x80)
429 shared_this->has_mask_ = true;
430 else //if the websocket specification is enforced and the message isn't masked, terminate the connection
431 {
432#ifndef CROW_ENFORCE_WS_SPEC
433 shared_this->has_mask_ = false;
434#else
435 shared_this->close_connection_ = true;
436 shared_this->adaptor_.shutdown_readwrite();
437 shared_this->adaptor_.close();
438 if (shared_this->error_handler_)
439 shared_this->error_handler_(*shared_this, "Client connection not masked.");
440 shared_this->check_destroy(CloseStatusCode::UnacceptableData);
441 return;
442#endif
443 }
444
445 if ((shared_this->mini_header_ & 0x7f) == 127)
446 {
447 shared_this->state_ = WebSocketReadState::Len64;
448 }
449 else if ((shared_this->mini_header_ & 0x7f) == 126)
450 {
451 shared_this->state_ = WebSocketReadState::Len16;
452 }
453 else
454 {
455 shared_this->remaining_length_ = shared_this->mini_header_ & 0x7f;
456 shared_this->state_ = WebSocketReadState::Mask;
457 }
458 shared_this->do_read();
459 }
460 else
461 {
462 shared_this->close_connection_ = true;
463 shared_this->adaptor_.shutdown_readwrite();
464 shared_this->adaptor_.close();
465 if (shared_this->error_handler_)
466 shared_this->error_handler_(*shared_this, ec.message());
467 shared_this->check_destroy();
468 }
469 });
470 }
471 break;
472 case WebSocketReadState::Len16:
473 {
474 remaining_length_ = 0;
475 remaining_length16_ = 0;
476 asio::async_read(
477 adaptor_.socket(), asio::buffer(&remaining_length16_, 2),
478 [shared_this = this->shared_from_this()](const error_code& ec, std::size_t
479#ifdef CROW_ENABLE_DEBUG
480 bytes_transferred
481#endif
482 ) {
483 shared_this->is_reading = false;
484 shared_this->remaining_length16_ = ntohs(shared_this->remaining_length16_);
485 shared_this->remaining_length_ = shared_this->remaining_length16_;
486#ifdef CROW_ENABLE_DEBUG
487 if (!ec && bytes_transferred != 2)
488 {
489 throw std::runtime_error("WebSocket:Len16:async_read fail:asio bug?");
490 }
491#endif
492
493 if (!ec)
494 {
495 shared_this->state_ = WebSocketReadState::Mask;
496 shared_this->do_read();
497 }
498 else
499 {
500 shared_this->close_connection_ = true;
501 shared_this->adaptor_.shutdown_readwrite();
502 shared_this->adaptor_.close();
503 if (shared_this->error_handler_)
504 shared_this->error_handler_(*shared_this, ec.message());
505 shared_this->check_destroy();
506 }
507 });
508 }
509 break;
510 case WebSocketReadState::Len64:
511 {
512 asio::async_read(
513 adaptor_.socket(), asio::buffer(&remaining_length_, 8),
514 [shared_this = this->shared_from_this()](const error_code& ec, std::size_t
515#ifdef CROW_ENABLE_DEBUG
516 bytes_transferred
517#endif
518 ) {
519 shared_this->is_reading = false;
520 shared_this->remaining_length_ = ((1 == ntohl(1)) ? (shared_this->remaining_length_) : (static_cast<uint64_t>(ntohl((shared_this->remaining_length_)&0xFFFFFFFF)) << 32) | ntohl((shared_this->remaining_length_) >> 32));
521#ifdef CROW_ENABLE_DEBUG
522 if (!ec && bytes_transferred != 8)
523 {
524 throw std::runtime_error("WebSocket:Len16:async_read fail:asio bug?");
525 }
526#endif
527
528 if (!ec)
529 {
530 shared_this->state_ = WebSocketReadState::Mask;
531 shared_this->do_read();
532 }
533 else
534 {
535 shared_this->close_connection_ = true;
536 shared_this->adaptor_.shutdown_readwrite();
537 shared_this->adaptor_.close();
538 if (shared_this->error_handler_)
539 shared_this->error_handler_(*shared_this, ec.message());
540 shared_this->check_destroy();
541 }
542 });
543 }
544 break;
545 case WebSocketReadState::Mask:
546 if (message_.size() > max_payload_bytes_ ||
547 remaining_length_ > max_payload_bytes_ - message_.size())
548 {
549 close_connection_ = true;
550 adaptor_.close();
551 if (error_handler_)
552 error_handler_(*this, "Message length exceeds maximum payload.");
553 check_destroy(MessageTooBig);
554 }
555 else if (has_mask_)
556 {
557 asio::async_read(
558 adaptor_.socket(), asio::buffer((char*)&mask_, 4),
559 [shared_this = this->shared_from_this()](const error_code& ec, std::size_t
560#ifdef CROW_ENABLE_DEBUG
561 bytes_transferred
562#endif
563 ) {
564 shared_this->is_reading = false;
565#ifdef CROW_ENABLE_DEBUG
566 if (!ec && bytes_transferred != 4)
567 {
568 throw std::runtime_error("WebSocket:Mask:async_read fail:asio bug?");
569 }
570#endif
571
572 if (!ec)
573 {
574 shared_this->state_ = WebSocketReadState::Payload;
575 shared_this->do_read();
576 }
577 else
578 {
579 shared_this->close_connection_ = true;
580 if (shared_this->error_handler_)
581 shared_this->error_handler_(*shared_this, ec.message());
582 shared_this->adaptor_.shutdown_readwrite();
583 shared_this->adaptor_.close();
584 shared_this->check_destroy();
585 }
586 });
587 }
588 else
589 {
590 state_ = WebSocketReadState::Payload;
591 do_read();
592 }
593 break;
594 case WebSocketReadState::Payload:
595 {
596 auto to_read = static_cast<std::uint64_t>(buffer_.size());
597 if (remaining_length_ < to_read)
598 to_read = remaining_length_;
599 adaptor_.socket().async_read_some(
600 asio::buffer(buffer_, static_cast<std::size_t>(to_read)),
601 [shared_this = this->shared_from_this()](const error_code& ec, std::size_t bytes_transferred) {
602 shared_this->is_reading = false;
603
604 if (!ec)
605 {
606 shared_this->fragment_.insert(shared_this->fragment_.end(), shared_this->buffer_.begin(), shared_this->buffer_.begin() + bytes_transferred);
607 shared_this->remaining_length_ -= bytes_transferred;
608 if (shared_this->remaining_length_ == 0)
609 {
610 if (shared_this->handle_fragment())
611 {
612 shared_this->state_ = WebSocketReadState::MiniHeader;
613 shared_this->do_read();
614 }
615 }
616 else
617 shared_this->do_read();
618 }
619 else
620 {
621 shared_this->close_connection_ = true;
622 if (shared_this->error_handler_)
623 shared_this->error_handler_(*shared_this, ec.message());
624 shared_this->adaptor_.shutdown_readwrite();
625 shared_this->adaptor_.close();
626 shared_this->check_destroy();
627 }
628 });
629 }
630 break;
631 }
632 }
633
634 /// Check if the FIN bit is set.
635 bool is_FIN()
636 {
637 return mini_header_ & 0x8000;
638 }
639
640 /// Extract the opcode from the header.
641 int opcode()
642 {
643 return (mini_header_ & 0x0f00) >> 8;
644 }
645
646 /// Process the payload fragment.
647
648 ///
649 /// Unmasks the fragment, checks the opcode, merges fragments into 1 message body, and calls the appropriate handler.
651 {
652 if (has_mask_)
653 {
654 for (decltype(fragment_.length()) i = 0; i < fragment_.length(); i++)
655 {
656 fragment_[i] ^= ((char*)&mask_)[i % 4];
657 }
658 }
659 if ((mini_header_ & 0x7000) != 0)
660 {
661 if (error_handler_)
662 error_handler_(*this, "RSV bits set without a negotiated extension.");
663 close("", CloseStatusCode::ProtocolError);
664 check_destroy(CloseStatusCode::ProtocolError);
665 return false;
666 }
667 if ((opcode() & 0x8) != 0 && (!is_FIN() || fragment_.size() > 125))
668 {
669 if (error_handler_)
670 error_handler_(*this, "Fragmented or oversized control frame.");
671 close("", CloseStatusCode::ProtocolError);
672 check_destroy(CloseStatusCode::ProtocolError);
673 return false;
674 }
675 switch (opcode())
676 {
677 case 0: // Continuation
678 {
679 if (!has_unfinished_message_)
680 {
681 if (error_handler_)
682 error_handler_(*this, "Continuation frame without a message to continue.");
683 close("", CloseStatusCode::ProtocolError);
684 check_destroy(CloseStatusCode::ProtocolError);
685 return false;
686 }
687 message_ += fragment_;
688 if (is_FIN() && !finish_message())
689 return false;
690 }
691 break;
692 case 1: // Text
693 case 2: // Binary
694 {
695 if (has_unfinished_message_)
696 {
697 if (error_handler_)
698 error_handler_(*this, "New message before the fragmented message was finished.");
699 close("", CloseStatusCode::ProtocolError);
700 check_destroy(CloseStatusCode::ProtocolError);
701 return false;
702 }
703 is_binary_ = opcode() == 2;
704 message_ += fragment_;
705 if (is_FIN())
706 {
707 if (!finish_message())
708 return false;
709 }
710 else
711 {
712 has_unfinished_message_ = true;
713 }
714 }
715 break;
716 case 0x8: // Close
717 {
718 has_recv_close_ = true;
719 uint16_t status_code = NoStatusCodePresent;
720 std::string::size_type message_start = 2;
721 if (fragment_.size() >= 2)
722 {
723 status_code = ntohs(((uint16_t*)fragment_.data())[0]);
724 } else {
725 // no message will crash substr
726 message_start = 0;
727 }
728
729 if (!has_sent_close_)
730 {
731 if (fragment_.size() == 1 || (fragment_.size() >= 2 && !is_valid_close_code(status_code)))
732 {
733 if (error_handler_)
734 error_handler_(*this, "Invalid close frame.");
735 close("", CloseStatusCode::ProtocolError);
736 }
737 else
738 {
739 close(fragment_.substr(message_start), status_code);
740 }
741 }
742 else
743 {
744
745 close_connection_ = true;
746 if (!is_close_handler_called_)
747 {
748 if (close_handler_)
749 close_handler_(*this, fragment_.substr(message_start), status_code);
750 is_close_handler_called_ = true;
751 }
752 adaptor_.shutdown_readwrite();
753 adaptor_.close();
754
755 // Close handler must have been called at this point so code does not matter
756 check_destroy();
757 return false;
758 }
759 }
760 break;
761 case 0x9: // Ping
762 {
763 send_pong(fragment_);
764 }
765 break;
766 case 0xA: // Pong
767 {
768 pong_received_ = true;
769 }
770 break;
771 default:
772 {
773 if (error_handler_)
774 error_handler_(*this, "Reserved opcode.");
775 close("", CloseStatusCode::ProtocolError);
776 check_destroy(CloseStatusCode::ProtocolError);
777 return false;
778 }
779 }
780
781 fragment_.clear();
782 return true;
783 }
784
785 /// Pass the complete message to the message handler and get ready for the next one.
786
787 ///
788 /// Returns false if the handler threw, in which case the connection is being closed.
790 {
791 has_unfinished_message_ = false;
792 bool handled = !message_handler_ || call_handler([this] { message_handler_(*this, message_, is_binary_); });
793 message_.clear();
794 return handled;
795 }
796
797 /// Call a user handler.
798
799 ///
800 /// An exception escaping the handler is reported to the error handler and the connection is closed with UnexpectedCondition.<br>
801 /// Returns false in that case, nothing more should be read from the connection.
802 template<typename Callable>
803 bool call_handler(Callable&& handler)
804 {
805 std::string error;
806 try
807 {
808 handler();
809 return true;
810 }
811 catch (const std::exception& e)
812 {
813 error = e.what();
814 }
815 catch (...)
816 {
817 error = "Unknown exception.";
818 }
819 CROW_LOG_ERROR << "An uncaught exception occurred in a websocket handler: " << error;
820 if (error_handler_)
821 error_handler_(*this, error);
822 if (!has_sent_close_)
823 close("", CloseStatusCode::UnexpectedCondition);
824 check_destroy(CloseStatusCode::UnexpectedCondition);
825 return false;
826 }
827
828 /// Send the buffers' data through the socket.
829
830 ///
831 /// Also destroys the object if the Close flag is set.
832 void do_write()
833 {
834 if (sending_buffers_.empty()) {
835 if (write_buffers_.empty()) return;
836
837 sending_buffers_.swap(write_buffers_);
838 std::vector<asio::const_buffer> buffers;
839 buffers.reserve(sending_buffers_.size());
840 for (auto &s: sending_buffers_)
841 {
842 buffers.emplace_back(asio::buffer(s));
843 }
844 auto watch = std::weak_ptr<void>{anchor_};
845 asio::async_write(
846 adaptor_.socket(), buffers,
847 [shared_this = this->shared_from_this(), watch](const error_code &ec, std::size_t /*bytes_transferred*/) {
848 auto anchor = watch.lock();
849 if (anchor == nullptr)
850 return;
851
852 if (!ec && !shared_this->close_connection_)
853 {
854 shared_this->sending_buffers_.clear();
855 if (!shared_this->write_buffers_.empty())
856 shared_this->do_write();
857 if (shared_this->has_sent_close_)
858 shared_this->close_connection_ = true;
859 }
860 else
861 {
862 shared_this->sending_buffers_.clear();
863 shared_this->close_connection_ = true;
864 shared_this->check_destroy();
865 }
866 });
867 }
868 }
869
870 /// Destroy the Connection.
871 /// Whether a peer may send the status code in a Close frame (RFC 6455 Section 7.4).
872 static bool is_valid_close_code(uint16_t code)
873 {
874 return (code >= 1000 && code <= 1003) || (code >= 1007 && code <= 1014) || (code >= 3000 && code <= 4999);
875 }
876
877 void check_destroy(websocket::CloseStatusCode code = CloseStatusCode::ClosedAbnormally)
878 {
879 // Note that if the close handler was not yet called at this point we did not receive a close packet (or send one)
880 // and thus we use ClosedAbnormally unless instructed otherwise
881 if (!is_close_handler_called_)
882 {
883 is_close_handler_called_ = true;
884 if (close_handler_)
885 {
886 close_handler_(*this, "uncleanly", code);
887 }
888 }
889
890 handler_->remove_websocket(this->shared_from_this());
891 }
892
893
895 {
896 std::string payload;
897 Connection* self;
898 int opcode;
899
900 void operator()()
901 {
902 self->send_data_impl(this);
903 }
904 };
905
906 void send_data_impl(SendMessageType* s)
907 {
908 auto header = build_header(s->opcode, s->payload.size());
909 write_buffers_.emplace_back(std::move(header));
910 write_buffers_.emplace_back(std::move(s->payload));
911 do_write();
912 }
913
914 void send_data(int opcode, std::string&& msg)
915 {
916 SendMessageType event_arg{
917 std::move(msg),
918 this,
919 opcode};
920
921 post(std::move(event_arg));
922 }
923
924 private:
925 Connection(Adaptor&& adaptor, Handler* handler, uint64_t max_payload,
926 std::function<void(crow::websocket::connection&)> open_handler,
927 std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler,
928 std::function<void(crow::websocket::connection&, const std::string&, uint16_t)> close_handler,
929 std::function<void(crow::websocket::connection&, const std::string&)> error_handler,
930 std::function<void(const crow::request&, std::optional<crow::response>&, void**)> accept_handler):
931 adaptor_(std::move(adaptor)),
932 handler_(handler),
933 max_payload_bytes_(max_payload),
934 open_handler_(std::move(open_handler)),
935 message_handler_(std::move(message_handler)),
936 close_handler_(std::move(close_handler)),
937 error_handler_(std::move(error_handler)),
938 accept_handler_(std::move(accept_handler))
939 {}
940
941 Adaptor adaptor_;
942 Handler* handler_;
943
944 std::vector<std::string> sending_buffers_;
945 std::vector<std::string> write_buffers_;
946
947 std::array<char, 4096> buffer_;
948 bool is_binary_{false};
949 bool has_unfinished_message_{false};
950 std::string message_;
951 std::string fragment_;
952 WebSocketReadState state_{WebSocketReadState::MiniHeader};
953 uint16_t remaining_length16_{0};
954 uint64_t remaining_length_{0};
955 uint64_t max_payload_bytes_{UINT64_MAX};
956 std::string subprotocol_;
957 std::string remote_ip_;
958 bool close_connection_{false};
959 bool is_reading{false};
960 bool has_mask_{false};
961 uint32_t mask_;
962 uint16_t mini_header_;
963 bool has_sent_close_{false};
964 bool has_recv_close_{false};
965 bool error_occurred_{false};
966 bool pong_received_{false};
967 bool is_close_handler_called_{false};
968
969 std::shared_ptr<void> anchor_ = std::make_shared<int>(); // Value is just for placeholding
970
971 std::function<void(crow::websocket::connection&)> open_handler_;
972 std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler_;
973 std::function<void(crow::websocket::connection&, const std::string&, uint16_t status_code)> close_handler_;
974 std::function<void(crow::websocket::connection&, const std::string&)> error_handler_;
975 std::function<void(const crow::request&, std::optional<crow::response>&, void**)> accept_handler_;
976 };
977 } // namespace websocket
978} // namespace crow
TinySHA1 - a header only implementation of the SHA1 algorithm in C++. Based on the implementation in ...
A websocket connection.
Definition websocket.h:114
void dispatch(CompletionHandler &&handler)
Send data through the socket.
Definition websocket.h:218
void do_read()
Read a websocket message.
Definition websocket.h:390
bool finish_message()
Pass the complete message to the message handler and get ready for the next one.
Definition websocket.h:789
void send_pong(std::string msg) override
Send a "Pong" message.
Definition websocket.h:247
bool handle_fragment()
Process the payload fragment.
Definition websocket.h:650
std::string build_header(int opcode, size_t size)
Generate the websocket headers using an opcode and the message size (in bytes).
Definition websocket.h:331
void close(std::string const &msg, uint16_t status_code) override
Send a close signal.
Definition websocket.h:268
void send_text(std::string msg) override
Send a plaintext message.
Definition websocket.h:259
std::string get_subprotocol() const override
Returns the matching client/server subprotocol, empty string if none matched.
Definition websocket.h:324
bool call_handler(Callable &&handler)
Call a user handler.
Definition websocket.h:803
int opcode()
Extract the opcode from the header.
Definition websocket.h:641
void do_write()
Send the buffers' data through the socket.
Definition websocket.h:832
void start(std::string &&hello)
Send the HTTP upgrade response.
Definition websocket.h:360
static bool is_valid_close_code(uint16_t code)
Definition websocket.h:872
bool is_FIN()
Check if the FIN bit is set.
Definition websocket.h:635
uint16_t get_remote_port() override
Returns the TCP port of the remote endpoint, 0 when unavailable (Unix domain socket or socket already...
Definition websocket.h:313
void send_ping(std::string msg) override
Send a "Ping" message.
Definition websocket.h:238
void send_binary(std::string msg) override
Send a binary encoded message.
Definition websocket.h:253
static void create(const crow::request &req, Adaptor adaptor, Handler *handler, uint64_t max_payload, const std::vector< std::string > &subprotocols, std::function< void(crow::websocket::connection &)> open_handler, std::function< void(crow::websocket::connection &, const std::string &, bool)> message_handler, std::function< void(crow::websocket::connection &, const std::string &, uint16_t)> close_handler, std::function< void(crow::websocket::connection &, const std::string &)> error_handler, std::function< void(const crow::request &, std::optional< crow::response > &, void **)> accept_handler, bool mirror_protocols, const detail::socket::tcp_socket_options &tcp_options={})
Definition websocket.h:120
void post(CompletionHandler &&handler)
Send data through the socket and return immediately.
Definition websocket.h:227
std::string get_remote_ip() override
Returns the IP address the connection was opened from, also once the socket is closed (empty for a Un...
Definition websocket.h:307
A tiny SHA1 algorithm implementation used internally in the Crow server (specifically in crow/websock...
Definition TinySHA1.hpp:48
The main namespace of the library. In this namespace is defined the most important classes and functi...
Definition tcp_socket_options.h:29
An HTTP request.
Definition http_request.h:47
bool keep_alive
Whether or not the server should send a connection: Keep-Alive header to the client.
Definition http_request.h:57
std::string remote_ip_address
The IP address from which the request was sent.
Definition http_request.h:54
A base class for websocket connection.
Definition websocket.h:69