-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathws.cpp
More file actions
303 lines (271 loc) · 9.91 KB
/
ws.cpp
File metadata and controls
303 lines (271 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**
* @file ws.cpp
* @brief Implementation of the WebSocket protocol for the qb Actor Framework
*
* This file contains the implementation of core WebSocket functionality including:
* - Secure random key generation for handshakes
* - Frame construction with proper masking
* - Serialization of different message types
*
* The implementation follows RFC 6455 (The WebSocket Protocol).
*
* @author qb - C++ Actor Framework
* @copyright Copyright (c) 2011-2025 qb - isndev (cpp.actor)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ws.h"
namespace qb {
namespace http {
namespace ws {
/**
* @brief Checks if a string view contains valid UTF-8 data.
*
* This function validates a sequence of bytes to ensure it conforms to the
* UTF-8 encoding rules as specified in RFC 3629. It checks for:
* - Correct number of continuation bytes for multi-byte sequences.
* - Correct format of continuation bytes (10xxxxxx).
* - Absence of overlong encodings.
* - Absence of surrogate code points (U+D800 to U+DFFF).
* - Code points within the valid Unicode range (up to U+10FFFF).
*
* @param sv The string_view to validate.
* @return True if the data is valid UTF-8, false otherwise.
*/
bool
is_utf8(std::string_view sv) noexcept {
auto it = sv.begin();
while (it != sv.end()) {
unsigned char c = *it;
++it;
if (c < 0x80) { // 0xxxxxxx (ASCII)
continue;
}
if (c < 0xC2 || c > 0xF4) { // Invalid start byte
return false;
}
size_t extra_bytes = 0;
if (c < 0xE0) { // 110xxxxx 10xxxxxx
extra_bytes = 1;
} else if (c < 0xF0) { // 1110xxxx 10xxxxxx 10xxxxxx
extra_bytes = 2;
} else { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
extra_bytes = 3;
}
if (std::distance(it, sv.end()) < static_cast<std::ptrdiff_t>(extra_bytes)) {
return false; // Not enough bytes left
}
// Check continuation bytes
for (size_t i = 0; i < extra_bytes; ++i) {
unsigned char next_byte = *it;
++it;
if ((next_byte & 0xC0) != 0x80) { // Must be 10xxxxxx
return false;
}
}
}
return true;
}
/**
* @brief Generate a random WebSocket key for handshake
* @return Base64-encoded random 16-byte value
*
* Creates a cryptographically secure random key for use in the WebSocket
* opening handshake. The key is a 16-byte nonce that is Base64-encoded
* as specified in RFC 6455 Section 4.1.
*/
std::string
generateKey() noexcept {
// Make random 16-byte nonce
char nonce[16] = "";
std::uniform_int_distribution<unsigned short> dist(0, 255);
std::random_device rd;
for (char &i : nonce) {
i = static_cast<char>(dist(rd));
}
return crypto::base64::encode({nonce, 16});
}
} // namespace ws
} // namespace http
} // namespace qb
namespace qb {
namespace allocator {
/**
* @brief Create an unmasked WebSocket frame in the output buffer
* @param pipe The output buffer to write the frame to
* @param msg The WebSocket message to format
*
* Formats a WebSocket message as an unmasked frame according to RFC 6455.
* This is typically used for server-to-client communication where masking
* is not required.
*/
static void
fill_unmasked_message(pipe<char> &pipe, const http::ws::Message &msg) {
std::size_t length = msg.size();
pipe.reserve(length + 10); // Reserve space for header and payload
// Write FIN, RSV, and opcode
pipe << static_cast<char>(msg.fin_rsv_opcode);
// Write payload length with appropriate format based on size
if (length >= 126) {
std::size_t num_bytes;
if (length > 0xffff) {
// For lengths >= 65536, use 8-byte length format
num_bytes = 8;
pipe << static_cast<char>(127); // 127 indicates 8-byte length
} else {
// For lengths >= 126 but < 65536, use 2-byte length format
num_bytes = 2;
pipe << static_cast<char>(126); // 126 indicates 2-byte length
}
// Write the length bytes in network byte order (big-endian)
for (std::size_t c = num_bytes - 1; c != static_cast<std::size_t>(-1); --c)
pipe << static_cast<char>(
(static_cast<unsigned long long>(length) >> (8 * c)) % 256);
} else {
// For lengths < 126, use 1-byte length format
pipe << static_cast<char>(length);
}
// Append the message payload
pipe << msg._data;
}
/**
* @brief Create a masked WebSocket frame in the output buffer
* @param pipe The output buffer to write the frame to
* @param msg The WebSocket message to format
*
* Formats a WebSocket message as a masked frame according to RFC 6455.
* This is required for client-to-server communication to prevent certain
* types of attacks on proxies and intermediaries.
*/
static void
fill_masked_message(pipe<char> &pipe, const http::ws::Message &msg) {
// Create a random 4-byte mask as required by the protocol
std::array<unsigned char, 4> mask{};
std::uniform_int_distribution<unsigned short> dist(0, 255);
std::random_device rd;
for (std::size_t c = 0; c < 4; ++c)
mask[c] = static_cast<unsigned char>(dist(rd));
std::size_t length = msg.size();
pipe.reserve(length + 14); // Reserve space for header, mask, and payload
// Write FIN, RSV, and opcode
pipe << static_cast<char>(msg.fin_rsv_opcode);
// Write payload length with appropriate format based on size
// Set the mask bit (0x80) in the first length byte
if (length >= 126) {
std::size_t num_bytes;
if (length > 0xffff) {
// For lengths >= 65536, use 8-byte length format
num_bytes = 8;
pipe << static_cast<char>(127 + 128); // 127 + mask bit
} else {
// For lengths >= 126 but < 65536, use 2-byte length format
num_bytes = 2;
pipe << static_cast<char>(126 + 128); // 126 + mask bit
}
// Write the length bytes in network byte order (big-endian)
for (std::size_t c = num_bytes - 1; c != static_cast<std::size_t>(-1); --c)
pipe << static_cast<char>(
(static_cast<unsigned long long>(length) >> (8 * c)) % 256);
} else {
// For lengths < 126, use 1-byte length format
pipe << static_cast<char>(length + 128); // length + mask bit
}
// Write the 4-byte mask
pipe.write(reinterpret_cast<char *>(mask.data()), 4);
// Apply the mask to the payload and write it
const auto msg_begin = msg._data.cbegin();
auto out_begin = pipe.allocate_back(length);
for (std::size_t i = 0; i < length; ++i)
out_begin[i] = static_cast<char>(msg_begin[i] ^ mask[i % 4]);
}
/**
* @brief Specialization to serialize a WebSocket Message into a pipe
* @param msg The WebSocket message to serialize
* @return Reference to this pipe for chaining
*
* Formats the WebSocket message according to the protocol specification,
* applying masking if required by the message's masked flag.
*/
template <>
pipe<char> &
pipe<char>::put<http::ws::Message>(const http::ws::Message &msg) {
if (msg.masked)
fill_masked_message(*this, msg);
else
fill_unmasked_message(*this, msg);
return *this;
}
/**
* @brief Specialization to serialize a WebSocket Ping message
* @param msg The Ping message to serialize
* @return Reference to this pipe for chaining
*/
template <>
pipe<char> &
pipe<char>::put<http::ws::MessagePing>(const http::ws::MessagePing &msg) {
return put(static_cast<http::ws::Message const &>(msg));
}
/**
* @brief Specialization to serialize a WebSocket Pong message
* @param msg The Pong message to serialize
* @return Reference to this pipe for chaining
*/
template <>
pipe<char> &
pipe<char>::put<http::ws::MessagePong>(const http::ws::MessagePong &msg) {
return put(static_cast<http::ws::Message const &>(msg));
}
/**
* @brief Specialization to serialize a WebSocket Text message
* @param msg The Text message to serialize
* @return Reference to this pipe for chaining
*/
template <>
pipe<char> &
pipe<char>::put<http::ws::MessageText>(const http::ws::MessageText &msg) {
return put(static_cast<http::ws::Message const &>(msg));
}
/**
* @brief Specialization to serialize a WebSocket Binary message
* @param msg The Binary message to serialize
* @return Reference to this pipe for chaining
*/
template <>
pipe<char> &
pipe<char>::put<http::ws::MessageBinary>(const http::ws::MessageBinary &msg) {
return put(static_cast<http::ws::Message const &>(msg));
}
/**
* @brief Specialization to serialize a WebSocket Close message
* @param msg The Close message to serialize
* @return Reference to this pipe for chaining
*/
template <>
pipe<char> &
pipe<char>::put<http::ws::MessageClose>(const http::ws::MessageClose &msg) {
return put(static_cast<http::ws::Message const &>(msg));
}
/**
* @brief Specialization to serialize a WebSocket handshake request
* @param msg The WebSocket handshake request to serialize
* @return Reference to this pipe for chaining
*
* Converts a WebSocketRequest to an HTTP Request for the initial handshake.
*/
template <>
pipe<char> &
pipe<char>::put<http::WebSocketRequest>(const http::WebSocketRequest &msg) {
return put(static_cast<const http::Request &>(msg));
}
} // namespace allocator
} // namespace qb
// #include <qb/io/async.h>