4#include "crow/logging.h"
5#include "crow/socket_adaptors.h"
6#include "crow/http_request.h"
8#include "crow/utility.h"
13 namespace asio = boost::asio;
14 using error_code = boost::system::error_code;
16 using error_code = asio::error_code;
28 enum class WebSocketReadState
38 enum CloseStatusCode : uint16_t {
40 EndpointGoingAway = 1001,
42 UnacceptableData = 1003,
43 InconsistentData = 1007,
44 PolicyViolated = 1008,
46 ExtensionsNotNegotiated = 1010,
47 UnexpectedCondition = 1011,
50 NoStatusCodePresent = 1005,
51 ClosedAbnormally = 1006,
52 TLSHandshakeFailure = 1015,
54 StartStatusCodesForLibraries = 3000,
55 StartStatusCodesForPrivateUse = 4000,
57 StartStatusCodes = NormalClosure,
58 EndStatusCodes = 4999,
64 virtual void send_binary(std::string msg) = 0;
65 virtual void send_text(std::string msg) = 0;
66 virtual void send_ping(std::string msg) = 0;
67 virtual void send_pong(std::string msg) = 0;
68 virtual void close(std::string
const& msg =
"quit", uint16_t status_code = CloseStatusCode::NormalClosure) = 0;
69 virtual std::string get_remote_ip() = 0;
70 virtual std::string get_subprotocol()
const = 0;
73 void userdata(
void* u) { userdata_ = u; }
74 void* userdata() {
return userdata_; }
105 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)
122 auto conn = std::shared_ptr<Connection>(
new Connection(std::move(adaptor),
123 handler, max_payload,
124 std::move(open_handler),
125 std::move(message_handler),
126 std::move(close_handler),
127 std::move(error_handler),
128 std::move(accept_handler)));
131 if (!utility::string_equals(req.get_header_value(
"upgrade"),
"websocket"))
133 conn->adaptor_.close();
137 std::string requested_subprotocols_header = req.get_header_value(
"Sec-WebSocket-Protocol");
138 if (!subprotocols.empty() || !requested_subprotocols_header.empty())
140 auto requested_subprotocols = utility::split(requested_subprotocols_header,
", ");
141 auto subprotocol = utility::find_first_of(subprotocols.begin(), subprotocols.end(), requested_subprotocols.begin(), requested_subprotocols.end());
142 if (subprotocol != subprotocols.end())
144 conn->subprotocol_ = *subprotocol;
148 if (mirror_protocols & !requested_subprotocols_header.empty())
150 conn->subprotocol_ = requested_subprotocols_header;
153 if (conn->accept_handler_)
156 if (!conn->accept_handler_(req, &ud))
158 conn->adaptor_.close();
166 std::string magic = req.get_header_value(
"Sec-WebSocket-Key") +
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
168 s.processBytes(magic.data(), magic.size());
170 s.getDigestBytes(digest);
172 conn->handler_->add_websocket(conn);
173 conn->start(crow::utility::base64encode((
unsigned char*)digest, 20));
178 template<typename Callable>
182 std::weak_ptr<void> watch;
186 if (
auto anchor = watch.lock())
188 std::move(callable)();
194 template<
typename CompletionHandler>
197 asio::dispatch(adaptor_.get_io_context(),
199 std::forward<CompletionHandler>(handler), anchor_});
203 template<
typename CompletionHandler>
204 void post(CompletionHandler&& handler)
206 asio::post(adaptor_.get_io_context(),
208 std::forward<CompletionHandler>(handler), anchor_});
217 send_data(0x9, std::move(msg));
226 send_data(0xA, std::move(msg));
232 send_data(0x2, std::move(msg));
238 send_data(0x1, std::move(msg));
245 void close(std::string
const& msg, uint16_t status_code)
override
247 dispatch([
this, msg, status_code]()
mutable {
248 has_sent_close_ =
true;
249 if (has_recv_close_ && !is_close_handler_called_)
251 is_close_handler_called_ =
true;
253 close_handler_(*
this, msg, status_code);
257 *(uint16_t*)(status_buf) = htons(status_code);
259 write_buffers_.emplace_back(std::move(header));
260 write_buffers_.emplace_back(std::string(status_buf, 2));
261 write_buffers_.emplace_back(msg);
266 std::string get_remote_ip()
override
268 return adaptor_.address();
271 void set_max_payload_size(uint64_t payload)
273 max_payload_bytes_ = payload;
286 char buf[2 + 8] =
"\x80\x00";
290 buf[1] +=
static_cast<char>(size);
291 return {buf, buf + 2};
293 else if (size < 0x10000)
296 *(uint16_t*)(buf + 2) = htons(
static_cast<uint16_t
>(size));
297 return {buf, buf + 4};
302 *
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));
303 return {buf, buf + 10};
313 static const std::string header =
314 "HTTP/1.1 101 Switching Protocols\r\n"
315 "Upgrade: websocket\r\n"
316 "Connection: Upgrade\r\n"
317 "Sec-WebSocket-Accept: ";
318 write_buffers_.emplace_back(header);
319 write_buffers_.emplace_back(std::move(hello));
320 write_buffers_.emplace_back(crlf);
321 if (!subprotocol_.empty())
323 write_buffers_.emplace_back(
"Sec-WebSocket-Protocol: ");
324 write_buffers_.emplace_back(subprotocol_);
325 write_buffers_.emplace_back(crlf);
327 write_buffers_.emplace_back(crlf);
330 open_handler_(*
this);
343 if (has_sent_close_ && has_recv_close_)
345 close_connection_ =
true;
346 adaptor_.shutdown_readwrite();
355 case WebSocketReadState::MiniHeader:
359 adaptor_.socket().async_read_some(
360 asio::buffer(&mini_header_, 2),
361 [
this](
const error_code& ec, std::size_t
362#ifdef CROW_ENABLE_DEBUG
369 mini_header_ = ntohs(mini_header_);
370#ifdef CROW_ENABLE_DEBUG
372 if (!ec && bytes_transferred != 2)
374 throw std::runtime_error(
"WebSocket:MiniHeader:async_read fail:asio bug?");
380 if ((mini_header_ & 0x80) == 0x80)
384#ifndef CROW_ENFORCE_WS_SPEC
387 close_connection_ =
true;
388 adaptor_.shutdown_readwrite();
391 error_handler_(*
this,
"Client connection not masked.");
396 if ((mini_header_ & 0x7f) == 127)
398 state_ = WebSocketReadState::Len64;
400 else if ((mini_header_ & 0x7f) == 126)
402 state_ = WebSocketReadState::Len16;
406 remaining_length_ = mini_header_ & 0x7f;
407 state_ = WebSocketReadState::Mask;
413 close_connection_ =
true;
414 adaptor_.shutdown_readwrite();
417 error_handler_(*
this, ec.message());
423 case WebSocketReadState::Len16:
425 remaining_length_ = 0;
426 remaining_length16_ = 0;
428 adaptor_.socket(), asio::buffer(&remaining_length16_, 2),
429 [
this](
const error_code& ec, std::size_t
430#ifdef CROW_ENABLE_DEBUG
435 remaining_length16_ = ntohs(remaining_length16_);
436 remaining_length_ = remaining_length16_;
437#ifdef CROW_ENABLE_DEBUG
438 if (!ec && bytes_transferred != 2)
440 throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
446 state_ = WebSocketReadState::Mask;
451 close_connection_ =
true;
452 adaptor_.shutdown_readwrite();
455 error_handler_(*
this, ec.message());
461 case WebSocketReadState::Len64:
464 adaptor_.socket(), asio::buffer(&remaining_length_, 8),
465 [
this](
const error_code& ec, std::size_t
466#ifdef CROW_ENABLE_DEBUG
471 remaining_length_ = ((1 == ntohl(1)) ? (remaining_length_) : (static_cast<uint64_t>(ntohl((remaining_length_)&0xFFFFFFFF)) << 32) | ntohl((remaining_length_) >> 32));
472#ifdef CROW_ENABLE_DEBUG
473 if (!ec && bytes_transferred != 8)
475 throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
481 state_ = WebSocketReadState::Mask;
486 close_connection_ =
true;
487 adaptor_.shutdown_readwrite();
490 error_handler_(*
this, ec.message());
496 case WebSocketReadState::Mask:
497 if (remaining_length_ > max_payload_bytes_)
499 close_connection_ =
true;
502 error_handler_(*
this,
"Message length exceeds maximum payload.");
508 adaptor_.socket(), asio::buffer((
char*)&mask_, 4),
509 [
this](
const error_code& ec, std::size_t
510#ifdef CROW_ENABLE_DEBUG
515#ifdef CROW_ENABLE_DEBUG
516 if (!ec && bytes_transferred != 4)
518 throw std::runtime_error(
"WebSocket:Mask:async_read fail:asio bug?");
524 state_ = WebSocketReadState::Payload;
529 close_connection_ =
true;
531 error_handler_(*
this, ec.message());
532 adaptor_.shutdown_readwrite();
540 state_ = WebSocketReadState::Payload;
544 case WebSocketReadState::Payload:
546 auto to_read =
static_cast<std::uint64_t
>(buffer_.size());
547 if (remaining_length_ < to_read)
548 to_read = remaining_length_;
549 adaptor_.socket().async_read_some(
550 asio::buffer(buffer_,
static_cast<std::size_t
>(to_read)),
551 [
this](
const error_code& ec, std::size_t bytes_transferred) {
556 fragment_.insert(fragment_.end(), buffer_.begin(), buffer_.begin() + bytes_transferred);
557 remaining_length_ -= bytes_transferred;
558 if (remaining_length_ == 0)
560 if (handle_fragment())
562 state_ = WebSocketReadState::MiniHeader;
571 close_connection_ =
true;
573 error_handler_(*
this, ec.message());
574 adaptor_.shutdown_readwrite();
587 return mini_header_ & 0x8000;
593 return (mini_header_ & 0x0f00) >> 8;
604 for (
decltype(fragment_.length()) i = 0; i < fragment_.length(); i++)
606 fragment_[i] ^= ((
char*)&mask_)[i % 4];
613 message_ += fragment_;
616 if (message_handler_)
617 message_handler_(*
this, message_, is_binary_);
625 message_ += fragment_;
628 if (message_handler_)
629 message_handler_(*
this, message_, is_binary_);
637 message_ += fragment_;
640 if (message_handler_)
641 message_handler_(*
this, message_, is_binary_);
648 has_recv_close_ =
true;
651 uint16_t status_code = NoStatusCodePresent;
652 std::string::size_type message_start = 2;
653 if (fragment_.size() >= 2)
655 status_code = ntohs(((uint16_t*)fragment_.data())[0]);
661 if (!has_sent_close_)
663 close(fragment_.substr(message_start), status_code);
668 close_connection_ =
true;
669 if (!is_close_handler_called_)
672 close_handler_(*
this, fragment_.substr(message_start), status_code);
673 is_close_handler_called_ =
true;
675 adaptor_.shutdown_readwrite();
686 send_pong(fragment_);
691 pong_received_ =
true;
706 if (write_buffers_.empty())
return;
708 sending_buffers_.swap(write_buffers_);
709 std::vector<asio::const_buffer> buffers;
710 buffers.reserve(sending_buffers_.size());
711 for (
auto& s : sending_buffers_)
713 buffers.emplace_back(asio::buffer(s));
715 auto watch = std::weak_ptr<void>{anchor_};
717 adaptor_.socket(), buffers,
718 [
this, watch](
const error_code& ec, std::size_t ) {
719 auto anchor = watch.lock();
720 if (anchor == nullptr)
723 if (!ec && !close_connection_)
725 sending_buffers_.clear();
726 if (!write_buffers_.empty())
729 close_connection_ = true;
733 sending_buffers_.clear();
734 close_connection_ = true;
741 void check_destroy(websocket::CloseStatusCode code = CloseStatusCode::ClosedAbnormally)
745 if (!is_close_handler_called_)
749 close_handler_(*
this,
"uncleanly", code);
753 handler_->remove_websocket(this->shared_from_this());
765 self->send_data_impl(
this);
771 auto header = build_header(s->opcode, s->payload.size());
772 write_buffers_.emplace_back(std::move(header));
773 write_buffers_.emplace_back(std::move(s->payload));
777 void send_data(
int opcode, std::string&& msg)
779 SendMessageType event_arg{
784 post(std::move(event_arg));
788 Connection(Adaptor&& adaptor, Handler* handler, uint64_t max_payload,
793 std::function<
bool(
const crow::request&,
void**)> accept_handler):
794 adaptor_(std::move(adaptor)),
796 max_payload_bytes_(max_payload),
797 open_handler_(std::move(open_handler)),
798 message_handler_(std::move(message_handler)),
799 close_handler_(std::move(close_handler)),
800 error_handler_(std::move(error_handler)),
801 accept_handler_(std::move(accept_handler))
807 std::vector<std::string> sending_buffers_;
808 std::vector<std::string> write_buffers_;
810 std::array<char, 4096> buffer_;
812 std::string message_;
813 std::string fragment_;
814 WebSocketReadState state_{WebSocketReadState::MiniHeader};
815 uint16_t remaining_length16_{0};
816 uint64_t remaining_length_{0};
817 uint64_t max_payload_bytes_{UINT64_MAX};
818 std::string subprotocol_;
819 bool close_connection_{
false};
820 bool is_reading{
false};
821 bool has_mask_{
false};
823 uint16_t mini_header_;
824 bool has_sent_close_{
false};
825 bool has_recv_close_{
false};
826 bool error_occurred_{
false};
827 bool pong_received_{
false};
828 bool is_close_handler_called_{
false};
830 std::shared_ptr<void> anchor_ = std::make_shared<int>();
836 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:107
void dispatch(CompletionHandler &&handler)
Send data through the socket.
Definition websocket.h:195
void do_read()
Read a websocket message.
Definition websocket.h:341
void send_pong(std::string msg) override
Send a "Pong" message.
Definition websocket.h:224
bool handle_fragment()
Process the payload fragment.
Definition websocket.h:600
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:284
void close(std::string const &msg, uint16_t status_code) override
Send a close signal.
Definition websocket.h:245
void send_text(std::string msg) override
Send a plaintext message.
Definition websocket.h:236
std::string get_subprotocol() const override
Returns the matching client/server subprotocol, empty string if none matched.
Definition websocket.h:277
int opcode()
Extract the opcode from the header.
Definition websocket.h:591
void do_write()
Send the buffers' data through the socket.
Definition websocket.h:704
void start(std::string &&hello)
Send the HTTP upgrade response.
Definition websocket.h:311
bool is_FIN()
Check if the FIN bit is set.
Definition websocket.h:585
void send_ping(std::string msg) override
Send a "Ping" message.
Definition websocket.h:215
void send_binary(std::string msg) override
Send a binary encoded message.
Definition websocket.h:230
void check_destroy(websocket::CloseStatusCode code=CloseStatusCode::ClosedAbnormally)
Destroy the Connection.
Definition websocket.h:741
void post(CompletionHandler &&handler)
Send data through the socket and return immediately.
Definition websocket.h:204
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< bool(const crow::request &, void **)> accept_handler, bool mirror_protocols)
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:758
Definition websocket.h:180
A base class for websocket connection.
Definition websocket.h:63