Debian Codegraph @

crt/aws-c-http/source/websocket_decoder.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_decoder.h>
7
8 #include <aws/common/encoding.h>
9
10 #include <inttypes.h>
11
12 typedef int(state_fn)(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data);
13
14 /* STATE_INIT: Resets things, consumes no data */
15 static int s_state_init(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
16 (void)data;
17 AWS_ZERO_STRUCT(decoder->current_frame);
18 decoder->state = AWS_WEBSOCKET_DECODER_STATE_OPCODE_BYTE;
19 return AWS_OP_SUCCESS;
20 }
21
22 /* STATE_OPCODE_BYTE: Decode first byte of frame, which has all kinds of goodies in it. */
23 static int s_state_opcode_byte(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
24 if (data->len == 0) {
25 return AWS_OP_SUCCESS;
26 }
27
28 uint8_t byte = data->ptr[0];
29 aws_byte_cursor_advance(data, 1);
30
31 /* first 4 bits are all bools */
32 decoder->current_frame.fin = byte & 0x80;
33 decoder->current_frame.rsv[0] = byte & 0x40;
34 decoder->current_frame.rsv[1] = byte & 0x20;
35 decoder->current_frame.rsv[2] = byte & 0x10;
36
37 /* next 4 bits are opcode */
38 decoder->current_frame.opcode = byte & 0x0F;
39
40 /* RFC-6455 Section 5.2 - Opcode
41 * If an unknown opcode is received, the receiving endpoint MUST _Fail the WebSocket Connection_. */
42 switch (decoder->current_frame.opcode) {
43 case AWS_WEBSOCKET_OPCODE_CONTINUATION:
44 case AWS_WEBSOCKET_OPCODE_TEXT:
45 case AWS_WEBSOCKET_OPCODE_BINARY:
46 case AWS_WEBSOCKET_OPCODE_CLOSE:
47 case AWS_WEBSOCKET_OPCODE_PING:
48 case AWS_WEBSOCKET_OPCODE_PONG:
49 break;
50 default:
51 AWS_LOGF_ERROR(
52 AWS_LS_HTTP_WEBSOCKET,
53 "id=%p: Received frame with unknown opcode 0x%" PRIx8,
54 (void *)decoder->user_data,
55 decoder->current_frame.opcode);
56 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_PROTOCOL_ERROR);
57 }
58
59 /* RFC-6455 Section 5.2 Fragmentation
60 *
61 * Data frames with the FIN bit clear are considered fragmented and must be followed by
62 * 1+ CONTINUATION frames, where only the final CONTINUATION frame's FIN bit is set.
63 *
64 * Control frames may be injected in the middle of a fragmented message,
65 * but control frames may not be fragmented themselves.
66 */
67 if (aws_websocket_is_data_frame(decoder->current_frame.opcode)) {
68 bool is_continuation_frame = AWS_WEBSOCKET_OPCODE_CONTINUATION == decoder->current_frame.opcode;
69
70 if (decoder->expecting_continuation_data_frame != is_continuation_frame) {
71 AWS_LOGF_ERROR(
72 AWS_LS_HTTP_WEBSOCKET,
73 "id=%p: Fragmentation error. Received start of new message before end of previous message",
74 (void *)decoder->user_data);
75 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_PROTOCOL_ERROR);
76 }
77
78 decoder->expecting_continuation_data_frame = !decoder->current_frame.fin;
79
80 } else {
81 /* Control frames themselves MUST NOT be fragmented. */
82 if (!decoder->current_frame.fin) {
83 AWS_LOGF_ERROR(
84 AWS_LS_HTTP_WEBSOCKET,
85 "id=%p: Received fragmented control frame. This is illegal",
86 (void *)decoder->user_data);
87 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_PROTOCOL_ERROR);
88 }
89 }
90
91 if (decoder->current_frame.opcode == AWS_WEBSOCKET_OPCODE_TEXT) {
92 decoder->processing_text_message = true;
93 }
94
95 decoder->state = AWS_WEBSOCKET_DECODER_STATE_LENGTH_BYTE;
96 return AWS_OP_SUCCESS;
97 }
98
99 /* STATE_LENGTH_BYTE: Decode byte containing length, determine if we need to decode extended length. */
100 static int s_state_length_byte(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
101 if (data->len == 0) {
102 return AWS_OP_SUCCESS;
103 }
104
105 uint8_t byte = data->ptr[0];
106 aws_byte_cursor_advance(data, 1);
107
108 /* first bit is a bool */
109 decoder->current_frame.masked = byte & 0x80;
110
111 /* remaining 7 bits are payload length */
112 decoder->current_frame.payload_length = byte & 0x7F;
113
114 if (decoder->current_frame.payload_length >= AWS_WEBSOCKET_7BIT_VALUE_FOR_2BYTE_EXTENDED_LENGTH) {
115 /* If 7bit payload length has a high value, then the next few bytes contain the real payload length */
116 decoder->state_bytes_processed = 0;
117 decoder->state = AWS_WEBSOCKET_DECODER_STATE_EXTENDED_LENGTH;
118 } else {
119 /* If 7bit payload length has low value, that's the actual payload size, jump past EXTENDED_LENGTH state */
120 decoder->state = AWS_WEBSOCKET_DECODER_STATE_MASKING_KEY_CHECK;
121 }
122
123 return AWS_OP_SUCCESS;
124 }
125
126 /* STATE_EXTENDED_LENGTH: Decode extended length (state skipped if no extended length). */
127 static int s_state_extended_length(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
128 if (data->len == 0) {
129 return AWS_OP_SUCCESS;
130 }
131
132 /* The 7bit payload value loaded during the previous state indicated that
133 * actual payload length is encoded across the next 2 or 8 bytes. */
134 uint8_t total_bytes_extended_length;
135 uint64_t min_acceptable_value;
136 uint64_t max_acceptable_value;
137 if (decoder->current_frame.payload_length == AWS_WEBSOCKET_7BIT_VALUE_FOR_2BYTE_EXTENDED_LENGTH) {
138 total_bytes_extended_length = 2;
139 min_acceptable_value = AWS_WEBSOCKET_2BYTE_EXTENDED_LENGTH_MIN_VALUE;
140 max_acceptable_value = AWS_WEBSOCKET_2BYTE_EXTENDED_LENGTH_MAX_VALUE;
141 } else {
142 AWS_ASSERT(decoder->current_frame.payload_length == AWS_WEBSOCKET_7BIT_VALUE_FOR_8BYTE_EXTENDED_LENGTH);
143
144 total_bytes_extended_length = 8;
145 min_acceptable_value = AWS_WEBSOCKET_8BYTE_EXTENDED_LENGTH_MIN_VALUE;
146 max_acceptable_value = AWS_WEBSOCKET_8BYTE_EXTENDED_LENGTH_MAX_VALUE;
147 }
148
149 /* Copy bytes of extended-length to state_cache, we'll process them later.*/
150 AWS_ASSERT(total_bytes_extended_length > decoder->state_bytes_processed);
151
152 size_t remaining_bytes = (size_t)(total_bytes_extended_length - decoder->state_bytes_processed);
153 size_t bytes_to_consume = remaining_bytes <= data->len ? remaining_bytes : data->len;
154
155 AWS_ASSERT(bytes_to_consume + decoder->state_bytes_processed <= sizeof(decoder->state_cache));
156
157 memcpy(decoder->state_cache + decoder->state_bytes_processed, data->ptr, bytes_to_consume);
158
159 aws_byte_cursor_advance(data, bytes_to_consume);
160 decoder->state_bytes_processed += bytes_to_consume;
161
162 /* Return, still waiting on more bytes */
163 if (decoder->state_bytes_processed < total_bytes_extended_length) {
164 return AWS_OP_SUCCESS;
165 }
166
167 /* All bytes have been copied into state_cache, now read them together as one number,
168 * transforming from network byte order (big endian) to native endianness. */
169 struct aws_byte_cursor cache_cursor = aws_byte_cursor_from_array(decoder->state_cache, total_bytes_extended_length);
170 if (total_bytes_extended_length == 2) {
171 uint16_t val;
172 aws_byte_cursor_read_be16(&cache_cursor, &val);
173 decoder->current_frame.payload_length = val;
174 } else {
175 aws_byte_cursor_read_be64(&cache_cursor, &decoder->current_frame.payload_length);
176 }
177
178 if (decoder->current_frame.payload_length < min_acceptable_value ||
179 decoder->current_frame.payload_length > max_acceptable_value) {
180
181 AWS_LOGF_ERROR(AWS_LS_HTTP_WEBSOCKET, "id=%p: Failed to decode payload length", (void *)decoder->user_data);
182 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_PROTOCOL_ERROR);
183 }
184
185 decoder->state = AWS_WEBSOCKET_DECODER_STATE_MASKING_KEY_CHECK;
186 return AWS_OP_SUCCESS;
187 }
188
189 /* MASKING_KEY_CHECK: Determine if we need to decode masking-key. Consumes no data. */
190 static int s_state_masking_key_check(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
191 (void)data;
192
193 /* If mask bit was set, move to next state to process 4 bytes of masking key.
194 * Otherwise skip next step, there is no masking key. */
195 if (decoder->current_frame.masked) {
196 decoder->state = AWS_WEBSOCKET_DECODER_STATE_MASKING_KEY;
197 decoder->state_bytes_processed = 0;
198 } else {
199 decoder->state = AWS_WEBSOCKET_DECODER_STATE_PAYLOAD_CHECK;
200 }
201
202 return AWS_OP_SUCCESS;
203 }
204
205 /* MASKING_KEY: Decode masking-key (state skipped if no masking key). */
206 static int s_state_masking_key(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
207 if (data->len == 0) {
208 return AWS_OP_SUCCESS;
209 }
210
211 AWS_ASSERT(4 > decoder->state_bytes_processed);
212 size_t bytes_remaining = 4 - (size_t)decoder->state_bytes_processed;
213 size_t bytes_to_consume = bytes_remaining < data->len ? bytes_remaining : data->len;
214
215 memcpy(decoder->current_frame.masking_key + decoder->state_bytes_processed, data->ptr, bytes_to_consume);
216
217 aws_byte_cursor_advance(data, bytes_to_consume);
218 decoder->state_bytes_processed += bytes_to_consume;
219
220 /* If all bytes consumed, proceed to next state */
221 if (decoder->state_bytes_processed == 4) {
222 decoder->state = AWS_WEBSOCKET_DECODER_STATE_PAYLOAD_CHECK;
223 }
224
225 return AWS_OP_SUCCESS;
226 }
227
228 /* PAYLOAD_CHECK: Determine if we need to decode a payload. Consumes no data. */
229 static int s_state_payload_check(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
230 (void)data;
231
232 /* Invoke on_frame() callback to inform user of non-payload data. */
233 int err = decoder->on_frame(&decoder->current_frame, decoder->user_data);
234 if (err) {
235 return AWS_OP_ERR;
236 }
237
238 /* Choose next state: either we have payload to process or we don't. */
239 if (decoder->current_frame.payload_length > 0) {
240 decoder->state_bytes_processed = 0;
241 decoder->state = AWS_WEBSOCKET_DECODER_STATE_PAYLOAD;
242 } else {
243 decoder->state = AWS_WEBSOCKET_DECODER_STATE_FRAME_END;
244 }
245
246 return AWS_OP_SUCCESS;
247 }
248
249 /* PAYLOAD: Decode payload until we're done (state skipped if no payload). */
250 static int s_state_payload(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
251 if (data->len == 0) {
252 return AWS_OP_SUCCESS;
253 }
254
255 AWS_ASSERT(decoder->current_frame.payload_length > decoder->state_bytes_processed);
256 uint64_t bytes_remaining = decoder->current_frame.payload_length - decoder->state_bytes_processed;
257 size_t bytes_to_consume = bytes_remaining < data->len ? (size_t)bytes_remaining : data->len;
258
259 struct aws_byte_cursor payload = aws_byte_cursor_advance(data, bytes_to_consume);
260
261 /* Unmask data, if necessary.
262 * RFC-6455 Section 5.3 Client-to-Server Masking
263 * Each byte of payload is XOR against a byte of the masking-key */
264 if (decoder->current_frame.masked) {
265 uint64_t mask_index = decoder->state_bytes_processed;
266
267 /* Optimization idea: don't do this 1 byte at a time */
268 uint8_t *current_byte = payload.ptr;
269 uint8_t *end_byte = payload.ptr + payload.len;
270 while (current_byte != end_byte) {
271 *current_byte++ ^= decoder->current_frame.masking_key[mask_index++ % 4];
272 }
273 }
274
275 /* TODO: validate payload of CLOSE frame */
276
277 /* Validate the UTF-8 for TEXT messages (a TEXT frame and any subsequent CONTINUATION frames) */
278 if (decoder->processing_text_message && aws_websocket_is_data_frame(decoder->current_frame.opcode)) {
279 if (aws_utf8_decoder_update(decoder->text_message_validator, payload)) {
280 AWS_LOGF_ERROR(AWS_LS_HTTP_WEBSOCKET, "id=%p: Received invalid UTF-8", (void *)decoder->user_data);
281 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_PROTOCOL_ERROR);
282 }
283 }
284
285 /* Invoke on_payload() callback to inform user of payload data */
286 int err = decoder->on_payload(payload, decoder->user_data);
287 if (err) {
288 return AWS_OP_ERR;
289 }
290
291 decoder->state_bytes_processed += payload.len;
292 AWS_ASSERT(decoder->state_bytes_processed <= decoder->current_frame.payload_length);
293
294 /* If all data consumed, proceed to next state. */
295 if (decoder->state_bytes_processed == decoder->current_frame.payload_length) {
296 decoder->state = AWS_WEBSOCKET_DECODER_STATE_FRAME_END;
297 }
298
299 return AWS_OP_SUCCESS;
300 }
301
302 /* FRAME_END: Perform checks once we reach the end of the frame. */
303 static int s_state_frame_end(struct aws_websocket_decoder *decoder, struct aws_byte_cursor *data) {
304 (void)data;
305
306 /* If we're done processing a text message (a TEXT frame and any subsequent CONTINUATION frames),
307 * complete the UTF-8 validation */
308 if (decoder->processing_text_message && aws_websocket_is_data_frame(decoder->current_frame.opcode) &&
309 decoder->current_frame.fin) {
310
311 if (aws_utf8_decoder_finalize(decoder->text_message_validator)) {
312 AWS_LOGF_ERROR(
313 AWS_LS_HTTP_WEBSOCKET,
314 "id=%p: Received invalid UTF-8 (incomplete encoding)",
315 (void *)decoder->user_data);
316 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_PROTOCOL_ERROR);
317 }
318
319 decoder->processing_text_message = false;
320 }
321
322 /* Done! */
323 decoder->state = AWS_WEBSOCKET_DECODER_STATE_DONE;
324 return AWS_OP_SUCCESS;
325 }
326
327 static state_fn *s_state_functions[AWS_WEBSOCKET_DECODER_STATE_DONE] = {
328 s_state_init,
329 s_state_opcode_byte,
330 s_state_length_byte,
331 s_state_extended_length,
332 s_state_masking_key_check,
333 s_state_masking_key,
334 s_state_payload_check,
335 s_state_payload,
336 s_state_frame_end,
337 };
338
339 int aws_websocket_decoder_process(
340 struct aws_websocket_decoder *decoder,
341 struct aws_byte_cursor *data,
342 bool *frame_complete) {
343
344 /* Run state machine until frame is completely decoded, or the state stops changing.
345 * Note that we don't stop looping when data->len reaches zero, because some states consume no data. */
346 while (decoder->state != AWS_WEBSOCKET_DECODER_STATE_DONE) {
347 enum aws_websocket_decoder_state prev_state = decoder->state;
348
349 int err = s_state_functions[decoder->state](decoder, data);
350 if (err) {
351 return AWS_OP_ERR;
352 }
353
354 if (decoder->state == prev_state) {
355 AWS_ASSERT(data->len == 0); /* If no more work to do, all possible data should have been consumed */
356 break;
357 }
358 }
359
360 if (decoder->state == AWS_WEBSOCKET_DECODER_STATE_DONE) {
361 decoder->state = AWS_WEBSOCKET_DECODER_STATE_INIT;
362 *frame_complete = true;
363 return AWS_OP_SUCCESS;
364 }
365
366 *frame_complete = false;
367 return AWS_OP_SUCCESS;
368 }
369
370 void aws_websocket_decoder_init(
371 struct aws_websocket_decoder *decoder,
372 struct aws_allocator *alloc,
373 aws_websocket_decoder_frame_fn *on_frame,
374 aws_websocket_decoder_payload_fn *on_payload,
375 void *user_data) {
376
377 AWS_ZERO_STRUCT(*decoder);
378 decoder->user_data = user_data;
379 decoder->on_frame = on_frame;
380 decoder->on_payload = on_payload;
381 decoder->text_message_validator = aws_utf8_decoder_new(alloc, NULL /*options*/);
382 }
383
384 void aws_websocket_decoder_clean_up(struct aws_websocket_decoder *decoder) {
385 aws_utf8_decoder_destroy(decoder->text_message_validator);
386 AWS_ZERO_STRUCT(*decoder);
387 }