Debian Codegraph @

crt/aws-c-http/source/h1_connection.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/common/clock.h>
6 #include <aws/common/math.h>
7 #include <aws/common/mutex.h>
8 #include <aws/common/string.h>
9 #include <aws/http/private/h1_connection.h>
10 #include <aws/http/private/h1_decoder.h>
11 #include <aws/http/private/h1_stream.h>
12 #include <aws/http/private/request_response_impl.h>
13 #include <aws/http/status_code.h>
14 #include <aws/io/event_loop.h>
15 #include <aws/io/logging.h>
16
17 #include <inttypes.h>
18
19 #ifdef _MSC_VER
20 # pragma warning(disable : 4204) /* non-constant aggregate initializer */
21 #endif
22
23 enum {
24 DECODER_INITIAL_SCRATCH_SIZE = 256,
25 };
26
27 static int s_handler_process_read_message(
28 struct aws_channel_handler *handler,
29 struct aws_channel_slot *slot,
30 struct aws_io_message *message);
31
32 static int s_handler_process_write_message(
33 struct aws_channel_handler *handler,
34 struct aws_channel_slot *slot,
35 struct aws_io_message *message);
36
37 static int s_handler_increment_read_window(
38 struct aws_channel_handler *handler,
39 struct aws_channel_slot *slot,
40 size_t size);
41
42 static int s_handler_shutdown(
43 struct aws_channel_handler *handler,
44 struct aws_channel_slot *slot,
45 enum aws_channel_direction dir,
46 int error_code,
47 bool free_scarce_resources_immediately);
48
49 static size_t s_handler_initial_window_size(struct aws_channel_handler *handler);
50 static size_t s_handler_message_overhead(struct aws_channel_handler *handler);
51 static void s_handler_destroy(struct aws_channel_handler *handler);
52 static void s_handler_installed(struct aws_channel_handler *handler, struct aws_channel_slot *slot);
53 static struct aws_http_stream *s_make_request(
54 struct aws_http_connection *client_connection,
55 const struct aws_http_make_request_options *options);
56 static struct aws_http_stream *s_new_server_request_handler_stream(
57 const struct aws_http_request_handler_options *options);
58 static int s_stream_send_response(struct aws_http_stream *stream, struct aws_http_message *response);
59 static void s_connection_close(struct aws_http_connection *connection_base);
60 static void s_connection_stop_new_request(struct aws_http_connection *connection_base);
61 static bool s_connection_is_open(const struct aws_http_connection *connection_base);
62 static bool s_connection_new_requests_allowed(const struct aws_http_connection *connection_base);
63 static int s_decoder_on_request(
64 enum aws_http_method method_enum,
65 const struct aws_byte_cursor *method_str,
66 const struct aws_byte_cursor *uri,
67 void *user_data);
68 static int s_decoder_on_response(int status_code, void *user_data);
69 static int s_decoder_on_header(const struct aws_h1_decoded_header *header, void *user_data);
70 static int s_decoder_on_body(const struct aws_byte_cursor *data, bool finished, void *user_data);
71 static int s_decoder_on_done(void *user_data);
72 static void s_reset_statistics(struct aws_channel_handler *handler);
73 static void s_gather_statistics(struct aws_channel_handler *handler, struct aws_array_list *stats);
74 static void s_write_outgoing_stream(struct aws_h1_connection *connection, bool first_try);
75 static int s_try_process_next_stream_read_message(struct aws_h1_connection *connection, bool *out_stop_processing);
76
77 static struct aws_http_connection_vtable s_h1_connection_vtable = {
78 .channel_handler_vtable =
79 {
80 .process_read_message = s_handler_process_read_message,
81 .process_write_message = s_handler_process_write_message,
82 .increment_read_window = s_handler_increment_read_window,
83 .shutdown = s_handler_shutdown,
84 .initial_window_size = s_handler_initial_window_size,
85 .message_overhead = s_handler_message_overhead,
86 .destroy = s_handler_destroy,
87 .reset_statistics = s_reset_statistics,
88 .gather_statistics = s_gather_statistics,
89 },
90 .on_channel_handler_installed = s_handler_installed,
91 .make_request = s_make_request,
92 .new_server_request_handler_stream = s_new_server_request_handler_stream,
93 .stream_send_response = s_stream_send_response,
94 .close = s_connection_close,
95 .stop_new_requests = s_connection_stop_new_request,
96 .is_open = s_connection_is_open,
97 .new_requests_allowed = s_connection_new_requests_allowed,
98 .change_settings = NULL,
99 .send_ping = NULL,
100 .send_goaway = NULL,
101 .get_sent_goaway = NULL,
102 .get_received_goaway = NULL,
103 .get_local_settings = NULL,
104 .get_remote_settings = NULL,
105 };
106
107 static const struct aws_h1_decoder_vtable s_h1_decoder_vtable = {
108 .on_request = s_decoder_on_request,
109 .on_response = s_decoder_on_response,
110 .on_header = s_decoder_on_header,
111 .on_body = s_decoder_on_body,
112 .on_done = s_decoder_on_done,
113 };
114
115 void aws_h1_connection_lock_synced_data(struct aws_h1_connection *connection) {
116 int err = aws_mutex_lock(&connection->synced_data.lock);
117 AWS_ASSERT(!err);
118 (void)err;
119 }
120
121 void aws_h1_connection_unlock_synced_data(struct aws_h1_connection *connection) {
122 int err = aws_mutex_unlock(&connection->synced_data.lock);
123 AWS_ASSERT(!err);
124 (void)err;
125 }
126
127 /**
128 * Internal function for bringing connection to a stop.
129 * Invoked multiple times, including when:
130 * - Channel is shutting down in the read direction.
131 * - Channel is shutting down in the write direction.
132 * - An error occurs.
133 */
134 static void s_stop(
135 struct aws_h1_connection *connection,
136 bool stop_reading,
137 bool stop_writing,
138 bool schedule_shutdown,
139 int error_code) {
140
141 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
142 AWS_ASSERT(stop_reading || stop_writing || schedule_shutdown); /* You are required to stop at least 1 thing */
143
144 if (stop_reading) {
145 if (connection->thread_data.read_state == AWS_CONNECTION_READ_OPEN) {
146 connection->thread_data.read_state = AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE;
147 } else if (connection->thread_data.read_state == AWS_CONNECTION_READ_SHUTTING_DOWN) {
148 /* Shutdown after pending */
149 if (connection->thread_data.pending_shutdown_error_code != 0) {
150 error_code = connection->thread_data.pending_shutdown_error_code;
151 }
152 connection->thread_data.read_state = AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE;
153 aws_channel_slot_on_handler_shutdown_complete(
154 connection->base.channel_slot, AWS_CHANNEL_DIR_READ, error_code, false);
155 }
156 }
157
158 if (stop_writing) {
159 connection->thread_data.is_writing_stopped = true;
160 }
161 { /* BEGIN CRITICAL SECTION */
162 aws_h1_connection_lock_synced_data(connection);
163
164 /* Even if we're not scheduling shutdown just yet (ex: sent final request but waiting to read final response)
165 * we don't consider the connection "open" anymore so user can't create more streams */
166 connection->synced_data.is_open = false;
167 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
168
169 aws_h1_connection_unlock_synced_data(connection);
170 } /* END CRITICAL SECTION */
171 if (schedule_shutdown) {
172 AWS_LOGF_INFO(
173 AWS_LS_HTTP_CONNECTION,
174 "id=%p: Shutting down connection with error code %d (%s).",
175 (void *)&connection->base,
176 error_code,
177 aws_error_name(error_code));
178
179 aws_channel_shutdown(connection->base.channel_slot->channel, error_code);
180
181 if (stop_reading) {
182 /* Increase the window size after shutdown starts, to prevent deadlock when data still pending in the TLS
183 * handler. */
184 aws_channel_slot_increment_read_window(connection->base.channel_slot, SIZE_MAX);
185 }
186 }
187 }
188
189 static void s_shutdown_due_to_error(struct aws_h1_connection *connection, int error_code) {
190 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
191
192 if (!error_code) {
193 error_code = AWS_ERROR_UNKNOWN;
194 }
195
196 /* Stop reading AND writing if an error occurs.
197 *
198 * It doesn't currently seem worth the complexity to distinguish between read errors and write errors.
199 * The only scenarios that would benefit from this are pipelining scenarios (ex: A server
200 * could continue sending a response to request A if there was an error reading request B).
201 * But pipelining in HTTP/1.1 is known to be fragile with regards to errors, so let's just keep it simple.
202 */
203 s_stop(connection, true /*stop_reading*/, true /*stop_writing*/, true /*schedule_shutdown*/, error_code);
204 }
205
206 /**
207 * Helper to shutdown the connection from non-channel thread. (User wishes to close the connection)
208 **/
209 static void s_shutdown_from_off_thread(struct aws_h1_connection *connection, int error_code) {
210 bool should_schedule_task = false;
211 { /* BEGIN CRITICAL SECTION */
212 aws_h1_connection_lock_synced_data(connection);
213 if (!connection->synced_data.is_cross_thread_work_task_scheduled) {
214 connection->synced_data.is_cross_thread_work_task_scheduled = true;
215 should_schedule_task = true;
216 }
217 if (!connection->synced_data.shutdown_requested) {
218 connection->synced_data.shutdown_requested = true;
219 connection->synced_data.shutdown_requested_error_code = error_code;
220 }
221 /* Connection has shutdown, new streams should not be allowed. */
222 connection->synced_data.is_open = false;
223 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
224 aws_h1_connection_unlock_synced_data(connection);
225 } /* END CRITICAL SECTION */
226
227 if (should_schedule_task) {
228 AWS_LOGF_TRACE(
229 AWS_LS_HTTP_CONNECTION, "id=%p: Scheduling connection cross-thread work task.", (void *)&connection->base);
230 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
231 } else {
232 AWS_LOGF_TRACE(
233 AWS_LS_HTTP_CONNECTION,
234 "id=%p: Connection cross-thread work task was already scheduled",
235 (void *)&connection->base);
236 }
237 }
238
239 /**
240 * Public function for closing connection.
241 */
242 static void s_connection_close(struct aws_http_connection *connection_base) {
243 struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
244 s_shutdown_from_off_thread(connection, AWS_ERROR_SUCCESS);
245 }
246
247 static void s_connection_stop_new_request(struct aws_http_connection *connection_base) {
248 struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
249
250 { /* BEGIN CRITICAL SECTION */
251 aws_h1_connection_lock_synced_data(connection);
252 if (!connection->synced_data.new_stream_error_code) {
253 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
254 }
255 aws_h1_connection_unlock_synced_data(connection);
256 } /* END CRITICAL SECTION */
257 }
258
259 static bool s_connection_is_open(const struct aws_http_connection *connection_base) {
260 struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
261 bool is_open;
262
263 { /* BEGIN CRITICAL SECTION */
264 aws_h1_connection_lock_synced_data(connection);
265 is_open = connection->synced_data.is_open;
266 aws_h1_connection_unlock_synced_data(connection);
267 } /* END CRITICAL SECTION */
268
269 return is_open;
270 }
271
272 static bool s_connection_new_requests_allowed(const struct aws_http_connection *connection_base) {
273 struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
274 int new_stream_error_code;
275 { /* BEGIN CRITICAL SECTION */
276 aws_h1_connection_lock_synced_data(connection);
277 new_stream_error_code = connection->synced_data.new_stream_error_code;
278 aws_h1_connection_unlock_synced_data(connection);
279 } /* END CRITICAL SECTION */
280 return new_stream_error_code == 0;
281 }
282
283 static int s_stream_send_response(struct aws_http_stream *stream, struct aws_http_message *response) {
284 AWS_PRECONDITION(stream);
285 AWS_PRECONDITION(response);
286 struct aws_h1_stream *h1_stream = AWS_CONTAINER_OF(stream, struct aws_h1_stream, base);
287 return aws_h1_stream_send_response(h1_stream, response);
288 }
289
290 /* Calculate the desired window size for connection that has switched protocols and become a midchannel handler. */
291 static size_t s_calculate_midchannel_desired_connection_window(struct aws_h1_connection *connection) {
292 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
293 AWS_ASSERT(connection->thread_data.has_switched_protocols);
294
295 if (!connection->base.channel_slot->adj_right) {
296 /* No downstream handler installed. */
297 return 0;
298 }
299
300 /* Connection is just dumbly forwarding aws_io_messages, so try to match downstream handler. */
301 return aws_channel_slot_downstream_read_window(connection->base.channel_slot);
302 }
303
304 /* Calculate the desired window size for a connection that is processing data for aws_http_streams. */
305 static size_t s_calculate_stream_mode_desired_connection_window(struct aws_h1_connection *connection) {
306 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
307 AWS_ASSERT(!connection->thread_data.has_switched_protocols);
308
309 if (!connection->base.stream_manual_window_management) {
310 return SIZE_MAX;
311 }
312
313 /* Connection window should match the available space in the read-buffer */
314 AWS_ASSERT(
315 connection->thread_data.read_buffer.pending_bytes <= connection->thread_data.read_buffer.capacity &&
316 "This isn't fatal, but our math is off");
317 const size_t desired_connection_window = aws_sub_size_saturating(
318 connection->thread_data.read_buffer.capacity, connection->thread_data.read_buffer.pending_bytes);
319
320 AWS_LOGF_TRACE(
321 AWS_LS_HTTP_CONNECTION,
322 "id=%p: Window stats: connection=%zu+%zu stream=%" PRIu64 " buffer=%zu/%zu",
323 (void *)&connection->base,
324 connection->thread_data.connection_window,
325 desired_connection_window - connection->thread_data.connection_window /*increment_size*/,
326 connection->thread_data.incoming_stream ? connection->thread_data.incoming_stream->thread_data.stream_window
327 : 0,
328 connection->thread_data.read_buffer.pending_bytes,
329 connection->thread_data.read_buffer.capacity);
330
331 return desired_connection_window;
332 }
333
334 /* Increment connection window, if necessary */
335 static int s_update_connection_window(struct aws_h1_connection *connection) {
336 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
337
338 if (connection->thread_data.read_state == AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE) {
339 return AWS_OP_SUCCESS;
340 }
341
342 const size_t desired_size = connection->thread_data.has_switched_protocols
343 ? s_calculate_midchannel_desired_connection_window(connection)
344 : s_calculate_stream_mode_desired_connection_window(connection);
345
346 const size_t increment_size = aws_sub_size_saturating(desired_size, connection->thread_data.connection_window);
347 if (increment_size > 0) {
348 /* Update local `connection_window`. See comments at variable's declaration site
349 * on why we use this instead of the official `aws_channel_slot.window_size` */
350 connection->thread_data.connection_window += increment_size;
351 connection->thread_data.recent_window_increments =
352 aws_add_size_saturating(connection->thread_data.recent_window_increments, increment_size);
353 if (aws_channel_slot_increment_read_window(connection->base.channel_slot, increment_size)) {
354 AWS_LOGF_ERROR(
355 AWS_LS_HTTP_CONNECTION,
356 "id=%p: Failed to increment read window, error %d (%s). Closing connection.",
357 (void *)&connection->base,
358 aws_last_error(),
359 aws_error_name(aws_last_error()));
360
361 return AWS_OP_ERR;
362 }
363 }
364
365 return AWS_OP_SUCCESS;
366 }
367
368 int aws_h1_stream_activate(struct aws_http_stream *stream) {
369 struct aws_h1_stream *h1_stream = AWS_CONTAINER_OF(stream, struct aws_h1_stream, base);
370
371 struct aws_http_connection *base_connection = stream->owning_connection;
372 struct aws_h1_connection *connection = AWS_CONTAINER_OF(base_connection, struct aws_h1_connection, base);
373
374 bool should_schedule_task = false;
375
376 { /* BEGIN CRITICAL SECTION */
377 /* Note: We're touching both the connection's and stream's synced_data in this section,
378 * which is OK because an h1_connection and all its h1_streams share a single lock. */
379 aws_h1_connection_lock_synced_data(connection);
380
381 if (stream->id) {
382 /* stream has already been activated. */
383 aws_h1_connection_unlock_synced_data(connection);
384 return AWS_OP_SUCCESS;
385 }
386
387 if (connection->synced_data.new_stream_error_code) {
388 aws_h1_connection_unlock_synced_data(connection);
389 AWS_LOGF_ERROR(
390 AWS_LS_HTTP_CONNECTION,
391 "id=%p: Failed to activate the stream id=%p, new streams are not allowed now. error %d (%s)",
392 (void *)&connection->base,
393 (void *)stream,
394 connection->synced_data.new_stream_error_code,
395 aws_error_name(connection->synced_data.new_stream_error_code));
396 return aws_raise_error(connection->synced_data.new_stream_error_code);
397 }
398
399 stream->id = aws_http_connection_get_next_stream_id(base_connection);
400 if (!stream->id) {
401 aws_h1_connection_unlock_synced_data(connection);
402 /* aws_http_connection_get_next_stream_id() raises its own error. */
403 return AWS_OP_ERR;
404 }
405
406 /* ID successfully assigned */
407 h1_stream->synced_data.api_state = AWS_H1_STREAM_API_STATE_ACTIVE;
408
409 aws_linked_list_push_back(&connection->synced_data.new_client_stream_list, &h1_stream->node);
410 if (!connection->synced_data.is_cross_thread_work_task_scheduled) {
411 connection->synced_data.is_cross_thread_work_task_scheduled = true;
412 should_schedule_task = true;
413 }
414
415 aws_h1_connection_unlock_synced_data(connection);
416 } /* END CRITICAL SECTION */
417
418 /* connection keeps activated stream alive until stream completes */
419 aws_atomic_fetch_add(&stream->refcount, 1);
420 stream->metrics.stream_id = stream->id;
421
422 if (should_schedule_task) {
423 AWS_LOGF_TRACE(
424 AWS_LS_HTTP_CONNECTION, "id=%p: Scheduling connection cross-thread work task.", (void *)base_connection);
425 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
426 } else {
427 AWS_LOGF_TRACE(
428 AWS_LS_HTTP_CONNECTION,
429 "id=%p: Connection cross-thread work task was already scheduled",
430 (void *)base_connection);
431 }
432
433 return AWS_OP_SUCCESS;
434 }
435
436 void aws_h1_stream_cancel(struct aws_http_stream *stream, int error_code) {
437 struct aws_h1_stream *h1_stream = AWS_CONTAINER_OF(stream, struct aws_h1_stream, base);
438 struct aws_http_connection *base_connection = stream->owning_connection;
439 struct aws_h1_connection *connection = AWS_CONTAINER_OF(base_connection, struct aws_h1_connection, base);
440
441 { /* BEGIN CRITICAL SECTION */
442 aws_h1_connection_lock_synced_data(connection);
443 if (h1_stream->synced_data.api_state != AWS_H1_STREAM_API_STATE_ACTIVE ||
444 connection->synced_data.is_open == false) {
445 /* Not active, nothing to cancel. */
446 aws_h1_connection_unlock_synced_data(connection);
447 AWS_LOGF_DEBUG(AWS_LS_HTTP_STREAM, "id=%p: Stream not active, nothing to cancel.", (void *)stream);
448 return;
449 }
450
451 aws_h1_connection_unlock_synced_data(connection);
452 } /* END CRITICAL SECTION */
453 AWS_LOGF_INFO(
454 AWS_LS_HTTP_CONNECTION,
455 "id=%p: Connection shutting down due to stream=%p cancelled with error code %d (%s).",
456 (void *)&connection->base,
457 (void *)stream,
458 error_code,
459 aws_error_name(error_code));
460 s_shutdown_from_off_thread(connection, error_code);
461 }
462
463 struct aws_http_stream *s_make_request(
464 struct aws_http_connection *client_connection,
465 const struct aws_http_make_request_options *options) {
466 struct aws_h1_stream *stream = aws_h1_stream_new_request(client_connection, options);
467 if (!stream) {
468 AWS_LOGF_ERROR(
469 AWS_LS_HTTP_CONNECTION,
470 "id=%p: Cannot create request stream, error %d (%s)",
471 (void *)client_connection,
472 aws_last_error(),
473 aws_error_name(aws_last_error()));
474
475 return NULL;
476 }
477
478 struct aws_h1_connection *connection = AWS_CONTAINER_OF(client_connection, struct aws_h1_connection, base);
479
480 /* Insert new stream into pending list, and schedule outgoing_stream_task if it's not already running. */
481 int new_stream_error_code;
482 { /* BEGIN CRITICAL SECTION */
483 aws_h1_connection_lock_synced_data(connection);
484 new_stream_error_code = connection->synced_data.new_stream_error_code;
485 aws_h1_connection_unlock_synced_data(connection);
486 } /* END CRITICAL SECTION */
487 if (new_stream_error_code) {
488 AWS_LOGF_ERROR(
489 AWS_LS_HTTP_CONNECTION,
490 "id=%p: Cannot create request stream, error %d (%s)",
491 (void *)client_connection,
492 new_stream_error_code,
493 aws_error_name(new_stream_error_code));
494
495 aws_raise_error(new_stream_error_code);
496 goto error;
497 }
498
499 /* Success! */
500 struct aws_byte_cursor method;
501 aws_http_message_get_request_method(options->request, &method);
502 stream->base.request_method = aws_http_str_to_method(method);
503 struct aws_byte_cursor path;
504 aws_http_message_get_request_path(options->request, &path);
505 AWS_LOGF_DEBUG(
506 AWS_LS_HTTP_STREAM,
507 "id=%p: Created client request on connection=%p: " PRInSTR " " PRInSTR " " PRInSTR,
508 (void *)&stream->base,
509 (void *)client_connection,
510 AWS_BYTE_CURSOR_PRI(method),
511 AWS_BYTE_CURSOR_PRI(path),
512 AWS_BYTE_CURSOR_PRI(aws_http_version_to_str(connection->base.http_version)));
513
514 return &stream->base;
515
516 error:
517 /* Force destruction of the stream, avoiding ref counting */
518 stream->base.vtable->destroy(&stream->base);
519 return NULL;
520 }
521
522 /* Extract work items from synced_data, and perform the work on-thread. */
523 static void s_cross_thread_work_task(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
524 (void)channel_task;
525 struct aws_h1_connection *connection = arg;
526
527 if (status != AWS_TASK_STATUS_RUN_READY) {
528 return;
529 }
530
531 AWS_LOGF_TRACE(
532 AWS_LS_HTTP_CONNECTION, "id=%p: Running connection cross-thread work task.", (void *)&connection->base);
533
534 /* BEGIN CRITICAL SECTION */
535 aws_h1_connection_lock_synced_data(connection);
536
537 connection->synced_data.is_cross_thread_work_task_scheduled = false;
538
539 bool has_new_client_streams = !aws_linked_list_empty(&connection->synced_data.new_client_stream_list);
540 aws_linked_list_move_all_back(
541 &connection->thread_data.stream_list, &connection->synced_data.new_client_stream_list);
542 bool shutdown_requested = connection->synced_data.shutdown_requested;
543 int shutdown_error = connection->synced_data.shutdown_requested_error_code;
544 connection->synced_data.shutdown_requested = false;
545 connection->synced_data.shutdown_requested_error_code = 0;
546
547 aws_h1_connection_unlock_synced_data(connection);
548 /* END CRITICAL SECTION */
549
550 if (shutdown_requested) {
551 s_stop(connection, true /*stop_reading*/, true /*stop_writing*/, true /*schedule_shutdown*/, shutdown_error);
552 }
553 /* Kick off outgoing-stream task if necessary */
554 if (has_new_client_streams) {
555 aws_h1_connection_try_write_outgoing_stream(connection);
556 }
557 }
558
559 static bool s_aws_http_stream_was_successful_connect(struct aws_h1_stream *stream) {
560 struct aws_http_stream *base = &stream->base;
561 if (base->request_method != AWS_HTTP_METHOD_CONNECT) {
562 return false;
563 }
564
565 if (base->client_data == NULL) {
566 return false;
567 }
568
569 if (base->client_data->response_status != AWS_HTTP_STATUS_CODE_200_OK) {
570 return false;
571 }
572
573 return true;
574 }
575
576 /**
577 * Validate and perform a protocol switch on a connection. Protocol switching essentially turns the connection's
578 * handler into a dummy pass-through. It is valid to switch protocols to the same protocol resulting in a channel
579 * that has a "dead" http handler in the middle of the channel (which negotiated the CONNECT through the proxy) and
580 * a "live" handler on the end which takes the actual http requests. By doing this, we get the exact same
581 * behavior whether we're transitioning to http or any other protocol: once the CONNECT succeeds
582 * the first http handler is put in pass-through mode and a new protocol (which could be http) is tacked onto the end.
583 */
584 static int s_aws_http1_switch_protocols(struct aws_h1_connection *connection) {
585 AWS_FATAL_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
586
587 /* Switching protocols while there are multiple streams is too complex to deal with.
588 * Ensure stream_list has exactly this 1 stream in it. */
589 if (aws_linked_list_begin(&connection->thread_data.stream_list) !=
590 aws_linked_list_rbegin(&connection->thread_data.stream_list)) {
591 AWS_LOGF_ERROR(
592 AWS_LS_HTTP_CONNECTION,
593 "id=%p: Cannot switch protocols while further streams are pending, closing connection.",
594 (void *)&connection->base);
595
596 return aws_raise_error(AWS_ERROR_INVALID_STATE);
597 }
598
599 AWS_LOGF_TRACE(
600 AWS_LS_HTTP_CONNECTION,
601 "id=%p: Connection has switched protocols, another channel handler must be installed to"
602 " deal with further data.",
603 (void *)&connection->base);
604
605 connection->thread_data.has_switched_protocols = true;
606 { /* BEGIN CRITICAL SECTION */
607 aws_h1_connection_lock_synced_data(connection);
608 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_SWITCHED_PROTOCOLS;
609 aws_h1_connection_unlock_synced_data(connection);
610 } /* END CRITICAL SECTION */
611
612 return AWS_OP_SUCCESS;
613 }
614
615 static void s_stream_complete(struct aws_h1_stream *stream, int error_code) {
616 struct aws_h1_connection *connection =
617 AWS_CONTAINER_OF(stream->base.owning_connection, struct aws_h1_connection, base);
618 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
619
620 /*
621 * If this is the end of a successful CONNECT request, mark ourselves as pass-through since the proxy layer
622 * will be tacking on a new http handler (and possibly a tls handler in-between).
623 */
624 if (error_code == AWS_ERROR_SUCCESS && s_aws_http_stream_was_successful_connect(stream)) {
625 if (s_aws_http1_switch_protocols(connection)) {
626 error_code = AWS_ERROR_HTTP_PROTOCOL_SWITCH_FAILURE;
627 s_shutdown_due_to_error(connection, error_code);
628 }
629 }
630
631 if (stream->base.client_data && stream->base.client_data->response_first_byte_timeout_task.fn != NULL) {
632 /* There is an outstanding response timeout task, but stream completed, we can cancel it now. We are
633 * safe to do it as we always on connection thread to schedule the task or cancel it */
634 struct aws_event_loop *connection_loop = aws_channel_get_event_loop(connection->base.channel_slot->channel);
635 /* The task will be zeroed out within the call */
636 aws_event_loop_cancel_task(connection_loop, &stream->base.client_data->response_first_byte_timeout_task);
637 }
638
639 if (error_code != AWS_ERROR_SUCCESS) {
640 if (stream->base.client_data && stream->thread_data.is_incoming_message_done) {
641 /* As a request that finished receiving the response, we ignore error and
642 * consider it finished successfully */
643 AWS_LOGF_DEBUG(
644 AWS_LS_HTTP_STREAM,
645 "id=%p: Ignoring error code %d (%s). The response has been fully received,"
646 "so the stream will complete successfully.",
647 (void *)&stream->base,
648 error_code,
649 aws_error_name(error_code));
650 error_code = AWS_ERROR_SUCCESS;
651 }
652 if (stream->base.server_data && stream->thread_data.is_outgoing_message_done) {
653 /* As a server finished sending the response, but still failed with the request was not finished receiving.
654 * We ignore error and consider it finished successfully */
655 AWS_LOGF_DEBUG(
656 AWS_LS_HTTP_STREAM,
657 "id=%p: Ignoring error code %d (%s). The response has been fully sent,"
658 " so the stream will complete successfully",
659 (void *)&stream->base,
660 error_code,
661 aws_error_name(error_code));
662 error_code = AWS_ERROR_SUCCESS;
663 }
664 }
665
666 /* Remove stream from list. */
667 aws_linked_list_remove(&stream->node);
668
669 /* Nice logging */
670 if (error_code) {
671 AWS_LOGF_DEBUG(
672 AWS_LS_HTTP_STREAM,
673 "id=%p: Stream completed with error code %d (%s).",
674 (void *)&stream->base,
675 error_code,
676 aws_error_name(error_code));
677
678 } else if (stream->base.client_data) {
679 AWS_LOGF_DEBUG(
680 AWS_LS_HTTP_STREAM,
681 "id=%p: Client request complete, response status: %d (%s).",
682 (void *)&stream->base,
683 stream->base.client_data->response_status,
684 aws_http_status_text(stream->base.client_data->response_status));
685 } else {
686 AWS_ASSERT(stream->base.server_data);
687 AWS_LOGF_DEBUG(
688 AWS_LS_HTTP_STREAM,
689 "id=%p: Server response to " PRInSTR " request complete.",
690 (void *)&stream->base,
691 AWS_BYTE_CURSOR_PRI(stream->base.server_data->request_method_str));
692 }
693
694 /* If connection must shut down, do it BEFORE invoking stream-complete callback.
695 * That way, if aws_http_connection_is_open() is called from stream-complete callback, it returns false. */
696 if (stream->thread_data.is_final_stream) {
697 AWS_LOGF_TRACE(
698 AWS_LS_HTTP_CONNECTION,
699 "id=%p: Closing connection due to completion of final stream.",
700 (void *)&connection->base);
701
702 s_connection_close(&connection->base);
703 }
704
705 { /* BEGIN CRITICAL SECTION */
706 /* Note: We're touching the stream's synced_data here, which is OK
707 * because an h1_connection and all its h1_streams share a single lock. */
708 aws_h1_connection_lock_synced_data(connection);
709
710 /* Mark stream complete */
711 stream->synced_data.api_state = AWS_H1_STREAM_API_STATE_COMPLETE;
712
713 /* Move chunks and data writes out of synced data */
714 aws_linked_list_move_all_back(&stream->thread_data.pending_chunk_list, &stream->synced_data.pending_chunk_list);
715 aws_linked_list_move_all_back(
716 &stream->thread_data.pending_data_write_list, &stream->synced_data.pending_data_write_list);
717
718 aws_h1_connection_unlock_synced_data(connection);
719 } /* END CRITICAL SECTION */
720
721 /* Complete any leftover chunks */
722 while (!aws_linked_list_empty(&stream->thread_data.pending_chunk_list)) {
723 struct aws_linked_list_node *node = aws_linked_list_pop_front(&stream->thread_data.pending_chunk_list);
724 struct aws_h1_chunk *chunk = AWS_CONTAINER_OF(node, struct aws_h1_chunk, node);
725 aws_h1_chunk_complete_and_destroy(chunk, &stream->base, AWS_ERROR_HTTP_STREAM_HAS_COMPLETED);
726 }
727
728 /* Complete any leftover data writes */
729 while (!aws_linked_list_empty(&stream->thread_data.pending_data_write_list)) {
730 struct aws_linked_list_node *node = aws_linked_list_pop_front(&stream->thread_data.pending_data_write_list);
731 struct aws_h1_data_write *data_write = AWS_CONTAINER_OF(node, struct aws_h1_data_write, node);
732 aws_h1_data_write_complete_and_destroy(data_write, &stream->base, AWS_ERROR_HTTP_STREAM_HAS_COMPLETED);
733 }
734
735 if (stream->base.on_metrics) {
736 stream->base.on_metrics(&stream->base, &stream->base.metrics, stream->base.user_data);
737 }
738
739 /* Invoke callback and clean up stream. */
740 if (stream->base.on_complete) {
741 stream->base.on_complete(&stream->base, error_code, stream->base.user_data);
742 }
743
744 aws_http_stream_release(&stream->base);
745 }
746
747 static void s_add_time_measurement_to_stats(uint64_t start_ns, uint64_t end_ns, uint64_t *output_ms) {
748 if (end_ns > start_ns) {
749 *output_ms += aws_timestamp_convert(end_ns - start_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_MILLIS, NULL);
750 }
751 }
752
753 static void s_set_outgoing_stream_ptr(
754 struct aws_h1_connection *connection,
755 struct aws_h1_stream *next_outgoing_stream) {
756 struct aws_h1_stream *prev = connection->thread_data.outgoing_stream;
757
758 uint64_t now_ns = 0;
759 aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns);
760 if (prev == NULL && next_outgoing_stream != NULL) {
761 /* transition from nothing to write -> something to write */
762 connection->thread_data.outgoing_stream_timestamp_ns = now_ns;
763 } else if (prev != NULL && next_outgoing_stream == NULL) {
764 /* transition from something to write -> nothing to write */
765 s_add_time_measurement_to_stats(
766 connection->thread_data.outgoing_stream_timestamp_ns,
767 now_ns,
768 &connection->thread_data.stats.pending_outgoing_stream_ms);
769 }
770
771 connection->thread_data.outgoing_stream = next_outgoing_stream;
772 }
773
774 static void s_set_incoming_stream_ptr(
775 struct aws_h1_connection *connection,
776 struct aws_h1_stream *next_incoming_stream) {
777 struct aws_h1_stream *prev = connection->thread_data.incoming_stream;
778
779 uint64_t now_ns = 0;
780 aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns);
781 if (prev == NULL && next_incoming_stream != NULL) {
782 /* transition from nothing to read -> something to read */
783 connection->thread_data.incoming_stream_timestamp_ns = now_ns;
784 } else if (prev != NULL && next_incoming_stream == NULL) {
785 /* transition from something to read -> nothing to read */
786 s_add_time_measurement_to_stats(
787 connection->thread_data.incoming_stream_timestamp_ns,
788 now_ns,
789 &connection->thread_data.stats.pending_incoming_stream_ms);
790 }
791
792 connection->thread_data.incoming_stream = next_incoming_stream;
793 }
794
795 /**
796 * Ensure `incoming_stream` is pointing at the correct stream, and update state if it changes.
797 */
798 static void s_client_update_incoming_stream_ptr(struct aws_h1_connection *connection) {
799 struct aws_linked_list *list = &connection->thread_data.stream_list;
800 struct aws_h1_stream *desired;
801 if (connection->thread_data.read_state == AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE) {
802 desired = NULL;
803 } else if (aws_linked_list_empty(list)) {
804 desired = NULL;
805 } else {
806 desired = AWS_CONTAINER_OF(aws_linked_list_begin(list), struct aws_h1_stream, node);
807 }
808
809 if (connection->thread_data.incoming_stream == desired) {
810 return;
811 }
812
813 AWS_LOGF_TRACE(
814 AWS_LS_HTTP_CONNECTION,
815 "id=%p: Current incoming stream is now %p.",
816 (void *)&connection->base,
817 desired ? (void *)&desired->base : NULL);
818
819 s_set_incoming_stream_ptr(connection, desired);
820 }
821
822 static void s_http_stream_response_first_byte_timeout_task(
823 struct aws_task *task,
824 void *arg,
825 enum aws_task_status status) {
826 (void)task;
827 struct aws_h1_stream *stream = arg;
828 struct aws_http_connection *connection_base = stream->base.owning_connection;
829 /* zero-out task to indicate that it's no longer scheduled */
830 AWS_ZERO_STRUCT(stream->base.client_data->response_first_byte_timeout_task);
831
832 if (status == AWS_TASK_STATUS_CANCELED) {
833 return;
834 }
835
836 struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
837 /* Timeout happened, close the connection */
838 uint64_t response_first_byte_timeout_ms = stream->base.client_data->response_first_byte_timeout_ms == 0
839 ? connection_base->client_data->response_first_byte_timeout_ms
840 : stream->base.client_data->response_first_byte_timeout_ms;
841 AWS_LOGF_INFO(
842 AWS_LS_HTTP_CONNECTION,
843 "id=%p: Closing connection. Timed out waiting for first byte of HTTP response, after sending the full request."
844 " response_first_byte_timeout_ms=%" PRIu64,
845 (void *)connection_base,
846 response_first_byte_timeout_ms);
847
848 /* Shutdown the connection. */
849 s_shutdown_due_to_error(connection, AWS_ERROR_HTTP_RESPONSE_FIRST_BYTE_TIMEOUT);
850 }
851
852 static void s_set_outgoing_message_done(struct aws_h1_stream *stream) {
853 struct aws_http_connection *connection = stream->base.owning_connection;
854 struct aws_channel *channel = aws_http_connection_get_channel(connection);
855 AWS_ASSERT(aws_channel_thread_is_callers_thread(channel));
856
857 if (stream->thread_data.is_outgoing_message_done) {
858 /* Already did the job */
859 return;
860 }
861
862 stream->thread_data.is_outgoing_message_done = true;
863 AWS_ASSERT(stream->base.metrics.send_end_timestamp_ns == -1);
864 aws_high_res_clock_get_ticks((uint64_t *)&stream->base.metrics.send_end_timestamp_ns);
865 AWS_ASSERT(stream->base.metrics.send_start_timestamp_ns != -1);
866 AWS_ASSERT(stream->base.metrics.send_end_timestamp_ns >= stream->base.metrics.send_start_timestamp_ns);
867 stream->base.metrics.sending_duration_ns =
868 stream->base.metrics.send_end_timestamp_ns - stream->base.metrics.send_start_timestamp_ns;
869 if (stream->base.metrics.receive_start_timestamp_ns == -1) {
870 /* We haven't receive any message, schedule the response timeout task */
871
872 uint64_t response_first_byte_timeout_ms = 0;
873 if (stream->base.client_data != NULL && connection->client_data != NULL) {
874 response_first_byte_timeout_ms = stream->base.client_data->response_first_byte_timeout_ms == 0
875 ? connection->client_data->response_first_byte_timeout_ms
876 : stream->base.client_data->response_first_byte_timeout_ms;
877 }
878 if (response_first_byte_timeout_ms != 0) {
879 /* The task should not be initialized before. */
880 AWS_ASSERT(stream->base.client_data->response_first_byte_timeout_task.fn == NULL);
881 aws_task_init(
882 &stream->base.client_data->response_first_byte_timeout_task,
883 s_http_stream_response_first_byte_timeout_task,
884 stream,
885 "http_stream_response_first_byte_timeout_task");
886 uint64_t now_ns = 0;
887 aws_channel_current_clock_time(channel, &now_ns);
888 struct aws_event_loop *connection_loop = aws_channel_get_event_loop(channel);
889 aws_event_loop_schedule_task_future(
890 connection_loop,
891 &stream->base.client_data->response_first_byte_timeout_task,
892 now_ns + aws_timestamp_convert(
893 response_first_byte_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL));
894 }
895 }
896 }
897
898 /**
899 * If necessary, update `outgoing_stream` so it is pointing at a stream
900 * with data to send, or NULL if all streams are done sending data.
901 *
902 * Called from event-loop thread.
903 * This function has lots of side effects.
904 */
905 static struct aws_h1_stream *s_update_outgoing_stream_ptr(struct aws_h1_connection *connection) {
906 struct aws_h1_stream *current = connection->thread_data.outgoing_stream;
907 bool current_changed = false;
908 int err;
909
910 /* If current stream is done sending data... */
911 if (current && !aws_h1_encoder_is_message_in_progress(&connection->thread_data.encoder)) {
912 s_set_outgoing_message_done(current);
913
914 /* RFC-7230 section 6.6: Tear-down.
915 * If this was the final stream, don't allows any further streams to be sent */
916 if (current->thread_data.is_final_stream) {
917 AWS_LOGF_TRACE(
918 AWS_LS_HTTP_CONNECTION,
919 "id=%p: Done sending final stream, no further streams will be sent.",
920 (void *)&connection->base);
921
922 s_stop(
923 connection,
924 false /*stop_reading*/,
925 true /*stop_writing*/,
926 false /*schedule_shutdown*/,
927 AWS_ERROR_SUCCESS);
928 }
929
930 /* If it's also done receiving data, then it's complete! */
931 if (current->thread_data.is_incoming_message_done) {
932 /* Only 1st stream in list could finish receiving before it finished sending */
933 AWS_ASSERT(&current->node == aws_linked_list_begin(&connection->thread_data.stream_list));
934
935 /* This removes stream from list */
936 s_stream_complete(current, AWS_ERROR_SUCCESS);
937 }
938
939 current = NULL;
940 current_changed = true;
941 }
942
943 /* If current stream is NULL, look for more work. */
944 if (!current && !connection->thread_data.is_writing_stopped) {
945
946 /* Look for next stream we can work on. */
947 for (struct aws_linked_list_node *node = aws_linked_list_begin(&connection->thread_data.stream_list);
948 node != aws_linked_list_end(&connection->thread_data.stream_list);
949 node = aws_linked_list_next(node)) {
950
951 struct aws_h1_stream *stream = AWS_CONTAINER_OF(node, struct aws_h1_stream, node);
952
953 /* If we already sent this stream's data, keep looking... */
954 if (stream->thread_data.is_outgoing_message_done) {
955 continue;
956 }
957
958 /* STOP if we're a server, and this stream's response isn't ready to send.
959 * It's not like we can skip this and start on the next stream because responses must be sent in order.
960 * Don't need a check like this for clients because their streams always start with data to send. */
961 if (connection->base.server_data && !stream->thread_data.has_outgoing_response) {
962 break;
963 }
964
965 /* We found a stream to work on! */
966 current = stream;
967 current_changed = true;
968 break;
969 }
970 }
971
972 /* Update current incoming and outgoing streams. */
973 if (current_changed) {
974 AWS_LOGF_TRACE(
975 AWS_LS_HTTP_CONNECTION,
976 "id=%p: Current outgoing stream is now %p.",
977 (void *)&connection->base,
978 current ? (void *)&current->base : NULL);
979
980 s_set_outgoing_stream_ptr(connection, current);
981
982 if (current) {
983 AWS_ASSERT(current->base.metrics.send_start_timestamp_ns == -1);
984 aws_high_res_clock_get_ticks((uint64_t *)&current->base.metrics.send_start_timestamp_ns);
985
986 err = aws_h1_encoder_start_message(
987 &connection->thread_data.encoder, &current->thread_data.encoder_message, &current->base);
988 (void)err;
989 AWS_ASSERT(connection->thread_data.encoder.state == AWS_H1_ENCODER_STATE_INIT);
990 AWS_ASSERT(!err);
991 }
992
993 /* incoming_stream update is only for client */
994 if (connection->base.client_data) {
995 s_client_update_incoming_stream_ptr(connection);
996 }
997 }
998
999 return current;
1000 }
1001
1002 /* Runs after an aws_io_message containing HTTP has completed (written to the network, or failed).
1003 * This does NOT run after switching protocols, when we're dumbly forwarding aws_io_messages
1004 * as a midchannel handler. */
1005 static void s_on_channel_write_complete(
1006 struct aws_channel *channel,
1007 struct aws_io_message *message,
1008 int err_code,
1009 void *user_data) {
1010
1011 (void)message;
1012 struct aws_h1_connection *connection = user_data;
1013 AWS_ASSERT(connection->thread_data.is_outgoing_stream_task_active);
1014 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1015
1016 if (err_code) {
1017 AWS_LOGF_TRACE(
1018 AWS_LS_HTTP_CONNECTION,
1019 "id=%p: Message did not write to network, error %d (%s)",
1020 (void *)&connection->base,
1021 err_code,
1022 aws_error_name(err_code));
1023
1024 s_shutdown_due_to_error(connection, err_code);
1025 return;
1026 }
1027
1028 AWS_LOGF_TRACE(
1029 AWS_LS_HTTP_CONNECTION,
1030 "id=%p: Message finished writing to network. Rescheduling outgoing stream task.",
1031 (void *)&connection->base);
1032
1033 /* To avoid wasting memory, we only want ONE of our written aws_io_messages in the channel at a time.
1034 * Therefore, we wait until it's written to the network before trying to send another
1035 * by running the outgoing-stream-task again.
1036 *
1037 * We also want to share the network with other channels.
1038 * Therefore, when the write completes, we SCHEDULE the outgoing-stream-task
1039 * to run again instead of calling the function directly.
1040 * This way, if the message completes synchronously,
1041 * we're not hogging the network by writing message after message in a tight loop */
1042 aws_channel_schedule_task_now(channel, &connection->outgoing_stream_task);
1043 }
1044
1045 static void s_outgoing_stream_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
1046 (void)task;
1047 if (status != AWS_TASK_STATUS_RUN_READY) {
1048 return;
1049 }
1050
1051 struct aws_h1_connection *connection = arg;
1052 AWS_ASSERT(connection->thread_data.is_outgoing_stream_task_active);
1053 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1054
1055 s_write_outgoing_stream(connection, false /*first_try*/);
1056 }
1057
1058 void aws_h1_connection_try_write_outgoing_stream(struct aws_h1_connection *connection) {
1059 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1060
1061 if (connection->thread_data.is_outgoing_stream_task_active) {
1062 /* Task is already active */
1063 return;
1064 }
1065
1066 connection->thread_data.is_outgoing_stream_task_active = true;
1067 s_write_outgoing_stream(connection, true /*first_try*/);
1068 }
1069
1070 /* Do the actual work of the outgoing-stream-task */
1071 static void s_write_outgoing_stream(struct aws_h1_connection *connection, bool first_try) {
1072 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1073 AWS_PRECONDITION(connection->thread_data.is_outgoing_stream_task_active);
1074
1075 /* Just stop if we're no longer writing stream data */
1076 if (connection->thread_data.is_writing_stopped || connection->thread_data.has_switched_protocols) {
1077 return;
1078 }
1079
1080 /* Determine whether we have data available to send, and end task immediately if there's not.
1081 * The outgoing stream task will be kicked off again when user adds more data (new stream, new chunk, etc) */
1082 struct aws_h1_stream *outgoing_stream = s_update_outgoing_stream_ptr(connection);
1083 bool waiting_for_chunks = aws_h1_encoder_is_waiting_for_chunks(&connection->thread_data.encoder);
1084 bool waiting_for_data_writes = aws_h1_encoder_is_waiting_for_data_writes(&connection->thread_data.encoder);
1085 if (!outgoing_stream || waiting_for_chunks || waiting_for_data_writes) {
1086 if (!first_try) {
1087 AWS_LOGF_TRACE(
1088 AWS_LS_HTTP_CONNECTION,
1089 "id=%p: Outgoing stream task stopped. outgoing_stream=%p waiting_for_chunks:%d "
1090 "waiting_for_data_writes:%d",
1091 (void *)&connection->base,
1092 outgoing_stream ? (void *)&outgoing_stream->base : NULL,
1093 waiting_for_chunks,
1094 waiting_for_data_writes);
1095 }
1096 connection->thread_data.is_outgoing_stream_task_active = false;
1097 return;
1098 }
1099
1100 if (first_try) {
1101 AWS_LOGF_TRACE(AWS_LS_HTTP_CONNECTION, "id=%p: Outgoing stream task has begun.", (void *)&connection->base);
1102 }
1103
1104 struct aws_io_message *msg = aws_channel_slot_acquire_max_message_for_write(connection->base.channel_slot);
1105 if (!msg) {
1106 AWS_LOGF_ERROR(
1107 AWS_LS_HTTP_CONNECTION,
1108 "id=%p: Failed to acquire message from pool, error %d (%s). Closing connection.",
1109 (void *)&connection->base,
1110 aws_last_error(),
1111 aws_error_name(aws_last_error()));
1112 goto error;
1113 }
1114
1115 /* Set up callback so we can send another message when this one completes */
1116 msg->on_completion = s_on_channel_write_complete;
1117 msg->user_data = connection;
1118
1119 /*
1120 * Fill message data from the outgoing stream.
1121 * Note that we might be resuming work on a stream from a previous run of this task.
1122 */
1123 if (AWS_OP_SUCCESS != aws_h1_encoder_process(&connection->thread_data.encoder, &msg->message_data)) {
1124 /* Error sending data, abandon ship */
1125 goto error;
1126 }
1127
1128 if (msg->message_data.len > 0) {
1129 AWS_LOGF_TRACE(
1130 AWS_LS_HTTP_CONNECTION,
1131 "id=%p: Outgoing stream task is sending message of size %zu.",
1132 (void *)&connection->base,
1133 msg->message_data.len);
1134
1135 if (aws_channel_slot_send_message(connection->base.channel_slot, msg, AWS_CHANNEL_DIR_WRITE)) {
1136 AWS_LOGF_ERROR(
1137 AWS_LS_HTTP_CONNECTION,
1138 "id=%p: Failed to send message in write direction, error %d (%s). Closing connection.",
1139 (void *)&connection->base,
1140 aws_last_error(),
1141 aws_error_name(aws_last_error()));
1142
1143 goto error;
1144 }
1145
1146 } else {
1147 /* If message is empty, warn that no work is being done
1148 * and reschedule the task to try again next tick.
1149 * It's likely that body isn't ready, so body streaming function has no data to write yet.
1150 * If this scenario turns out to be common we should implement a "pause" feature. */
1151 AWS_LOGF_WARN(
1152 AWS_LS_HTTP_CONNECTION,
1153 "id=%p: Current outgoing stream %p sent no data, will try again next tick.",
1154 (void *)&connection->base,
1155 outgoing_stream ? (void *)&outgoing_stream->base : NULL);
1156
1157 aws_mem_release(msg->allocator, msg);
1158
1159 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->outgoing_stream_task);
1160 }
1161
1162 return;
1163 error:
1164 if (msg) {
1165 aws_mem_release(msg->allocator, msg);
1166 }
1167 s_shutdown_due_to_error(connection, aws_last_error());
1168 }
1169
1170 static int s_decoder_on_request(
1171 enum aws_http_method method_enum,
1172 const struct aws_byte_cursor *method_str,
1173 const struct aws_byte_cursor *uri,
1174 void *user_data) {
1175
1176 struct aws_h1_connection *connection = user_data;
1177 struct aws_h1_stream *incoming_stream = connection->thread_data.incoming_stream;
1178
1179 AWS_FATAL_ASSERT(connection->thread_data.incoming_stream->base.server_data); /* Request but I'm a client?!?!? */
1180
1181 AWS_ASSERT(incoming_stream->base.server_data->request_method_str.len == 0);
1182 AWS_ASSERT(incoming_stream->base.server_data->request_path.len == 0);
1183
1184 AWS_LOGF_TRACE(
1185 AWS_LS_HTTP_STREAM,
1186 "id=%p: Incoming request: method=" PRInSTR " uri=" PRInSTR,
1187 (void *)&incoming_stream->base,
1188 AWS_BYTE_CURSOR_PRI(*method_str),
1189 AWS_BYTE_CURSOR_PRI(*uri));
1190
1191 /* Copy strings to internal buffer */
1192 struct aws_byte_buf *storage_buf = &incoming_stream->thread_data.incoming_storage_buf;
1193 AWS_ASSERT(storage_buf->capacity == 0);
1194
1195 size_t storage_size = 0;
1196 int err = aws_add_size_checked(uri->len, method_str->len, &storage_size);
1197 if (err) {
1198 goto error;
1199 }
1200
1201 err = aws_byte_buf_init(storage_buf, incoming_stream->base.alloc, storage_size);
1202 if (err) {
1203 goto error;
1204 }
1205
1206 aws_byte_buf_write_from_whole_cursor(storage_buf, *method_str);
1207 incoming_stream->base.server_data->request_method_str = aws_byte_cursor_from_buf(storage_buf);
1208
1209 aws_byte_buf_write_from_whole_cursor(storage_buf, *uri);
1210 incoming_stream->base.server_data->request_path = aws_byte_cursor_from_buf(storage_buf);
1211 aws_byte_cursor_advance(&incoming_stream->base.server_data->request_path, storage_buf->len - uri->len);
1212 incoming_stream->base.request_method = method_enum;
1213
1214 /* No user callbacks, so we're not checking for shutdown */
1215 return AWS_OP_SUCCESS;
1216
1217 error:
1218 AWS_LOGF_ERROR(
1219 AWS_LS_HTTP_CONNECTION,
1220 "id=%p: Failed to process new incoming request, error %d (%s).",
1221 (void *)&connection->base,
1222 aws_last_error(),
1223 aws_error_name(aws_last_error()));
1224
1225 return AWS_OP_ERR;
1226 }
1227
1228 static int s_decoder_on_response(int status_code, void *user_data) {
1229 struct aws_h1_connection *connection = user_data;
1230
1231 AWS_FATAL_ASSERT(connection->thread_data.incoming_stream->base.client_data); /* Response but I'm a server?!?!? */
1232
1233 AWS_LOGF_TRACE(
1234 AWS_LS_HTTP_STREAM,
1235 "id=%p: Incoming response status: %d (%s).",
1236 (void *)&connection->thread_data.incoming_stream->base,
1237 status_code,
1238 aws_http_status_text(status_code));
1239
1240 connection->thread_data.incoming_stream->base.client_data->response_status = status_code;
1241
1242 /* No user callbacks, so we're not checking for shutdown */
1243 return AWS_OP_SUCCESS;
1244 }
1245
1246 static int s_decoder_on_header(const struct aws_h1_decoded_header *header, void *user_data) {
1247 struct aws_h1_connection *connection = user_data;
1248 struct aws_h1_stream *incoming_stream = connection->thread_data.incoming_stream;
1249
1250 AWS_LOGF_TRACE(
1251 AWS_LS_HTTP_STREAM,
1252 "id=%p: Incoming header: " PRInSTR ": " PRInSTR,
1253 (void *)&incoming_stream->base,
1254 AWS_BYTE_CURSOR_PRI(header->name_data),
1255 AWS_BYTE_CURSOR_PRI(header->value_data));
1256
1257 enum aws_http_header_block header_block =
1258 aws_h1_decoder_get_header_block(connection->thread_data.incoming_stream_decoder);
1259
1260 /* RFC-7230 section 6.1.
1261 * "Connection: close" header signals that a connection will not persist after the current request/response */
1262 if (header->name == AWS_HTTP_HEADER_CONNECTION) {
1263 /* Certain L7 proxies send a connection close header on a 200/OK response to a CONNECT request. This is nutty
1264 * behavior, but the obviously desired behavior on a 200 CONNECT response is to leave the connection open
1265 * for the tunneling. */
1266 bool ignore_connection_close =
1267 incoming_stream->base.request_method == AWS_HTTP_METHOD_CONNECT && incoming_stream->base.client_data &&
1268 incoming_stream->base.client_data->response_status == AWS_HTTP_STATUS_CODE_200_OK;
1269
1270 if (!ignore_connection_close && aws_byte_cursor_eq_c_str_ignore_case(&header->value_data, "close")) {
1271 AWS_LOGF_TRACE(
1272 AWS_LS_HTTP_STREAM,
1273 "id=%p: Received 'Connection: close' header. This will be the final stream on this connection.",
1274 (void *)&incoming_stream->base);
1275
1276 incoming_stream->thread_data.is_final_stream = true;
1277 { /* BEGIN CRITICAL SECTION */
1278 aws_h1_connection_lock_synced_data(connection);
1279 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
1280 aws_h1_connection_unlock_synced_data(connection);
1281 } /* END CRITICAL SECTION */
1282
1283 if (connection->base.client_data) {
1284 /**
1285 * RFC-9112 section 9.6.
1286 * A client that receives a "close" connection option MUST cease sending
1287 * requests on that connection and close the connection after reading the
1288 * response message containing the "close" connection option.
1289 *
1290 * Mark the stream's outgoing message as complete,
1291 * so that we stop sending, and stop waiting for it to finish sending.
1292 **/
1293 if (!incoming_stream->thread_data.is_outgoing_message_done) {
1294 AWS_LOGF_DEBUG(
1295 AWS_LS_HTTP_STREAM,
1296 "id=%p: Received 'Connection: close' header, no more request data will be sent.",
1297 (void *)&incoming_stream->base);
1298 s_set_outgoing_message_done(incoming_stream);
1299 }
1300 /* Stop writing right now.
1301 * Shutdown will be scheduled after we finishing parsing the response */
1302 s_stop(
1303 connection,
1304 false /*stop_reading*/,
1305 true /*stop_writing*/,
1306 false /*schedule_shutdown*/,
1307 AWS_ERROR_SUCCESS);
1308 }
1309 }
1310 }
1311
1312 if (incoming_stream->base.on_incoming_headers) {
1313 struct aws_http_header deliver = {
1314 .name = header->name_data,
1315 .value = header->value_data,
1316 };
1317
1318 int err = incoming_stream->base.on_incoming_headers(
1319 &incoming_stream->base, header_block, &deliver, 1, incoming_stream->base.user_data);
1320
1321 if (err) {
1322 AWS_LOGF_ERROR(
1323 AWS_LS_HTTP_STREAM,
1324 "id=%p: Incoming header callback raised error %d (%s).",
1325 (void *)&incoming_stream->base,
1326 aws_last_error(),
1327 aws_error_name(aws_last_error()));
1328
1329 return AWS_OP_ERR;
1330 }
1331 }
1332
1333 return AWS_OP_SUCCESS;
1334 }
1335
1336 static int s_mark_head_done(struct aws_h1_stream *incoming_stream) {
1337 /* Bail out if we've already done this */
1338 if (incoming_stream->thread_data.is_incoming_head_done) {
1339 return AWS_OP_SUCCESS;
1340 }
1341
1342 struct aws_h1_connection *connection =
1343 AWS_CONTAINER_OF(incoming_stream->base.owning_connection, struct aws_h1_connection, base);
1344
1345 enum aws_http_header_block header_block =
1346 aws_h1_decoder_get_header_block(connection->thread_data.incoming_stream_decoder);
1347
1348 if (header_block == AWS_HTTP_HEADER_BLOCK_MAIN) {
1349 AWS_LOGF_TRACE(AWS_LS_HTTP_STREAM, "id=%p: Main header block done.", (void *)&incoming_stream->base);
1350 incoming_stream->thread_data.is_incoming_head_done = true;
1351
1352 } else if (header_block == AWS_HTTP_HEADER_BLOCK_INFORMATIONAL) {
1353 AWS_LOGF_TRACE(AWS_LS_HTTP_STREAM, "id=%p: Informational header block done.", (void *)&incoming_stream->base);
1354
1355 /* Only clients can receive informational headers.
1356 * Check whether we're switching protocols */
1357 if (incoming_stream->base.client_data->response_status == AWS_HTTP_STATUS_CODE_101_SWITCHING_PROTOCOLS) {
1358 if (s_aws_http1_switch_protocols(connection)) {
1359 return AWS_OP_ERR;
1360 }
1361 }
1362 }
1363
1364 /* Invoke user cb */
1365 if (incoming_stream->base.on_incoming_header_block_done) {
1366 int err = incoming_stream->base.on_incoming_header_block_done(
1367 &incoming_stream->base, header_block, incoming_stream->base.user_data);
1368 if (err) {
1369 AWS_LOGF_ERROR(
1370 AWS_LS_HTTP_STREAM,
1371 "id=%p: Incoming-header-block-done callback raised error %d (%s).",
1372 (void *)&incoming_stream->base,
1373 aws_last_error(),
1374 aws_error_name(aws_last_error()));
1375
1376 return AWS_OP_ERR;
1377 }
1378 }
1379
1380 return AWS_OP_SUCCESS;
1381 }
1382
1383 static int s_decoder_on_body(const struct aws_byte_cursor *data, bool finished, void *user_data) {
1384 (void)finished;
1385
1386 struct aws_h1_connection *connection = user_data;
1387 struct aws_h1_stream *incoming_stream = connection->thread_data.incoming_stream;
1388 AWS_ASSERT(incoming_stream);
1389
1390 int err = s_mark_head_done(incoming_stream);
1391 if (err) {
1392 return AWS_OP_ERR;
1393 }
1394
1395 /* No need to invoke callback for 0-length data */
1396 if (data->len == 0) {
1397 return AWS_OP_SUCCESS;
1398 }
1399
1400 AWS_LOGF_TRACE(
1401 AWS_LS_HTTP_STREAM, "id=%p: Incoming body: %zu bytes received.", (void *)&incoming_stream->base, data->len);
1402
1403 if (connection->base.stream_manual_window_management) {
1404 /* Let stream window shrink by amount of body data received */
1405 if (data->len > incoming_stream->thread_data.stream_window) {
1406 /* This error shouldn't be possible, but it's all complicated, so do runtime check to be safe. */
1407 AWS_LOGF_ERROR(
1408 AWS_LS_HTTP_STREAM,
1409 "id=%p: Internal error. Data exceeds HTTP-stream's window.",
1410 (void *)&incoming_stream->base);
1411 return aws_raise_error(AWS_ERROR_INVALID_STATE);
1412 }
1413 incoming_stream->thread_data.stream_window -= data->len;
1414
1415 if (incoming_stream->thread_data.stream_window == 0) {
1416 AWS_LOGF_DEBUG(
1417 AWS_LS_HTTP_STREAM,
1418 "id=%p: Flow-control window has reached 0. No more data can be received until window is updated.",
1419 (void *)&incoming_stream->base);
1420 }
1421 }
1422
1423 if (incoming_stream->base.on_incoming_body) {
1424 err = incoming_stream->base.on_incoming_body(&incoming_stream->base, data, incoming_stream->base.user_data);
1425 if (err) {
1426 AWS_LOGF_ERROR(
1427 AWS_LS_HTTP_STREAM,
1428 "id=%p: Incoming body callback raised error %d (%s).",
1429 (void *)&incoming_stream->base,
1430 aws_last_error(),
1431 aws_error_name(aws_last_error()));
1432
1433 return AWS_OP_ERR;
1434 }
1435 }
1436
1437 return AWS_OP_SUCCESS;
1438 }
1439
1440 static int s_decoder_on_done(void *user_data) {
1441 struct aws_h1_connection *connection = user_data;
1442 struct aws_h1_stream *incoming_stream = connection->thread_data.incoming_stream;
1443 AWS_ASSERT(incoming_stream);
1444
1445 /* Ensure head was marked done */
1446 int err = s_mark_head_done(incoming_stream);
1447 if (err) {
1448 return AWS_OP_ERR;
1449 }
1450 /* If it is a informational response, we stop here, keep waiting for new response */
1451 enum aws_http_header_block header_block =
1452 aws_h1_decoder_get_header_block(connection->thread_data.incoming_stream_decoder);
1453 if (header_block == AWS_HTTP_HEADER_BLOCK_INFORMATIONAL) {
1454 return AWS_OP_SUCCESS;
1455 }
1456
1457 /* Otherwise the incoming stream is finished decoding and we will update it if needed */
1458 incoming_stream->thread_data.is_incoming_message_done = true;
1459 aws_high_res_clock_get_ticks((uint64_t *)&incoming_stream->base.metrics.receive_end_timestamp_ns);
1460 AWS_ASSERT(incoming_stream->base.metrics.receive_start_timestamp_ns != -1);
1461 AWS_ASSERT(
1462 incoming_stream->base.metrics.receive_end_timestamp_ns >=
1463 incoming_stream->base.metrics.receive_start_timestamp_ns);
1464 incoming_stream->base.metrics.receiving_duration_ns = incoming_stream->base.metrics.receive_end_timestamp_ns -
1465 incoming_stream->base.metrics.receive_start_timestamp_ns;
1466
1467 /* RFC-7230 section 6.6
1468 * After reading the final message, the connection must not read any more */
1469 if (incoming_stream->thread_data.is_final_stream) {
1470 AWS_LOGF_TRACE(
1471 AWS_LS_HTTP_CONNECTION,
1472 "id=%p: Done reading final stream, no further streams will be read.",
1473 (void *)&connection->base);
1474
1475 s_stop(
1476 connection, true /*stop_reading*/, false /*stop_writing*/, false /*schedule_shutdown*/, AWS_ERROR_SUCCESS);
1477 }
1478
1479 if (connection->base.server_data) {
1480 /* Server side */
1481 aws_http_on_incoming_request_done_fn *on_request_done = incoming_stream->base.server_data->on_request_done;
1482 if (on_request_done) {
1483 err = on_request_done(&incoming_stream->base, incoming_stream->base.user_data);
1484 if (err) {
1485 AWS_LOGF_ERROR(
1486 AWS_LS_HTTP_STREAM,
1487 "id=%p: Incoming request done callback raised error %d (%s).",
1488 (void *)&incoming_stream->base,
1489 aws_last_error(),
1490 aws_error_name(aws_last_error()));
1491 return AWS_OP_ERR;
1492 }
1493 }
1494 if (incoming_stream->thread_data.is_outgoing_message_done) {
1495 AWS_ASSERT(&incoming_stream->node == aws_linked_list_begin(&connection->thread_data.stream_list));
1496 s_stream_complete(incoming_stream, AWS_ERROR_SUCCESS);
1497 }
1498 s_set_incoming_stream_ptr(connection, NULL);
1499
1500 } else if (incoming_stream->thread_data.is_outgoing_message_done) {
1501 /* Client side */
1502 AWS_ASSERT(&incoming_stream->node == aws_linked_list_begin(&connection->thread_data.stream_list));
1503
1504 s_stream_complete(incoming_stream, AWS_ERROR_SUCCESS);
1505
1506 s_client_update_incoming_stream_ptr(connection);
1507 }
1508
1509 /* Report success even if user's on_complete() callback shuts down on the connection.
1510 * We don't want it to look like something went wrong while decoding.
1511 * The decode() function returns after each message completes,
1512 * and we won't call decode() again if the connection has been shut down */
1513 return AWS_OP_SUCCESS;
1514 }
1515
1516 /* Common new() logic for server & client */
1517 static struct aws_h1_connection *s_connection_new(
1518 struct aws_allocator *alloc,
1519 bool manual_window_management,
1520 size_t initial_window_size,
1521 const struct aws_http1_connection_options *http1_options,
1522 bool server) {
1523
1524 struct aws_h1_connection *connection = aws_mem_calloc(alloc, 1, sizeof(struct aws_h1_connection));
1525 if (!connection) {
1526 goto error_connection_alloc;
1527 }
1528
1529 connection->base.vtable = &s_h1_connection_vtable;
1530 connection->base.alloc = alloc;
1531 connection->base.channel_handler.vtable = &s_h1_connection_vtable.channel_handler_vtable;
1532 connection->base.channel_handler.alloc = alloc;
1533 connection->base.channel_handler.impl = connection;
1534 connection->base.http_version = AWS_HTTP_VERSION_1_1;
1535 connection->base.stream_manual_window_management = manual_window_management;
1536
1537 /* Init the next stream id (server must use even ids, client odd [RFC 7540 5.1.1])*/
1538 connection->base.next_stream_id = server ? 2 : 1;
1539
1540 /* 1 refcount for user */
1541 aws_atomic_init_int(&connection->base.refcount, 1);
1542
1543 if (manual_window_management) {
1544 connection->initial_stream_window_size = initial_window_size;
1545
1546 if (http1_options->read_buffer_capacity > 0) {
1547 connection->thread_data.read_buffer.capacity = http1_options->read_buffer_capacity;
1548 } else {
1549 /* User did not set capacity, choose something reasonable based on initial_window_size */
1550 /* NOTE: These values are currently guesses, we should test to find good values */
1551 const size_t clamp_min = aws_min_size(g_aws_channel_max_fragment_size * 4, /*256KB*/ 256 * 1024);
1552 const size_t clamp_max = /*1MB*/ 1 * 1024 * 1024;
1553 connection->thread_data.read_buffer.capacity =
1554 aws_max_size(clamp_min, aws_min_size(clamp_max, initial_window_size));
1555 }
1556
1557 connection->thread_data.connection_window = connection->thread_data.read_buffer.capacity;
1558 } else {
1559 /* No backpressure, keep connection window at SIZE_MAX */
1560 connection->initial_stream_window_size = SIZE_MAX;
1561 connection->thread_data.read_buffer.capacity = SIZE_MAX;
1562 connection->thread_data.connection_window = SIZE_MAX;
1563 }
1564
1565 aws_h1_encoder_init(&connection->thread_data.encoder, alloc);
1566
1567 aws_channel_task_init(
1568 &connection->outgoing_stream_task, s_outgoing_stream_task, connection, "http1_connection_outgoing_stream");
1569 aws_channel_task_init(
1570 &connection->cross_thread_work_task,
1571 s_cross_thread_work_task,
1572 connection,
1573 "http1_connection_cross_thread_work");
1574 aws_linked_list_init(&connection->thread_data.stream_list);
1575 aws_linked_list_init(&connection->thread_data.read_buffer.messages);
1576 aws_crt_statistics_http1_channel_init(&connection->thread_data.stats);
1577
1578 int err = aws_mutex_init(&connection->synced_data.lock);
1579 if (err) {
1580 AWS_LOGF_ERROR(
1581 AWS_LS_HTTP_CONNECTION,
1582 "static: Failed to initialize mutex, error %d (%s).",
1583 aws_last_error(),
1584 aws_error_name(aws_last_error()));
1585
1586 goto error_mutex;
1587 }
1588
1589 aws_linked_list_init(&connection->synced_data.new_client_stream_list);
1590 connection->synced_data.is_open = true;
1591
1592 struct aws_h1_decoder_params options = {
1593 .alloc = alloc,
1594 .is_decoding_requests = server,
1595 .user_data = connection,
1596 .vtable = s_h1_decoder_vtable,
1597 .scratch_space_initial_size = DECODER_INITIAL_SCRATCH_SIZE,
1598 };
1599 connection->thread_data.incoming_stream_decoder = aws_h1_decoder_new(&options);
1600 if (!connection->thread_data.incoming_stream_decoder) {
1601 AWS_LOGF_ERROR(
1602 AWS_LS_HTTP_CONNECTION,
1603 "static: Failed to create decoder, error %d (%s).",
1604 aws_last_error(),
1605 aws_error_name(aws_last_error()));
1606
1607 goto error_decoder;
1608 }
1609
1610 return connection;
1611
1612 error_decoder:
1613 aws_mutex_clean_up(&connection->synced_data.lock);
1614 error_mutex:
1615 aws_mem_release(alloc, connection);
1616 error_connection_alloc:
1617 return NULL;
1618 }
1619
1620 struct aws_http_connection *aws_http_connection_new_http1_1_server(
1621 struct aws_allocator *allocator,
1622 bool manual_window_management,
1623 size_t initial_window_size,
1624 const struct aws_http1_connection_options *http1_options) {
1625
1626 struct aws_h1_connection *connection =
1627 s_connection_new(allocator, manual_window_management, initial_window_size, http1_options, true /*is_server*/);
1628 if (!connection) {
1629 return NULL;
1630 }
1631
1632 connection->base.server_data = &connection->base.client_or_server_data.server;
1633
1634 return &connection->base;
1635 }
1636
1637 struct aws_http_connection *aws_http_connection_new_http1_1_client(
1638 struct aws_allocator *allocator,
1639 bool manual_window_management,
1640 size_t initial_window_size,
1641 const struct aws_http1_connection_options *http1_options) {
1642
1643 struct aws_h1_connection *connection =
1644 s_connection_new(allocator, manual_window_management, initial_window_size, http1_options, false /*is_server*/);
1645 if (!connection) {
1646 return NULL;
1647 }
1648
1649 connection->base.client_data = &connection->base.client_or_server_data.client;
1650
1651 return &connection->base;
1652 }
1653
1654 static void s_handler_destroy(struct aws_channel_handler *handler) {
1655 struct aws_h1_connection *connection = handler->impl;
1656
1657 AWS_LOGF_TRACE(AWS_LS_HTTP_CONNECTION, "id=%p: Destroying connection.", (void *)&connection->base);
1658
1659 AWS_ASSERT(aws_linked_list_empty(&connection->thread_data.stream_list));
1660 AWS_ASSERT(aws_linked_list_empty(&connection->synced_data.new_client_stream_list));
1661
1662 /* Clean up any buffered read messages. */
1663 while (!aws_linked_list_empty(&connection->thread_data.read_buffer.messages)) {
1664 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->thread_data.read_buffer.messages);
1665 struct aws_io_message *msg = AWS_CONTAINER_OF(node, struct aws_io_message, queueing_handle);
1666 aws_mem_release(msg->allocator, msg);
1667 }
1668
1669 aws_h1_decoder_destroy(connection->thread_data.incoming_stream_decoder);
1670 aws_h1_encoder_clean_up(&connection->thread_data.encoder);
1671 aws_mutex_clean_up(&connection->synced_data.lock);
1672 aws_mem_release(connection->base.alloc, connection);
1673 }
1674
1675 static void s_handler_installed(struct aws_channel_handler *handler, struct aws_channel_slot *slot) {
1676 struct aws_h1_connection *connection = handler->impl;
1677 connection->base.channel_slot = slot;
1678
1679 /* Acquire a hold on the channel to prevent its destruction until the user has
1680 * given the go-ahead via aws_http_connection_release() */
1681 aws_channel_acquire_hold(slot->channel);
1682 }
1683
1684 /* Try to send the next queued aws_io_message to the downstream handler.
1685 * This can only be called after the connection has switched protocols and becoming a midchannel handler. */
1686 static int s_try_process_next_midchannel_read_message(struct aws_h1_connection *connection, bool *out_stop_processing) {
1687 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1688 AWS_ASSERT(connection->thread_data.has_switched_protocols);
1689 AWS_ASSERT(connection->thread_data.read_state != AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE);
1690 AWS_ASSERT(!aws_linked_list_empty(&connection->thread_data.read_buffer.messages));
1691
1692 *out_stop_processing = false;
1693 struct aws_io_message *sending_msg = NULL;
1694
1695 if (!connection->base.channel_slot->adj_right) {
1696 AWS_LOGF_ERROR(
1697 AWS_LS_HTTP_CONNECTION,
1698 "id=%p: Connection has switched protocols, but no handler is installed to deal with this data.",
1699 (void *)connection);
1700
1701 return aws_raise_error(AWS_ERROR_HTTP_SWITCHED_PROTOCOLS);
1702 }
1703
1704 size_t downstream_window = aws_channel_slot_downstream_read_window(connection->base.channel_slot);
1705 if (downstream_window == 0) {
1706 AWS_LOGF_TRACE(
1707 AWS_LS_HTTP_CONNECTION,
1708 "id=%p: Downstream window is 0, cannot send switched-protocol message now.",
1709 (void *)&connection->base);
1710
1711 *out_stop_processing = true;
1712 return AWS_OP_SUCCESS;
1713 }
1714
1715 struct aws_linked_list_node *queued_msg_node = aws_linked_list_front(&connection->thread_data.read_buffer.messages);
1716 struct aws_io_message *queued_msg = AWS_CONTAINER_OF(queued_msg_node, struct aws_io_message, queueing_handle);
1717
1718 /* Note that copy_mark is used to mark the progress of partially sent messages. */
1719 AWS_ASSERT(queued_msg->message_data.len > queued_msg->copy_mark);
1720 size_t sending_bytes = aws_min_size(queued_msg->message_data.len - queued_msg->copy_mark, downstream_window);
1721
1722 AWS_ASSERT(connection->thread_data.read_buffer.pending_bytes >= sending_bytes);
1723 connection->thread_data.read_buffer.pending_bytes -= sending_bytes;
1724
1725 /* If we can't send the whole entire queued_msg, copy its data into a new aws_io_message and send that. */
1726 if (sending_bytes != queued_msg->message_data.len) {
1727 sending_msg = aws_channel_acquire_message_from_pool(
1728 connection->base.channel_slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, sending_bytes);
1729 if (!sending_msg) {
1730 goto error;
1731 }
1732
1733 aws_byte_buf_write(
1734 &sending_msg->message_data, queued_msg->message_data.buffer + queued_msg->copy_mark, sending_bytes);
1735
1736 queued_msg->copy_mark += sending_bytes;
1737
1738 AWS_LOGF_TRACE(
1739 AWS_LS_HTTP_CONNECTION,
1740 "id=%p: Sending %zu bytes switched-protocol message to downstream handler, %zu bytes remain.",
1741 (void *)&connection->base,
1742 sending_bytes,
1743 queued_msg->message_data.len - queued_msg->copy_mark);
1744
1745 /* If the last of queued_msg has been copied, it can be deleted now. */
1746 if (queued_msg->copy_mark == queued_msg->message_data.len) {
1747 aws_linked_list_remove(queued_msg_node);
1748 aws_mem_release(queued_msg->allocator, queued_msg);
1749 }
1750 } else {
1751 /* Sending all of queued_msg along. */
1752 AWS_LOGF_TRACE(
1753 AWS_LS_HTTP_CONNECTION,
1754 "id=%p: Sending full switched-protocol message of size %zu to downstream handler.",
1755 (void *)&connection->base,
1756 queued_msg->message_data.len);
1757
1758 aws_linked_list_remove(queued_msg_node);
1759 sending_msg = queued_msg;
1760 }
1761
1762 int err = aws_channel_slot_send_message(connection->base.channel_slot, sending_msg, AWS_CHANNEL_DIR_READ);
1763 if (err) {
1764 AWS_LOGF_ERROR(
1765 AWS_LS_HTTP_CONNECTION,
1766 "id=%p: Failed to send message in read direction, error %d (%s).",
1767 (void *)&connection->base,
1768 aws_last_error(),
1769 aws_error_name(aws_last_error()));
1770 goto error;
1771 }
1772
1773 return AWS_OP_SUCCESS;
1774
1775 error:
1776 if (sending_msg) {
1777 aws_mem_release(sending_msg->allocator, sending_msg);
1778 }
1779 return AWS_OP_ERR;
1780 }
1781
1782 static struct aws_http_stream *s_new_server_request_handler_stream(
1783 const struct aws_http_request_handler_options *options) {
1784
1785 struct aws_h1_connection *connection = AWS_CONTAINER_OF(options->server_connection, struct aws_h1_connection, base);
1786
1787 if (!aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel) ||
1788 !connection->thread_data.can_create_request_handler_stream) {
1789
1790 AWS_LOGF_ERROR(
1791 AWS_LS_HTTP_CONNECTION,
1792 "id=%p: aws_http_stream_new_server_request_handler() can only be called during incoming request callback.",
1793 (void *)&connection->base);
1794
1795 aws_raise_error(AWS_ERROR_INVALID_STATE);
1796 return NULL;
1797 }
1798
1799 struct aws_h1_stream *stream = aws_h1_stream_new_request_handler(options);
1800 if (!stream) {
1801 AWS_LOGF_ERROR(
1802 AWS_LS_HTTP_CONNECTION,
1803 "id=%p: Failed to create request handler stream, error %d (%s).",
1804 (void *)&connection->base,
1805 aws_last_error(),
1806 aws_error_name(aws_last_error()));
1807
1808 return NULL;
1809 }
1810
1811 /*
1812 * Success!
1813 * Everything beyond this point cannot fail
1814 */
1815
1816 /* Prevent further streams from being created until it's ok to do so. */
1817 connection->thread_data.can_create_request_handler_stream = false;
1818
1819 /* Stream is waiting for response. */
1820 aws_linked_list_push_back(&connection->thread_data.stream_list, &stream->node);
1821
1822 /* Connection owns stream, and must outlive stream */
1823 aws_http_connection_acquire(&connection->base);
1824
1825 AWS_LOGF_TRACE(
1826 AWS_LS_HTTP_STREAM,
1827 "id=%p: Created request handler stream on server connection=%p",
1828 (void *)&stream->base,
1829 (void *)&connection->base);
1830
1831 return &stream->base;
1832 }
1833
1834 /* Invokes the on_incoming_request callback and returns new stream. */
1835 static struct aws_h1_stream *s_server_invoke_on_incoming_request(struct aws_h1_connection *connection) {
1836 AWS_PRECONDITION(connection->base.server_data);
1837 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1838 AWS_PRECONDITION(!connection->thread_data.can_create_request_handler_stream);
1839 AWS_PRECONDITION(!connection->thread_data.incoming_stream);
1840
1841 /**
1842 * The user MUST create the new request-handler stream during the on-incoming-request callback.
1843 */
1844 connection->thread_data.can_create_request_handler_stream = true;
1845
1846 struct aws_http_stream *new_stream =
1847 connection->base.server_data->on_incoming_request(&connection->base, connection->base.user_data);
1848
1849 connection->thread_data.can_create_request_handler_stream = false;
1850
1851 return new_stream ? AWS_CONTAINER_OF(new_stream, struct aws_h1_stream, base) : NULL;
1852 }
1853
1854 static int s_handler_process_read_message(
1855 struct aws_channel_handler *handler,
1856 struct aws_channel_slot *slot,
1857 struct aws_io_message *message) {
1858
1859 (void)slot;
1860 struct aws_h1_connection *connection = handler->impl;
1861 const size_t message_size = message->message_data.len;
1862
1863 AWS_LOGF_TRACE(
1864 AWS_LS_HTTP_CONNECTION, "id=%p: Incoming message of size %zu.", (void *)&connection->base, message_size);
1865 if (connection->thread_data.read_state == AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE) {
1866 /* Read has stopped, ignore the data, shutdown the channel incase it has not started yet. */
1867 aws_mem_release(message->allocator, message); /* Release the message as we return success. */
1868 s_shutdown_due_to_error(connection, AWS_ERROR_HTTP_CONNECTION_CLOSED);
1869 return AWS_OP_SUCCESS;
1870 }
1871
1872 /* Shrink connection window by amount of data received. See comments at variable's
1873 * declaration site on why we use this instead of the official `aws_channel_slot.window_size`. */
1874 if (message_size > connection->thread_data.connection_window) {
1875 /* This error shouldn't be possible, but this is all complicated so check at runtime to be safe. */
1876 AWS_LOGF_ERROR(
1877 AWS_LS_HTTP_CONNECTION,
1878 "id=%p: Internal error. Message exceeds connection's window.",
1879 (void *)&connection->base);
1880 return aws_raise_error(AWS_ERROR_INVALID_STATE);
1881 }
1882 connection->thread_data.connection_window -= message_size;
1883
1884 /* Push message into queue of buffered messages */
1885 aws_linked_list_push_back(&connection->thread_data.read_buffer.messages, &message->queueing_handle);
1886 connection->thread_data.read_buffer.pending_bytes += message_size;
1887
1888 /* Try to process messages in queue */
1889 aws_h1_connection_try_process_read_messages(connection);
1890 return AWS_OP_SUCCESS;
1891 }
1892
1893 void aws_h1_connection_try_process_read_messages(struct aws_h1_connection *connection) {
1894 int error_code = 0;
1895 /* Protect against this function being called recursively. */
1896 if (connection->thread_data.is_processing_read_messages) {
1897 return;
1898 }
1899 connection->thread_data.is_processing_read_messages = true;
1900
1901 /* Process queued messages */
1902 while (!aws_linked_list_empty(&connection->thread_data.read_buffer.messages)) {
1903 if (connection->thread_data.read_state == AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE) {
1904 AWS_LOGF_ERROR(
1905 AWS_LS_HTTP_CONNECTION,
1906 "id=%p: Cannot process message because connection is shutting down.",
1907 (void *)&connection->base);
1908
1909 aws_raise_error(AWS_ERROR_HTTP_CONNECTION_CLOSED);
1910 goto shutdown;
1911 }
1912
1913 bool stop_processing = false;
1914
1915 /* When connection has switched protocols, messages are processed very differently.
1916 * We need to do this check in the middle of the normal processing loop,
1917 * in case the switch happens in the middle of processing a message. */
1918 if (connection->thread_data.has_switched_protocols) {
1919 if (s_try_process_next_midchannel_read_message(connection, &stop_processing)) {
1920 goto shutdown;
1921 }
1922 } else {
1923 if (s_try_process_next_stream_read_message(connection, &stop_processing)) {
1924 goto shutdown;
1925 }
1926 }
1927
1928 /* Break out of loop if we can't process any more data */
1929 if (stop_processing) {
1930 break;
1931 }
1932 }
1933
1934 if (connection->thread_data.read_state == AWS_CONNECTION_READ_SHUTTING_DOWN &&
1935 connection->thread_data.read_buffer.pending_bytes == 0) {
1936 /* Done processing the pending buffer. */
1937 aws_raise_error(connection->thread_data.pending_shutdown_error_code);
1938 goto shutdown;
1939 }
1940
1941 /* Increment connection window, if necessary */
1942 if (s_update_connection_window(connection)) {
1943 goto shutdown;
1944 }
1945
1946 connection->thread_data.is_processing_read_messages = false;
1947 return;
1948
1949 shutdown:
1950 error_code = aws_last_error();
1951 if (connection->thread_data.read_state == AWS_CONNECTION_READ_SHUTTING_DOWN &&
1952 connection->thread_data.pending_shutdown_error_code != 0) {
1953 error_code = connection->thread_data.pending_shutdown_error_code;
1954 }
1955 if (error_code == 0) {
1956 /* Graceful shutdown, don't stop writing yet. */
1957 s_stop(connection, true /*stop_reading*/, false /*stop_writing*/, true /*schedule_shutdown*/, error_code);
1958 } else {
1959 s_shutdown_due_to_error(connection, aws_last_error());
1960 }
1961 }
1962
1963 /* Try to process the next queued aws_io_message as normal HTTP data for an aws_http_stream.
1964 * This MUST NOT be called if the connection has switched protocols and become a midchannel handler. */
1965 static int s_try_process_next_stream_read_message(struct aws_h1_connection *connection, bool *out_stop_processing) {
1966 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1967 AWS_ASSERT(!connection->thread_data.has_switched_protocols);
1968 AWS_ASSERT(connection->thread_data.read_state != AWS_CONNECTION_READ_SHUT_DOWN_COMPLETE);
1969 AWS_ASSERT(!aws_linked_list_empty(&connection->thread_data.read_buffer.messages));
1970
1971 *out_stop_processing = false;
1972
1973 /* Ensure that an incoming stream exists to receive the data */
1974 if (!connection->thread_data.incoming_stream) {
1975 if (aws_http_connection_is_client(&connection->base)) {
1976 /* Client side */
1977 AWS_LOGF_ERROR(
1978 AWS_LS_HTTP_CONNECTION,
1979 "id=%p: Cannot process message because no requests are currently awaiting response, closing "
1980 "connection.",
1981 (void *)&connection->base);
1982
1983 return aws_raise_error(AWS_ERROR_INVALID_STATE);
1984
1985 } else {
1986 /* Server side.
1987 * Invoke on-incoming-request callback. The user MUST create a new stream from this callback.
1988 * The new stream becomes the current incoming stream */
1989 s_set_incoming_stream_ptr(connection, s_server_invoke_on_incoming_request(connection));
1990 if (!connection->thread_data.incoming_stream) {
1991 AWS_LOGF_ERROR(
1992 AWS_LS_HTTP_CONNECTION,
1993 "id=%p: Incoming request callback failed to provide a new stream, last error %d (%s). "
1994 "Closing connection.",
1995 (void *)&connection->base,
1996 aws_last_error(),
1997 aws_error_name(aws_last_error()));
1998
1999 return AWS_OP_ERR;
2000 }
2001 }
2002 }
2003
2004 struct aws_h1_stream *incoming_stream = connection->thread_data.incoming_stream;
2005
2006 /* Stop processing if stream's window reaches 0. */
2007 const uint64_t stream_window = incoming_stream->thread_data.stream_window;
2008 if (stream_window == 0) {
2009 AWS_LOGF_TRACE(
2010 AWS_LS_HTTP_CONNECTION,
2011 "id=%p: HTTP-stream's window is 0, cannot process message now.",
2012 (void *)&connection->base);
2013 *out_stop_processing = true;
2014 return AWS_OP_SUCCESS;
2015 }
2016
2017 struct aws_linked_list_node *queued_msg_node = aws_linked_list_front(&connection->thread_data.read_buffer.messages);
2018 struct aws_io_message *queued_msg = AWS_CONTAINER_OF(queued_msg_node, struct aws_io_message, queueing_handle);
2019
2020 /* Note that copy_mark is used to mark the progress of partially decoded messages */
2021 struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&queued_msg->message_data);
2022 aws_byte_cursor_advance(&message_cursor, queued_msg->copy_mark);
2023
2024 /* Don't process more data than the stream's window can accept.
2025 *
2026 * TODO: Let the decoder know about stream-window size so it can stop itself,
2027 * instead of limiting the amount of data we feed into the decoder at a time.
2028 * This would be more optimal, AND avoid an edge-case where the stream-window goes
2029 * to 0 as the body ends, and the connection can't proceed to the trailing headers.
2030 */
2031 message_cursor.len = (size_t)aws_min_u64(message_cursor.len, stream_window);
2032
2033 const size_t prev_cursor_len = message_cursor.len;
2034
2035 /* Set some decoder state, based on current stream */
2036 aws_h1_decoder_set_logging_id(connection->thread_data.incoming_stream_decoder, incoming_stream);
2037
2038 bool body_headers_ignored = incoming_stream->base.request_method == AWS_HTTP_METHOD_HEAD;
2039 aws_h1_decoder_set_body_headers_ignored(connection->thread_data.incoming_stream_decoder, body_headers_ignored);
2040
2041 if (incoming_stream->base.metrics.receive_start_timestamp_ns == -1) {
2042 /* That's the first time for the stream receives any message */
2043 aws_high_res_clock_get_ticks((uint64_t *)&incoming_stream->base.metrics.receive_start_timestamp_ns);
2044 if (incoming_stream->base.client_data &&
2045 incoming_stream->base.client_data->response_first_byte_timeout_task.fn != NULL) {
2046 /* There is an outstanding response timeout task, as we already received the data, we can cancel it now. We
2047 * are safe to do it as we always on connection thread to schedule the task or cancel it */
2048 struct aws_event_loop *connection_loop = aws_channel_get_event_loop(connection->base.channel_slot->channel);
2049 /* The task will be zeroed out within the call */
2050 aws_event_loop_cancel_task(
2051 connection_loop, &incoming_stream->base.client_data->response_first_byte_timeout_task);
2052 }
2053 }
2054
2055 /* As decoder runs, it invokes the internal s_decoder_X callbacks, which in turn invoke user callbacks.
2056 * The decoder will stop once it hits the end of the request/response OR the end of the message data. */
2057 if (aws_h1_decode(connection->thread_data.incoming_stream_decoder, &message_cursor)) {
2058 AWS_LOGF_ERROR(
2059 AWS_LS_HTTP_CONNECTION,
2060 "id=%p: Message processing failed, error %d (%s). Closing connection.",
2061 (void *)&connection->base,
2062 aws_last_error(),
2063 aws_error_name(aws_last_error()));
2064
2065 return AWS_OP_ERR;
2066 }
2067
2068 size_t bytes_processed = prev_cursor_len - message_cursor.len;
2069 queued_msg->copy_mark += bytes_processed;
2070
2071 AWS_ASSERT(connection->thread_data.read_buffer.pending_bytes >= bytes_processed);
2072 connection->thread_data.read_buffer.pending_bytes -= bytes_processed;
2073
2074 AWS_LOGF_TRACE(
2075 AWS_LS_HTTP_CONNECTION,
2076 "id=%p: Decoded %zu bytes of message, %zu bytes remain.",
2077 (void *)&connection->base,
2078 bytes_processed,
2079 queued_msg->message_data.len - queued_msg->copy_mark);
2080
2081 /* If the last of queued_msg has been processed, it can be deleted now.
2082 * Otherwise, it remains in the queue for further processing later. */
2083 if (queued_msg->copy_mark == queued_msg->message_data.len) {
2084 aws_linked_list_remove(&queued_msg->queueing_handle);
2085 aws_mem_release(queued_msg->allocator, queued_msg);
2086 }
2087
2088 return AWS_OP_SUCCESS;
2089 }
2090
2091 static int s_handler_process_write_message(
2092 struct aws_channel_handler *handler,
2093 struct aws_channel_slot *slot,
2094 struct aws_io_message *message) {
2095
2096 struct aws_h1_connection *connection = handler->impl;
2097
2098 if (connection->thread_data.is_writing_stopped) {
2099 aws_raise_error(AWS_ERROR_HTTP_CONNECTION_CLOSED);
2100 goto error;
2101 }
2102
2103 if (!connection->thread_data.has_switched_protocols) {
2104 aws_raise_error(AWS_ERROR_INVALID_STATE);
2105 goto error;
2106 }
2107
2108 /* Pass the message right along. */
2109 int err = aws_channel_slot_send_message(slot, message, AWS_CHANNEL_DIR_WRITE);
2110 if (err) {
2111 goto error;
2112 }
2113
2114 return AWS_OP_SUCCESS;
2115
2116 error:
2117 AWS_LOGF_ERROR(
2118 AWS_LS_HTTP_CONNECTION,
2119 "id=%p: Destroying write message without passing it along, error %d (%s)",
2120 (void *)&connection->base,
2121 aws_last_error(),
2122 aws_error_name(aws_last_error()));
2123
2124 if (message->on_completion) {
2125 message->on_completion(connection->base.channel_slot->channel, message, aws_last_error(), message->user_data);
2126 }
2127 aws_mem_release(message->allocator, message);
2128 s_shutdown_due_to_error(connection, aws_last_error());
2129 return AWS_OP_SUCCESS;
2130 }
2131
2132 static int s_handler_increment_read_window(
2133 struct aws_channel_handler *handler,
2134 struct aws_channel_slot *slot,
2135 size_t size) {
2136
2137 (void)slot;
2138 struct aws_h1_connection *connection = handler->impl;
2139
2140 if (!connection->thread_data.has_switched_protocols) {
2141 AWS_LOGF_ERROR(
2142 AWS_LS_HTTP_CONNECTION,
2143 "id=%p: HTTP connection cannot have a downstream handler without first switching protocols",
2144 (void *)&connection->base);
2145
2146 aws_raise_error(AWS_ERROR_INVALID_STATE);
2147 goto error;
2148 }
2149
2150 AWS_LOGF_TRACE(
2151 AWS_LS_HTTP_CONNECTION,
2152 "id=%p: Handler in read direction incremented read window by %zu. Sending queued messages, if any.",
2153 (void *)&connection->base,
2154 size);
2155
2156 /* Send along any queued messages, and increment connection's window if necessary */
2157 aws_h1_connection_try_process_read_messages(connection);
2158 return AWS_OP_SUCCESS;
2159
2160 error:
2161 s_shutdown_due_to_error(connection, aws_last_error());
2162 return AWS_OP_SUCCESS;
2163 }
2164
2165 static void s_initialize_read_delay_shutdown(struct aws_h1_connection *connection, int error_code) {
2166
2167 AWS_LOGF_DEBUG(
2168 AWS_LS_HTTP_CONNECTION,
2169 "id=%p: Connection still have pending data to be delivered during shutdown. Wait until downstream "
2170 "reads the data.",
2171 (void *)&connection->base);
2172
2173 AWS_LOGF_TRACE(
2174 AWS_LS_HTTP_CONNECTION,
2175 "id=%p: Current window stats: connection=%zu, stream=%" PRIu64 " buffer=%zu/%zu",
2176 (void *)&connection->base,
2177 connection->thread_data.connection_window,
2178 connection->thread_data.incoming_stream ? connection->thread_data.incoming_stream->thread_data.stream_window
2179 : 0,
2180 connection->thread_data.read_buffer.pending_bytes,
2181 connection->thread_data.read_buffer.capacity);
2182
2183 /* Still have data buffered in connection, wait for it to be processed */
2184 connection->thread_data.read_state = AWS_CONNECTION_READ_SHUTTING_DOWN;
2185 connection->thread_data.pending_shutdown_error_code = error_code;
2186 /* Try to process messages in queue */
2187 aws_h1_connection_try_process_read_messages(connection);
2188 }
2189
2190 static int s_handler_shutdown(
2191 struct aws_channel_handler *handler,
2192 struct aws_channel_slot *slot,
2193 enum aws_channel_direction dir,
2194 int error_code,
2195 bool free_scarce_resources_immediately) {
2196
2197 (void)free_scarce_resources_immediately;
2198 struct aws_h1_connection *connection = handler->impl;
2199
2200 AWS_LOGF_TRACE(
2201 AWS_LS_HTTP_CONNECTION,
2202 "id=%p: Channel shutting down in %s direction with error code %d (%s).",
2203 (void *)&connection->base,
2204 (dir == AWS_CHANNEL_DIR_READ) ? "read" : "write",
2205 error_code,
2206 aws_error_name(error_code));
2207
2208 if (dir == AWS_CHANNEL_DIR_READ) {
2209 /* This call ensures that no further streams will be created or worked on. */
2210 if (!free_scarce_resources_immediately && connection->thread_data.read_state == AWS_CONNECTION_READ_OPEN &&
2211 connection->thread_data.read_buffer.pending_bytes > 0) {
2212 s_initialize_read_delay_shutdown(connection, error_code);
2213 /* Return success, and wait for the buffered data to be processed to propagate the shutdown. */
2214 return AWS_OP_SUCCESS;
2215 }
2216 s_stop(connection, true /*stop_reading*/, false /*stop_writing*/, false /*schedule_shutdown*/, error_code);
2217 } else /* dir == AWS_CHANNEL_DIR_WRITE */ {
2218
2219 s_stop(connection, false /*stop_reading*/, true /*stop_writing*/, false /*schedule_shutdown*/, error_code);
2220
2221 /* Mark all pending streams as complete. */
2222 int stream_error_code = error_code == AWS_ERROR_SUCCESS ? AWS_ERROR_HTTP_CONNECTION_CLOSED : error_code;
2223
2224 while (!aws_linked_list_empty(&connection->thread_data.stream_list)) {
2225 struct aws_linked_list_node *node = aws_linked_list_front(&connection->thread_data.stream_list);
2226 s_stream_complete(AWS_CONTAINER_OF(node, struct aws_h1_stream, node), stream_error_code);
2227 }
2228
2229 /* It's OK to access synced_data.new_client_stream_list without holding the lock because
2230 * no more streams can be added after s_stop() has been invoked. */
2231 while (!aws_linked_list_empty(&connection->synced_data.new_client_stream_list)) {
2232 struct aws_linked_list_node *node = aws_linked_list_front(&connection->synced_data.new_client_stream_list);
2233 s_stream_complete(AWS_CONTAINER_OF(node, struct aws_h1_stream, node), stream_error_code);
2234 }
2235 }
2236
2237 aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, free_scarce_resources_immediately);
2238 return AWS_OP_SUCCESS;
2239 }
2240
2241 static size_t s_handler_initial_window_size(struct aws_channel_handler *handler) {
2242 struct aws_h1_connection *connection = handler->impl;
2243 return connection->thread_data.connection_window;
2244 }
2245
2246 static size_t s_handler_message_overhead(struct aws_channel_handler *handler) {
2247 (void)handler;
2248 return 0;
2249 }
2250
2251 static void s_reset_statistics(struct aws_channel_handler *handler) {
2252 struct aws_h1_connection *connection = handler->impl;
2253
2254 aws_crt_statistics_http1_channel_reset(&connection->thread_data.stats);
2255 }
2256
2257 static void s_pull_up_stats_timestamps(struct aws_h1_connection *connection) {
2258 uint64_t now_ns = 0;
2259 if (aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns)) {
2260 return;
2261 }
2262
2263 if (connection->thread_data.outgoing_stream) {
2264 s_add_time_measurement_to_stats(
2265 connection->thread_data.outgoing_stream_timestamp_ns,
2266 now_ns,
2267 &connection->thread_data.stats.pending_outgoing_stream_ms);
2268
2269 connection->thread_data.outgoing_stream_timestamp_ns = now_ns;
2270
2271 connection->thread_data.stats.current_outgoing_stream_id =
2272 aws_http_stream_get_id(&connection->thread_data.outgoing_stream->base);
2273 }
2274
2275 if (connection->thread_data.incoming_stream) {
2276 s_add_time_measurement_to_stats(
2277 connection->thread_data.incoming_stream_timestamp_ns,
2278 now_ns,
2279 &connection->thread_data.stats.pending_incoming_stream_ms);
2280
2281 connection->thread_data.incoming_stream_timestamp_ns = now_ns;
2282
2283 connection->thread_data.stats.current_incoming_stream_id =
2284 aws_http_stream_get_id(&connection->thread_data.incoming_stream->base);
2285 }
2286 }
2287
2288 static void s_gather_statistics(struct aws_channel_handler *handler, struct aws_array_list *stats) {
2289 struct aws_h1_connection *connection = handler->impl;
2290
2291 /* TODO: Need update the way we calculate statistics, to account for user-controlled pauses.
2292 * If user is adding chunks 1 by 1, there can naturally be a gap in the upload.
2293 * If the user lets the stream-window go to zero, there can naturally be a gap in the download. */
2294 s_pull_up_stats_timestamps(connection);
2295
2296 void *stats_base = &connection->thread_data.stats;
2297 aws_array_list_push_back(stats, &stats_base);
2298 }
2299
2300 struct aws_crt_statistics_http1_channel *aws_h1_connection_get_statistics(struct aws_http_connection *connection) {
2301 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->channel_slot->channel));
2302
2303 struct aws_h1_connection *h1_conn = (void *)connection;
2304
2305 return &h1_conn->thread_data.stats;
2306 }
2307
2308 struct aws_h1_window_stats aws_h1_connection_window_stats(struct aws_http_connection *connection_base) {
2309 struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
2310 struct aws_h1_window_stats stats = {
2311 .connection_window = connection->thread_data.connection_window,
2312 .buffer_capacity = connection->thread_data.read_buffer.capacity,
2313 .buffer_pending_bytes = connection->thread_data.read_buffer.pending_bytes,
2314 .recent_window_increments = connection->thread_data.recent_window_increments,
2315 .has_incoming_stream = connection->thread_data.incoming_stream != NULL,
2316 .stream_window = connection->thread_data.incoming_stream
2317 ? connection->thread_data.incoming_stream->thread_data.stream_window
2318 : 0,
2319 };
2320
2321 /* Resets each time it's queried */
2322 connection->thread_data.recent_window_increments = 0;
2323
2324 return stats;
2325 }