Debian Codegraph @

crt/aws-c-http/source/h1_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 #include <aws/http/private/h1_encoder.h>
6 #include <aws/http/private/h1_stream.h>
7 #include <aws/http/private/strutil.h>
8 #include <aws/http/status_code.h>
9 #include <aws/io/logging.h>
10 #include <aws/io/stream.h>
11
12 #include <inttypes.h>
13
14 #define ENCODER_LOGF(level, encoder, text, ...) \
15 AWS_LOGF_##level(AWS_LS_HTTP_STREAM, "id=%p: " text, (void *)encoder->current_stream, __VA_ARGS__)
16 #define ENCODER_LOG(level, encoder, text) ENCODER_LOGF(level, encoder, "%s", text)
17
18 #define MAX_ASCII_HEX_CHUNK_STR_SIZE (sizeof(uint64_t) * 2 + 1)
19 #define CRLF_SIZE 2
20
21 /**
22 * Scan headers to detect errors and determine anything we'll need to know later (ex: total length).
23 */
24 static int s_scan_outgoing_headers(
25 struct aws_h1_encoder_message *encoder_message,
26 const struct aws_http_message *message,
27 size_t *out_header_lines_len,
28 bool body_headers_ignored,
29 bool body_headers_forbidden,
30 bool use_manual_data_writes) {
31
32 size_t total = 0;
33 bool has_body_stream = aws_http_message_get_body_stream(message);
34 bool has_content_length_header = false;
35 bool has_transfer_encoding_header = false;
36
37 const size_t num_headers = aws_http_message_get_header_count(message);
38 for (size_t i = 0; i < num_headers; ++i) {
39 struct aws_http_header header;
40 aws_http_message_get_header(message, &header, i);
41
42 /* Validate header field-name (RFC-7230 3.2): field-name = token */
43 if (!aws_strutil_is_http_token(header.name)) {
44 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Header name is invalid");
45 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_NAME);
46 }
47
48 /* Validate header field-value.
49 * The value itself isn't supposed to have whitespace on either side,
50 * but we'll trim it off before validation so we don't start needlessly
51 * failing requests that used to work before we added validation.
52 * This should be OK because field-value can be sent with any amount
53 * of whitespace around it, which the other side will just ignore (RFC-7230 3.2):
54 * header-field = field-name ":" OWS field-value OWS */
55 struct aws_byte_cursor field_value = aws_strutil_trim_http_whitespace(header.value);
56 if (!aws_strutil_is_http_field_value(field_value)) {
57 AWS_LOGF_ERROR(
58 AWS_LS_HTTP_STREAM,
59 "id=static: Header '" PRInSTR "' has invalid value",
60 AWS_BYTE_CURSOR_PRI(header.name));
61 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_VALUE);
62 }
63
64 enum aws_http_header_name name_enum = aws_http_str_to_header_name(header.name);
65 switch (name_enum) {
66 case AWS_HTTP_HEADER_CONNECTION: {
67 if (aws_byte_cursor_eq_c_str(&field_value, "close")) {
68 encoder_message->has_connection_close_header = true;
69 }
70 } break;
71 case AWS_HTTP_HEADER_CONTENT_LENGTH: {
72 has_content_length_header = true;
73 if (aws_byte_cursor_utf8_parse_u64(field_value, &encoder_message->content_length)) {
74 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Invalid Content-Length");
75 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_VALUE);
76 }
77 } break;
78 case AWS_HTTP_HEADER_TRANSFER_ENCODING: {
79 has_transfer_encoding_header = true;
80 if (0 == field_value.len) {
81 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Transfer-Encoding must include a valid value");
82 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_VALUE);
83 }
84 struct aws_byte_cursor substr;
85 AWS_ZERO_STRUCT(substr);
86 while (aws_byte_cursor_next_split(&field_value, ',', &substr)) {
87 struct aws_byte_cursor trimmed = aws_strutil_trim_http_whitespace(substr);
88 if (0 == trimmed.len) {
89 AWS_LOGF_ERROR(
90 AWS_LS_HTTP_STREAM,
91 "id=static: Transfer-Encoding header whitespace only "
92 "comma delimited header value");
93 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_VALUE);
94 }
95 if (encoder_message->has_chunked_encoding_header) {
96 AWS_LOGF_ERROR(
97 AWS_LS_HTTP_STREAM, "id=static: Transfer-Encoding header must end with \"chunked\"");
98 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_VALUE);
99 }
100 if (aws_byte_cursor_eq_c_str(&trimmed, "chunked")) {
101 encoder_message->has_chunked_encoding_header = true;
102 }
103 }
104 } break;
105 default:
106 break;
107 }
108
109 /* header-line: "{name}: {value}\r\n" */
110 int err = 0;
111 err |= aws_add_size_checked(header.name.len, total, &total);
112 err |= aws_add_size_checked(header.value.len, total, &total);
113 err |= aws_add_size_checked(4, total, &total); /* ": " + "\r\n" */
114 if (err) {
115 return AWS_OP_ERR;
116 }
117 }
118
119 if (!encoder_message->has_chunked_encoding_header && has_transfer_encoding_header) {
120 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Transfer-Encoding header must include \"chunked\"");
121 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_VALUE);
122 }
123
124 /* Per RFC 7230: A sender MUST NOT send a Content-Length header field in any message that contains a
125 * Transfer-Encoding header field. */
126 if (encoder_message->has_chunked_encoding_header && has_content_length_header) {
127 AWS_LOGF_ERROR(
128 AWS_LS_HTTP_STREAM, "id=static: Both Content-Length and Transfer-Encoding are set. Only one may be used");
129 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_FIELD);
130 }
131
132 if (body_headers_forbidden && (encoder_message->content_length > 0 || has_transfer_encoding_header)) {
133 AWS_LOGF_ERROR(
134 AWS_LS_HTTP_STREAM,
135 "id=static: Transfer-Encoding or Content-Length headers may not be present in such a message");
136 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_FIELD);
137 }
138
139 if (body_headers_ignored) {
140 /* Don't send body, no matter what the headers are */
141 encoder_message->content_length = 0;
142 encoder_message->has_chunked_encoding_header = false;
143 }
144
145 if (use_manual_data_writes && has_body_stream) {
146 AWS_LOGF_ERROR(
147 AWS_LS_HTTP_STREAM, "id=static: Body stream must not be set when manual data writes are enabled");
148 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_FIELD);
149 }
150
151 if (encoder_message->content_length > 0 && !has_body_stream && !use_manual_data_writes) {
152 return aws_raise_error(AWS_ERROR_HTTP_MISSING_BODY_STREAM);
153 }
154
155 *out_header_lines_len = total;
156 return AWS_OP_SUCCESS;
157 }
158
159 static int s_scan_outgoing_trailer(const struct aws_http_headers *headers, size_t *out_size) {
160 const size_t num_headers = aws_http_headers_count(headers);
161 size_t total = 0;
162 for (size_t i = 0; i < num_headers; i++) {
163 struct aws_http_header header;
164 aws_http_headers_get_index(headers, i, &header);
165 /* Validate header field-name (RFC-7230 3.2): field-name = token */
166 if (!aws_strutil_is_http_token(header.name)) {
167 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Header name is invalid");
168 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_NAME);
169 }
170
171 /* Validate header field-value.
172 * The value itself isn't supposed to have whitespace on either side,
173 * but we'll trim it off before validation so we don't start needlessly
174 * failing requests that used to work before we added validation.
175 * This should be OK because field-value can be sent with any amount
176 * of whitespace around it, which the other side will just ignore (RFC-7230 3.2):
177 * header-field = field-name ":" OWS field-value OWS */
178 struct aws_byte_cursor field_value = aws_strutil_trim_http_whitespace(header.value);
179 if (!aws_strutil_is_http_field_value(field_value)) {
180 AWS_LOGF_ERROR(
181 AWS_LS_HTTP_STREAM,
182 "id=static: Header '" PRInSTR "' has invalid value",
183 AWS_BYTE_CURSOR_PRI(header.name));
184 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_VALUE);
185 }
186
187 enum aws_http_header_name name_enum = aws_http_str_to_header_name(header.name);
188 if (name_enum == AWS_HTTP_HEADER_TRANSFER_ENCODING || name_enum == AWS_HTTP_HEADER_CONTENT_LENGTH ||
189 name_enum == AWS_HTTP_HEADER_HOST || name_enum == AWS_HTTP_HEADER_EXPECT ||
190 name_enum == AWS_HTTP_HEADER_CACHE_CONTROL || name_enum == AWS_HTTP_HEADER_MAX_FORWARDS ||
191 name_enum == AWS_HTTP_HEADER_PRAGMA || name_enum == AWS_HTTP_HEADER_RANGE ||
192 name_enum == AWS_HTTP_HEADER_TE || name_enum == AWS_HTTP_HEADER_CONTENT_ENCODING ||
193 name_enum == AWS_HTTP_HEADER_CONTENT_TYPE || name_enum == AWS_HTTP_HEADER_CONTENT_RANGE ||
194 name_enum == AWS_HTTP_HEADER_TRAILER || name_enum == AWS_HTTP_HEADER_WWW_AUTHENTICATE ||
195 name_enum == AWS_HTTP_HEADER_AUTHORIZATION || name_enum == AWS_HTTP_HEADER_PROXY_AUTHENTICATE ||
196 name_enum == AWS_HTTP_HEADER_PROXY_AUTHORIZATION || name_enum == AWS_HTTP_HEADER_SET_COOKIE ||
197 name_enum == AWS_HTTP_HEADER_COOKIE || name_enum == AWS_HTTP_HEADER_AGE ||
198 name_enum == AWS_HTTP_HEADER_EXPIRES || name_enum == AWS_HTTP_HEADER_DATE ||
199 name_enum == AWS_HTTP_HEADER_LOCATION || name_enum == AWS_HTTP_HEADER_RETRY_AFTER ||
200 name_enum == AWS_HTTP_HEADER_VARY || name_enum == AWS_HTTP_HEADER_WARNING) {
201 AWS_LOGF_ERROR(
202 AWS_LS_HTTP_STREAM,
203 "id=static: Trailing Header '" PRInSTR "' has invalid value",
204 AWS_BYTE_CURSOR_PRI(header.name));
205 return aws_raise_error(AWS_ERROR_HTTP_INVALID_HEADER_FIELD);
206 }
207
208 int err = 0;
209 err |= aws_add_size_checked(header.name.len, total, &total);
210 err |= aws_add_size_checked(header.value.len, total, &total);
211 err |= aws_add_size_checked(4, total, &total); /* ": " + "\r\n" */
212 if (err) {
213 return AWS_OP_ERR;
214 }
215 }
216 if (aws_add_size_checked(2, total, &total)) { /* "\r\n" */
217 return AWS_OP_ERR;
218 }
219 *out_size = total;
220 return AWS_OP_SUCCESS;
221 }
222
223 static bool s_write_crlf(struct aws_byte_buf *dst) {
224 AWS_PRECONDITION(aws_byte_buf_is_valid(dst));
225 struct aws_byte_cursor crlf_cursor = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("\r\n");
226 return aws_byte_buf_write_from_whole_cursor(dst, crlf_cursor);
227 }
228
229 static void s_write_headers(struct aws_byte_buf *dst, const struct aws_http_headers *headers) {
230
231 const size_t num_headers = aws_http_headers_count(headers);
232
233 bool wrote_all = true;
234 for (size_t i = 0; i < num_headers; ++i) {
235 struct aws_http_header header;
236 aws_http_headers_get_index(headers, i, &header);
237
238 /* header-line: "{name}: {value}\r\n" */
239 wrote_all &= aws_byte_buf_write_from_whole_cursor(dst, header.name);
240 wrote_all &= aws_byte_buf_write_u8(dst, ':');
241 wrote_all &= aws_byte_buf_write_u8(dst, ' ');
242 wrote_all &= aws_byte_buf_write_from_whole_cursor(dst, header.value);
243 wrote_all &= s_write_crlf(dst);
244 }
245 AWS_ASSERT(wrote_all);
246 (void)wrote_all;
247 }
248
249 int aws_h1_encoder_message_init_from_request(
250 struct aws_h1_encoder_message *message,
251 struct aws_allocator *allocator,
252 const struct aws_http_message *request,
253 struct aws_linked_list *pending_chunk_list,
254 struct aws_linked_list *pending_data_write_list,
255 bool use_manual_data_writes) {
256
257 AWS_PRECONDITION(aws_linked_list_is_valid(pending_chunk_list));
258
259 AWS_ZERO_STRUCT(*message);
260
261 message->body = aws_input_stream_acquire(aws_http_message_get_body_stream(request));
262 message->pending_chunk_list = pending_chunk_list;
263 message->pending_data_write_list = pending_data_write_list;
264 message->has_manual_data_writes = use_manual_data_writes;
265
266 struct aws_byte_cursor method;
267 int err = aws_http_message_get_request_method(request, &method);
268 if (err) {
269 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Request method not set");
270 aws_raise_error(AWS_ERROR_HTTP_INVALID_METHOD);
271 goto error;
272 }
273 /* RFC-7230 3.1.1: method = token */
274 if (!aws_strutil_is_http_token(method)) {
275 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Request method is invalid");
276 aws_raise_error(AWS_ERROR_HTTP_INVALID_METHOD);
277 goto error;
278 }
279
280 struct aws_byte_cursor uri;
281 err = aws_http_message_get_request_path(request, &uri);
282 if (err) {
283 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Request path not set");
284 aws_raise_error(AWS_ERROR_HTTP_INVALID_PATH);
285 goto error;
286 }
287 if (!aws_strutil_is_http_request_target(uri)) {
288 AWS_LOGF_ERROR(AWS_LS_HTTP_STREAM, "id=static: Request path is invalid");
289 aws_raise_error(AWS_ERROR_HTTP_INVALID_PATH);
290 goto error;
291 }
292
293 /* For manual data writes, auto-add Transfer-Encoding: chunked if neither
294 * Content-Length nor Transfer-Encoding is set */
295 if (use_manual_data_writes) {
296 struct aws_http_headers *headers = aws_http_message_get_headers(request);
297 if (!aws_http_headers_has(headers, aws_byte_cursor_from_c_str("Content-Length")) &&
298 !aws_http_headers_has(headers, aws_byte_cursor_from_c_str("Transfer-Encoding"))) {
299 if (aws_http_headers_add(
300 headers, aws_byte_cursor_from_c_str("Transfer-Encoding"), aws_byte_cursor_from_c_str("chunked"))) {
301 goto error;
302 }
303 }
304 }
305
306 struct aws_byte_cursor version = aws_http_version_to_str(AWS_HTTP_VERSION_1_1);
307
308 /**
309 * Calculate total size needed for outgoing_head_buffer, then write to buffer.
310 */
311
312 size_t header_lines_len;
313 err = s_scan_outgoing_headers(
314 message,
315 request,
316 &header_lines_len,
317 false /*body_headers_ignored*/,
318 false /*body_headers_forbidden*/,
319 use_manual_data_writes);
320 if (err) {
321 goto error;
322 }
323
324 /* request-line: "{method} {uri} {version}\r\n" */
325 size_t request_line_len = 4; /* 2 spaces + "\r\n" */
326 err |= aws_add_size_checked(method.len, request_line_len, &request_line_len);
327 err |= aws_add_size_checked(uri.len, request_line_len, &request_line_len);
328 err |= aws_add_size_checked(version.len, request_line_len, &request_line_len);
329
330 /* head-end: "\r\n" */
331 size_t head_end_len = 2;
332
333 size_t head_total_len = request_line_len;
334 err |= aws_add_size_checked(header_lines_len, head_total_len, &head_total_len);
335 err |= aws_add_size_checked(head_end_len, head_total_len, &head_total_len);
336 if (err) {
337 goto error;
338 }
339
340 err = aws_byte_buf_init(&message->outgoing_head_buf, allocator, head_total_len);
341 if (err) {
342 goto error;
343 }
344
345 bool wrote_all = true;
346
347 wrote_all &= aws_byte_buf_write_from_whole_cursor(&message->outgoing_head_buf, method);
348 wrote_all &= aws_byte_buf_write_u8(&message->outgoing_head_buf, ' ');
349 wrote_all &= aws_byte_buf_write_from_whole_cursor(&message->outgoing_head_buf, uri);
350 wrote_all &= aws_byte_buf_write_u8(&message->outgoing_head_buf, ' ');
351 wrote_all &= aws_byte_buf_write_from_whole_cursor(&message->outgoing_head_buf, version);
352 wrote_all &= s_write_crlf(&message->outgoing_head_buf);
353
354 s_write_headers(&message->outgoing_head_buf, aws_http_message_get_const_headers(request));
355
356 wrote_all &= s_write_crlf(&message->outgoing_head_buf);
357 (void)wrote_all;
358 AWS_ASSERT(wrote_all);
359
360 return AWS_OP_SUCCESS;
361 error:
362 aws_h1_encoder_message_clean_up(message);
363 return AWS_OP_ERR;
364 }
365
366 int aws_h1_encoder_message_init_from_response(
367 struct aws_h1_encoder_message *message,
368 struct aws_allocator *allocator,
369 const struct aws_http_message *response,
370 bool body_headers_ignored,
371 struct aws_linked_list *pending_chunk_list) {
372
373 AWS_PRECONDITION(aws_linked_list_is_valid(pending_chunk_list));
374
375 AWS_ZERO_STRUCT(*message);
376
377 message->body = aws_input_stream_acquire(aws_http_message_get_body_stream(response));
378 message->pending_chunk_list = pending_chunk_list;
379
380 struct aws_byte_cursor version = aws_http_version_to_str(AWS_HTTP_VERSION_1_1);
381
382 int status_int;
383 int err = aws_http_message_get_response_status(response, &status_int);
384 if (err) {
385 return aws_raise_error(AWS_ERROR_HTTP_INVALID_STATUS_CODE);
386 }
387
388 /* Status code must fit in 3 digits */
389 AWS_ASSERT(status_int >= 0 && status_int <= 999); /* aws_http_message should have already checked this */
390 char status_code_str[4] = "XXX";
391 snprintf(status_code_str, sizeof(status_code_str), "%03d", status_int);
392 struct aws_byte_cursor status_code = aws_byte_cursor_from_c_str(status_code_str);
393
394 struct aws_byte_cursor status_text = aws_byte_cursor_from_c_str(aws_http_status_text(status_int));
395
396 /**
397 * Calculate total size needed for outgoing_head_buffer, then write to buffer.
398 */
399
400 size_t header_lines_len;
401 /**
402 * no body needed in the response
403 * RFC-7230 section 3.3 Message Body
404 */
405 body_headers_ignored |= status_int == AWS_HTTP_STATUS_CODE_304_NOT_MODIFIED;
406 bool body_headers_forbidden = status_int == AWS_HTTP_STATUS_CODE_204_NO_CONTENT || status_int / 100 == 1;
407 err = s_scan_outgoing_headers(
408 message,
409 response,
410 &header_lines_len,
411 body_headers_ignored,
412 body_headers_forbidden,
413 false /*use_manual_data_writes*/);
414 if (err) {
415 goto error;
416 }
417
418 /* valid status must be three digital code, change it into byte_cursor */
419 /* response-line: "{version} {status} {status_text}\r\n" */
420 size_t response_line_len = 4; /* 2 spaces + "\r\n" */
421 err |= aws_add_size_checked(version.len, response_line_len, &response_line_len);
422 err |= aws_add_size_checked(status_code.len, response_line_len, &response_line_len);
423 err |= aws_add_size_checked(status_text.len, response_line_len, &response_line_len);
424
425 /* head-end: "\r\n" */
426 size_t head_end_len = 2;
427 size_t head_total_len = response_line_len;
428 err |= aws_add_size_checked(header_lines_len, head_total_len, &head_total_len);
429 err |= aws_add_size_checked(head_end_len, head_total_len, &head_total_len);
430 if (err) {
431 goto error;
432 }
433
434 aws_byte_buf_init(&message->outgoing_head_buf, allocator, head_total_len);
435
436 bool wrote_all = true;
437
438 wrote_all &= aws_byte_buf_write_from_whole_cursor(&message->outgoing_head_buf, version);
439 wrote_all &= aws_byte_buf_write_u8(&message->outgoing_head_buf, ' ');
440 wrote_all &= aws_byte_buf_write_from_whole_cursor(&message->outgoing_head_buf, status_code);
441 wrote_all &= aws_byte_buf_write_u8(&message->outgoing_head_buf, ' ');
442 wrote_all &= aws_byte_buf_write_from_whole_cursor(&message->outgoing_head_buf, status_text);
443 wrote_all &= s_write_crlf(&message->outgoing_head_buf);
444
445 s_write_headers(&message->outgoing_head_buf, aws_http_message_get_const_headers(response));
446
447 wrote_all &= s_write_crlf(&message->outgoing_head_buf);
448 (void)wrote_all;
449 AWS_ASSERT(wrote_all);
450
451 /* Success! */
452 return AWS_OP_SUCCESS;
453
454 error:
455 aws_h1_encoder_message_clean_up(message);
456 return AWS_OP_ERR;
457 }
458
459 void aws_h1_encoder_message_clean_up(struct aws_h1_encoder_message *message) {
460 aws_input_stream_release(message->body);
461 aws_byte_buf_clean_up(&message->outgoing_head_buf);
462 aws_h1_trailer_destroy(message->trailer);
463 AWS_ZERO_STRUCT(*message);
464 }
465
466 void aws_h1_encoder_init(struct aws_h1_encoder *encoder, struct aws_allocator *allocator) {
467 AWS_ZERO_STRUCT(*encoder);
468 encoder->allocator = allocator;
469 }
470
471 void aws_h1_encoder_clean_up(struct aws_h1_encoder *encoder) {
472 AWS_ZERO_STRUCT(*encoder);
473 }
474
475 int aws_h1_encoder_start_message(
476 struct aws_h1_encoder *encoder,
477 struct aws_h1_encoder_message *message,
478 struct aws_http_stream *stream) {
479
480 AWS_PRECONDITION(encoder);
481 AWS_PRECONDITION(message);
482
483 if (encoder->message) {
484 ENCODER_LOG(ERROR, encoder, "Attempting to start new request while previous request is in progress.");
485 return aws_raise_error(AWS_ERROR_INVALID_STATE);
486 }
487
488 encoder->current_stream = stream;
489 encoder->message = message;
490
491 return AWS_OP_SUCCESS;
492 }
493
494 static bool s_write_chunk_size(struct aws_byte_buf *dst, uint64_t chunk_size) {
495 AWS_PRECONDITION(dst);
496 AWS_PRECONDITION(aws_byte_buf_is_valid(dst));
497 char ascii_hex_chunk_size_str[MAX_ASCII_HEX_CHUNK_STR_SIZE] = {0};
498 snprintf(ascii_hex_chunk_size_str, sizeof(ascii_hex_chunk_size_str), "%" PRIX64, chunk_size);
499 return aws_byte_buf_write_from_whole_cursor(dst, aws_byte_cursor_from_c_str(ascii_hex_chunk_size_str));
500 }
501
502 static bool s_write_chunk_extension(struct aws_byte_buf *dst, struct aws_http1_chunk_extension *chunk_extension) {
503 AWS_PRECONDITION(chunk_extension);
504 AWS_PRECONDITION(aws_byte_buf_is_valid(dst));
505 bool wrote_all = true;
506 wrote_all &= aws_byte_buf_write_u8(dst, ';');
507 wrote_all &= aws_byte_buf_write_from_whole_cursor(dst, chunk_extension->key);
508 wrote_all &= aws_byte_buf_write_u8(dst, '=');
509 wrote_all &= aws_byte_buf_write_from_whole_cursor(dst, chunk_extension->value);
510 return wrote_all;
511 }
512
513 static size_t s_calculate_chunk_line_size(const struct aws_http1_chunk_options *options) {
514 size_t chunk_line_size = MAX_ASCII_HEX_CHUNK_STR_SIZE + CRLF_SIZE;
515 for (size_t i = 0; i < options->num_extensions; ++i) {
516 struct aws_http1_chunk_extension *chunk_extension = options->extensions + i;
517 chunk_line_size += 1 /* ; */;
518 chunk_line_size += chunk_extension->key.len;
519 chunk_line_size += 1 /* = */;
520 chunk_line_size += chunk_extension->value.len;
521 }
522 return chunk_line_size;
523 }
524
525 static void s_populate_chunk_line_buffer(
526 struct aws_byte_buf *chunk_line,
527 const struct aws_http1_chunk_options *options) {
528
529 bool wrote_chunk_line = true;
530 wrote_chunk_line &= s_write_chunk_size(chunk_line, options->chunk_data_size);
531 for (size_t i = 0; i < options->num_extensions; ++i) {
532 wrote_chunk_line &= s_write_chunk_extension(chunk_line, options->extensions + i);
533 }
534 wrote_chunk_line &= s_write_crlf(chunk_line);
535 AWS_ASSERT(wrote_chunk_line);
536 (void)wrote_chunk_line;
537 }
538
539 struct aws_h1_trailer *aws_h1_trailer_new(
540 struct aws_allocator *allocator,
541 const struct aws_http_headers *trailing_headers) {
542 /* Allocate trailer along with storage for the trailer-line */
543 size_t trailer_size = 0;
544 if (s_scan_outgoing_trailer(trailing_headers, &trailer_size)) {
545 return NULL;
546 }
547
548 struct aws_h1_trailer *trailer = aws_mem_calloc(allocator, 1, sizeof(struct aws_h1_trailer));
549 trailer->allocator = allocator;
550
551 aws_byte_buf_init(&trailer->trailer_data, allocator, trailer_size); /* cannot fail */
552 s_write_headers(&trailer->trailer_data, trailing_headers);
553 s_write_crlf(&trailer->trailer_data); /* \r\n */
554 return trailer;
555 }
556
557 void aws_h1_trailer_destroy(struct aws_h1_trailer *trailer) {
558 if (trailer == NULL) {
559 return;
560 }
561 aws_byte_buf_clean_up(&trailer->trailer_data);
562 aws_mem_release(trailer->allocator, trailer);
563 }
564
565 struct aws_h1_chunk *aws_h1_chunk_new(struct aws_allocator *allocator, const struct aws_http1_chunk_options *options) {
566 /* Allocate chunk along with storage for the chunk-line */
567 struct aws_h1_chunk *chunk;
568 size_t chunk_line_size = s_calculate_chunk_line_size(options);
569 void *chunk_line_storage;
570 if (!aws_mem_acquire_many(
571 allocator, 2, &chunk, sizeof(struct aws_h1_chunk), &chunk_line_storage, chunk_line_size)) {
572 return NULL;
573 }
574
575 chunk->allocator = allocator;
576 chunk->data = aws_input_stream_acquire(options->chunk_data);
577 chunk->data_size = options->chunk_data_size;
578 chunk->on_complete = options->on_complete;
579 chunk->user_data = options->user_data;
580 chunk->chunk_line = aws_byte_buf_from_empty_array(chunk_line_storage, chunk_line_size);
581 s_populate_chunk_line_buffer(&chunk->chunk_line, options);
582 return chunk;
583 }
584
585 void aws_h1_chunk_destroy(struct aws_h1_chunk *chunk) {
586 AWS_PRECONDITION(chunk);
587 aws_input_stream_release(chunk->data);
588 aws_mem_release(chunk->allocator, chunk);
589 }
590
591 void aws_h1_chunk_complete_and_destroy(
592 struct aws_h1_chunk *chunk,
593 struct aws_http_stream *http_stream,
594 int error_code) {
595
596 AWS_PRECONDITION(chunk);
597
598 aws_http1_stream_write_chunk_complete_fn *on_complete = chunk->on_complete;
599 void *user_data = chunk->user_data;
600
601 /* Clean up before firing callback */
602 aws_h1_chunk_destroy(chunk);
603
604 if (NULL != on_complete) {
605 on_complete(http_stream, error_code, user_data);
606 }
607 }
608
609 static void s_clean_up_current_chunk(struct aws_h1_encoder *encoder, int error_code) {
610 AWS_PRECONDITION(encoder->current_chunk);
611 AWS_PRECONDITION(&encoder->current_chunk->node == aws_linked_list_front(encoder->message->pending_chunk_list));
612
613 aws_linked_list_remove(&encoder->current_chunk->node);
614 aws_h1_chunk_complete_and_destroy(encoder->current_chunk, encoder->current_stream, error_code);
615 encoder->current_chunk = NULL;
616 }
617
618 /* Write as much as possible from src_buf to dst, using encoder->progress_len to track progress.
619 * Returns true if the entire src_buf has been copied */
620 static bool s_encode_buf(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst, const struct aws_byte_buf *src) {
621
622 /* advance src_cursor to current position in src_buf */
623 struct aws_byte_cursor src_cursor = aws_byte_cursor_from_buf(src);
624 aws_byte_cursor_advance(&src_cursor, (size_t)encoder->progress_bytes);
625
626 /* write as much as possible to dst, src_cursor is advanced as write occurs */
627 struct aws_byte_cursor written = aws_byte_buf_write_to_capacity(dst, &src_cursor);
628 encoder->progress_bytes += written.len;
629
630 return src_cursor.len == 0;
631 }
632
633 /* Write as much body stream as possible into dst buffer.
634 * Increments encoder->progress_bytes to track progress */
635 static int s_encode_stream(
636 struct aws_h1_encoder *encoder,
637 struct aws_byte_buf *dst,
638 struct aws_input_stream *stream,
639 uint64_t total_length,
640 bool *out_done) {
641
642 *out_done = false;
643
644 if (dst->capacity == dst->len) {
645 /* Return success because we want to try again later */
646 return AWS_OP_SUCCESS;
647 }
648
649 /* Read from stream */
650 ENCODER_LOG(TRACE, encoder, "Reading from body stream.");
651 const size_t prev_len = dst->len;
652 int err = aws_input_stream_read(stream, dst);
653 const size_t amount_read = dst->len - prev_len;
654
655 if (err) {
656 ENCODER_LOGF(
657 ERROR,
658 encoder,
659 "Failed to read body stream, error %d (%s)",
660 aws_last_error(),
661 aws_error_name(aws_last_error()));
662
663 return AWS_OP_ERR;
664 }
665
666 /* Increment progress_bytes, and make sure we haven't written too much */
667 int add_err = aws_add_u64_checked(encoder->progress_bytes, amount_read, &encoder->progress_bytes);
668 if (add_err || encoder->progress_bytes > total_length) {
669 ENCODER_LOGF(ERROR, encoder, "Body stream has exceeded expected length: %" PRIu64, total_length);
670 return aws_raise_error(AWS_ERROR_HTTP_OUTGOING_STREAM_LENGTH_INCORRECT);
671 }
672
673 ENCODER_LOGF(
674 TRACE,
675 encoder,
676 "Sending %zu bytes of body, progress: %" PRIu64 "/%" PRIu64,
677 amount_read,
678 encoder->progress_bytes,
679 total_length);
680
681 /* Return if we're done sending stream */
682 if (encoder->progress_bytes == total_length) {
683 *out_done = true;
684 return AWS_OP_SUCCESS;
685 }
686
687 /* Return if stream failed to write anything. Maybe the data isn't ready yet. */
688 if (amount_read == 0) {
689 /* Ensure we're not at end-of-stream too early */
690 struct aws_stream_status status;
691 err = aws_input_stream_get_status(stream, &status);
692 if (err) {
693 ENCODER_LOGF(
694 ERROR,
695 encoder,
696 "Failed to query body stream status, error %d (%s)",
697 aws_last_error(),
698 aws_error_name(aws_last_error()));
699
700 return AWS_OP_ERR;
701 }
702 if (status.is_end_of_stream) {
703 ENCODER_LOGF(
704 ERROR,
705 encoder,
706 "Reached end of body stream but sent less than declared length %" PRIu64 "/%" PRIu64,
707 encoder->progress_bytes,
708 total_length);
709 return aws_raise_error(AWS_ERROR_HTTP_OUTGOING_STREAM_LENGTH_INCORRECT);
710 }
711 }
712
713 /* Not done streaming data out yet */
714 return AWS_OP_SUCCESS;
715 }
716
717 /* A state function should:
718 * - Raise an error only if unrecoverable error occurs.
719 * - `return s_switch_state(...)` to switch states.
720 * - `return AWS_OP_SUCCESS` if it can't progress any further (waiting for more
721 * space to write into, waiting for more chunks, etc). */
722 typedef int encoder_state_fn(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst);
723
724 /* Switch state.
725 * The only reason this returns a value is so it can be called with `return` to conclude a state function */
726 static int s_switch_state(struct aws_h1_encoder *encoder, enum aws_h1_encoder_state state) {
727 /* Don't reset progress_bytes when transitioning between DATA_WRITE states,
728 * as we need to track cumulative progress across multiple writes */
729 bool preserve_progress =
730 (encoder->state == AWS_H1_ENCODER_STATE_DATA_WRITE_NEXT ||
731 encoder->state == AWS_H1_ENCODER_STATE_DATA_WRITE_BODY) &&
732 (state == AWS_H1_ENCODER_STATE_DATA_WRITE_NEXT || state == AWS_H1_ENCODER_STATE_DATA_WRITE_BODY);
733
734 encoder->state = state;
735 if (!preserve_progress) {
736 encoder->progress_bytes = 0;
737 }
738 return AWS_OP_SUCCESS;
739 }
740
741 /* Initial state. Waits until a new message is set */
742 static int s_state_fn_init(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
743 (void)dst;
744
745 if (!encoder->message) {
746 /* Remain in this state. */
747 return AWS_OP_SUCCESS;
748 }
749
750 /* Start encoding message */
751 ENCODER_LOG(TRACE, encoder, "Starting to send data.");
752 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_HEAD);
753 }
754
755 /* Write out first line of request/response, plus all the headers.
756 * These have been pre-encoded in aws_h1_encoder_message->outgoing_head_buf. */
757 static int s_state_fn_head(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
758 bool done = s_encode_buf(encoder, dst, &encoder->message->outgoing_head_buf);
759 if (!done) {
760 /* Remain in this state */
761 return AWS_OP_SUCCESS;
762 }
763
764 /* Don't NEED to free this buffer now, but we don't need it anymore, so why not */
765 aws_byte_buf_clean_up(&encoder->message->outgoing_head_buf);
766
767 /* Pick next state */
768 if (encoder->message->has_manual_data_writes && encoder->message->has_chunked_encoding_header) {
769 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_NEXT);
770
771 } else if (encoder->message->has_manual_data_writes) {
772 /* if chunked encoding header is not present we automatically assume the content-length header was provided
773 * because content length provided can also be zero. */
774 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_DATA_WRITE_NEXT);
775
776 } else if (encoder->message->body && encoder->message->content_length) {
777 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_UNCHUNKED_BODY_STREAM);
778
779 } else if (encoder->message->body && encoder->message->has_chunked_encoding_header) {
780 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNKED_BODY_STREAM);
781
782 } else if (encoder->message->has_chunked_encoding_header) {
783 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_NEXT);
784 } else {
785 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_DONE);
786 }
787 }
788
789 /* Write out body with known Content-Length (not using chunked encoding). */
790 static int s_state_fn_unchunked_body_stream(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
791 bool done;
792 if (s_encode_stream(encoder, dst, encoder->message->body, encoder->message->content_length, &done)) {
793 return AWS_OP_ERR;
794 }
795
796 if (!done) {
797 /* Remain in this state until we're done writing out body */
798 return AWS_OP_SUCCESS;
799 }
800
801 /* Message is done */
802 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_DONE);
803 }
804
805 /* Write out body (of unknown Content-Length) using chunked encoding.
806 * Each pass through this state writes out 1 chunk of body data (or nothing at all). */
807 static int s_state_fn_chunked_body_stream(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
808
809 /* Each chunk is prefixed with: CHUNK-LENGTH-IN-ASCII-HEX CRLF
810 * and suffixed with: CRLF
811 *
812 * When reading from the stream, we don't know how much data we'll get,
813 * but the length needs to go in the prefix, before the data!
814 * Therefore, leave space at start of dst buffer for the prefix,
815 * we'll go back and write it AFTER streaming the body data.
816 * Leave space at the end for the suffix too.
817 *
818 * Use a predictable length for the prefix.
819 * 8 hex chars (i.e. "000000F7") seems reasonable (4 is too small, 16 is ridiculous, dynamic is complicated). */
820 enum { padded_hex_len = 8 }; /* enum, because it's used as size for stack array */
821 const char *padded_hex_fmt = "%08zX";
822 const size_t max_hex_value_given_padding = UINT32_MAX; /* fits in 8 chars */
823 const size_t chunk_prefix_len = padded_hex_len + CRLF_SIZE;
824 const size_t chunk_suffix_len = CRLF_SIZE;
825
826 /* If dst buffer nearly full, don't bother reading from stream.
827 * Remain in this state and we'll get a fresh buffer next tick. */
828 const size_t dont_bother_if_space_less_than = 128; /* magic number, seems reasonable */
829 AWS_ASSERT(dont_bother_if_space_less_than > chunk_prefix_len + chunk_suffix_len);
830 if (dst->capacity - dst->len < dont_bother_if_space_less_than) {
831 /* If this buffer is empty, and still not big enough, just give up.
832 * Probably never happens, but g_aws_channel_max_fragment_size can theoretically be tweaked by user. */
833 if (dst->len == 0) {
834 AWS_LOGF_ERROR(
835 AWS_LS_HTTP_STREAM, "id=%p Channel max fragment size is too small.", (void *)encoder->current_stream);
836 return aws_raise_error(AWS_ERROR_INVALID_STATE);
837 }
838
839 /* Remain in this state and we'll get a fresh buffer next tick */
840 return AWS_OP_SUCCESS;
841 }
842
843 /* Use a sub-buffer to limit where body can go.
844 * Body will go after chunk-prefix, and needs to leave enough space for chunk-suffix afterwards. */
845 uint8_t *body_sub_buf_start = dst->buffer + dst->len + chunk_prefix_len;
846 uint8_t *body_sub_buf_end = dst->buffer + dst->capacity - chunk_suffix_len;
847 struct aws_byte_buf body_sub_buf =
848 aws_byte_buf_from_empty_array(body_sub_buf_start, body_sub_buf_end - body_sub_buf_start);
849 /* We set aside a fixed number of bytes to encode the length, don't read more than that */
850 body_sub_buf.capacity = aws_min_size(body_sub_buf.capacity, max_hex_value_given_padding);
851
852 /* Stream body into sub-buffer */
853 ENCODER_LOG(TRACE, encoder, "Reading from body stream.");
854 if (aws_input_stream_read(encoder->message->body, &body_sub_buf) != AWS_OP_SUCCESS) {
855 ENCODER_LOGF(
856 ERROR,
857 encoder,
858 "Failed to read body stream, error %d (%s)",
859 aws_last_error(),
860 aws_error_name(aws_last_error()));
861 return AWS_OP_ERR;
862 }
863
864 /* If ANY body data was streamed, then write in chunk prefix and suffix.
865 *
866 * (else no body data streamed, so dst remains untouched. Maybe we've
867 * reached end of stream, maybe user just doesn't have data yet to send) */
868 if (body_sub_buf.len > 0) {
869 encoder->chunk_count++;
870 ENCODER_LOGF(
871 TRACE, encoder, "Sending chunk #%" PRIu64 " with size %zu", encoder->chunk_count, body_sub_buf.len);
872 bool wrote_all = true;
873
874 /* Write chunk-prefix: LENGTH-IN-HEX CRLF */
875 char hexbuf[padded_hex_len + 1] = {0};
876 AWS_ASSERT(body_sub_buf.len <= max_hex_value_given_padding); /* guaranteed, b/c we clamped .capacity earlier */
877 snprintf(hexbuf, sizeof(hexbuf), padded_hex_fmt, body_sub_buf.len);
878
879 wrote_all &= aws_byte_buf_write_from_whole_cursor(dst, aws_byte_cursor_from_c_str(hexbuf));
880 wrote_all &= s_write_crlf(dst);
881
882 /* Increment dst->len, since we already copied body in there via sub-buffer */
883 AWS_ASSERT(dst->buffer + dst->len == body_sub_buf_start); /* written chunk-prefix should end at body start */
884 dst->len += body_sub_buf.len; /* safe b/c we clamped body_sub_buf.capacity earlier */
885
886 /* Write chunk-suffix: CRLF */
887 wrote_all &= s_write_crlf(dst);
888
889 AWS_ASSERT(wrote_all); /* everything should have fit, we did a lot of math and clamping to guarantee it */
890 (void)wrote_all;
891 }
892
893 /* If body stream has ended: switch states.
894 * As an optimization, we only do this check when the stream didn't 100% fill the buffer */
895 if (body_sub_buf.len < body_sub_buf.capacity) {
896 struct aws_stream_status stream_status;
897 if (aws_input_stream_get_status(encoder->message->body, &stream_status) != AWS_OP_SUCCESS) {
898 ENCODER_LOGF(
899 ERROR,
900 encoder,
901 "Failed to query body stream status, error %d (%s)",
902 aws_last_error(),
903 aws_error_name(aws_last_error()));
904 return AWS_OP_ERR;
905 }
906
907 if (stream_status.is_end_of_stream) {
908 encoder->chunk_count++;
909 ENCODER_LOGF(TRACE, encoder, "Sending last chunk #%" PRIu64, encoder->chunk_count);
910 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNKED_BODY_STREAM_LAST_CHUNK);
911 }
912 }
913
914 /* Remain in state until done streaming body */
915 return AWS_OP_SUCCESS;
916 }
917
918 /* Note: this state is ONLY used when streaming a body of unknown Content-Length.
919 * It is NOT used when the write_chunk() API is being used. */
920 static int s_state_fn_chunked_body_stream_last_chunk(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
921
922 struct aws_byte_cursor last_chunk = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("0\r\n");
923 if (aws_byte_buf_write_from_whole_cursor(dst, last_chunk) == true) {
924 ENCODER_LOG(TRACE, encoder, "Last chunk complete");
925 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_TRAILER);
926 } else {
927 /* Remain in state until there's enough space to write */
928 return AWS_OP_SUCCESS;
929 }
930 }
931
932 /* Select next chunk to work on.
933 * Encoder is essentially "paused" here if no chunks are available. */
934 static int s_state_fn_chunk_next(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
935 (void)dst;
936
937 if (aws_linked_list_empty(encoder->message->pending_chunk_list)) {
938 /* Remain in this state until more chunks arrive */
939 ENCODER_LOG(TRACE, encoder, "No chunks ready to send, waiting for more...");
940 return AWS_OP_SUCCESS;
941 }
942
943 /* Set next chunk and go to next state */
944 struct aws_linked_list_node *node = aws_linked_list_front(encoder->message->pending_chunk_list);
945 encoder->current_chunk = AWS_CONTAINER_OF(node, struct aws_h1_chunk, node);
946 encoder->chunk_count++;
947 ENCODER_LOGF(
948 TRACE,
949 encoder,
950 "Begin sending chunk #%" PRIu64 " with size %" PRIu64,
951 encoder->chunk_count,
952 encoder->current_chunk->data_size);
953
954 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_LINE);
955 }
956
957 /* Write out "chunk-size [chunk-ext] CRLF".
958 * This data is pre-encoded in the chunk's chunk_line buffer */
959 static int s_state_fn_chunk_line(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
960 bool done = s_encode_buf(encoder, dst, &encoder->current_chunk->chunk_line);
961 if (!done) {
962 /* Remain in state until done writing line */
963 return AWS_OP_SUCCESS;
964 }
965
966 /* Pick next state */
967 if (encoder->current_chunk->data_size == 0) {
968 /* If data_size is 0, then this was the last chunk, which has no body.
969 * Mark it complete and move on to trailer. */
970 ENCODER_LOG(TRACE, encoder, "Final chunk complete");
971 s_clean_up_current_chunk(encoder, AWS_ERROR_SUCCESS);
972
973 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_TRAILER);
974 }
975
976 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_BODY);
977 }
978
979 /* Write out data for current chunk */
980 static int s_state_fn_chunk_body(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
981 bool done;
982 if (s_encode_stream(encoder, dst, encoder->current_chunk->data, encoder->current_chunk->data_size, &done)) {
983 int error_code = aws_last_error();
984
985 /* The error was caused by the chunk itself, report that specific error in its completion callback */
986 s_clean_up_current_chunk(encoder, error_code);
987
988 /* Re-raise error, in case it got cleared during user callback */
989 return aws_raise_error(error_code);
990 }
991 if (!done) {
992 /* Remain in this state until we're done writing out body */
993 return AWS_OP_SUCCESS;
994 }
995
996 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_END);
997 }
998
999 /* Write CRLF and mark chunk as complete */
1000 static int s_state_fn_chunk_end(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
1001 bool done = s_write_crlf(dst);
1002 if (!done) {
1003 /* Remain in this state until done writing out CRLF */
1004 return AWS_OP_SUCCESS;
1005 }
1006
1007 ENCODER_LOG(TRACE, encoder, "Chunk complete");
1008 s_clean_up_current_chunk(encoder, AWS_ERROR_SUCCESS);
1009
1010 /* Pick next chunk to work on */
1011 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_CHUNK_NEXT);
1012 }
1013
1014 /* Write out trailer after last chunk */
1015 static int s_state_fn_chunk_trailer(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
1016 bool done;
1017 /* if a chunked trailer was set */
1018 if (encoder->message->trailer) {
1019 done = s_encode_buf(encoder, dst, &encoder->message->trailer->trailer_data);
1020 } else {
1021 done = s_write_crlf(dst);
1022 }
1023 if (!done) {
1024 /* Remain in this state until we're done writing out trailer */
1025 return AWS_OP_SUCCESS;
1026 }
1027
1028 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_DONE);
1029 }
1030
1031 /* Select next data write to work on for manual data writes with Content-Length.
1032 * Encoder is essentially "paused" here if no data writes are available. */
1033 static int s_encoder_state_data_write_next(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
1034 (void)dst;
1035
1036 if (aws_linked_list_empty(encoder->message->pending_data_write_list)) {
1037 ENCODER_LOG(TRACE, encoder, "No data writes ready, waiting...");
1038 return AWS_OP_SUCCESS;
1039 }
1040
1041 struct aws_linked_list_node *node = aws_linked_list_front(encoder->message->pending_data_write_list);
1042 encoder->message->current_data_write = AWS_CONTAINER_OF(node, struct aws_h1_data_write, node);
1043
1044 ENCODER_LOG(TRACE, encoder, "Begin sending manual data write");
1045 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_DATA_WRITE_BODY);
1046 }
1047
1048 /* Write out data from current manual data write */
1049 static int s_encoder_state_data_write_body(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
1050 struct aws_h1_data_write *data_write = encoder->message->current_data_write;
1051
1052 if (dst->capacity == dst->len) {
1053 return AWS_OP_SUCCESS;
1054 }
1055
1056 /* Read from stream */
1057 ENCODER_LOG(TRACE, encoder, "Reading from manual data write stream");
1058 const size_t prev_len = dst->len;
1059 size_t amount_read = dst->len - prev_len;
1060 int error_code = AWS_OP_ERR;
1061
1062 if (data_write->data) {
1063 int err = aws_input_stream_read(data_write->data, dst);
1064 amount_read = dst->len - prev_len;
1065
1066 if (err) {
1067 ENCODER_LOGF(
1068 ERROR,
1069 encoder,
1070 "Failed to read data write stream, error %d (%s)",
1071 aws_last_error(),
1072 aws_error_name(aws_last_error()));
1073 error_code = aws_last_error();
1074 goto error;
1075 }
1076 }
1077
1078 /* Increment progress_bytes and check we haven't exceeded Content-Length */
1079 if (aws_add_u64_checked(encoder->progress_bytes, amount_read, &encoder->progress_bytes) ||
1080 encoder->progress_bytes > encoder->message->content_length) {
1081 ENCODER_LOGF(
1082 ERROR, encoder, "Manual data writes exceeded Content-Length: %" PRIu64, encoder->message->content_length);
1083 error_code = AWS_ERROR_HTTP_OUTGOING_STREAM_LENGTH_INCORRECT;
1084 goto error;
1085 }
1086
1087 ENCODER_LOGF(
1088 TRACE,
1089 encoder,
1090 "Sent %zu bytes from manual data write, total progress: %" PRIu64 "/%" PRIu64,
1091 amount_read,
1092 encoder->progress_bytes,
1093 encoder->message->content_length);
1094
1095 if (data_write->data) {
1096 /* If we read something or reached end of stream, check if stream is complete */
1097 struct aws_stream_status status;
1098 int err = aws_input_stream_get_status(data_write->data, &status);
1099 if (err) {
1100 ENCODER_LOGF(
1101 ERROR,
1102 encoder,
1103 "Failed to query data write stream status, error %d (%s)",
1104 aws_last_error(),
1105 aws_error_name(aws_last_error()));
1106 error_code = aws_last_error();
1107 goto error;
1108 }
1109
1110 if (!status.is_end_of_stream) {
1111 /* Stream not done yet, remain in state */
1112 return AWS_OP_SUCCESS;
1113 }
1114 }
1115
1116 /* This data write is complete */
1117 ENCODER_LOG(TRACE, encoder, "Manual data write complete");
1118 bool is_end = data_write->is_end_stream;
1119 aws_linked_list_remove(&data_write->node);
1120 aws_h1_data_write_complete_and_destroy(data_write, encoder->current_stream, AWS_ERROR_SUCCESS);
1121 encoder->message->current_data_write = NULL;
1122
1123 if (is_end) {
1124 /* This was the final write, validate total matches Content-Length */
1125 if (encoder->progress_bytes != encoder->message->content_length) {
1126 ENCODER_LOGF(
1127 ERROR,
1128 encoder,
1129 "Manual data writes sent %" PRIu64 " bytes but Content-Length is %" PRIu64,
1130 encoder->progress_bytes,
1131 encoder->message->content_length);
1132 error_code = AWS_ERROR_HTTP_OUTGOING_STREAM_LENGTH_INCORRECT;
1133 return aws_raise_error(error_code);
1134 }
1135 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_DONE);
1136 }
1137
1138 /* More writes expected, go back to waiting for next write */
1139 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_DATA_WRITE_NEXT);
1140
1141 error:
1142 aws_linked_list_remove(&data_write->node);
1143 aws_h1_data_write_complete_and_destroy(data_write, encoder->current_stream, error_code);
1144 encoder->message->current_data_write = NULL;
1145 return aws_raise_error(error_code);
1146 }
1147
1148 /* Message is done, loop back to start of state machine */
1149 static int s_state_fn_done(struct aws_h1_encoder *encoder, struct aws_byte_buf *dst) {
1150 (void)dst;
1151
1152 ENCODER_LOG(TRACE, encoder, "Done sending data.");
1153 encoder->message = NULL;
1154 return s_switch_state(encoder, AWS_H1_ENCODER_STATE_INIT);
1155 }
1156
1157 struct encoder_state_def {
1158 encoder_state_fn *fn;
1159 const char *name;
1160 };
1161
1162 static struct encoder_state_def s_encoder_states[] = {
1163 [AWS_H1_ENCODER_STATE_INIT] = {.fn = s_state_fn_init, .name = "INIT"},
1164 [AWS_H1_ENCODER_STATE_HEAD] = {.fn = s_state_fn_head, .name = "HEAD"},
1165 [AWS_H1_ENCODER_STATE_UNCHUNKED_BODY_STREAM] = {.fn = s_state_fn_unchunked_body_stream, .name = "BODY"},
1166 [AWS_H1_ENCODER_STATE_CHUNKED_BODY_STREAM] = {.fn = s_state_fn_chunked_body_stream, .name = "CHUNKED_BODY_STREAM"},
1167 [AWS_H1_ENCODER_STATE_CHUNKED_BODY_STREAM_LAST_CHUNK] =
1168 {.fn = s_state_fn_chunked_body_stream_last_chunk, .name = "LAST_CHUNK"},
1169 [AWS_H1_ENCODER_STATE_CHUNK_NEXT] = {.fn = s_state_fn_chunk_next, .name = "CHUNK_NEXT"},
1170 [AWS_H1_ENCODER_STATE_CHUNK_LINE] = {.fn = s_state_fn_chunk_line, .name = "CHUNK_LINE"},
1171 [AWS_H1_ENCODER_STATE_CHUNK_BODY] = {.fn = s_state_fn_chunk_body, .name = "CHUNK_BODY"},
1172 [AWS_H1_ENCODER_STATE_CHUNK_END] = {.fn = s_state_fn_chunk_end, .name = "CHUNK_END"},
1173 [AWS_H1_ENCODER_STATE_CHUNK_TRAILER] = {.fn = s_state_fn_chunk_trailer, .name = "CHUNK_TRAILER"},
1174 [AWS_H1_ENCODER_STATE_DATA_WRITE_NEXT] = {.fn = s_encoder_state_data_write_next, .name = "DATA_WRITE_NEXT"},
1175 [AWS_H1_ENCODER_STATE_DATA_WRITE_BODY] = {.fn = s_encoder_state_data_write_body, .name = "DATA_WRITE_BODY"},
1176 [AWS_H1_ENCODER_STATE_DONE] = {.fn = s_state_fn_done, .name = "DONE"},
1177 };
1178
1179 int aws_h1_encoder_process(struct aws_h1_encoder *encoder, struct aws_byte_buf *out_buf) {
1180 AWS_PRECONDITION(encoder);
1181 AWS_PRECONDITION(out_buf);
1182
1183 if (!encoder->message) {
1184 ENCODER_LOG(ERROR, encoder, "No message is currently set for encoding.");
1185 return aws_raise_error(AWS_ERROR_INVALID_STATE);
1186 }
1187
1188 /* Run state machine until states stop changing. (due to out_buf running
1189 * out of space, input_stream stalling, waiting for more chunks, etc) */
1190 enum aws_h1_encoder_state prev_state;
1191 do {
1192 prev_state = encoder->state;
1193 if (s_encoder_states[encoder->state].fn(encoder, out_buf)) {
1194 return AWS_OP_ERR;
1195 }
1196 } while (prev_state != encoder->state);
1197
1198 return AWS_OP_SUCCESS;
1199 }
1200
1201 bool aws_h1_encoder_is_message_in_progress(const struct aws_h1_encoder *encoder) {
1202 return encoder->message;
1203 }
1204
1205 bool aws_h1_encoder_is_waiting_for_chunks(const struct aws_h1_encoder *encoder) {
1206 return encoder->state == AWS_H1_ENCODER_STATE_CHUNK_NEXT &&
1207 aws_linked_list_empty(encoder->message->pending_chunk_list);
1208 }
1209
1210 bool aws_h1_encoder_is_waiting_for_data_writes(const struct aws_h1_encoder *encoder) {
1211 return encoder->state == AWS_H1_ENCODER_STATE_DATA_WRITE_NEXT &&
1212 aws_linked_list_empty(encoder->message->pending_data_write_list);
1213 }