Debian Codegraph @

crt/aws-c-http/source/websocket_encoder.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/http/private/websocket_encoder.h>
7
8 #include <inttypes.h>
9
10 typedef int(state_fn)(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf);
11
12 /* STATE_INIT: Outputs no data */
13 static int s_state_init(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
14 (void)out_buf;
15
16 if (!encoder->is_frame_in_progress) {
17 return aws_raise_error(AWS_ERROR_INVALID_STATE);
18 }
19
20 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_OPCODE_BYTE;
21 return AWS_OP_SUCCESS;
22 }
23
24 /* STATE_OPCODE_BYTE: Outputs 1st byte of frame, which is packed with goodies. */
25 static int s_state_opcode_byte(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
26
27 AWS_ASSERT((encoder->frame.opcode & 0xF0) == 0); /* Should be impossible, the opcode was checked in start_frame() */
28
29 /* Right 4 bits are opcode, left 4 bits are fin|rsv1|rsv2|rsv3 */
30 uint8_t byte = encoder->frame.opcode;
31 byte |= (encoder->frame.fin << 7);
32 byte |= (encoder->frame.rsv[0] << 6);
33 byte |= (encoder->frame.rsv[1] << 5);
34 byte |= (encoder->frame.rsv[2] << 4);
35
36 /* If buffer has room to write, proceed to next state */
37 if (aws_byte_buf_write_u8(out_buf, byte)) {
38 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_LENGTH_BYTE;
39 }
40
41 return AWS_OP_SUCCESS;
42 }
43
44 /* STATE_LENGTH_BYTE: Output 2nd byte of frame, which indicates payload length */
45 static int s_state_length_byte(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
46 /* First bit is masking bool */
47 uint8_t byte = (uint8_t)(encoder->frame.masked << 7);
48
49 /* Next 7bits are length, if length is small.
50 * Otherwise next 7bits are a magic number indicating how many bytes will be required to encode actual length */
51 bool extended_length_required;
52
53 if (encoder->frame.payload_length < AWS_WEBSOCKET_2BYTE_EXTENDED_LENGTH_MIN_VALUE) {
54 byte |= (uint8_t)encoder->frame.payload_length;
55 extended_length_required = false;
56 } else if (encoder->frame.payload_length <= AWS_WEBSOCKET_2BYTE_EXTENDED_LENGTH_MAX_VALUE) {
57 byte |= AWS_WEBSOCKET_7BIT_VALUE_FOR_2BYTE_EXTENDED_LENGTH;
58 extended_length_required = true;
59 } else {
60 AWS_ASSERT(encoder->frame.payload_length <= AWS_WEBSOCKET_8BYTE_EXTENDED_LENGTH_MAX_VALUE);
61 byte |= AWS_WEBSOCKET_7BIT_VALUE_FOR_8BYTE_EXTENDED_LENGTH;
62 extended_length_required = true;
63 }
64
65 /* If buffer has room to write, proceed to next appropriate state */
66 if (aws_byte_buf_write_u8(out_buf, byte)) {
67 if (extended_length_required) {
68 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_EXTENDED_LENGTH;
69 encoder->state_bytes_processed = 0;
70 } else {
71 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_MASKING_KEY_CHECK;
72 }
73 }
74
75 return AWS_OP_SUCCESS;
76 }
77
78 /* STATE_EXTENDED_LENGTH: Output extended length (state skipped if not using extended length). */
79 static int s_state_extended_length(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
80 /* Fill tmp buffer with extended-length in network byte order */
81 uint8_t network_bytes_array[8] = {0};
82 struct aws_byte_buf network_bytes_buf =
83 aws_byte_buf_from_empty_array(network_bytes_array, sizeof(network_bytes_array));
84 if (encoder->frame.payload_length <= AWS_WEBSOCKET_2BYTE_EXTENDED_LENGTH_MAX_VALUE) {
85 aws_byte_buf_write_be16(&network_bytes_buf, (uint16_t)encoder->frame.payload_length);
86 } else {
87 aws_byte_buf_write_be64(&network_bytes_buf, encoder->frame.payload_length);
88 }
89
90 /* Use cursor to iterate over tmp buffer */
91 struct aws_byte_cursor network_bytes_cursor = aws_byte_cursor_from_buf(&network_bytes_buf);
92
93 /* Advance cursor if some bytes already written */
94 aws_byte_cursor_advance(&network_bytes_cursor, (size_t)encoder->state_bytes_processed);
95
96 /* Shorten cursor if it won't all fit in out_buf */
97 bool all_data_written = true;
98 size_t space_available = out_buf->capacity - out_buf->len;
99 if (network_bytes_cursor.len > space_available) {
100 network_bytes_cursor.len = space_available;
101 all_data_written = false;
102 }
103
104 aws_byte_buf_write_from_whole_cursor(out_buf, network_bytes_cursor);
105 encoder->state_bytes_processed += network_bytes_cursor.len;
106
107 /* If all bytes written, advance to next state */
108 if (all_data_written) {
109 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_MASKING_KEY_CHECK;
110 }
111
112 return AWS_OP_SUCCESS;
113 }
114
115 /* MASKING_KEY_CHECK: Outputs no data. Gets things ready for (or decides to skip) the STATE_MASKING_KEY */
116 static int s_state_masking_key_check(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
117 (void)out_buf;
118
119 if (encoder->frame.masked) {
120 encoder->state_bytes_processed = 0;
121 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_MASKING_KEY;
122 } else {
123 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_PAYLOAD_CHECK;
124 }
125
126 return AWS_OP_SUCCESS;
127 }
128
129 /* MASKING_KEY: Output masking-key (state skipped if no masking key). */
130 static int s_state_masking_key(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
131 /* Prepare cursor to iterate over masking-key bytes */
132 struct aws_byte_cursor cursor =
133 aws_byte_cursor_from_array(encoder->frame.masking_key, sizeof(encoder->frame.masking_key));
134
135 /* Advance cursor if some bytes already written (moves ptr forward but shortens len so end stays in place) */
136 aws_byte_cursor_advance(&cursor, (size_t)encoder->state_bytes_processed);
137
138 /* Shorten cursor if it won't all fit in out_buf */
139 bool all_data_written = true;
140 size_t space_available = out_buf->capacity - out_buf->len;
141 if (cursor.len > space_available) {
142 cursor.len = space_available;
143 all_data_written = false;
144 }
145
146 aws_byte_buf_write_from_whole_cursor(out_buf, cursor);
147 encoder->state_bytes_processed += cursor.len;
148
149 /* If all bytes written, advance to next state */
150 if (all_data_written) {
151 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_PAYLOAD_CHECK;
152 }
153
154 return AWS_OP_SUCCESS;
155 }
156
157 /* MASKING_KEY_CHECK: Outputs no data. Gets things ready for (or decides to skip) STATE_PAYLOAD */
158 static int s_state_payload_check(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
159 (void)out_buf;
160
161 if (encoder->frame.payload_length > 0) {
162 encoder->state_bytes_processed = 0;
163 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_PAYLOAD;
164 } else {
165 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_DONE;
166 }
167
168 return AWS_OP_SUCCESS;
169 }
170
171 /* PAYLOAD: Output payload until we're done (state skipped if no payload). */
172 static int s_state_payload(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
173
174 /* Bail early if out_buf has no space for writing */
175 if (out_buf->len >= out_buf->capacity) {
176 return AWS_OP_SUCCESS;
177 }
178
179 const uint64_t prev_bytes_processed = encoder->state_bytes_processed;
180 const struct aws_byte_buf prev_buf = *out_buf;
181
182 /* Invoke callback which will write to buffer */
183 int err = encoder->stream_outgoing_payload(out_buf, encoder->user_data);
184 if (err) {
185 return AWS_OP_ERR;
186 }
187
188 /* Ensure that user did not commit forbidden acts upon the out_buf */
189 AWS_FATAL_ASSERT(
190 (out_buf->buffer == prev_buf.buffer) && (out_buf->capacity == prev_buf.capacity) &&
191 (out_buf->len >= prev_buf.len));
192
193 size_t bytes_written = out_buf->len - prev_buf.len;
194
195 err = aws_add_u64_checked(encoder->state_bytes_processed, bytes_written, &encoder->state_bytes_processed);
196 if (err) {
197 return aws_raise_error(AWS_ERROR_HTTP_OUTGOING_STREAM_LENGTH_INCORRECT);
198 }
199
200 /* Mask data, if necessary.
201 * RFC-6455 Section 5.3 Client-to-Server Masking
202 * Each byte of payload is XOR against a byte of the masking-key */
203 if (encoder->frame.masked) {
204 uint64_t mask_index = prev_bytes_processed;
205
206 /* Optimization idea: don't do this 1 byte at a time */
207 uint8_t *current_byte = out_buf->buffer + prev_buf.len;
208 uint8_t *end_byte = out_buf->buffer + out_buf->len;
209 while (current_byte != end_byte) {
210 *current_byte++ ^= encoder->frame.masking_key[mask_index++ % 4];
211 }
212 }
213
214 /* If done writing payload, proceed to next state */
215 if (encoder->state_bytes_processed == encoder->frame.payload_length) {
216 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_DONE;
217 } else {
218 /* Some more error-checking... */
219 if (encoder->state_bytes_processed > encoder->frame.payload_length) {
220 AWS_LOGF_ERROR(
221 AWS_LS_HTTP_WEBSOCKET,
222 "id=%p: Outgoing stream has exceeded stated payload length of %" PRIu64,
223 (void *)encoder->user_data,
224 encoder->frame.payload_length);
225 return aws_raise_error(AWS_ERROR_HTTP_OUTGOING_STREAM_LENGTH_INCORRECT);
226 }
227 }
228
229 return AWS_OP_SUCCESS;
230 }
231
232 static state_fn *s_state_functions[AWS_WEBSOCKET_ENCODER_STATE_DONE] = {
233 s_state_init,
234 s_state_opcode_byte,
235 s_state_length_byte,
236 s_state_extended_length,
237 s_state_masking_key_check,
238 s_state_masking_key,
239 s_state_payload_check,
240 s_state_payload,
241 };
242
243 int aws_websocket_encoder_process(struct aws_websocket_encoder *encoder, struct aws_byte_buf *out_buf) {
244
245 /* Run state machine until frame is completely decoded, or the state stops changing.
246 * Note that we don't necessarily stop looping when out_buf is full, because not all states need to output data */
247 while (encoder->state != AWS_WEBSOCKET_ENCODER_STATE_DONE) {
248 const enum aws_websocket_encoder_state prev_state = encoder->state;
249
250 int err = s_state_functions[encoder->state](encoder, out_buf);
251 if (err) {
252 return AWS_OP_ERR;
253 }
254
255 if (prev_state == encoder->state) {
256 /* dev-assert: Check that each state is doing as much work as it possibly can.
257 * Except for the PAYLOAD state, where it's up to the user to fill the buffer. */
258 AWS_ASSERT((out_buf->len == out_buf->capacity) || (encoder->state == AWS_WEBSOCKET_ENCODER_STATE_PAYLOAD));
259
260 break;
261 }
262 }
263
264 if (encoder->state == AWS_WEBSOCKET_ENCODER_STATE_DONE) {
265 encoder->state = AWS_WEBSOCKET_ENCODER_STATE_INIT;
266 encoder->is_frame_in_progress = false;
267 }
268
269 return AWS_OP_SUCCESS;
270 }
271
272 int aws_websocket_encoder_start_frame(struct aws_websocket_encoder *encoder, const struct aws_websocket_frame *frame) {
273 /* Error-check as much as possible before accepting next frame */
274 if (encoder->is_frame_in_progress) {
275 return aws_raise_error(AWS_ERROR_INVALID_STATE);
276 }
277
278 /* RFC-6455 Section 5.2 contains all these rules... */
279
280 /* Opcode must fit in 4bits */
281 if (frame->opcode != (frame->opcode & 0x0F)) {
282 AWS_LOGF_ERROR(
283 AWS_LS_HTTP_WEBSOCKET,
284 "id=%p: Outgoing frame has unknown opcode 0x%" PRIx8,
285 (void *)encoder->user_data,
286 frame->opcode);
287 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
288 }
289
290 /* High bit of 8byte length must be clear */
291 if (frame->payload_length > AWS_WEBSOCKET_8BYTE_EXTENDED_LENGTH_MAX_VALUE) {
292 AWS_LOGF_ERROR(
293 AWS_LS_HTTP_WEBSOCKET,
294 "id=%p: Outgoing frame's payload length exceeds the max",
295 (void *)encoder->user_data);
296 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
297 }
298
299 /* Data frames with the FIN bit clear are considered fragmented and must be followed by
300 * 1+ CONTINUATION frames, where only the final CONTINUATION frame's FIN bit is set.
301 *
302 * Control frames may be injected in the middle of a fragmented message,
303 * but control frames may not be fragmented themselves. */
304 bool keep_expecting_continuation_data_frame = encoder->expecting_continuation_data_frame;
305 if (aws_websocket_is_data_frame(frame->opcode)) {
306 bool is_continuation_frame = (AWS_WEBSOCKET_OPCODE_CONTINUATION == frame->opcode);
307
308 if (encoder->expecting_continuation_data_frame != is_continuation_frame) {
309 AWS_LOGF_ERROR(
310 AWS_LS_HTTP_WEBSOCKET,
311 "id=%p: Fragmentation error. Outgoing frame starts a new message but previous message has not ended",
312 (void *)encoder->user_data);
313 return aws_raise_error(AWS_ERROR_INVALID_STATE);
314 }
315
316 keep_expecting_continuation_data_frame = !frame->fin;
317 } else {
318 /* Control frames themselves MUST NOT be fragmented. */
319 if (!frame->fin) {
320 AWS_LOGF_ERROR(
321 AWS_LS_HTTP_WEBSOCKET,
322 "id=%p: It is illegal to send a fragmented control frame",
323 (void *)encoder->user_data);
324
325 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
326 }
327 }
328
329 /* Frame accepted */
330 encoder->frame = *frame;
331 encoder->is_frame_in_progress = true;
332 encoder->expecting_continuation_data_frame = keep_expecting_continuation_data_frame;
333
334 return AWS_OP_SUCCESS;
335 }
336
337 bool aws_websocket_encoder_is_frame_in_progress(const struct aws_websocket_encoder *encoder) {
338 return encoder->is_frame_in_progress;
339 }
340
341 void aws_websocket_encoder_init(
342 struct aws_websocket_encoder *encoder,
343 aws_websocket_encoder_payload_fn *stream_outgoing_payload,
344 void *user_data) {
345
346 AWS_ZERO_STRUCT(*encoder);
347 encoder->user_data = user_data;
348 encoder->stream_outgoing_payload = stream_outgoing_payload;
349 }
350
351 uint64_t aws_websocket_frame_encoded_size(const struct aws_websocket_frame *frame) {
352 /* This is an internal function, so asserts are sufficient error handling */
353 AWS_ASSERT(frame);
354 AWS_ASSERT(frame->payload_length <= AWS_WEBSOCKET_8BYTE_EXTENDED_LENGTH_MAX_VALUE);
355
356 /* All frames start with at least 2 bytes */
357 uint64_t total = 2;
358
359 /* If masked, add 4 bytes for masking-key */
360 if (frame->masked) {
361 total += 4;
362 }
363
364 /* If extended payload length, add 2 or 8 bytes */
365 if (frame->payload_length >= AWS_WEBSOCKET_8BYTE_EXTENDED_LENGTH_MIN_VALUE) {
366 total += 8;
367 } else if (frame->payload_length >= AWS_WEBSOCKET_2BYTE_EXTENDED_LENGTH_MIN_VALUE) {
368 total += 2;
369 }
370
371 /* Plus payload itself */
372 total += frame->payload_length;
373
374 return total;
375 }