Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
WebSocketConnection.hpp
Go to the documentation of this file.
1#pragma once
3#include <string>
4#include <functional>
5#include <vector>
6#include <cstdint>
7#include <atomic>
8#include <mutex>
9#include <string_view>
10
11#include <zlib.h>
12
13namespace orbit::server {
14 class Connection; // Forward declaration
15}
16
17namespace orbit::http {
18struct HttpRequest;
19namespace websocket {
20
21namespace detail {
22
27 bool fin;
28 uint8_t opcode;
29 bool masked;
31 uint8_t mask_key[4];
33};
34
47bool parse_frame_header(const std::vector<char>& buffer, FrameHeader& header);
48
52enum class FrameStatus {
55 Complete,
56 Invalid
57};
58
67FrameStatus inspect_frame(const std::vector<char>& buffer, FrameHeader& header);
68
74void unmask_payload(std::string& payload, const uint8_t mask_key[4]);
75
78bool is_valid_utf8(std::string_view data);
79
81bool is_valid_close_code(uint16_t code);
82
83} // namespace detail
84
89public:
91 struct Transport {
92 std::function<void(const std::vector<char>&)> write;
93 std::function<void()> close;
94 };
95
96 explicit WebSocketConnection(server::Connection& underlying_connection, bool enable_deflate = false);
97 explicit WebSocketConnection(Transport transport, bool enable_deflate = false);
99
100 // User-facing API
101
106 void on_message(std::function<void(const std::string&)> handler);
107
113 void on_binary_message(std::function<void(const std::string&)> handler);
114
119 void on_close(std::function<void()> handler);
120
126 void send(const std::string& message);
127
131 void send_binary(const std::string& data);
132
136 void close(uint16_t status_code = 1000);
137
140 void ping();
141
148
154 void set_max_message_size(size_t bytes) { max_message_size_ = bytes; }
155
167 void set_handshake_request(const HttpRequest* request) { handshake_request_ = request; }
168
169 // Internal API called by Connection::handle_read when in WEBSOCKET state
170 void process_raw_data(std::vector<char>& buffer);
171
172private:
175 std::function<void(const std::string&)> message_handler_;
176 std::function<void(const std::string&)> binary_handler_;
177 std::function<void()> close_handler_;
178
179 std::atomic<bool> is_closed_{false};
180 size_t max_message_size_{16 * 1024 * 1024};
181
182 // Serialises frame construction, compression and queueing: send() may be
183 // called from any thread (e.g. EventRouter broadcasts) while the event
184 // loop answers pings and closes.
185 std::mutex send_mutex_;
186
187 // Message being reassembled from fragments (event-loop thread only).
188 uint8_t fragment_opcode_{0}; // 0 = none in progress
190 std::string fragment_payload_;
191
192 void send_frame(uint8_t opcode, const std::string& payload);
193 void write_frame_locked(uint8_t first_byte, const std::string& payload);
194 void fail_connection(uint16_t status_code);
195 // Returns false if the connection was failed.
196 bool deliver_message(uint8_t opcode, bool compressed, std::string payload);
197 void handle_close_frame(const std::string& payload);
198
199 bool deflate_enabled_{false};
200 z_stream inflate_stream_{};
201 z_stream deflate_stream_{};
203
206 std::string deflate_payload(const std::string& payload);
207 bool inflate_payload(const std::string& payload, std::string& out);
208};
209
210} // namespace websocket
211} // namespace http
Represents an active WebSocket connection.
Definition WebSocketConnection.hpp:88
void on_message(std::function< void(const std::string &)> handler)
Registers a callback to be called when a message is received.
void send_frame(uint8_t opcode, const std::string &payload)
void send(const std::string &message)
Sends a text message over the WebSocket connection. Safe to call from any thread.
bool deliver_message(uint8_t opcode, bool compressed, std::string payload)
bool inflate_payload(const std::string &payload, std::string &out)
uint8_t fragment_opcode_
Definition WebSocketConnection.hpp:188
bool streams_initialized_
Definition WebSocketConnection.hpp:202
std::string deflate_payload(const std::string &payload)
bool deflate_enabled_
Definition WebSocketConnection.hpp:199
void handle_close_frame(const std::string &payload)
void close(uint16_t status_code=1000)
Closes the WebSocket connection gracefully.
void set_handshake_request(const HttpRequest *request)
Set by the server around the handler call.
Definition WebSocketConnection.hpp:167
std::function< void(const std::string &)> message_handler_
Definition WebSocketConnection.hpp:175
std::function< void()> close_handler_
Definition WebSocketConnection.hpp:177
WebSocketConnection(server::Connection &underlying_connection, bool enable_deflate=false)
std::string fragment_payload_
Definition WebSocketConnection.hpp:190
std::function< void(const std::string &)> binary_handler_
Definition WebSocketConnection.hpp:176
void on_close(std::function< void()> handler)
Registers a callback to be called when the connection is closed.
size_t max_message_size_
Definition WebSocketConnection.hpp:180
z_stream deflate_stream_
Definition WebSocketConnection.hpp:201
void send_binary(const std::string &data)
Sends a binary message. Safe to call from any thread.
std::atomic< bool > is_closed_
Definition WebSocketConnection.hpp:179
void on_binary_message(std::function< void(const std::string &)> handler)
Registers a callback for binary messages. When set, binary messages go here and on_message() receives...
z_stream inflate_stream_
Definition WebSocketConnection.hpp:200
void write_frame_locked(uint8_t first_byte, const std::string &payload)
void set_max_message_size(size_t bytes)
Sets the largest message payload accepted from the client, after decompression. Larger messages close...
Definition WebSocketConnection.hpp:154
std::mutex send_mutex_
Definition WebSocketConnection.hpp:185
const HttpRequest * handshake_request() const
The HTTP request that opened this WebSocket: path, query, headers, cookies, and whatever the route's ...
Definition WebSocketConnection.hpp:165
Transport transport_
Definition WebSocketConnection.hpp:173
void handle_transport_closed()
Internal: the underlying transport has gone away (peer disconnect, timeout or I/O error)....
void process_raw_data(std::vector< char > &buffer)
void fail_connection(uint16_t status_code)
const HttpRequest * handshake_request_
Definition WebSocketConnection.hpp:174
bool fragment_compressed_
Definition WebSocketConnection.hpp:189
WebSocketConnection(Transport transport, bool enable_deflate=false)
Represents an active client connection, handling request parsing and response writing.
Definition Connection.hpp:67
FrameStatus
Progress of parsing the frame at the front of a buffer.
Definition WebSocketConnection.hpp:52
@ NeedPayload
The header is parsed (payload_length is known); the payload has not fully arrived.
@ NeedHeader
The frame header has not fully arrived.
@ Invalid
The frame violates RFC 6455 and the connection must be failed.
@ Complete
The whole frame is in the buffer.
bool is_valid_close_code(uint16_t code)
True if a close frame may carry this status code (RFC 6455 section 7.4).
void unmask_payload(std::string &payload, const uint8_t mask_key[4])
Unmasks a frame payload in place using the frame's masking key.
bool is_valid_utf8(std::string_view data)
bool parse_frame_header(const std::vector< char > &buffer, FrameHeader &header)
Decodes an RFC 6455 frame header from the front of a buffer.
FrameStatus inspect_frame(const std::vector< char > &buffer, FrameHeader &header)
Parses the frame header at the front of buffer.
Definition Task.hpp:10
Definition Http2Session.hpp:18
Definition legacy_namespaces.hpp:27
Represents an incoming HTTP request.
Definition HttpRequest.hpp:54
Where frames go. Lets the protocol logic run without a socket (tests).
Definition WebSocketConnection.hpp:91
std::function< void(const std::vector< char > &)> write
Queue bytes to the peer.
Definition WebSocketConnection.hpp:92
std::function< void()> close
Close once queued bytes are sent.
Definition WebSocketConnection.hpp:93
A decoded RFC 6455 frame header.
Definition WebSocketConnection.hpp:26
uint8_t mask_key[4]
Definition WebSocketConnection.hpp:31
uint8_t opcode
Definition WebSocketConnection.hpp:28
bool masked
Definition WebSocketConnection.hpp:29
bool fin
Definition WebSocketConnection.hpp:27
size_t header_length
Definition WebSocketConnection.hpp:32
uint64_t payload_length
Definition WebSocketConnection.hpp:30