3#include "crow/logging.h"
4#include "crow/socket_adaptors.h"
5#include "crow/http_request.h"
7#include "crow/utility.h"
12 namespace asio = boost::asio;
13 using error_code = boost::system::error_code;
15 using error_code = asio::error_code;
27 enum class WebSocketReadState
37 enum CloseStatusCode : uint16_t {
39 EndpointGoingAway = 1001,
41 UnacceptableData = 1003,
42 InconsistentData = 1007,
43 PolicyViolated = 1008,
45 ExtensionsNotNegotiated = 1010,
46 UnexpectedCondition = 1011,
49 NoStatusCodePresent = 1005,
50 ClosedAbnormally = 1006,
51 TLSHandshakeFailure = 1015,
53 StartStatusCodesForLibraries = 3000,
54 StartStatusCodesForPrivateUse = 4000,
56 StartStatusCodes = NormalClosure,
57 EndStatusCodes = 4999,
63 virtual void send_binary(std::string msg) = 0;
64 virtual void send_text(std::string msg) = 0;
65 virtual void send_ping(std::string msg) = 0;
66 virtual void send_pong(std::string msg) = 0;
67 virtual void close(std::string
const& msg =
"quit", uint16_t status_code = CloseStatusCode::NormalClosure) = 0;
68 virtual std::string get_remote_ip() = 0;
69 virtual std::string get_subprotocol()
const = 0;
72 void userdata(
void* u) { userdata_ = u; }
73 void* userdata() {
return userdata_; }
104 template<
typename Adaptor,
typename Handler>
114 uint64_t max_payload,
const std::vector<std::string>& subprotocols,
119 std::function<
bool(
const crow::request&,
void**)> accept_handler,
120 bool mirror_protocols):
121 adaptor_(std::move(adaptor)),
123 max_payload_bytes_(max_payload),
124 open_handler_(std::move(open_handler)),
125 message_handler_(std::move(message_handler)),
126 close_handler_(std::move(close_handler)),
127 error_handler_(std::move(error_handler)),
128 accept_handler_(std::move(accept_handler))
130 if (!utility::string_equals(req.get_header_value(
"upgrade"),
"websocket"))
133 handler_->remove_websocket(
this);
138 std::string requested_subprotocols_header = req.get_header_value(
"Sec-WebSocket-Protocol");
139 if (!subprotocols.empty() || !requested_subprotocols_header.empty())
141 auto requested_subprotocols = utility::split(requested_subprotocols_header,
", ");
142 auto subprotocol = utility::find_first_of(subprotocols.begin(), subprotocols.end(), requested_subprotocols.begin(), requested_subprotocols.end());
143 if (subprotocol != subprotocols.end())
145 subprotocol_ = *subprotocol;
149 if (mirror_protocols & !requested_subprotocols_header.empty())
151 subprotocol_ = requested_subprotocols_header;
157 if (!accept_handler_(req, &ud))
160 handler_->remove_websocket(
this);
169 std::string magic = req.get_header_value(
"Sec-WebSocket-Key") +
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
171 s.processBytes(magic.data(), magic.size());
173 s.getDigestBytes(digest);
175 start(crow::utility::base64encode((
unsigned char*)digest, 20));
181 auto watch = std::weak_ptr<void>{anchor_};
186 while (watch.use_count() > 2)
188 std::this_thread::yield();
192 template<
typename Callable>
196 std::weak_ptr<void> watch;
200 if (
auto anchor = watch.lock())
202 std::move(callable)();
208 template<
typename CompletionHandler>
211 asio::dispatch(adaptor_.get_io_context(),
213 std::forward<CompletionHandler>(handler), anchor_});
217 template<
typename CompletionHandler>
218 void post(CompletionHandler&& handler)
220 asio::post(adaptor_.get_io_context(),
222 std::forward<CompletionHandler>(handler), anchor_});
231 send_data(0x9, std::move(msg));
240 send_data(0xA, std::move(msg));
246 send_data(0x2, std::move(msg));
252 send_data(0x1, std::move(msg));
259 void close(std::string
const& msg, uint16_t status_code)
override
261 dispatch([
this, msg, status_code]()
mutable {
262 has_sent_close_ =
true;
263 if (has_recv_close_ && !is_close_handler_called_)
265 is_close_handler_called_ =
true;
267 close_handler_(*
this, msg, status_code);
271 *(uint16_t*)(status_buf) = htons(status_code);
273 write_buffers_.emplace_back(std::move(header));
274 write_buffers_.emplace_back(std::string(status_buf, 2));
275 write_buffers_.emplace_back(msg);
280 std::string get_remote_ip()
override
282 return adaptor_.remote_endpoint().address().to_string();
285 void set_max_payload_size(uint64_t payload)
287 max_payload_bytes_ = payload;
300 char buf[2 + 8] =
"\x80\x00";
304 buf[1] +=
static_cast<char>(size);
305 return {buf, buf + 2};
307 else if (size < 0x10000)
310 *(uint16_t*)(buf + 2) = htons(
static_cast<uint16_t
>(size));
311 return {buf, buf + 4};
316 *
reinterpret_cast<uint64_t*
>(buf + 2) = ((1 == htonl(1)) ?
static_cast<uint64_t
>(size) : (
static_cast<uint64_t
>(htonl((size)&0xFFFFFFFF)) << 32) | htonl(
static_cast<uint64_t
>(size) >> 32));
317 return {buf, buf + 10};
327 static const std::string header =
328 "HTTP/1.1 101 Switching Protocols\r\n"
329 "Upgrade: websocket\r\n"
330 "Connection: Upgrade\r\n"
331 "Sec-WebSocket-Accept: ";
332 write_buffers_.emplace_back(header);
333 write_buffers_.emplace_back(std::move(hello));
334 write_buffers_.emplace_back(crlf);
335 if (!subprotocol_.empty())
337 write_buffers_.emplace_back(
"Sec-WebSocket-Protocol: ");
338 write_buffers_.emplace_back(subprotocol_);
339 write_buffers_.emplace_back(crlf);
341 write_buffers_.emplace_back(crlf);
344 open_handler_(*
this);
357 if (has_sent_close_ && has_recv_close_)
359 close_connection_ =
true;
360 adaptor_.shutdown_readwrite();
369 case WebSocketReadState::MiniHeader:
373 adaptor_.socket().async_read_some(
374 asio::buffer(&mini_header_, 2),
375 [
this](
const error_code& ec, std::size_t
376#ifdef CROW_ENABLE_DEBUG
383 mini_header_ = ntohs(mini_header_);
384#ifdef CROW_ENABLE_DEBUG
386 if (!ec && bytes_transferred != 2)
388 throw std::runtime_error(
"WebSocket:MiniHeader:async_read fail:asio bug?");
394 if ((mini_header_ & 0x80) == 0x80)
398#ifndef CROW_ENFORCE_WS_SPEC
401 close_connection_ =
true;
402 adaptor_.shutdown_readwrite();
405 error_handler_(*
this,
"Client connection not masked.");
410 if ((mini_header_ & 0x7f) == 127)
412 state_ = WebSocketReadState::Len64;
414 else if ((mini_header_ & 0x7f) == 126)
416 state_ = WebSocketReadState::Len16;
420 remaining_length_ = mini_header_ & 0x7f;
421 state_ = WebSocketReadState::Mask;
427 close_connection_ =
true;
428 adaptor_.shutdown_readwrite();
431 error_handler_(*
this, ec.message());
437 case WebSocketReadState::Len16:
439 remaining_length_ = 0;
440 remaining_length16_ = 0;
442 adaptor_.socket(), asio::buffer(&remaining_length16_, 2),
443 [
this](
const error_code& ec, std::size_t
444#ifdef CROW_ENABLE_DEBUG
449 remaining_length16_ = ntohs(remaining_length16_);
450 remaining_length_ = remaining_length16_;
451#ifdef CROW_ENABLE_DEBUG
452 if (!ec && bytes_transferred != 2)
454 throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
460 state_ = WebSocketReadState::Mask;
465 close_connection_ =
true;
466 adaptor_.shutdown_readwrite();
469 error_handler_(*
this, ec.message());
475 case WebSocketReadState::Len64:
478 adaptor_.socket(), asio::buffer(&remaining_length_, 8),
479 [
this](
const error_code& ec, std::size_t
480#ifdef CROW_ENABLE_DEBUG
485 remaining_length_ = ((1 == ntohl(1)) ? (remaining_length_) : (static_cast<uint64_t>(ntohl((remaining_length_)&0xFFFFFFFF)) << 32) | ntohl((remaining_length_) >> 32));
486#ifdef CROW_ENABLE_DEBUG
487 if (!ec && bytes_transferred != 8)
489 throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
495 state_ = WebSocketReadState::Mask;
500 close_connection_ =
true;
501 adaptor_.shutdown_readwrite();
504 error_handler_(*
this, ec.message());
510 case WebSocketReadState::Mask:
511 if (remaining_length_ > max_payload_bytes_)
513 close_connection_ =
true;
516 error_handler_(*
this,
"Message length exceeds maximum payload.");
522 adaptor_.socket(), asio::buffer((
char*)&mask_, 4),
523 [
this](
const error_code& ec, std::size_t
524#ifdef CROW_ENABLE_DEBUG
529#ifdef CROW_ENABLE_DEBUG
530 if (!ec && bytes_transferred != 4)
532 throw std::runtime_error(
"WebSocket:Mask:async_read fail:asio bug?");
538 state_ = WebSocketReadState::Payload;
543 close_connection_ =
true;
545 error_handler_(*
this, ec.message());
546 adaptor_.shutdown_readwrite();
554 state_ = WebSocketReadState::Payload;
558 case WebSocketReadState::Payload:
560 auto to_read =
static_cast<std::uint64_t
>(buffer_.size());
561 if (remaining_length_ < to_read)
562 to_read = remaining_length_;
563 adaptor_.socket().async_read_some(
564 asio::buffer(buffer_,
static_cast<std::size_t
>(to_read)),
565 [
this](
const error_code& ec, std::size_t bytes_transferred) {
570 fragment_.insert(fragment_.end(), buffer_.begin(), buffer_.begin() + bytes_transferred);
571 remaining_length_ -= bytes_transferred;
572 if (remaining_length_ == 0)
574 if (handle_fragment())
576 state_ = WebSocketReadState::MiniHeader;
585 close_connection_ =
true;
587 error_handler_(*
this, ec.message());
588 adaptor_.shutdown_readwrite();
601 return mini_header_ & 0x8000;
607 return (mini_header_ & 0x0f00) >> 8;
618 for (
decltype(fragment_.length()) i = 0; i < fragment_.length(); i++)
620 fragment_[i] ^= ((
char*)&mask_)[i % 4];
627 message_ += fragment_;
630 if (message_handler_)
631 message_handler_(*
this, message_, is_binary_);
639 message_ += fragment_;
642 if (message_handler_)
643 message_handler_(*
this, message_, is_binary_);
651 message_ += fragment_;
654 if (message_handler_)
655 message_handler_(*
this, message_, is_binary_);
662 has_recv_close_ =
true;
665 uint16_t status_code = NoStatusCodePresent;
666 std::string::size_type message_start = 2;
667 if (fragment_.size() >= 2)
669 status_code = ntohs(((uint16_t*)fragment_.data())[0]);
675 if (!has_sent_close_)
677 close(fragment_.substr(message_start), status_code);
682 close_connection_ =
true;
683 if (!is_close_handler_called_)
686 close_handler_(*
this, fragment_.substr(message_start), status_code);
687 is_close_handler_called_ =
true;
689 adaptor_.shutdown_readwrite();
700 send_pong(fragment_);
705 pong_received_ =
true;
720 if (sending_buffers_.empty())
722 sending_buffers_.swap(write_buffers_);
723 std::vector<asio::const_buffer> buffers;
724 buffers.reserve(sending_buffers_.size());
725 for (
auto& s : sending_buffers_)
727 buffers.emplace_back(asio::buffer(s));
729 auto watch = std::weak_ptr<void>{anchor_};
731 adaptor_.socket(), buffers,
732 [&, watch](
const error_code& ec, std::size_t ) {
733 if (!ec && !close_connection_)
735 sending_buffers_.clear();
736 if (!write_buffers_.empty())
739 close_connection_ = true;
743 auto anchor = watch.lock();
744 if (anchor == nullptr) { return; }
746 sending_buffers_.clear();
747 close_connection_ =
true;
755 void check_destroy(websocket::CloseStatusCode code = CloseStatusCode::ClosedAbnormally)
759 if (!is_close_handler_called_)
761 close_handler_(*
this,
"uncleanly", code);
762 handler_->remove_websocket(
this);
763 if (sending_buffers_.empty() && !is_reading)
776 self->send_data_impl(
this);
782 auto header = build_header(s->opcode, s->payload.size());
783 write_buffers_.emplace_back(std::move(header));
784 write_buffers_.emplace_back(std::move(s->payload));
788 void send_data(
int opcode, std::string&& msg)
790 SendMessageType event_arg{
795 post(std::move(event_arg));
802 std::vector<std::string> sending_buffers_;
803 std::vector<std::string> write_buffers_;
805 std::array<char, 4096> buffer_;
807 std::string message_;
808 std::string fragment_;
809 WebSocketReadState state_{WebSocketReadState::MiniHeader};
810 uint16_t remaining_length16_{0};
811 uint64_t remaining_length_{0};
812 uint64_t max_payload_bytes_{UINT64_MAX};
813 std::string subprotocol_;
814 bool close_connection_{
false};
815 bool is_reading{
false};
816 bool has_mask_{
false};
818 uint16_t mini_header_;
819 bool has_sent_close_{
false};
820 bool has_recv_close_{
false};
821 bool error_occurred_{
false};
822 bool pong_received_{
false};
823 bool is_close_handler_called_{
false};
825 std::shared_ptr<void> anchor_ = std::make_shared<int>();
831 std::function<bool(
const crow::request&,
void**)> accept_handler_;
TinySHA1 - a header only implementation of the SHA1 algorithm in C++. Based on the implementation in ...
A websocket connection.
Definition websocket.h:106
void dispatch(CompletionHandler &&handler)
Send data through the socket.
Definition websocket.h:209
void do_read()
Read a websocket message.
Definition websocket.h:355
void send_pong(std::string msg) override
Send a "Pong" message.
Definition websocket.h:238
bool handle_fragment()
Process the payload fragment.
Definition websocket.h:614
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:298
void close(std::string const &msg, uint16_t status_code) override
Send a close signal.
Definition websocket.h:259
void send_text(std::string msg) override
Send a plaintext message.
Definition websocket.h:250
std::string get_subprotocol() const override
Returns the matching client/server subprotocol, empty string if none matched.
Definition websocket.h:291
int opcode()
Extract the opcode from the header.
Definition websocket.h:605
void do_write()
Send the buffers' data through the socket.
Definition websocket.h:718
void start(std::string &&hello)
Send the HTTP upgrade response.
Definition websocket.h:325
bool is_FIN()
Check if the FIN bit is set.
Definition websocket.h:599
void send_ping(std::string msg) override
Send a "Ping" message.
Definition websocket.h:229
void send_binary(std::string msg) override
Send a binary encoded message.
Definition websocket.h:244
void check_destroy(websocket::CloseStatusCode code=CloseStatusCode::ClosedAbnormally)
Destroy the Connection.
Definition websocket.h:755
void post(CompletionHandler &&handler)
Send data through the socket and return immediately.
Definition websocket.h:218
Connection(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< bool(const crow::request &, void **)> accept_handler, bool mirror_protocols)
Constructor for a connection.
Definition websocket.h:113
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...
An HTTP request.
Definition http_request.h:36
Definition websocket.h:769
Definition websocket.h:194
A base class for websocket connection.
Definition websocket.h:62