121 uint64_t max_payload,
const std::vector<std::string>& subprotocols,
126 std::function<
void(
const crow::request&, std::optional<crow::response>&,
void**)> accept_handler,
127 bool mirror_protocols,
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)));
139 detail::socket::apply_tcp_socket_options(conn->adaptor_.socket(), tcp_options);
145 if (!utility::string_equals(req.get_header_value(
"upgrade"),
"websocket"))
147 conn->adaptor_.close();
151 std::string requested_subprotocols_header = req.get_header_value(
"Sec-WebSocket-Protocol");
152 if (!subprotocols.empty() || !requested_subprotocols_header.empty())
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())
158 conn->subprotocol_ = *subprotocol;
162 if (mirror_protocols & !requested_subprotocols_header.empty())
164 conn->subprotocol_ = requested_subprotocols_header;
167 if (conn->accept_handler_)
170 std::optional<crow::response> res;
171 conn->accept_handler_(req, res, &ud);
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());
180 asio::write(conn->adaptor_.socket(), buffers, ec);
181 conn->adaptor_.close();
189 std::string magic = req.get_header_value(
"Sec-WebSocket-Key") +
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
191 s.processBytes(magic.data(), magic.size());
193 s.getDigestBytes(digest);
195 conn->handler_->add_websocket(conn);
196 conn->start(crow::utility::base64encode((
unsigned char*)digest, 20));
268 void close(std::string
const& msg, uint16_t status_code)
override
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_)
274 shared_this->is_close_handler_called_ = true;
275 if (shared_this->close_handler_)
276 shared_this->close_handler_(*shared_this, msg, status_code);
279 switch(status_code) {
281 case NoStatusCodePresent:
282 case ClosedAbnormally:
283 case TLSHandshakeFailure:
287 shared_this->write_buffers_.emplace_back(shared_this->build_header(0x8, 0));
292 auto header = shared_this->build_header(0x8, msg.size() + 2);
294 uint16_t network_status_code = htons(status_code);
295 std::memcpy(status_buf, &network_status_code,
sizeof(network_status_code));
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);
302 shared_this->do_write();
392 if (has_sent_close_ && has_recv_close_)
394 close_connection_ =
true;
395 adaptor_.shutdown_readwrite();
404 case WebSocketReadState::MiniHeader:
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
416 shared_this->is_reading = false;
417 shared_this->mini_header_ = ntohs(shared_this->mini_header_);
418#ifdef CROW_ENABLE_DEBUG
420 if (!ec && bytes_transferred != 2)
422 throw std::runtime_error(
"WebSocket:MiniHeader:async_read fail:asio bug?");
428 if ((shared_this->mini_header_ & 0x80) == 0x80)
429 shared_this->has_mask_ =
true;
432#ifndef CROW_ENFORCE_WS_SPEC
433 shared_this->has_mask_ =
false;
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);
445 if ((shared_this->mini_header_ & 0x7f) == 127)
447 shared_this->state_ = WebSocketReadState::Len64;
449 else if ((shared_this->mini_header_ & 0x7f) == 126)
451 shared_this->state_ = WebSocketReadState::Len16;
455 shared_this->remaining_length_ = shared_this->mini_header_ & 0x7f;
456 shared_this->state_ = WebSocketReadState::Mask;
458 shared_this->do_read();
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();
472 case WebSocketReadState::Len16:
474 remaining_length_ = 0;
475 remaining_length16_ = 0;
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
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)
489 throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
495 shared_this->state_ = WebSocketReadState::Mask;
496 shared_this->do_read();
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();
510 case WebSocketReadState::Len64:
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
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)
524 throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
530 shared_this->state_ = WebSocketReadState::Mask;
531 shared_this->do_read();
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();
545 case WebSocketReadState::Mask:
546 if (message_.size() > max_payload_bytes_ ||
547 remaining_length_ > max_payload_bytes_ - message_.size())
549 close_connection_ =
true;
552 error_handler_(*
this,
"Message length exceeds maximum payload.");
553 check_destroy(MessageTooBig);
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
564 shared_this->is_reading = false;
565#ifdef CROW_ENABLE_DEBUG
566 if (!ec && bytes_transferred != 4)
568 throw std::runtime_error(
"WebSocket:Mask:async_read fail:asio bug?");
574 shared_this->state_ = WebSocketReadState::Payload;
575 shared_this->do_read();
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();
590 state_ = WebSocketReadState::Payload;
594 case WebSocketReadState::Payload:
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;
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)
610 if (shared_this->handle_fragment())
612 shared_this->state_ = WebSocketReadState::MiniHeader;
613 shared_this->do_read();
617 shared_this->do_read();
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();
654 for (
decltype(fragment_.length()) i = 0; i < fragment_.length(); i++)
656 fragment_[i] ^= ((
char*)&mask_)[i % 4];
659 if ((mini_header_ & 0x7000) != 0)
662 error_handler_(*
this,
"RSV bits set without a negotiated extension.");
663 close(
"", CloseStatusCode::ProtocolError);
664 check_destroy(CloseStatusCode::ProtocolError);
667 if ((opcode() & 0x8) != 0 && (!is_FIN() || fragment_.size() > 125))
670 error_handler_(*
this,
"Fragmented or oversized control frame.");
671 close(
"", CloseStatusCode::ProtocolError);
672 check_destroy(CloseStatusCode::ProtocolError);
679 if (!has_unfinished_message_)
682 error_handler_(*
this,
"Continuation frame without a message to continue.");
683 close(
"", CloseStatusCode::ProtocolError);
684 check_destroy(CloseStatusCode::ProtocolError);
687 message_ += fragment_;
688 if (is_FIN() && !finish_message())
695 if (has_unfinished_message_)
698 error_handler_(*
this,
"New message before the fragmented message was finished.");
699 close(
"", CloseStatusCode::ProtocolError);
700 check_destroy(CloseStatusCode::ProtocolError);
703 is_binary_ = opcode() == 2;
704 message_ += fragment_;
707 if (!finish_message())
712 has_unfinished_message_ =
true;
718 has_recv_close_ =
true;
719 uint16_t status_code = NoStatusCodePresent;
720 std::string::size_type message_start = 2;
721 if (fragment_.size() >= 2)
723 status_code = ntohs(((uint16_t*)fragment_.data())[0]);
729 if (!has_sent_close_)
731 if (fragment_.size() == 1 || (fragment_.size() >= 2 && !is_valid_close_code(status_code)))
734 error_handler_(*
this,
"Invalid close frame.");
735 close(
"", CloseStatusCode::ProtocolError);
739 close(fragment_.substr(message_start), status_code);
745 close_connection_ =
true;
746 if (!is_close_handler_called_)
749 close_handler_(*
this, fragment_.substr(message_start), status_code);
750 is_close_handler_called_ =
true;
752 adaptor_.shutdown_readwrite();
763 send_pong(fragment_);
768 pong_received_ =
true;
774 error_handler_(*
this,
"Reserved opcode.");
775 close(
"", CloseStatusCode::ProtocolError);
776 check_destroy(CloseStatusCode::ProtocolError);
834 if (sending_buffers_.empty()) {
835 if (write_buffers_.empty())
return;
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_)
842 buffers.emplace_back(asio::buffer(s));
844 auto watch = std::weak_ptr<void>{anchor_};
846 adaptor_.socket(), buffers,
847 [shared_this = this->shared_from_this(), watch](
const error_code &ec, std::size_t ) {
848 auto anchor = watch.lock();
849 if (anchor == nullptr)
852 if (!ec && !shared_this->close_connection_)
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;
862 shared_this->sending_buffers_.clear();
863 shared_this->close_connection_ = true;
864 shared_this->check_destroy();