Debian Codegraph @

crt/aws-c-http/source/h2_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
6 #include <aws/http/private/h2_connection.h>
7 #include <aws/http/private/h2_stream.h>
8
9 #include <aws/http/private/h2_decoder.h>
10 #include <aws/http/private/h2_stream.h>
11 #include <aws/http/private/strutil.h>
12
13 #include <aws/common/clock.h>
14 #include <aws/common/logging.h>
15
16 #ifdef _MSC_VER
17 # pragma warning(disable : 4204) /* non-constant aggregate initializer */
18 #endif
19
20 /* Apple toolchains such as xcode and swiftpm define the DEBUG symbol. undef it here so we can actually use the token */
21 #undef DEBUG
22
23 #define CONNECTION_LOGF(level, connection, text, ...) \
24 AWS_LOGF_##level(AWS_LS_HTTP_CONNECTION, "id=%p: " text, (void *)(connection), __VA_ARGS__)
25 #define CONNECTION_LOG(level, connection, text) CONNECTION_LOGF(level, connection, "%s", text)
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_connection_make_request(
54 struct aws_http_connection *client_connection,
55 const struct aws_http_make_request_options *options);
56 static void s_connection_close(struct aws_http_connection *connection_base);
57 static void s_connection_stop_new_request(struct aws_http_connection *connection_base);
58 static bool s_connection_is_open(const struct aws_http_connection *connection_base);
59 static bool s_connection_new_requests_allowed(const struct aws_http_connection *connection_base);
60 static void s_connection_update_window(struct aws_http_connection *connection_base, uint32_t increment_size);
61 static int s_connection_change_settings(
62 struct aws_http_connection *connection_base,
63 const struct aws_http2_setting *settings_array,
64 size_t num_settings,
65 aws_http2_on_change_settings_complete_fn *on_completed,
66 void *user_data);
67 static int s_connection_send_ping(
68 struct aws_http_connection *connection_base,
69 const struct aws_byte_cursor *optional_opaque_data,
70 aws_http2_on_ping_complete_fn *on_completed,
71 void *user_data);
72 static void s_connection_send_goaway(
73 struct aws_http_connection *connection_base,
74 uint32_t http2_error,
75 bool allow_more_streams,
76 const struct aws_byte_cursor *optional_debug_data);
77 static int s_connection_get_sent_goaway(
78 struct aws_http_connection *connection_base,
79 uint32_t *out_http2_error,
80 uint32_t *out_last_stream_id);
81 static int s_connection_get_received_goaway(
82 struct aws_http_connection *connection_base,
83 uint32_t *out_http2_error,
84 uint32_t *out_last_stream_id);
85 static void s_connection_get_local_settings(
86 const struct aws_http_connection *connection_base,
87 struct aws_http2_setting out_settings[AWS_HTTP2_SETTINGS_COUNT]);
88 static void s_connection_get_remote_settings(
89 const struct aws_http_connection *connection_base,
90 struct aws_http2_setting out_settings[AWS_HTTP2_SETTINGS_COUNT]);
91
92 static void s_cross_thread_work_task(struct aws_channel_task *task, void *arg, enum aws_task_status status);
93 static void s_outgoing_frames_task(struct aws_channel_task *task, void *arg, enum aws_task_status status);
94 static int s_encode_outgoing_frames_queue(struct aws_h2_connection *connection, struct aws_byte_buf *output);
95 static int s_encode_data_from_outgoing_streams(struct aws_h2_connection *connection, struct aws_byte_buf *output);
96 static int s_record_closed_stream(
97 struct aws_h2_connection *connection,
98 uint32_t stream_id,
99 enum aws_h2_stream_closed_when closed_when);
100 static void s_stream_complete(struct aws_h2_connection *connection, struct aws_h2_stream *stream, int error_code);
101 static void s_write_outgoing_frames(struct aws_h2_connection *connection, bool first_try);
102 static void s_finish_shutdown(struct aws_h2_connection *connection);
103 static void s_send_goaway(
104 struct aws_h2_connection *connection,
105 uint32_t h2_error_code,
106 bool allow_more_streams,
107 const struct aws_byte_cursor *optional_debug_data);
108 static struct aws_h2_pending_settings *s_new_pending_settings(
109 struct aws_allocator *allocator,
110 bool add_initial_window,
111 size_t initial_window_size,
112 const struct aws_http2_setting *settings_array,
113 size_t num_settings,
114 aws_http2_on_change_settings_complete_fn *on_completed,
115 void *user_data);
116
117 static struct aws_h2err s_decoder_on_headers_begin(uint32_t stream_id, void *userdata);
118 static struct aws_h2err s_decoder_on_headers_i(
119 uint32_t stream_id,
120 const struct aws_http_header *header,
121 enum aws_http_header_name name_enum,
122 enum aws_http_header_block block_type,
123 void *userdata);
124 static struct aws_h2err s_decoder_on_headers_end(
125 uint32_t stream_id,
126 bool malformed,
127 enum aws_http_header_block block_type,
128 void *userdata);
129 static struct aws_h2err s_decoder_on_push_promise(uint32_t stream_id, uint32_t promised_stream_id, void *userdata);
130 static struct aws_h2err s_decoder_on_data_begin(
131 uint32_t stream_id,
132 uint32_t payload_len,
133 uint32_t total_padding_bytes,
134 bool end_stream,
135 void *userdata);
136 static struct aws_h2err s_decoder_on_data_i(uint32_t stream_id, struct aws_byte_cursor data, void *userdata);
137 static struct aws_h2err s_decoder_on_end_stream(uint32_t stream_id, void *userdata);
138 static struct aws_h2err s_decoder_on_rst_stream(uint32_t stream_id, uint32_t h2_error_code, void *userdata);
139 static struct aws_h2err s_decoder_on_ping_ack(uint8_t opaque_data[AWS_HTTP2_PING_DATA_SIZE], void *userdata);
140 static struct aws_h2err s_decoder_on_ping(uint8_t opaque_data[AWS_HTTP2_PING_DATA_SIZE], void *userdata);
141 static struct aws_h2err s_decoder_on_settings(
142 const struct aws_http2_setting *settings_array,
143 size_t num_settings,
144 void *userdata);
145 static struct aws_h2err s_decoder_on_settings_ack(void *userdata);
146 static struct aws_h2err s_decoder_on_window_update(uint32_t stream_id, uint32_t window_size_increment, void *userdata);
147 struct aws_h2err s_decoder_on_goaway(
148 uint32_t last_stream,
149 uint32_t error_code,
150 struct aws_byte_cursor debug_data,
151 void *userdata);
152 static void s_reset_statistics(struct aws_channel_handler *handler);
153 static void s_gather_statistics(struct aws_channel_handler *handler, struct aws_array_list *stats);
154
155 static struct aws_http_connection_vtable s_h2_connection_vtable = {
156 .channel_handler_vtable =
157 {
158 .process_read_message = s_handler_process_read_message,
159 .process_write_message = s_handler_process_write_message,
160 .increment_read_window = s_handler_increment_read_window,
161 .shutdown = s_handler_shutdown,
162 .initial_window_size = s_handler_initial_window_size,
163 .message_overhead = s_handler_message_overhead,
164 .destroy = s_handler_destroy,
165 .reset_statistics = s_reset_statistics,
166 .gather_statistics = s_gather_statistics,
167 },
168
169 .on_channel_handler_installed = s_handler_installed,
170 .make_request = s_connection_make_request,
171 .new_server_request_handler_stream = NULL,
172 .stream_send_response = NULL,
173 .close = s_connection_close,
174 .stop_new_requests = s_connection_stop_new_request,
175 .is_open = s_connection_is_open,
176 .new_requests_allowed = s_connection_new_requests_allowed,
177 .update_window = s_connection_update_window,
178 .change_settings = s_connection_change_settings,
179 .send_ping = s_connection_send_ping,
180 .send_goaway = s_connection_send_goaway,
181 .get_sent_goaway = s_connection_get_sent_goaway,
182 .get_received_goaway = s_connection_get_received_goaway,
183 .get_local_settings = s_connection_get_local_settings,
184 .get_remote_settings = s_connection_get_remote_settings,
185 };
186
187 static const struct aws_h2_decoder_vtable s_h2_decoder_vtable = {
188 .on_headers_begin = s_decoder_on_headers_begin,
189 .on_headers_i = s_decoder_on_headers_i,
190 .on_headers_end = s_decoder_on_headers_end,
191 .on_push_promise_begin = s_decoder_on_push_promise,
192 .on_data_begin = s_decoder_on_data_begin,
193 .on_data_i = s_decoder_on_data_i,
194 .on_end_stream = s_decoder_on_end_stream,
195 .on_rst_stream = s_decoder_on_rst_stream,
196 .on_ping_ack = s_decoder_on_ping_ack,
197 .on_ping = s_decoder_on_ping,
198 .on_settings = s_decoder_on_settings,
199 .on_settings_ack = s_decoder_on_settings_ack,
200 .on_window_update = s_decoder_on_window_update,
201 .on_goaway = s_decoder_on_goaway,
202 };
203
204 static void s_lock_synced_data(struct aws_h2_connection *connection) {
205 int err = aws_mutex_lock(&connection->synced_data.lock);
206 AWS_ASSERT(!err && "lock failed");
207 (void)err;
208 }
209
210 static void s_unlock_synced_data(struct aws_h2_connection *connection) {
211 int err = aws_mutex_unlock(&connection->synced_data.lock);
212 AWS_ASSERT(!err && "unlock failed");
213 (void)err;
214 }
215
216 static void s_acquire_stream_and_connection_lock(struct aws_h2_stream *stream, struct aws_h2_connection *connection) {
217 int err = aws_mutex_lock(&stream->synced_data.lock);
218 err |= aws_mutex_lock(&connection->synced_data.lock);
219 AWS_ASSERT(!err && "lock connection and stream failed");
220 (void)err;
221 }
222
223 static void s_release_stream_and_connection_lock(struct aws_h2_stream *stream, struct aws_h2_connection *connection) {
224 int err = aws_mutex_unlock(&connection->synced_data.lock);
225 err |= aws_mutex_unlock(&stream->synced_data.lock);
226 AWS_ASSERT(!err && "unlock connection and stream failed");
227 (void)err;
228 }
229
230 static void s_add_time_measurement_to_stats(uint64_t start_ns, uint64_t end_ns, uint64_t *output_ms) {
231 if (end_ns > start_ns) {
232 *output_ms += aws_timestamp_convert(end_ns - start_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_MILLIS, NULL);
233 } else {
234 *output_ms = 0;
235 }
236 }
237
238 /**
239 * Internal function for bringing connection to a stop.
240 * Invoked multiple times, including when:
241 * - Channel is shutting down in the read direction.
242 * - Channel is shutting down in the write direction.
243 * - An error occurs that will shutdown the channel.
244 * - User wishes to close the connection (this is the only case where the function may run off-thread).
245 */
246 static void s_stop(
247 struct aws_h2_connection *connection,
248 bool stop_reading,
249 bool stop_writing,
250 bool schedule_shutdown,
251 int error_code) {
252
253 AWS_ASSERT(stop_reading || stop_writing || schedule_shutdown); /* You are required to stop at least 1 thing */
254
255 if (stop_reading) {
256 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
257 connection->thread_data.is_reading_stopped = true;
258 }
259
260 if (stop_writing) {
261 AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
262 connection->thread_data.is_writing_stopped = true;
263 }
264
265 /* Even if we're not scheduling shutdown just yet (ex: sent final request but waiting to read final response)
266 * we don't consider the connection "open" anymore so user can't create more streams */
267 { /* BEGIN CRITICAL SECTION */
268 s_lock_synced_data(connection);
269 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
270 connection->synced_data.is_open = false;
271 s_unlock_synced_data(connection);
272 } /* END CRITICAL SECTION */
273
274 if (schedule_shutdown) {
275 AWS_LOGF_INFO(
276 AWS_LS_HTTP_CONNECTION,
277 "id=%p: Shutting down connection with error code %d (%s).",
278 (void *)&connection->base,
279 error_code,
280 aws_error_name(error_code));
281
282 aws_channel_shutdown(connection->base.channel_slot->channel, error_code);
283 }
284 }
285
286 void aws_h2_connection_shutdown_due_to_write_err(struct aws_h2_connection *connection, int error_code) {
287 AWS_PRECONDITION(error_code);
288 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
289
290 if (connection->thread_data.channel_shutdown_waiting_for_goaway_to_be_written) {
291 /* If shutdown is waiting for writes to complete, but writes are now broken,
292 * then we must finish shutdown now */
293 s_finish_shutdown(connection);
294 } else {
295 s_stop(connection, false /*stop_reading*/, true /*stop_writing*/, true /*schedule_shutdown*/, error_code);
296 }
297 }
298
299 /* Common new() logic for server & client */
300 static struct aws_h2_connection *s_connection_new(
301 struct aws_allocator *alloc,
302 bool manual_window_management,
303 size_t initial_window_size,
304 const struct aws_http2_connection_options *http2_options,
305 bool server) {
306
307 AWS_PRECONDITION(http2_options);
308
309 struct aws_h2_connection *connection = aws_mem_calloc(alloc, 1, sizeof(struct aws_h2_connection));
310 if (!connection) {
311 return NULL;
312 }
313 connection->base.vtable = &s_h2_connection_vtable;
314 connection->base.alloc = alloc;
315 connection->base.channel_handler.vtable = &s_h2_connection_vtable.channel_handler_vtable;
316 connection->base.channel_handler.alloc = alloc;
317 connection->base.channel_handler.impl = connection;
318 connection->base.http_version = AWS_HTTP_VERSION_2;
319 /* Init the next stream id (server must use even ids, client odd [RFC 7540 5.1.1])*/
320 connection->base.next_stream_id = (server ? 2 : 1);
321 /* Stream window management */
322 connection->base.stream_manual_window_management = manual_window_management;
323
324 /* Connection window management */
325 connection->conn_manual_window_management = http2_options->conn_manual_window_management;
326 connection->on_goaway_received = http2_options->on_goaway_received;
327 connection->on_remote_settings_change = http2_options->on_remote_settings_change;
328
329 aws_channel_task_init(
330 &connection->cross_thread_work_task, s_cross_thread_work_task, connection, "HTTP/2 cross-thread work");
331
332 aws_channel_task_init(
333 &connection->outgoing_frames_task, s_outgoing_frames_task, connection, "HTTP/2 outgoing frames");
334
335 /* 1 refcount for user */
336 aws_atomic_init_int(&connection->base.refcount, 1);
337 uint32_t max_stream_id = AWS_H2_STREAM_ID_MAX;
338 connection->synced_data.goaway_sent_last_stream_id = max_stream_id + 1;
339 connection->synced_data.goaway_received_last_stream_id = max_stream_id + 1;
340
341 aws_linked_list_init(&connection->synced_data.pending_stream_list);
342 aws_linked_list_init(&connection->synced_data.pending_frame_list);
343 aws_linked_list_init(&connection->synced_data.pending_settings_list);
344 aws_linked_list_init(&connection->synced_data.pending_ping_list);
345 aws_linked_list_init(&connection->synced_data.pending_goaway_list);
346
347 aws_linked_list_init(&connection->thread_data.outgoing_streams_list);
348 aws_linked_list_init(&connection->thread_data.pending_settings_queue);
349 aws_linked_list_init(&connection->thread_data.pending_ping_queue);
350 aws_linked_list_init(&connection->thread_data.stalled_window_streams_list);
351 aws_linked_list_init(&connection->thread_data.waiting_streams_list);
352 aws_linked_list_init(&connection->thread_data.outgoing_frames_queue);
353
354 if (aws_mutex_init(&connection->synced_data.lock)) {
355 CONNECTION_LOGF(
356 ERROR, connection, "Mutex init error %d (%s).", aws_last_error(), aws_error_name(aws_last_error()));
357 goto error;
358 }
359
360 if (aws_hash_table_init(
361 &connection->thread_data.active_streams_map, alloc, 8, aws_hash_ptr, aws_ptr_eq, NULL, NULL)) {
362
363 CONNECTION_LOGF(
364 ERROR, connection, "Hashtable init error %d (%s).", aws_last_error(), aws_error_name(aws_last_error()));
365 goto error;
366 }
367 size_t max_closed_streams = AWS_HTTP2_DEFAULT_MAX_CLOSED_STREAMS;
368 if (http2_options->max_closed_streams) {
369 max_closed_streams = http2_options->max_closed_streams;
370 }
371
372 connection->thread_data.closed_streams =
373 aws_cache_new_fifo(alloc, aws_hash_ptr, aws_ptr_eq, NULL, NULL, max_closed_streams);
374 if (!connection->thread_data.closed_streams) {
375 CONNECTION_LOGF(
376 ERROR, connection, "FIFO cache init error %d (%s).", aws_last_error(), aws_error_name(aws_last_error()));
377 goto error;
378 }
379
380 /* Initialize the value of settings */
381 memcpy(connection->thread_data.settings_peer, aws_h2_settings_initial, sizeof(aws_h2_settings_initial));
382 memcpy(connection->thread_data.settings_self, aws_h2_settings_initial, sizeof(aws_h2_settings_initial));
383
384 memcpy(connection->synced_data.settings_peer, aws_h2_settings_initial, sizeof(aws_h2_settings_initial));
385 memcpy(connection->synced_data.settings_self, aws_h2_settings_initial, sizeof(aws_h2_settings_initial));
386
387 connection->thread_data.window_size_peer = AWS_H2_INIT_WINDOW_SIZE;
388 connection->thread_data.window_size_self = AWS_H2_INIT_WINDOW_SIZE;
389
390 /* Default to half of the initial window size */
391 if (http2_options->conn_window_size_threshold_to_send_update) {
392 connection->window_size_threshold_to_send_update = http2_options->conn_window_size_threshold_to_send_update;
393 } else {
394 connection->window_size_threshold_to_send_update = (uint32_t)(AWS_H2_INIT_WINDOW_SIZE / 2);
395 }
396 /* Cap it to int32 max, since stream window allows negative. */
397 connection->stream_window_size_threshold_to_send_update =
398 aws_min_u32(http2_options->stream_window_size_threshold_to_send_update, INT32_MAX);
399
400 connection->thread_data.goaway_received_last_stream_id = AWS_H2_STREAM_ID_MAX;
401 connection->thread_data.goaway_sent_last_stream_id = AWS_H2_STREAM_ID_MAX;
402
403 aws_crt_statistics_http2_channel_init(&connection->thread_data.stats);
404 connection->thread_data.stats.was_inactive = true; /* Start with non active streams */
405
406 connection->synced_data.is_open = true;
407 connection->synced_data.new_stream_error_code = AWS_ERROR_SUCCESS;
408
409 /* Create a new decoder */
410 struct aws_h2_decoder_params params = {
411 .alloc = alloc,
412 .vtable = &s_h2_decoder_vtable,
413 .userdata = connection,
414 .logging_id = connection,
415 .is_server = server,
416 };
417 connection->thread_data.decoder = aws_h2_decoder_new(&params);
418 if (!connection->thread_data.decoder) {
419 CONNECTION_LOGF(
420 ERROR, connection, "Decoder init error %d (%s)", aws_last_error(), aws_error_name(aws_last_error()));
421 goto error;
422 }
423
424 if (aws_h2_frame_encoder_init(&connection->thread_data.encoder, alloc, &connection->base)) {
425 CONNECTION_LOGF(
426 ERROR, connection, "Encoder init error %d (%s)", aws_last_error(), aws_error_name(aws_last_error()));
427 goto error;
428 }
429 /* User data from connection base is not ready until the handler installed */
430 connection->thread_data.init_pending_settings = s_new_pending_settings(
431 connection->base.alloc,
432 manual_window_management &&
433 initial_window_size != AWS_H2_INIT_WINDOW_SIZE, /* If the initial window size equals to the initial window
434 size, don't need to send an extra one. */
435 initial_window_size,
436 http2_options->initial_settings_array,
437 http2_options->num_initial_settings,
438 http2_options->on_initial_settings_completed,
439 NULL /* user_data is set later... */);
440 if (!connection->thread_data.init_pending_settings) {
441 goto error;
442 }
443 /* We enqueue the inital settings when handler get installed */
444 return connection;
445
446 error:
447 s_handler_destroy(&connection->base.channel_handler);
448
449 return NULL;
450 }
451
452 struct aws_http_connection *aws_http_connection_new_http2_server(
453 struct aws_allocator *allocator,
454 bool manual_window_management,
455 size_t initial_window_size,
456 const struct aws_http2_connection_options *http2_options) {
457
458 struct aws_h2_connection *connection =
459 s_connection_new(allocator, manual_window_management, initial_window_size, http2_options, true);
460 if (!connection) {
461 return NULL;
462 }
463
464 connection->base.server_data = &connection->base.client_or_server_data.server;
465
466 return &connection->base;
467 }
468
469 struct aws_http_connection *aws_http_connection_new_http2_client(
470 struct aws_allocator *allocator,
471 bool manual_window_management,
472 size_t initial_window_size,
473 const struct aws_http2_connection_options *http2_options) {
474
475 struct aws_h2_connection *connection =
476 s_connection_new(allocator, manual_window_management, initial_window_size, http2_options, false);
477 if (!connection) {
478 return NULL;
479 }
480
481 connection->base.client_data = &connection->base.client_or_server_data.client;
482
483 return &connection->base;
484 }
485
486 static void s_handler_destroy(struct aws_channel_handler *handler) {
487 struct aws_h2_connection *connection = handler->impl;
488 CONNECTION_LOG(TRACE, connection, "Destroying connection");
489
490 /* No streams should be left in internal datastructures */
491 AWS_ASSERT(
492 !aws_hash_table_is_valid(&connection->thread_data.active_streams_map) ||
493 aws_hash_table_get_entry_count(&connection->thread_data.active_streams_map) == 0);
494
495 AWS_ASSERT(aws_linked_list_empty(&connection->thread_data.waiting_streams_list));
496 AWS_ASSERT(aws_linked_list_empty(&connection->thread_data.stalled_window_streams_list));
497 AWS_ASSERT(aws_linked_list_empty(&connection->thread_data.outgoing_streams_list));
498 AWS_ASSERT(aws_linked_list_empty(&connection->synced_data.pending_stream_list));
499 AWS_ASSERT(aws_linked_list_empty(&connection->synced_data.pending_frame_list));
500 AWS_ASSERT(aws_linked_list_empty(&connection->synced_data.pending_settings_list));
501 AWS_ASSERT(aws_linked_list_empty(&connection->synced_data.pending_ping_list));
502 AWS_ASSERT(aws_linked_list_empty(&connection->synced_data.pending_goaway_list));
503 AWS_ASSERT(aws_linked_list_empty(&connection->thread_data.pending_ping_queue));
504 AWS_ASSERT(aws_linked_list_empty(&connection->thread_data.pending_settings_queue));
505
506 /* Clean up any unsent frames and structures */
507 struct aws_linked_list *outgoing_frames_queue = &connection->thread_data.outgoing_frames_queue;
508 while (!aws_linked_list_empty(outgoing_frames_queue)) {
509 struct aws_linked_list_node *node = aws_linked_list_pop_front(outgoing_frames_queue);
510 struct aws_h2_frame *frame = AWS_CONTAINER_OF(node, struct aws_h2_frame, node);
511 aws_h2_frame_destroy(frame);
512 }
513 if (connection->thread_data.init_pending_settings) {
514 /* if initial settings were never sent, we need to clear the memory here */
515 aws_mem_release(connection->base.alloc, connection->thread_data.init_pending_settings);
516 }
517 aws_h2_decoder_destroy(connection->thread_data.decoder);
518 aws_h2_frame_encoder_clean_up(&connection->thread_data.encoder);
519 aws_hash_table_clean_up(&connection->thread_data.active_streams_map);
520 aws_cache_destroy(connection->thread_data.closed_streams);
521 aws_mutex_clean_up(&connection->synced_data.lock);
522 aws_mem_release(connection->base.alloc, connection);
523 }
524
525 static struct aws_h2_pending_settings *s_new_pending_settings(
526 struct aws_allocator *allocator,
527 bool add_initial_window,
528 size_t initial_window_size,
529 const struct aws_http2_setting *settings_array,
530 size_t passin_num_settings,
531 aws_http2_on_change_settings_complete_fn *on_completed,
532 void *user_data) {
533 size_t num_settings = passin_num_settings;
534 if (add_initial_window) {
535 if (initial_window_size > AWS_H2_WINDOW_UPDATE_MAX) {
536 AWS_LOGF_ERROR(
537 AWS_LS_HTTP_CONNECTION,
538 "Initial window size %zu is larger than max %d",
539 initial_window_size,
540 AWS_H2_WINDOW_UPDATE_MAX);
541 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
542 return NULL;
543 }
544 num_settings++;
545 }
546
547 size_t settings_storage_size = sizeof(struct aws_http2_setting) * num_settings;
548 struct aws_h2_pending_settings *pending_settings;
549 uint8_t *settings_storage;
550 if (!aws_mem_acquire_many(
551 allocator,
552 2,
553 &pending_settings,
554 sizeof(struct aws_h2_pending_settings),
555 &settings_storage,
556 settings_storage_size)) {
557 return NULL;
558 }
559
560 AWS_ZERO_STRUCT(*pending_settings);
561 /* We buffer the settings up, incase the caller has freed them when the ACK arrives */
562 pending_settings->settings_array = (void *)settings_storage;
563 if (add_initial_window) {
564 /* insert the initial window size settings to the first of all the settings. */
565 pending_settings->settings_array[0].id = AWS_HTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
566 pending_settings->settings_array[0].value = (uint32_t)initial_window_size;
567 /* Move the storage pointer to the second in the list */
568 settings_storage = settings_storage + sizeof(struct aws_http2_setting);
569 }
570 if (settings_array) {
571 /* copy all passin settings to the settings storage. */
572 memcpy(settings_storage, settings_array, passin_num_settings * sizeof(struct aws_http2_setting));
573 }
574 pending_settings->num_settings = num_settings;
575 pending_settings->on_completed = on_completed;
576 pending_settings->user_data = user_data;
577
578 return pending_settings;
579 }
580
581 static struct aws_h2_pending_ping *s_new_pending_ping(
582 struct aws_allocator *allocator,
583 const struct aws_byte_cursor *optional_opaque_data,
584 const uint64_t started_time,
585 void *user_data,
586 aws_http2_on_ping_complete_fn *on_completed) {
587
588 struct aws_h2_pending_ping *pending_ping = aws_mem_calloc(allocator, 1, sizeof(struct aws_h2_pending_ping));
589 if (!pending_ping) {
590 return NULL;
591 }
592 if (optional_opaque_data) {
593 memcpy(pending_ping->opaque_data, optional_opaque_data->ptr, AWS_HTTP2_PING_DATA_SIZE);
594 }
595 pending_ping->started_time = started_time;
596 pending_ping->on_completed = on_completed;
597 pending_ping->user_data = user_data;
598 return pending_ping;
599 }
600
601 static struct aws_h2_pending_goaway *s_new_pending_goaway(
602 struct aws_allocator *allocator,
603 uint32_t http2_error,
604 bool allow_more_streams,
605 const struct aws_byte_cursor *optional_debug_data) {
606
607 struct aws_byte_cursor debug_data;
608 AWS_ZERO_STRUCT(debug_data);
609 if (optional_debug_data) {
610 debug_data = *optional_debug_data;
611 }
612 struct aws_h2_pending_goaway *pending_goaway;
613 void *debug_data_storage;
614 /* mem acquire cannot fail anymore */
615 aws_mem_acquire_many(
616 allocator, 2, &pending_goaway, sizeof(struct aws_h2_pending_goaway), &debug_data_storage, debug_data.len);
617 if (debug_data.len) {
618 memcpy(debug_data_storage, debug_data.ptr, debug_data.len);
619 debug_data.ptr = debug_data_storage;
620 }
621 pending_goaway->debug_data = debug_data;
622 pending_goaway->http2_error = http2_error;
623 pending_goaway->allow_more_streams = allow_more_streams;
624 return pending_goaway;
625 }
626
627 void aws_h2_connection_enqueue_outgoing_frame(struct aws_h2_connection *connection, struct aws_h2_frame *frame) {
628 AWS_PRECONDITION(frame->type != AWS_H2_FRAME_T_DATA);
629 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
630
631 if (frame->high_priority) {
632 /* Check from the head of the queue, and find a node with normal priority, and insert before it */
633 struct aws_linked_list_node *iter = aws_linked_list_begin(&connection->thread_data.outgoing_frames_queue);
634 /* one past the last element */
635 const struct aws_linked_list_node *end = aws_linked_list_end(&connection->thread_data.outgoing_frames_queue);
636 while (iter != end) {
637 struct aws_h2_frame *frame_i = AWS_CONTAINER_OF(iter, struct aws_h2_frame, node);
638 if (connection->thread_data.current_outgoing_frame == frame_i) {
639 iter = iter->next;
640 continue;
641 }
642 if (!frame_i->high_priority) {
643 break;
644 }
645 iter = iter->next;
646 }
647 aws_linked_list_insert_before(iter, &frame->node);
648 } else {
649 aws_linked_list_push_back(&connection->thread_data.outgoing_frames_queue, &frame->node);
650 }
651 }
652
653 static void s_on_channel_write_complete(
654 struct aws_channel *channel,
655 struct aws_io_message *message,
656 int err_code,
657 void *user_data) {
658
659 (void)message;
660 struct aws_h2_connection *connection = user_data;
661
662 if (err_code) {
663 CONNECTION_LOGF(ERROR, connection, "Message did not write to network, error %s", aws_error_name(err_code));
664 aws_h2_connection_shutdown_due_to_write_err(connection, err_code);
665 return;
666 }
667
668 CONNECTION_LOG(TRACE, connection, "Message finished writing to network. Rescheduling outgoing frame task");
669
670 /* To avoid wasting memory, we only want ONE of our written aws_io_messages in the channel at a time.
671 * Therefore, we wait until it's written to the network before trying to send another
672 * by running the outgoing-frame-task again.
673 *
674 * We also want to share the network with other channels.
675 * Therefore, when the write completes, we SCHEDULE the outgoing-frame-task
676 * to run again instead of calling the function directly.
677 * This way, if the message completes synchronously,
678 * we're not hogging the network by writing message after message in a tight loop */
679 aws_channel_schedule_task_now(channel, &connection->outgoing_frames_task);
680 }
681
682 static void s_outgoing_frames_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
683 (void)task;
684
685 if (status != AWS_TASK_STATUS_RUN_READY) {
686 return;
687 }
688
689 struct aws_h2_connection *connection = arg;
690 s_write_outgoing_frames(connection, false /*first_try*/);
691 }
692
693 static void s_write_outgoing_frames(struct aws_h2_connection *connection, bool first_try) {
694 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
695 AWS_PRECONDITION(connection->thread_data.is_outgoing_frames_task_active);
696
697 struct aws_channel_slot *channel_slot = connection->base.channel_slot;
698 struct aws_linked_list *outgoing_frames_queue = &connection->thread_data.outgoing_frames_queue;
699 struct aws_linked_list *outgoing_streams_list = &connection->thread_data.outgoing_streams_list;
700
701 if (connection->thread_data.is_writing_stopped) {
702 return;
703 }
704
705 /* Determine whether there's work to do, and end task immediately if there's not.
706 * Note that we stop writing DATA frames if the channel is trying to shut down */
707 bool has_control_frames = !aws_linked_list_empty(outgoing_frames_queue);
708 bool has_data_frames = !aws_linked_list_empty(outgoing_streams_list);
709 bool may_write_data_frames = (connection->thread_data.window_size_peer > AWS_H2_MIN_WINDOW_SIZE) &&
710 !connection->thread_data.channel_shutdown_waiting_for_goaway_to_be_written;
711 bool will_write = has_control_frames || (has_data_frames && may_write_data_frames);
712
713 if (!will_write) {
714 if (!first_try) {
715 CONNECTION_LOGF(
716 TRACE,
717 connection,
718 "Outgoing frames task stopped. has_control_frames:%d has_data_frames:%d may_write_data_frames:%d",
719 has_control_frames,
720 has_data_frames,
721 may_write_data_frames);
722 }
723
724 connection->thread_data.is_outgoing_frames_task_active = false;
725
726 if (connection->thread_data.channel_shutdown_waiting_for_goaway_to_be_written) {
727 s_finish_shutdown(connection);
728 }
729
730 return;
731 }
732
733 if (first_try) {
734 CONNECTION_LOG(TRACE, connection, "Starting outgoing frames task");
735 }
736
737 /* Acquire aws_io_message, that we will attempt to fill up */
738 struct aws_io_message *msg = aws_channel_slot_acquire_max_message_for_write(channel_slot);
739 if (AWS_UNLIKELY(!msg)) {
740 CONNECTION_LOG(ERROR, connection, "Failed to acquire message from pool, closing connection.");
741 goto error;
742 }
743
744 /* Set up callback so we can send another message when this one completes */
745 msg->on_completion = s_on_channel_write_complete;
746 msg->user_data = connection;
747
748 CONNECTION_LOGF(
749 TRACE,
750 connection,
751 "Outgoing frames task acquired message with %zu bytes available",
752 msg->message_data.capacity - msg->message_data.len);
753
754 /* Write as many frames from outgoing_frames_queue as possible. */
755 if (s_encode_outgoing_frames_queue(connection, &msg->message_data)) {
756 goto error;
757 }
758
759 /* If outgoing_frames_queue emptied, and connection is running normally,
760 * then write as many DATA frames from outgoing_streams_list as possible. */
761 if (aws_linked_list_empty(outgoing_frames_queue) && may_write_data_frames) {
762 if (s_encode_data_from_outgoing_streams(connection, &msg->message_data)) {
763 goto error;
764 }
765 }
766
767 if (msg->message_data.len) {
768 /* Write message to channel.
769 * outgoing_frames_task will resume when message completes. */
770 CONNECTION_LOGF(TRACE, connection, "Outgoing frames task sending message of size %zu", msg->message_data.len);
771
772 if (aws_channel_slot_send_message(channel_slot, msg, AWS_CHANNEL_DIR_WRITE)) {
773 CONNECTION_LOGF(
774 ERROR,
775 connection,
776 "Failed to send channel message: %s. Closing connection.",
777 aws_error_name(aws_last_error()));
778
779 goto error;
780 }
781 } else {
782 /* Message is empty, warn that no work is being done and reschedule the task to try again next tick.
783 * It's likely that body isn't ready, so body streaming function has no data to write yet.
784 * If this scenario turns out to be common we should implement a "pause" feature. */
785 CONNECTION_LOG(WARN, connection, "Outgoing frames task sent no data, will try again next tick.");
786
787 aws_mem_release(msg->allocator, msg);
788
789 aws_channel_schedule_task_now(channel_slot->channel, &connection->outgoing_frames_task);
790 }
791 return;
792
793 error:;
794 int error_code = aws_last_error();
795
796 if (msg) {
797 aws_mem_release(msg->allocator, msg);
798 }
799
800 aws_h2_connection_shutdown_due_to_write_err(connection, error_code);
801 }
802
803 /* Write as many frames from outgoing_frames_queue as possible (contains all non-DATA frames) */
804 static int s_encode_outgoing_frames_queue(struct aws_h2_connection *connection, struct aws_byte_buf *output) {
805
806 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
807 struct aws_linked_list *outgoing_frames_queue = &connection->thread_data.outgoing_frames_queue;
808
809 /* Write as many frames from outgoing_frames_queue as possible. */
810 while (!aws_linked_list_empty(outgoing_frames_queue)) {
811 struct aws_linked_list_node *frame_node = aws_linked_list_front(outgoing_frames_queue);
812 struct aws_h2_frame *frame = AWS_CONTAINER_OF(frame_node, struct aws_h2_frame, node);
813 connection->thread_data.current_outgoing_frame = frame;
814 bool frame_complete;
815 if (aws_h2_encode_frame(&connection->thread_data.encoder, frame, output, &frame_complete)) {
816 CONNECTION_LOGF(
817 ERROR,
818 connection,
819 "Error encoding frame: type=%s stream=%" PRIu32 " error=%s",
820 aws_h2_frame_type_to_str(frame->type),
821 frame->stream_id,
822 aws_error_name(aws_last_error()));
823 return AWS_OP_ERR;
824 }
825
826 if (!frame_complete) {
827 if (output->len == 0) {
828 /* We're in trouble if an empty message isn't big enough for this frame to do any work with */
829 CONNECTION_LOGF(
830 ERROR,
831 connection,
832 "Message is too small for encoder. frame-type=%s stream=%" PRIu32 " available-space=%zu",
833 aws_h2_frame_type_to_str(frame->type),
834 frame->stream_id,
835 output->capacity);
836 aws_raise_error(AWS_ERROR_INVALID_STATE);
837 return AWS_OP_ERR;
838 }
839
840 CONNECTION_LOG(TRACE, connection, "Outgoing frames task filled message, and has more frames to send later");
841 break;
842 }
843
844 /* Done encoding frame, pop from queue and cleanup*/
845 aws_linked_list_remove(frame_node);
846 aws_h2_frame_destroy(frame);
847 connection->thread_data.current_outgoing_frame = NULL;
848 }
849
850 return AWS_OP_SUCCESS;
851 }
852
853 /* Write as many DATA frames from outgoing_streams_list as possible. */
854 static int s_encode_data_from_outgoing_streams(struct aws_h2_connection *connection, struct aws_byte_buf *output) {
855
856 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
857 struct aws_linked_list *outgoing_streams_list = &connection->thread_data.outgoing_streams_list;
858 if (aws_linked_list_empty(outgoing_streams_list)) {
859 return AWS_OP_SUCCESS;
860 }
861 struct aws_linked_list *stalled_window_streams_list = &connection->thread_data.stalled_window_streams_list;
862 struct aws_linked_list *waiting_streams_list = &connection->thread_data.waiting_streams_list;
863
864 /* If a stream stalls, put it in this list until the function ends so we don't keep trying to read from it.
865 * We put it back at the end of function. */
866 struct aws_linked_list stalled_streams_list;
867 aws_linked_list_init(&stalled_streams_list);
868
869 int aws_error_code = 0;
870
871 /* We simply round-robin through streams, instead of using stream priority.
872 * Respecting priority is not required (RFC-7540 5.3), so we're ignoring it for now. This also keeps use safe
873 * from priority DOS attacks: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-9513 */
874 while (!aws_linked_list_empty(outgoing_streams_list)) {
875 if (connection->thread_data.window_size_peer <= AWS_H2_MIN_WINDOW_SIZE) {
876 CONNECTION_LOGF(
877 DEBUG,
878 connection,
879 "Peer connection's flow-control window is too small now %" PRIu32
880 ". Connection will stop sending DATA until "
881 "WINDOW_UPDATE is received.",
882 connection->thread_data.window_size_peer);
883 goto done;
884 }
885
886 /* Stop looping if message is so full it's not worth the bother */
887 size_t space_available = output->capacity - output->len;
888 size_t worth_trying_threshold = AWS_H2_FRAME_PREFIX_SIZE * 2;
889 if (space_available < worth_trying_threshold) {
890 CONNECTION_LOG(TRACE, connection, "Outgoing frames task filled message, and has more frames to send later");
891 goto done;
892 }
893
894 struct aws_linked_list_node *node = aws_linked_list_pop_front(outgoing_streams_list);
895 struct aws_h2_stream *stream = AWS_CONTAINER_OF(node, struct aws_h2_stream, node);
896
897 /* Ask stream to encode a data frame.
898 * Stream may complete itself as a result of encoding its data,
899 * in which case it will vanish from the connection's datastructures as a side-effect of this call.
900 * But if stream has more data to send, push it back into the appropriate list. */
901 int data_encode_status;
902 if (aws_h2_stream_encode_data_frame(stream, &connection->thread_data.encoder, output, &data_encode_status)) {
903
904 aws_error_code = aws_last_error();
905 CONNECTION_LOGF(
906 ERROR,
907 connection,
908 "Connection error while encoding DATA on stream %" PRIu32 ", %s",
909 stream->base.id,
910 aws_error_name(aws_error_code));
911 goto done;
912 }
913
914 /* If stream has more data, push it into the appropriate list. */
915 switch (data_encode_status) {
916 case AWS_H2_DATA_ENCODE_COMPLETE:
917 break;
918 case AWS_H2_DATA_ENCODE_ONGOING:
919 aws_linked_list_push_back(outgoing_streams_list, node);
920 break;
921 case AWS_H2_DATA_ENCODE_ONGOING_BODY_STREAM_STALLED:
922 aws_linked_list_push_back(&stalled_streams_list, node);
923 break;
924 case AWS_H2_DATA_ENCODE_ONGOING_WAITING_FOR_WRITES:
925 stream->thread_data.waiting_for_writes = true;
926 aws_linked_list_push_back(waiting_streams_list, node);
927 break;
928 case AWS_H2_DATA_ENCODE_ONGOING_WINDOW_STALLED:
929 aws_linked_list_push_back(stalled_window_streams_list, node);
930 AWS_H2_STREAM_LOG(
931 DEBUG,
932 stream,
933 "Peer stream's flow-control window is too small. Data frames on this stream will not be sent until "
934 "WINDOW_UPDATE. ");
935 break;
936 default:
937 CONNECTION_LOG(ERROR, connection, "Data encode status is invalid.");
938 aws_error_code = AWS_ERROR_INVALID_STATE;
939 }
940 }
941
942 done:
943 /* Return any stalled streams to outgoing_streams_list */
944 while (!aws_linked_list_empty(&stalled_streams_list)) {
945 aws_linked_list_push_back(outgoing_streams_list, aws_linked_list_pop_front(&stalled_streams_list));
946 }
947
948 if (aws_error_code) {
949 return aws_raise_error(aws_error_code);
950 }
951
952 if (aws_linked_list_empty(outgoing_streams_list)) {
953 /* transition from something to write -> nothing to write */
954 uint64_t now_ns = 0;
955 aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns);
956 s_add_time_measurement_to_stats(
957 connection->thread_data.outgoing_timestamp_ns,
958 now_ns,
959 &connection->thread_data.stats.pending_outgoing_stream_ms);
960 }
961
962 return AWS_OP_SUCCESS;
963 }
964
965 /* If the outgoing-frames-task isn't scheduled, run it immediately. */
966 void aws_h2_try_write_outgoing_frames(struct aws_h2_connection *connection) {
967 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
968
969 if (connection->thread_data.is_outgoing_frames_task_active) {
970 return;
971 }
972
973 connection->thread_data.is_outgoing_frames_task_active = true;
974 s_write_outgoing_frames(connection, true /*first_try*/);
975 }
976
977 /**
978 * Returns successfully and sets `out_stream` if stream is currently active.
979 * Returns successfully and sets `out_stream` to NULL if the frame should be ignored.
980 * Returns failed aws_h2err if it is a connection error to receive this frame.
981 */
982 struct aws_h2err s_get_active_stream_for_incoming_frame(
983 struct aws_h2_connection *connection,
984 uint32_t stream_id,
985 enum aws_h2_frame_type frame_type,
986 struct aws_h2_stream **out_stream) {
987
988 *out_stream = NULL;
989
990 /* Check active streams */
991 struct aws_hash_element *found = NULL;
992 const void *stream_id_key = (void *)(size_t)stream_id;
993 aws_hash_table_find(&connection->thread_data.active_streams_map, stream_id_key, &found);
994 if (found) {
995 /* Found it! return */
996 *out_stream = found->value;
997 return AWS_H2ERR_SUCCESS;
998 }
999
1000 bool client_initiated = (stream_id % 2) == 1;
1001 bool self_initiated_stream = client_initiated && (connection->base.client_data != NULL);
1002 bool peer_initiated_stream = !self_initiated_stream;
1003
1004 if ((self_initiated_stream && stream_id >= connection->base.next_stream_id) ||
1005 (peer_initiated_stream && stream_id > connection->thread_data.latest_peer_initiated_stream_id)) {
1006 /* Illegal to receive frames for a stream in the idle state (stream doesn't exist yet)
1007 * (except server receiving HEADERS to start a stream, but that's handled elsewhere) */
1008 CONNECTION_LOGF(
1009 ERROR,
1010 connection,
1011 "Illegal to receive %s frame on stream id=%" PRIu32 " state=IDLE",
1012 aws_h2_frame_type_to_str(frame_type),
1013 stream_id);
1014 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1015 }
1016
1017 if (peer_initiated_stream && stream_id > connection->thread_data.goaway_sent_last_stream_id) {
1018 /* Once GOAWAY sent, ignore frames for peer-initiated streams whose id > last-stream-id */
1019 CONNECTION_LOGF(
1020 TRACE,
1021 connection,
1022 "Ignoring %s frame on stream id=%" PRIu32 " because GOAWAY sent with last-stream-id=%" PRIu32,
1023 aws_h2_frame_type_to_str(frame_type),
1024 stream_id,
1025 connection->thread_data.goaway_sent_last_stream_id);
1026
1027 return AWS_H2ERR_SUCCESS;
1028 }
1029
1030 void *cached_value = NULL;
1031 /* Stream is closed, check whether it's legal for a few more frames to trickle in */
1032 if (aws_cache_find(connection->thread_data.closed_streams, stream_id_key, &cached_value)) {
1033 return aws_h2err_from_last_error();
1034 }
1035 if (cached_value) {
1036 if (frame_type == AWS_H2_FRAME_T_PRIORITY) {
1037 /* If we support PRIORITY, do something here. Right now just ignore it */
1038 return AWS_H2ERR_SUCCESS;
1039 }
1040 enum aws_h2_stream_closed_when closed_when = (enum aws_h2_stream_closed_when)(size_t)cached_value;
1041 switch (closed_when) {
1042 case AWS_H2_STREAM_CLOSED_WHEN_BOTH_SIDES_END_STREAM:
1043 /* WINDOW_UPDATE or RST_STREAM frames can be received ... for a short period after
1044 * a DATA or HEADERS frame containing an END_STREAM flag is sent.
1045 * Endpoints MUST ignore WINDOW_UPDATE or RST_STREAM frames received in this state */
1046 if (frame_type == AWS_H2_FRAME_T_WINDOW_UPDATE || frame_type == AWS_H2_FRAME_T_RST_STREAM) {
1047 CONNECTION_LOGF(
1048 TRACE,
1049 connection,
1050 "Ignoring %s frame on stream id=%" PRIu32 " because END_STREAM flag was recently sent.",
1051 aws_h2_frame_type_to_str(frame_type),
1052 stream_id);
1053
1054 return AWS_H2ERR_SUCCESS;
1055 } else {
1056 CONNECTION_LOGF(
1057 ERROR,
1058 connection,
1059 "Illegal to receive %s frame on stream id=%" PRIu32 " after END_STREAM has been received.",
1060 aws_h2_frame_type_to_str(frame_type),
1061 stream_id);
1062
1063 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_STREAM_CLOSED);
1064 }
1065 break;
1066 case AWS_H2_STREAM_CLOSED_WHEN_RST_STREAM_RECEIVED:
1067 /* An endpoint that receives any frame other than PRIORITY after receiving a RST_STREAM
1068 * MUST treat that as a stream error (Section 5.4.2) of type STREAM_CLOSED */
1069 CONNECTION_LOGF(
1070 ERROR,
1071 connection,
1072 "Illegal to receive %s frame on stream id=%" PRIu32 " after RST_STREAM has been received",
1073 aws_h2_frame_type_to_str(frame_type),
1074 stream_id);
1075 struct aws_h2_frame *rst_stream =
1076 aws_h2_frame_new_rst_stream(connection->base.alloc, stream_id, AWS_HTTP2_ERR_STREAM_CLOSED);
1077 if (!rst_stream) {
1078 CONNECTION_LOGF(
1079 ERROR, connection, "Error creating RST_STREAM frame, %s", aws_error_name(aws_last_error()));
1080 return aws_h2err_from_last_error();
1081 }
1082 aws_h2_connection_enqueue_outgoing_frame(connection, rst_stream);
1083 return AWS_H2ERR_SUCCESS;
1084 case AWS_H2_STREAM_CLOSED_WHEN_RST_STREAM_SENT:
1085 /* An endpoint MUST ignore frames that it receives on closed streams after it has sent a RST_STREAM
1086 * frame */
1087 CONNECTION_LOGF(
1088 TRACE,
1089 connection,
1090 "Ignoring %s frame on stream id=%" PRIu32 " because RST_STREAM was recently sent.",
1091 aws_h2_frame_type_to_str(frame_type),
1092 stream_id);
1093
1094 return AWS_H2ERR_SUCCESS;
1095 break;
1096 default:
1097 CONNECTION_LOGF(
1098 ERROR, connection, "Invalid state fo cached closed stream, stream id=%" PRIu32, stream_id);
1099 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_INTERNAL_ERROR);
1100 break;
1101 }
1102 }
1103 if (frame_type == AWS_H2_FRAME_T_PRIORITY) {
1104 /* ignored if the stream has been removed from the dependency tree */
1105 return AWS_H2ERR_SUCCESS;
1106 }
1107
1108 /* Stream closed (purged from closed_streams, or implicitly closed when its ID was skipped) */
1109 CONNECTION_LOGF(
1110 ERROR,
1111 connection,
1112 "Illegal to receive %s frame on stream id=%" PRIu32
1113 ", no memory of closed stream (ID skipped, or removed from cache)",
1114 aws_h2_frame_type_to_str(frame_type),
1115 stream_id);
1116
1117 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1118 }
1119
1120 /* Decoder callbacks */
1121
1122 struct aws_h2err s_decoder_on_headers_begin(uint32_t stream_id, void *userdata) {
1123 struct aws_h2_connection *connection = userdata;
1124
1125 if (connection->base.server_data) {
1126 /* Server would create new request-handler stream... */
1127 return aws_h2err_from_aws_code(AWS_ERROR_UNIMPLEMENTED);
1128 }
1129
1130 struct aws_h2_stream *stream;
1131 struct aws_h2err err =
1132 s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_HEADERS, &stream);
1133 if (aws_h2err_failed(err)) {
1134 return err;
1135 }
1136
1137 if (stream) {
1138 err = aws_h2_stream_on_decoder_headers_begin(stream);
1139 if (aws_h2err_failed(err)) {
1140 return err;
1141 }
1142 }
1143
1144 return AWS_H2ERR_SUCCESS;
1145 }
1146
1147 struct aws_h2err s_decoder_on_headers_i(
1148 uint32_t stream_id,
1149 const struct aws_http_header *header,
1150 enum aws_http_header_name name_enum,
1151 enum aws_http_header_block block_type,
1152 void *userdata) {
1153
1154 struct aws_h2_connection *connection = userdata;
1155 struct aws_h2_stream *stream;
1156 struct aws_h2err err =
1157 s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_HEADERS, &stream);
1158 if (aws_h2err_failed(err)) {
1159 return err;
1160 }
1161
1162 if (stream) {
1163 err = aws_h2_stream_on_decoder_headers_i(stream, header, name_enum, block_type);
1164 if (aws_h2err_failed(err)) {
1165 return err;
1166 }
1167 }
1168
1169 return AWS_H2ERR_SUCCESS;
1170 }
1171
1172 struct aws_h2err s_decoder_on_headers_end(
1173 uint32_t stream_id,
1174 bool malformed,
1175 enum aws_http_header_block block_type,
1176 void *userdata) {
1177
1178 struct aws_h2_connection *connection = userdata;
1179 struct aws_h2_stream *stream;
1180 struct aws_h2err err =
1181 s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_HEADERS, &stream);
1182 if (aws_h2err_failed(err)) {
1183 return err;
1184 }
1185
1186 if (stream) {
1187 err = aws_h2_stream_on_decoder_headers_end(stream, malformed, block_type);
1188 if (aws_h2err_failed(err)) {
1189 return err;
1190 }
1191 }
1192
1193 return AWS_H2ERR_SUCCESS;
1194 }
1195
1196 struct aws_h2err s_decoder_on_push_promise(uint32_t stream_id, uint32_t promised_stream_id, void *userdata) {
1197 struct aws_h2_connection *connection = userdata;
1198 AWS_ASSERT(connection->base.client_data); /* decoder has already enforced this */
1199 AWS_ASSERT(promised_stream_id % 2 == 0); /* decoder has already enforced this */
1200
1201 /* The identifier of a newly established stream MUST be numerically greater
1202 * than all streams that the initiating endpoint has opened or reserved (RFC-7540 5.1.1) */
1203 if (promised_stream_id <= connection->thread_data.latest_peer_initiated_stream_id) {
1204 CONNECTION_LOGF(
1205 ERROR,
1206 connection,
1207 "Newly promised stream ID %" PRIu32 " must be higher than previously established ID %" PRIu32,
1208 promised_stream_id,
1209 connection->thread_data.latest_peer_initiated_stream_id);
1210 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1211 }
1212 connection->thread_data.latest_peer_initiated_stream_id = promised_stream_id;
1213
1214 /* If we ever fully support PUSH_PROMISE, this is where we'd add the
1215 * promised_stream_id to some reserved_streams datastructure */
1216
1217 struct aws_h2_stream *stream;
1218 struct aws_h2err err =
1219 s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_PUSH_PROMISE, &stream);
1220 if (aws_h2err_failed(err)) {
1221 return err;
1222 }
1223
1224 if (stream) {
1225 err = aws_h2_stream_on_decoder_push_promise(stream, promised_stream_id);
1226 if (aws_h2err_failed(err)) {
1227 return err;
1228 }
1229 }
1230
1231 return AWS_H2ERR_SUCCESS;
1232 }
1233
1234 /* Calculate the capped windows update delta */
1235 uint32_t aws_h2_calculate_cap_window_update_delta(int64_t current_window, uint64_t pending_update_size) {
1236
1237 /* UPDATE_WINDOW frame can't exceed AWS_H2_WINDOW_UPDATE_MAX (aka INT32_MAX) */
1238 int64_t delta = (int64_t)aws_min_u64(pending_update_size, INT32_MAX);
1239 /* resulting window size can't exceed INT32_MAX */
1240 delta = aws_min_i64(delta, (int64_t)INT32_MAX - current_window);
1241 /* assert should hold, based on our clamping above */
1242 AWS_ASSERT(delta >= 0 && delta <= AWS_H2_WINDOW_UPDATE_MAX);
1243 return (uint32_t)delta;
1244 }
1245
1246 static int s_connection_send_update_window_if_needed(
1247 struct aws_h2_connection *connection,
1248 uint64_t window_update_size) {
1249 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1250
1251 /**
1252 * Only send a WINDOW_UPDATE frame if the connection window is below the threshold
1253 * If the pending amount is greater than uin64 max. Probably an unexpected error, ignores it and cap it.
1254 */
1255 connection->thread_data.pending_window_update_size_self =
1256 aws_add_u64_saturating(connection->thread_data.pending_window_update_size_self, window_update_size);
1257 if (connection->thread_data.pending_window_update_size_self == 0) {
1258 /* Nothing to do */
1259 return AWS_OP_SUCCESS;
1260 }
1261 if (connection->thread_data.window_size_self >= connection->window_size_threshold_to_send_update) {
1262 CONNECTION_LOGF(
1263 TRACE,
1264 connection,
1265 "Ignoring sending connection window update of size %" PRIu64 ". Current size: %" PRIu32
1266 ", threshold: %" PRIu32 " pending: %" PRIu64,
1267 window_update_size,
1268 connection->thread_data.window_size_self,
1269 connection->window_size_threshold_to_send_update,
1270 connection->thread_data.pending_window_update_size_self);
1271 return AWS_OP_SUCCESS;
1272 }
1273
1274 /* Cap the window to AWS_H2_WINDOW_UPDATE_MAX */
1275 uint32_t window_delta = aws_h2_calculate_cap_window_update_delta(
1276 connection->thread_data.window_size_self, connection->thread_data.pending_window_update_size_self);
1277
1278 if (window_delta != connection->thread_data.pending_window_update_size_self) {
1279 CONNECTION_LOGF(
1280 DEBUG,
1281 (void *)connection,
1282 "Capping window update delta from %" PRIu64 " to %" PRIu32,
1283 connection->thread_data.pending_window_update_size_self,
1284 window_delta);
1285 }
1286
1287 if (window_delta > 0) {
1288 struct aws_h2_frame *connection_window_update_frame =
1289 aws_h2_frame_new_window_update(connection->base.alloc, 0, window_delta);
1290 if (!connection_window_update_frame) {
1291 CONNECTION_LOGF(
1292 ERROR,
1293 connection,
1294 "WINDOW_UPDATE frame on connection failed to be sent, error %s",
1295 aws_error_name(aws_last_error()));
1296 return AWS_OP_ERR;
1297 }
1298 CONNECTION_LOGF(DEBUG, connection, "Sending connection window by %" PRIu32 ".", window_delta);
1299 aws_h2_connection_enqueue_outgoing_frame(connection, connection_window_update_frame);
1300 /* The math in aws_h2_calculate_cap_window_update_delta makes sure no overflow afterwards. */
1301 connection->thread_data.window_size_self += window_delta;
1302 connection->thread_data.pending_window_update_size_self -= window_delta;
1303 }
1304
1305 return AWS_OP_SUCCESS;
1306 }
1307
1308 struct aws_h2err s_decoder_on_data_begin(
1309 uint32_t stream_id,
1310 uint32_t payload_len,
1311 uint32_t total_padding_bytes,
1312 bool end_stream,
1313 void *userdata) {
1314 struct aws_h2_connection *connection = userdata;
1315
1316 /* A receiver that receives a flow-controlled frame MUST always account for its contribution against the connection
1317 * flow-control window, unless the receiver treats this as a connection error */
1318 if (aws_sub_u32_checked(
1319 connection->thread_data.window_size_self, payload_len, &connection->thread_data.window_size_self)) {
1320 CONNECTION_LOGF(
1321 ERROR,
1322 connection,
1323 "DATA length %" PRIu32 " exceeds flow-control window %" PRIu32 ".",
1324 payload_len,
1325 connection->thread_data.window_size_self);
1326 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FLOW_CONTROL_ERROR);
1327 }
1328
1329 struct aws_h2_stream *stream;
1330 struct aws_h2err err = s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_DATA, &stream);
1331 if (aws_h2err_failed(err)) {
1332 return err;
1333 }
1334
1335 if (stream) {
1336 err = aws_h2_stream_on_decoder_data_begin(stream, payload_len, total_padding_bytes, end_stream);
1337 if (aws_h2err_failed(err)) {
1338 return err;
1339 }
1340 }
1341 /* Handle automatic updates of the connection flow window */
1342 uint32_t auto_window_update;
1343 if (connection->conn_manual_window_management) {
1344 /* Automatically update the flow-window to account for padding, even though "manual window management"
1345 * is enabled. We do this because the current API doesn't have any way to inform the user about padding,
1346 * so we can't expect them to manage it themselves. */
1347 auto_window_update = total_padding_bytes;
1348 } else {
1349 /* Automatically update the full amount we just received */
1350 auto_window_update = payload_len;
1351 }
1352
1353 if (s_connection_send_update_window_if_needed(connection, auto_window_update)) {
1354 return aws_h2err_from_last_error();
1355 }
1356
1357 return AWS_H2ERR_SUCCESS;
1358 }
1359
1360 struct aws_h2err s_decoder_on_data_i(uint32_t stream_id, struct aws_byte_cursor data, void *userdata) {
1361 struct aws_h2_connection *connection = userdata;
1362
1363 /* Pass data to stream */
1364 struct aws_h2_stream *stream;
1365 struct aws_h2err err = s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_DATA, &stream);
1366 if (aws_h2err_failed(err)) {
1367 return err;
1368 }
1369
1370 if (stream) {
1371 err = aws_h2_stream_on_decoder_data_i(stream, data);
1372 if (aws_h2err_failed(err)) {
1373 return err;
1374 }
1375 }
1376
1377 return AWS_H2ERR_SUCCESS;
1378 }
1379
1380 struct aws_h2err s_decoder_on_end_stream(uint32_t stream_id, void *userdata) {
1381 struct aws_h2_connection *connection = userdata;
1382
1383 /* Not calling s_get_active_stream_for_incoming_frame() here because END_STREAM
1384 * isn't an actual frame type. It's a flag on DATA or HEADERS frames, and we
1385 * already checked the legality of those frames in their respective callbacks. */
1386
1387 struct aws_hash_element *found = NULL;
1388 aws_hash_table_find(&connection->thread_data.active_streams_map, (void *)(size_t)stream_id, &found);
1389 if (found) {
1390 struct aws_h2_stream *stream = found->value;
1391 struct aws_h2err err = aws_h2_stream_on_decoder_end_stream(stream);
1392 if (aws_h2err_failed(err)) {
1393 return err;
1394 }
1395 }
1396
1397 return AWS_H2ERR_SUCCESS;
1398 }
1399
1400 static struct aws_h2err s_decoder_on_rst_stream(uint32_t stream_id, uint32_t h2_error_code, void *userdata) {
1401 struct aws_h2_connection *connection = userdata;
1402
1403 /* Pass RST_STREAM to stream */
1404 struct aws_h2_stream *stream;
1405 struct aws_h2err err =
1406 s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_RST_STREAM, &stream);
1407 if (aws_h2err_failed(err)) {
1408 return err;
1409 }
1410
1411 if (stream) {
1412 err = aws_h2_stream_on_decoder_rst_stream(stream, h2_error_code);
1413 if (aws_h2err_failed(err)) {
1414 return err;
1415 }
1416 }
1417
1418 return AWS_H2ERR_SUCCESS;
1419 }
1420
1421 static struct aws_h2err s_decoder_on_ping_ack(uint8_t opaque_data[AWS_HTTP2_PING_DATA_SIZE], void *userdata) {
1422 struct aws_h2_connection *connection = userdata;
1423 if (aws_linked_list_empty(&connection->thread_data.pending_ping_queue)) {
1424 CONNECTION_LOG(ERROR, connection, "Received extraneous PING ACK.");
1425 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1426 }
1427 struct aws_h2err err;
1428 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->thread_data.pending_ping_queue);
1429 struct aws_h2_pending_ping *pending_ping = AWS_CONTAINER_OF(node, struct aws_h2_pending_ping, node);
1430 /* Check the payload */
1431 if (!aws_array_eq(opaque_data, AWS_HTTP2_PING_DATA_SIZE, pending_ping->opaque_data, AWS_HTTP2_PING_DATA_SIZE)) {
1432 CONNECTION_LOG(ERROR, connection, "Received PING ACK with mismatched opaque-data.");
1433 err = aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1434 goto error;
1435 }
1436 uint64_t time_stamp;
1437 if (aws_high_res_clock_get_ticks(&time_stamp)) {
1438 CONNECTION_LOGF(
1439 ERROR,
1440 connection,
1441 "Failed getting the time stamp when PING ACK received, error %s",
1442 aws_error_name(aws_last_error()));
1443 err = aws_h2err_from_last_error();
1444 goto error;
1445 }
1446 uint64_t rtt;
1447 if (aws_sub_u64_checked(time_stamp, pending_ping->started_time, &rtt)) {
1448 CONNECTION_LOGF(
1449 ERROR,
1450 connection,
1451 "Overflow from time stamp when PING ACK received, error %s",
1452 aws_error_name(aws_last_error()));
1453 err = aws_h2err_from_last_error();
1454 goto error;
1455 }
1456 CONNECTION_LOGF(TRACE, connection, "Round trip time is %lf ms, approximately", (double)rtt / 1000000);
1457 /* fire the callback */
1458 if (pending_ping->on_completed) {
1459 pending_ping->on_completed(&connection->base, rtt, AWS_ERROR_SUCCESS, pending_ping->user_data);
1460 }
1461 aws_mem_release(connection->base.alloc, pending_ping);
1462 return AWS_H2ERR_SUCCESS;
1463 error:
1464 if (pending_ping->on_completed) {
1465 pending_ping->on_completed(&connection->base, 0 /* fake rtt */, err.aws_code, pending_ping->user_data);
1466 }
1467 aws_mem_release(connection->base.alloc, pending_ping);
1468 return err;
1469 }
1470
1471 static struct aws_h2err s_decoder_on_ping(uint8_t opaque_data[AWS_HTTP2_PING_DATA_SIZE], void *userdata) {
1472 struct aws_h2_connection *connection = userdata;
1473
1474 /* send a PING frame with the ACK flag set in response, with an identical payload. */
1475 struct aws_h2_frame *ping_ack_frame = aws_h2_frame_new_ping(connection->base.alloc, true, opaque_data);
1476 if (!ping_ack_frame) {
1477 CONNECTION_LOGF(
1478 ERROR, connection, "Ping ACK frame failed to be sent, error %s", aws_error_name(aws_last_error()));
1479 return aws_h2err_from_last_error();
1480 }
1481
1482 aws_h2_connection_enqueue_outgoing_frame(connection, ping_ack_frame);
1483 return AWS_H2ERR_SUCCESS;
1484 }
1485
1486 static struct aws_h2err s_decoder_on_settings(
1487 const struct aws_http2_setting *settings_array,
1488 size_t num_settings,
1489 void *userdata) {
1490 struct aws_h2_connection *connection = userdata;
1491 struct aws_h2err err;
1492 /* Once all values have been processed, the recipient MUST immediately emit a SETTINGS frame with the ACK flag
1493 * set.(RFC-7540 6.5.3) */
1494 CONNECTION_LOG(TRACE, connection, "Setting frame processing ends");
1495 struct aws_h2_frame *settings_ack_frame = aws_h2_frame_new_settings(connection->base.alloc, NULL, 0, true);
1496 if (!settings_ack_frame) {
1497 CONNECTION_LOGF(
1498 ERROR, connection, "Settings ACK frame failed to be sent, error %s", aws_error_name(aws_last_error()));
1499 return aws_h2err_from_last_error();
1500 }
1501 aws_h2_connection_enqueue_outgoing_frame(connection, settings_ack_frame);
1502
1503 /* Allocate a block of memory for settings_array in callback, which will only includes the settings we changed,
1504 * freed once the callback finished */
1505 struct aws_http2_setting *callback_array = NULL;
1506 if (num_settings) {
1507 callback_array = aws_mem_acquire(connection->base.alloc, num_settings * sizeof(struct aws_http2_setting));
1508 if (!callback_array) {
1509 return aws_h2err_from_last_error();
1510 }
1511 }
1512 size_t callback_array_num = 0;
1513
1514 /* Apply the change to encoder and connection */
1515 struct aws_h2_frame_encoder *encoder = &connection->thread_data.encoder;
1516 for (size_t i = 0; i < num_settings; i++) {
1517 if (connection->thread_data.settings_peer[settings_array[i].id] == settings_array[i].value) {
1518 /* No change, don't do any work */
1519 continue;
1520 }
1521 switch (settings_array[i].id) {
1522 case AWS_HTTP2_SETTINGS_HEADER_TABLE_SIZE: {
1523 aws_h2_frame_encoder_set_setting_header_table_size(encoder, settings_array[i].value);
1524 } break;
1525 case AWS_HTTP2_SETTINGS_INITIAL_WINDOW_SIZE: {
1526 /* When the value of SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST adjust the size of all stream
1527 * flow-control windows that it maintains by the difference between the new value and the old value. */
1528 int32_t size_changed =
1529 settings_array[i].value - connection->thread_data.settings_peer[settings_array[i].id];
1530 struct aws_hash_iter stream_iter = aws_hash_iter_begin(&connection->thread_data.active_streams_map);
1531 while (!aws_hash_iter_done(&stream_iter)) {
1532 struct aws_h2_stream *stream = stream_iter.element.value;
1533 aws_hash_iter_next(&stream_iter);
1534 err = aws_h2_stream_window_size_change_direct(stream, size_changed, false /*self*/);
1535 if (aws_h2err_failed(err)) {
1536 CONNECTION_LOG(
1537 ERROR,
1538 connection,
1539 "Connection error, change to SETTINGS_INITIAL_WINDOW_SIZE caused a stream's flow-control "
1540 "window to exceed the maximum size");
1541 goto error;
1542 }
1543 }
1544 } break;
1545 case AWS_HTTP2_SETTINGS_MAX_FRAME_SIZE: {
1546 aws_h2_frame_encoder_set_setting_max_frame_size(encoder, settings_array[i].value);
1547 } break;
1548 default:
1549 break;
1550 }
1551 connection->thread_data.settings_peer[settings_array[i].id] = settings_array[i].value;
1552 callback_array[callback_array_num++] = settings_array[i];
1553 }
1554 if (connection->on_remote_settings_change) {
1555 connection->on_remote_settings_change(
1556 &connection->base, callback_array, callback_array_num, connection->base.user_data);
1557 }
1558 { /* BEGIN CRITICAL SECTION */
1559 s_lock_synced_data(connection);
1560
1561 memcpy(
1562 connection->synced_data.settings_peer,
1563 connection->thread_data.settings_peer,
1564 sizeof(connection->thread_data.settings_peer));
1565
1566 s_unlock_synced_data(connection);
1567 } /* END CRITICAL SECTION */
1568 aws_mem_release(connection->base.alloc, callback_array);
1569 return AWS_H2ERR_SUCCESS;
1570 error:
1571 aws_mem_release(connection->base.alloc, callback_array);
1572 return err;
1573 }
1574
1575 static struct aws_h2err s_decoder_on_settings_ack(void *userdata) {
1576 struct aws_h2_connection *connection = userdata;
1577 if (aws_linked_list_empty(&connection->thread_data.pending_settings_queue)) {
1578 CONNECTION_LOG(ERROR, connection, "Received a malicious extra SETTINGS acknowledgment");
1579 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1580 }
1581 struct aws_h2err err;
1582 struct aws_h2_pending_settings *pending_settings = NULL;
1583 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->thread_data.pending_settings_queue);
1584 pending_settings = AWS_CONTAINER_OF(node, struct aws_h2_pending_settings, node);
1585
1586 struct aws_http2_setting *settings_array = pending_settings->settings_array;
1587 /* Apply the settings */
1588 struct aws_h2_decoder *decoder = connection->thread_data.decoder;
1589 for (size_t i = 0; i < pending_settings->num_settings; i++) {
1590 if (connection->thread_data.settings_self[settings_array[i].id] == settings_array[i].value) {
1591 /* No change, don't do any work */
1592 continue;
1593 }
1594 switch (settings_array[i].id) {
1595 case AWS_HTTP2_SETTINGS_HEADER_TABLE_SIZE: {
1596 aws_h2_decoder_set_setting_header_table_size(decoder, settings_array[i].value);
1597 } break;
1598 case AWS_HTTP2_SETTINGS_ENABLE_PUSH: {
1599 aws_h2_decoder_set_setting_enable_push(decoder, settings_array[i].value);
1600 } break;
1601 case AWS_HTTP2_SETTINGS_INITIAL_WINDOW_SIZE: {
1602 /* When the value of SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST adjust the size of all stream
1603 * flow-control windows that it maintains by the difference between the new value and the old value. */
1604 int32_t size_changed =
1605 settings_array[i].value - connection->thread_data.settings_self[settings_array[i].id];
1606 struct aws_hash_iter stream_iter = aws_hash_iter_begin(&connection->thread_data.active_streams_map);
1607 while (!aws_hash_iter_done(&stream_iter)) {
1608 struct aws_h2_stream *stream = stream_iter.element.value;
1609 aws_hash_iter_next(&stream_iter);
1610 err = aws_h2_stream_window_size_change_direct(stream, size_changed, true /*self*/);
1611 if (aws_h2err_failed(err)) {
1612 CONNECTION_LOG(
1613 ERROR,
1614 connection,
1615 "Connection error, change to SETTINGS_INITIAL_WINDOW_SIZE from internal caused a stream's "
1616 "flow-control window to exceed the maximum size");
1617 goto error;
1618 }
1619 }
1620 } break;
1621 case AWS_HTTP2_SETTINGS_MAX_FRAME_SIZE: {
1622 aws_h2_decoder_set_setting_max_frame_size(decoder, settings_array[i].value);
1623 } break;
1624 default:
1625 break;
1626 }
1627 connection->thread_data.settings_self[settings_array[i].id] = settings_array[i].value;
1628 }
1629 /* invoke the change settings completed user callback */
1630 if (pending_settings->on_completed) {
1631 pending_settings->on_completed(&connection->base, AWS_ERROR_SUCCESS, pending_settings->user_data);
1632 }
1633 { /* BEGIN CRITICAL SECTION */
1634 s_lock_synced_data(connection);
1635
1636 memcpy(
1637 connection->synced_data.settings_self,
1638 connection->thread_data.settings_self,
1639 sizeof(connection->thread_data.settings_self));
1640
1641 s_unlock_synced_data(connection);
1642 } /* END CRITICAL SECTION */
1643 /* clean up the pending_settings */
1644 aws_mem_release(connection->base.alloc, pending_settings);
1645 return AWS_H2ERR_SUCCESS;
1646 error:
1647 /* invoke the user callback with error code */
1648 if (pending_settings->on_completed) {
1649 pending_settings->on_completed(&connection->base, err.aws_code, pending_settings->user_data);
1650 }
1651 /* clean up the pending settings here */
1652 aws_mem_release(connection->base.alloc, pending_settings);
1653 return err;
1654 }
1655
1656 static struct aws_h2err s_decoder_on_window_update(uint32_t stream_id, uint32_t window_size_increment, void *userdata) {
1657 struct aws_h2_connection *connection = userdata;
1658
1659 if (stream_id == 0) {
1660 /* Let's update the connection flow-control window size */
1661 if (window_size_increment == 0) {
1662 /* flow-control window increment of 0 MUST be treated as error (RFC7540 6.9.1) */
1663 CONNECTION_LOG(ERROR, connection, "Window update frame with 0 increment size");
1664 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1665 }
1666 if (connection->thread_data.window_size_peer + window_size_increment > AWS_H2_WINDOW_UPDATE_MAX) {
1667 /* We MUST NOT allow a flow-control window to exceed the max */
1668 CONNECTION_LOG(
1669 ERROR,
1670 connection,
1671 "Window update frame causes the connection flow-control window exceeding the maximum size");
1672 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_FLOW_CONTROL_ERROR);
1673 }
1674 if (connection->thread_data.window_size_peer <= AWS_H2_MIN_WINDOW_SIZE) {
1675 CONNECTION_LOGF(
1676 DEBUG,
1677 connection,
1678 "Peer connection's flow-control window is resumed from too small to %" PRIu32
1679 ". Connection will resume sending DATA.",
1680 window_size_increment);
1681 }
1682 connection->thread_data.window_size_peer += window_size_increment;
1683 return AWS_H2ERR_SUCCESS;
1684 } else {
1685 /* Update the flow-control window size for stream */
1686 struct aws_h2_stream *stream;
1687 bool window_resume;
1688 struct aws_h2err err =
1689 s_get_active_stream_for_incoming_frame(connection, stream_id, AWS_H2_FRAME_T_WINDOW_UPDATE, &stream);
1690 if (aws_h2err_failed(err)) {
1691 return err;
1692 }
1693 if (stream) {
1694 err = aws_h2_stream_on_decoder_window_update(stream, window_size_increment, &window_resume);
1695 if (aws_h2err_failed(err)) {
1696 return err;
1697 }
1698 if (window_resume) {
1699 /* Set the stream free from stalled list */
1700 AWS_H2_STREAM_LOGF(
1701 DEBUG,
1702 stream,
1703 "Peer stream's flow-control window is resumed from 0 or negative to %" PRIu32
1704 " Stream will resume sending data.",
1705 stream->thread_data.window_size_peer);
1706 aws_linked_list_remove(&stream->node);
1707 aws_linked_list_push_back(&connection->thread_data.outgoing_streams_list, &stream->node);
1708 }
1709 }
1710 }
1711 return AWS_H2ERR_SUCCESS;
1712 }
1713
1714 struct aws_h2err s_decoder_on_goaway(
1715 uint32_t last_stream,
1716 uint32_t error_code,
1717 struct aws_byte_cursor debug_data,
1718 void *userdata) {
1719 struct aws_h2_connection *connection = userdata;
1720
1721 if (last_stream > connection->thread_data.goaway_received_last_stream_id) {
1722 CONNECTION_LOGF(
1723 ERROR,
1724 connection,
1725 "Received GOAWAY with invalid last-stream-id=%" PRIu32 ", must not exceed previous last-stream-id=%" PRIu32,
1726 last_stream,
1727 connection->thread_data.goaway_received_last_stream_id);
1728 return aws_h2err_from_h2_code(AWS_HTTP2_ERR_PROTOCOL_ERROR);
1729 }
1730 /* stop sending any new stream and making new request */
1731 { /* BEGIN CRITICAL SECTION */
1732 s_lock_synced_data(connection);
1733
1734 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_GOAWAY_RECEIVED;
1735 connection->synced_data.goaway_received_last_stream_id = last_stream;
1736 connection->synced_data.goaway_received_http2_error_code = error_code;
1737
1738 s_unlock_synced_data(connection);
1739 } /* END CRITICAL SECTION */
1740 connection->thread_data.goaway_received_last_stream_id = last_stream;
1741 CONNECTION_LOGF(
1742 DEBUG,
1743 connection,
1744 "Received GOAWAY error-code=%s(0x%x) last-stream-id=%" PRIu32,
1745 aws_http2_error_code_to_str(error_code),
1746 error_code,
1747 last_stream);
1748 /* Complete activated streams whose id is higher than last_stream, since they will not process by peer. We should
1749 * treat them as they had never been created at all.
1750 * This would be more efficient if we could iterate streams in reverse-id order */
1751 struct aws_hash_iter stream_iter = aws_hash_iter_begin(&connection->thread_data.active_streams_map);
1752 while (!aws_hash_iter_done(&stream_iter)) {
1753 struct aws_h2_stream *stream = stream_iter.element.value;
1754 aws_hash_iter_next(&stream_iter);
1755 if (stream->base.id > last_stream) {
1756 AWS_H2_STREAM_LOG(
1757 DEBUG,
1758 stream,
1759 "stream ID is higher than GOAWAY last stream ID, please retry this stream on a new connection.");
1760 s_stream_complete(connection, stream, AWS_ERROR_HTTP_GOAWAY_RECEIVED);
1761 }
1762 }
1763 if (connection->on_goaway_received) {
1764 /* Inform user about goaway received and the error code. */
1765 connection->on_goaway_received(
1766 &connection->base, last_stream, error_code, debug_data, connection->base.user_data);
1767 }
1768
1769 return AWS_H2ERR_SUCCESS;
1770 }
1771
1772 /* End decoder callbacks */
1773
1774 static int s_send_connection_preface_client_string(struct aws_h2_connection *connection) {
1775
1776 /* Just send the magic string on its own aws_io_message. */
1777 struct aws_io_message *msg = aws_channel_acquire_message_from_pool(
1778 connection->base.channel_slot->channel,
1779 AWS_IO_MESSAGE_APPLICATION_DATA,
1780 aws_h2_connection_preface_client_string.len);
1781 if (!msg) {
1782 goto error;
1783 }
1784
1785 if (!aws_byte_buf_write_from_whole_cursor(&msg->message_data, aws_h2_connection_preface_client_string)) {
1786 aws_raise_error(AWS_ERROR_INVALID_STATE);
1787 goto error;
1788 }
1789
1790 if (aws_channel_slot_send_message(connection->base.channel_slot, msg, AWS_CHANNEL_DIR_WRITE)) {
1791 goto error;
1792 }
1793
1794 return AWS_OP_SUCCESS;
1795
1796 error:
1797 if (msg) {
1798 aws_mem_release(msg->allocator, msg);
1799 }
1800 return AWS_OP_ERR;
1801 }
1802
1803 static void s_handler_installed(struct aws_channel_handler *handler, struct aws_channel_slot *slot) {
1804 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(slot->channel));
1805 struct aws_h2_connection *connection = handler->impl;
1806
1807 connection->base.channel_slot = slot;
1808
1809 /* Acquire a hold on the channel to prevent its destruction until the user has
1810 * given the go-ahead via aws_http_connection_release() */
1811 aws_channel_acquire_hold(slot->channel);
1812
1813 /* Send HTTP/2 connection preface (RFC-7540 3.5)
1814 * - clients must send magic string
1815 * - both client and server must send SETTINGS frame */
1816
1817 if (connection->base.client_data) {
1818 if (s_send_connection_preface_client_string(connection)) {
1819 CONNECTION_LOGF(
1820 ERROR,
1821 connection,
1822 "Failed to send client connection preface string, %s",
1823 aws_error_name(aws_last_error()));
1824 goto error;
1825 }
1826 }
1827 struct aws_h2_pending_settings *init_pending_settings = connection->thread_data.init_pending_settings;
1828 aws_linked_list_push_back(&connection->thread_data.pending_settings_queue, &init_pending_settings->node);
1829 connection->thread_data.init_pending_settings = NULL;
1830 /* Set user_data here, the user_data is valid now */
1831 init_pending_settings->user_data = connection->base.user_data;
1832
1833 struct aws_h2_frame *init_settings_frame = aws_h2_frame_new_settings(
1834 connection->base.alloc,
1835 init_pending_settings->settings_array,
1836 init_pending_settings->num_settings,
1837 false /*ACK*/);
1838 if (!init_settings_frame) {
1839 CONNECTION_LOGF(
1840 ERROR,
1841 connection,
1842 "Failed to create the initial settings frame, error %s",
1843 aws_error_name(aws_last_error()));
1844 aws_mem_release(connection->base.alloc, init_pending_settings);
1845 goto error;
1846 }
1847 /* enqueue the initial settings frame here */
1848 aws_linked_list_push_back(&connection->thread_data.outgoing_frames_queue, &init_settings_frame->node);
1849
1850 /* If not manual connection window management, update the connection window to max. */
1851 if (!connection->conn_manual_window_management) {
1852 uint32_t initial_window_update_size = AWS_H2_WINDOW_UPDATE_MAX - AWS_H2_INIT_WINDOW_SIZE;
1853 struct aws_h2_frame *connection_window_update_frame =
1854 aws_h2_frame_new_window_update(connection->base.alloc, 0 /* stream_id */, initial_window_update_size);
1855 AWS_ASSERT(connection_window_update_frame);
1856 /* enqueue the windows update frame here */
1857 aws_linked_list_push_back(
1858 &connection->thread_data.outgoing_frames_queue, &connection_window_update_frame->node);
1859 connection->thread_data.window_size_self += initial_window_update_size;
1860 }
1861 aws_h2_try_write_outgoing_frames(connection);
1862 return;
1863
1864 error:
1865 aws_h2_connection_shutdown_due_to_write_err(connection, aws_last_error());
1866 }
1867
1868 static void s_stream_complete(struct aws_h2_connection *connection, struct aws_h2_stream *stream, int error_code) {
1869 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1870
1871 /* Guard against double-completion (e.g. GOAWAY completes stream, then pending cancel task fires) */
1872 if (stream->thread_data.is_complete) {
1873 AWS_H2_STREAM_LOG(DEBUG, stream, "stream already completed, ignoring.");
1874 return;
1875 }
1876 stream->thread_data.is_complete = true;
1877
1878 /* Nice logging */
1879 if (error_code) {
1880 AWS_H2_STREAM_LOGF(
1881 ERROR, stream, "Stream completed with error %d (%s).", error_code, aws_error_name(error_code));
1882 } else if (stream->base.client_data) {
1883 int status = stream->base.client_data->response_status;
1884 AWS_H2_STREAM_LOGF(
1885 DEBUG, stream, "Client stream complete, response status %d (%s)", status, aws_http_status_text(status));
1886 } else {
1887 AWS_H2_STREAM_LOG(DEBUG, stream, "Server stream complete");
1888 }
1889
1890 /* Remove stream from active_streams_map and outgoing_stream_list (if it was in them at all) */
1891 aws_hash_table_remove(&connection->thread_data.active_streams_map, (void *)(size_t)stream->base.id, NULL, NULL);
1892 if (stream->node.next) {
1893 aws_linked_list_remove(&stream->node);
1894 }
1895
1896 if (aws_hash_table_get_entry_count(&connection->thread_data.active_streams_map) == 0 &&
1897 connection->thread_data.incoming_timestamp_ns != 0) {
1898 uint64_t now_ns = 0;
1899 aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns);
1900 /* transition from something to read -> nothing to read and nothing to write */
1901 s_add_time_measurement_to_stats(
1902 connection->thread_data.incoming_timestamp_ns,
1903 now_ns,
1904 &connection->thread_data.stats.pending_incoming_stream_ms);
1905 connection->thread_data.stats.was_inactive = true;
1906 connection->thread_data.incoming_timestamp_ns = 0;
1907 }
1908
1909 aws_h2_stream_complete(stream, error_code);
1910
1911 /* release connection's hold on stream */
1912 aws_http_stream_release(&stream->base);
1913 }
1914
1915 int aws_h2_connection_on_stream_closed(
1916 struct aws_h2_connection *connection,
1917 struct aws_h2_stream *stream,
1918 enum aws_h2_stream_closed_when closed_when,
1919 int aws_error_code) {
1920
1921 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1922 AWS_PRECONDITION(stream->thread_data.state == AWS_H2_STREAM_STATE_CLOSED);
1923 AWS_PRECONDITION(stream->base.id != 0);
1924
1925 uint32_t stream_id = stream->base.id;
1926
1927 /* Mark stream complete. This removes the stream from any "active" datastructures,
1928 * invokes its completion callback, and releases its refcount. */
1929 s_stream_complete(connection, stream, aws_error_code);
1930 stream = NULL; /* Reference released, do not touch again */
1931
1932 if (s_record_closed_stream(connection, stream_id, closed_when)) {
1933 return AWS_OP_ERR;
1934 }
1935
1936 return AWS_OP_SUCCESS;
1937 }
1938
1939 static int s_record_closed_stream(
1940 struct aws_h2_connection *connection,
1941 uint32_t stream_id,
1942 enum aws_h2_stream_closed_when closed_when) {
1943
1944 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1945
1946 if (aws_cache_put(connection->thread_data.closed_streams, (void *)(size_t)stream_id, (void *)(size_t)closed_when)) {
1947 CONNECTION_LOG(ERROR, connection, "Failed inserting ID into cache of recently closed streams");
1948 return AWS_OP_ERR;
1949 }
1950
1951 return AWS_OP_SUCCESS;
1952 }
1953
1954 int aws_h2_connection_send_rst_and_close_reserved_stream(
1955 struct aws_h2_connection *connection,
1956 uint32_t stream_id,
1957 uint32_t h2_error_code) {
1958 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1959
1960 struct aws_h2_frame *rst_stream = aws_h2_frame_new_rst_stream(connection->base.alloc, stream_id, h2_error_code);
1961 if (!rst_stream) {
1962 CONNECTION_LOGF(ERROR, connection, "Error creating RST_STREAM frame, %s", aws_error_name(aws_last_error()));
1963 return AWS_OP_ERR;
1964 }
1965 aws_h2_connection_enqueue_outgoing_frame(connection, rst_stream);
1966
1967 /* If we ever fully support PUSH_PROMISE, this is where we'd remove the
1968 * promised_stream_id from some reserved_streams datastructure */
1969
1970 return s_record_closed_stream(connection, stream_id, AWS_H2_STREAM_CLOSED_WHEN_RST_STREAM_SENT);
1971 }
1972
1973 /* Move stream into "active" datastructures and notify stream that it can send frames now */
1974 static void s_move_stream_to_thread(
1975 struct aws_h2_connection *connection,
1976 struct aws_h2_stream *stream,
1977 int new_stream_error_code) {
1978 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
1979
1980 if (new_stream_error_code) {
1981 aws_raise_error(new_stream_error_code);
1982 AWS_H2_STREAM_LOGF(
1983 ERROR,
1984 stream,
1985 "Failed activating stream, error %d (%s)",
1986 aws_last_error(),
1987 aws_error_name(aws_last_error()));
1988 goto error;
1989 }
1990
1991 uint32_t max_concurrent_streams = connection->thread_data.settings_peer[AWS_HTTP2_SETTINGS_MAX_CONCURRENT_STREAMS];
1992 if (aws_hash_table_get_entry_count(&connection->thread_data.active_streams_map) >= max_concurrent_streams) {
1993 AWS_H2_STREAM_LOG(ERROR, stream, "Failed activating stream, max concurrent streams are reached");
1994 aws_raise_error(AWS_ERROR_HTTP_MAX_CONCURRENT_STREAMS_EXCEEDED);
1995 goto error;
1996 }
1997
1998 if (aws_hash_table_put(
1999 &connection->thread_data.active_streams_map, (void *)(size_t)stream->base.id, stream, NULL)) {
2000 AWS_H2_STREAM_LOG(ERROR, stream, "Failed inserting stream into map");
2001 goto error;
2002 }
2003
2004 enum aws_h2_stream_body_state body_state = AWS_H2_STREAM_BODY_STATE_NONE;
2005 if (aws_h2_stream_on_activated(stream, &body_state)) {
2006 goto error;
2007 }
2008
2009 if (aws_hash_table_get_entry_count(&connection->thread_data.active_streams_map) == 1) {
2010 /* transition from nothing to read -> something to read */
2011 uint64_t now_ns = 0;
2012 aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns);
2013 connection->thread_data.incoming_timestamp_ns = now_ns;
2014 }
2015
2016 switch (body_state) {
2017 case AWS_H2_STREAM_BODY_STATE_WAITING_WRITES:
2018 aws_linked_list_push_back(&connection->thread_data.waiting_streams_list, &stream->node);
2019 break;
2020 case AWS_H2_STREAM_BODY_STATE_ONGOING:
2021 aws_linked_list_push_back(&connection->thread_data.outgoing_streams_list, &stream->node);
2022 break;
2023 default:
2024 break;
2025 }
2026 return;
2027 error:
2028 /* If the stream got into any datastructures, s_stream_complete() will remove it */
2029 s_stream_complete(connection, stream, aws_last_error());
2030 }
2031
2032 /* Perform on-thread work that is triggered by calls to the connection/stream API */
2033 static void s_cross_thread_work_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
2034 (void)task;
2035 if (status != AWS_TASK_STATUS_RUN_READY) {
2036 return;
2037 }
2038
2039 struct aws_h2_connection *connection = arg;
2040
2041 struct aws_linked_list pending_frames;
2042 aws_linked_list_init(&pending_frames);
2043
2044 struct aws_linked_list pending_streams;
2045 aws_linked_list_init(&pending_streams);
2046
2047 struct aws_linked_list pending_settings;
2048 aws_linked_list_init(&pending_settings);
2049
2050 struct aws_linked_list pending_ping;
2051 aws_linked_list_init(&pending_ping);
2052
2053 struct aws_linked_list pending_goaway;
2054 aws_linked_list_init(&pending_goaway);
2055
2056 uint64_t window_update_size;
2057 int new_stream_error_code;
2058 { /* BEGIN CRITICAL SECTION */
2059 s_lock_synced_data(connection);
2060 connection->synced_data.is_cross_thread_work_task_scheduled = false;
2061
2062 aws_linked_list_swap_contents(&connection->synced_data.pending_frame_list, &pending_frames);
2063 aws_linked_list_swap_contents(&connection->synced_data.pending_stream_list, &pending_streams);
2064 aws_linked_list_swap_contents(&connection->synced_data.pending_settings_list, &pending_settings);
2065 aws_linked_list_swap_contents(&connection->synced_data.pending_ping_list, &pending_ping);
2066 aws_linked_list_swap_contents(&connection->synced_data.pending_goaway_list, &pending_goaway);
2067 window_update_size = connection->synced_data.pending_window_update_size_self;
2068 connection->synced_data.pending_window_update_size_self = 0;
2069 new_stream_error_code = connection->synced_data.new_stream_error_code;
2070
2071 s_unlock_synced_data(connection);
2072 } /* END CRITICAL SECTION */
2073
2074 /* Enqueue new pending control frames */
2075 while (!aws_linked_list_empty(&pending_frames)) {
2076 struct aws_linked_list_node *node = aws_linked_list_pop_front(&pending_frames);
2077 struct aws_h2_frame *frame = AWS_CONTAINER_OF(node, struct aws_h2_frame, node);
2078 aws_h2_connection_enqueue_outgoing_frame(connection, frame);
2079 }
2080
2081 /* Add window update and enqueue the frame if needed */
2082 s_connection_send_update_window_if_needed(connection, window_update_size);
2083
2084 /* Process new pending_streams */
2085 while (!aws_linked_list_empty(&pending_streams)) {
2086 struct aws_linked_list_node *node = aws_linked_list_pop_front(&pending_streams);
2087 struct aws_h2_stream *stream = AWS_CONTAINER_OF(node, struct aws_h2_stream, node);
2088 s_move_stream_to_thread(connection, stream, new_stream_error_code);
2089 }
2090
2091 /* Move pending settings to thread data */
2092 while (!aws_linked_list_empty(&pending_settings)) {
2093 aws_linked_list_push_back(
2094 &connection->thread_data.pending_settings_queue, aws_linked_list_pop_front(&pending_settings));
2095 }
2096
2097 /* Move pending PING to thread data */
2098 while (!aws_linked_list_empty(&pending_ping)) {
2099 aws_linked_list_push_back(
2100 &connection->thread_data.pending_ping_queue, aws_linked_list_pop_front(&pending_ping));
2101 }
2102
2103 /* Send user requested goaways */
2104 while (!aws_linked_list_empty(&pending_goaway)) {
2105 struct aws_linked_list_node *node = aws_linked_list_pop_front(&pending_goaway);
2106 struct aws_h2_pending_goaway *goaway = AWS_CONTAINER_OF(node, struct aws_h2_pending_goaway, node);
2107 s_send_goaway(connection, goaway->http2_error, goaway->allow_more_streams, &goaway->debug_data);
2108 aws_mem_release(connection->base.alloc, goaway);
2109 }
2110
2111 /* It's likely that frames were queued while processing cross-thread work.
2112 * If so, try writing them now */
2113 aws_h2_try_write_outgoing_frames(connection);
2114 }
2115
2116 int aws_h2_stream_activate(struct aws_http_stream *stream) {
2117 struct aws_h2_stream *h2_stream = AWS_CONTAINER_OF(stream, struct aws_h2_stream, base);
2118
2119 struct aws_http_connection *base_connection = stream->owning_connection;
2120 struct aws_h2_connection *connection = AWS_CONTAINER_OF(base_connection, struct aws_h2_connection, base);
2121
2122 int err;
2123 bool was_cross_thread_work_scheduled = false;
2124 { /* BEGIN CRITICAL SECTION */
2125 s_acquire_stream_and_connection_lock(h2_stream, connection);
2126
2127 if (stream->id) {
2128 /* stream has already been activated. */
2129 s_release_stream_and_connection_lock(h2_stream, connection);
2130 return AWS_OP_SUCCESS;
2131 }
2132
2133 err = connection->synced_data.new_stream_error_code;
2134 if (err) {
2135 s_release_stream_and_connection_lock(h2_stream, connection);
2136 goto error;
2137 }
2138
2139 stream->id = aws_http_connection_get_next_stream_id(base_connection);
2140
2141 if (stream->id) {
2142 /* success */
2143 was_cross_thread_work_scheduled = connection->synced_data.is_cross_thread_work_task_scheduled;
2144 connection->synced_data.is_cross_thread_work_task_scheduled = true;
2145
2146 aws_linked_list_push_back(&connection->synced_data.pending_stream_list, &h2_stream->node);
2147 h2_stream->synced_data.api_state = AWS_H2_STREAM_API_STATE_ACTIVE;
2148 }
2149
2150 s_release_stream_and_connection_lock(h2_stream, connection);
2151 } /* END CRITICAL SECTION */
2152
2153 if (!stream->id) {
2154 /* aws_http_connection_get_next_stream_id() raises its own error. */
2155 return AWS_OP_ERR;
2156 }
2157
2158 /* connection keeps activated stream alive until stream completes */
2159 aws_atomic_fetch_add(&stream->refcount, 1);
2160 stream->metrics.stream_id = stream->id;
2161
2162 if (!was_cross_thread_work_scheduled) {
2163 CONNECTION_LOG(TRACE, connection, "Scheduling cross-thread work task");
2164 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
2165 }
2166
2167 return AWS_OP_SUCCESS;
2168
2169 error:
2170 CONNECTION_LOGF(
2171 ERROR,
2172 connection,
2173 "Failed to activate the stream id=%p, new streams are not allowed now. error %d (%s)",
2174 (void *)stream,
2175 err,
2176 aws_error_name(err));
2177 return aws_raise_error(err);
2178 }
2179
2180 static struct aws_http_stream *s_connection_make_request(
2181 struct aws_http_connection *client_connection,
2182 const struct aws_http_make_request_options *options) {
2183
2184 struct aws_h2_connection *connection = AWS_CONTAINER_OF(client_connection, struct aws_h2_connection, base);
2185
2186 /* #TODO: http/2-ify the request (ex: add ":method" header). Should we mutate a copy or the original? Validate?
2187 * Or just pass pointer to headers struct and let encoder transform it while encoding? */
2188
2189 struct aws_h2_stream *stream = aws_h2_stream_new_request(client_connection, options);
2190 if (!stream) {
2191 CONNECTION_LOGF(
2192 ERROR,
2193 connection,
2194 "Failed to create stream, error %d (%s)",
2195 aws_last_error(),
2196 aws_error_name(aws_last_error()));
2197 return NULL;
2198 }
2199
2200 int new_stream_error_code;
2201 { /* BEGIN CRITICAL SECTION */
2202 s_lock_synced_data(connection);
2203 new_stream_error_code = connection->synced_data.new_stream_error_code;
2204 s_unlock_synced_data(connection);
2205 } /* END CRITICAL SECTION */
2206 if (new_stream_error_code) {
2207 aws_raise_error(new_stream_error_code);
2208 CONNECTION_LOGF(
2209 ERROR,
2210 connection,
2211 "Cannot create request stream, error %d (%s)",
2212 aws_last_error(),
2213 aws_error_name(aws_last_error()));
2214 goto error;
2215 }
2216
2217 AWS_H2_STREAM_LOG(DEBUG, stream, "Created HTTP/2 request stream"); /* #TODO: print method & path */
2218 return &stream->base;
2219
2220 error:
2221 /* Force destruction of the stream, avoiding ref counting */
2222 stream->base.vtable->destroy(&stream->base);
2223 return NULL;
2224 }
2225
2226 static void s_connection_close(struct aws_http_connection *connection_base) {
2227 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2228
2229 /* Don't stop reading/writing immediately, let that happen naturally during the channel shutdown process. */
2230 s_stop(connection, false /*stop_reading*/, false /*stop_writing*/, true /*schedule_shutdown*/, AWS_ERROR_SUCCESS);
2231 }
2232
2233 static void s_connection_stop_new_request(struct aws_http_connection *connection_base) {
2234 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2235
2236 { /* BEGIN CRITICAL SECTION */
2237 s_lock_synced_data(connection);
2238 if (!connection->synced_data.new_stream_error_code) {
2239 connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
2240 }
2241 s_unlock_synced_data(connection);
2242 } /* END CRITICAL SECTION */
2243 }
2244
2245 static bool s_connection_is_open(const struct aws_http_connection *connection_base) {
2246 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2247 bool is_open;
2248
2249 { /* BEGIN CRITICAL SECTION */
2250 s_lock_synced_data(connection);
2251 is_open = connection->synced_data.is_open;
2252 s_unlock_synced_data(connection);
2253 } /* END CRITICAL SECTION */
2254
2255 return is_open;
2256 }
2257
2258 static bool s_connection_new_requests_allowed(const struct aws_http_connection *connection_base) {
2259 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2260 int new_stream_error_code;
2261 { /* BEGIN CRITICAL SECTION */
2262 s_lock_synced_data(connection);
2263 new_stream_error_code = connection->synced_data.new_stream_error_code;
2264 s_unlock_synced_data(connection);
2265 } /* END CRITICAL SECTION */
2266 return new_stream_error_code == 0;
2267 }
2268
2269 static void s_connection_update_window(struct aws_http_connection *connection_base, uint32_t increment_size) {
2270 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2271 if (increment_size == 0) {
2272 /* Silently do nothing. */
2273 return;
2274 }
2275 if (!connection->conn_manual_window_management) {
2276 /* auto-mode, manual update window is not supported, silently do nothing with warning log. */
2277 CONNECTION_LOG(
2278 DEBUG,
2279 connection,
2280 "Connection manual window management is off, update window operations are not supported.");
2281 return;
2282 }
2283 bool cross_thread_work_should_schedule = false;
2284 bool connection_open = false;
2285 { /* BEGIN CRITICAL SECTION */
2286 s_lock_synced_data(connection);
2287 connection_open = connection->synced_data.is_open;
2288 if (connection_open) {
2289 cross_thread_work_should_schedule = !connection->synced_data.is_cross_thread_work_task_scheduled;
2290 connection->synced_data.is_cross_thread_work_task_scheduled = true;
2291 /**
2292 * Be more user friendly, if the increment size is too large, we will just saturate it to the max.
2293 * AWS_H2_WINDOW_UPDATE_MAX will be checked during the actual sending of the window update frame.
2294 */
2295 connection->synced_data.pending_window_update_size_self =
2296 aws_add_u64_saturating(connection->synced_data.pending_window_update_size_self, increment_size);
2297 connection_open = connection->synced_data.is_open;
2298 }
2299 s_unlock_synced_data(connection);
2300 } /* END CRITICAL SECTION */
2301
2302 if (cross_thread_work_should_schedule) {
2303 CONNECTION_LOG(TRACE, connection, "Scheduling cross-thread work task");
2304 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
2305 }
2306
2307 if (!connection_open) {
2308 /* connection already closed, just do nothing */
2309 return;
2310 }
2311 CONNECTION_LOGF(
2312 TRACE,
2313 connection,
2314 "User requested to update the HTTP/2 connection's flow-control windows by %" PRIu32 ".",
2315 increment_size);
2316 return;
2317 }
2318
2319 static int s_connection_change_settings(
2320 struct aws_http_connection *connection_base,
2321 const struct aws_http2_setting *settings_array,
2322 size_t num_settings,
2323 aws_http2_on_change_settings_complete_fn *on_completed,
2324 void *user_data) {
2325
2326 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2327
2328 if (!settings_array && num_settings) {
2329 CONNECTION_LOG(ERROR, connection, "Settings_array is NULL and num_settings is not zero.");
2330 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
2331 }
2332
2333 struct aws_h2_pending_settings *pending_settings = s_new_pending_settings(
2334 connection->base.alloc,
2335 false /*add initial window*/,
2336 0 /*initial window size*/,
2337 settings_array,
2338 num_settings,
2339 on_completed,
2340 user_data);
2341 if (!pending_settings) {
2342 return AWS_OP_ERR;
2343 }
2344 struct aws_h2_frame *settings_frame =
2345 aws_h2_frame_new_settings(connection->base.alloc, settings_array, num_settings, false /*ACK*/);
2346 if (!settings_frame) {
2347 CONNECTION_LOGF(
2348 ERROR, connection, "Failed to create settings frame, error %s", aws_error_name(aws_last_error()));
2349 aws_mem_release(connection->base.alloc, pending_settings);
2350 return AWS_OP_ERR;
2351 }
2352
2353 bool was_cross_thread_work_scheduled = false;
2354 bool connection_open;
2355 { /* BEGIN CRITICAL SECTION */
2356 s_lock_synced_data(connection);
2357
2358 connection_open = connection->synced_data.is_open;
2359 if (!connection_open) {
2360 s_unlock_synced_data(connection);
2361 goto closed;
2362 }
2363 was_cross_thread_work_scheduled = connection->synced_data.is_cross_thread_work_task_scheduled;
2364 connection->synced_data.is_cross_thread_work_task_scheduled = true;
2365 aws_linked_list_push_back(&connection->synced_data.pending_frame_list, &settings_frame->node);
2366 aws_linked_list_push_back(&connection->synced_data.pending_settings_list, &pending_settings->node);
2367
2368 s_unlock_synced_data(connection);
2369 } /* END CRITICAL SECTION */
2370
2371 if (!was_cross_thread_work_scheduled) {
2372 CONNECTION_LOG(TRACE, connection, "Scheduling cross-thread work task");
2373 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
2374 }
2375
2376 return AWS_OP_SUCCESS;
2377 closed:
2378 CONNECTION_LOG(ERROR, connection, "Failed to change settings, connection is closed or closing.");
2379 aws_h2_frame_destroy(settings_frame);
2380 aws_mem_release(connection->base.alloc, pending_settings);
2381 return aws_raise_error(AWS_ERROR_INVALID_STATE);
2382 }
2383
2384 static int s_connection_send_ping(
2385 struct aws_http_connection *connection_base,
2386 const struct aws_byte_cursor *optional_opaque_data,
2387 aws_http2_on_ping_complete_fn *on_completed,
2388 void *user_data) {
2389
2390 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2391 if (optional_opaque_data && optional_opaque_data->len != 8) {
2392 CONNECTION_LOG(ERROR, connection, "Only 8 bytes opaque data supported for PING in HTTP/2");
2393 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
2394 }
2395 uint64_t time_stamp;
2396 if (aws_high_res_clock_get_ticks(&time_stamp)) {
2397 CONNECTION_LOGF(
2398 ERROR,
2399 connection,
2400 "Failed getting the time stamp to start PING, error %s",
2401 aws_error_name(aws_last_error()));
2402 return AWS_OP_ERR;
2403 }
2404 struct aws_h2_pending_ping *pending_ping =
2405 s_new_pending_ping(connection->base.alloc, optional_opaque_data, time_stamp, user_data, on_completed);
2406 if (!pending_ping) {
2407 return AWS_OP_ERR;
2408 }
2409 struct aws_h2_frame *ping_frame =
2410 aws_h2_frame_new_ping(connection->base.alloc, false /*ACK*/, pending_ping->opaque_data);
2411 if (!ping_frame) {
2412 CONNECTION_LOGF(ERROR, connection, "Failed to create PING frame, error %s", aws_error_name(aws_last_error()));
2413 aws_mem_release(connection->base.alloc, pending_ping);
2414 return AWS_OP_ERR;
2415 }
2416
2417 bool was_cross_thread_work_scheduled = false;
2418 bool connection_open;
2419 { /* BEGIN CRITICAL SECTION */
2420 s_lock_synced_data(connection);
2421
2422 connection_open = connection->synced_data.is_open;
2423 if (!connection_open) {
2424 s_unlock_synced_data(connection);
2425 goto closed;
2426 }
2427 was_cross_thread_work_scheduled = connection->synced_data.is_cross_thread_work_task_scheduled;
2428 connection->synced_data.is_cross_thread_work_task_scheduled = true;
2429 aws_linked_list_push_back(&connection->synced_data.pending_frame_list, &ping_frame->node);
2430 aws_linked_list_push_back(&connection->synced_data.pending_ping_list, &pending_ping->node);
2431
2432 s_unlock_synced_data(connection);
2433 } /* END CRITICAL SECTION */
2434
2435 if (!was_cross_thread_work_scheduled) {
2436 CONNECTION_LOG(TRACE, connection, "Scheduling cross-thread work task");
2437 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
2438 }
2439
2440 return AWS_OP_SUCCESS;
2441
2442 closed:
2443 CONNECTION_LOG(ERROR, connection, "Failed to send ping, connection is closed or closing.");
2444 aws_h2_frame_destroy(ping_frame);
2445 aws_mem_release(connection->base.alloc, pending_ping);
2446 return aws_raise_error(AWS_ERROR_INVALID_STATE);
2447 }
2448
2449 static void s_connection_send_goaway(
2450 struct aws_http_connection *connection_base,
2451 uint32_t http2_error,
2452 bool allow_more_streams,
2453 const struct aws_byte_cursor *optional_debug_data) {
2454
2455 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2456 struct aws_h2_pending_goaway *pending_goaway =
2457 s_new_pending_goaway(connection->base.alloc, http2_error, allow_more_streams, optional_debug_data);
2458
2459 bool was_cross_thread_work_scheduled = false;
2460 bool connection_open;
2461 { /* BEGIN CRITICAL SECTION */
2462 s_lock_synced_data(connection);
2463
2464 connection_open = connection->synced_data.is_open;
2465 if (!connection_open) {
2466 s_unlock_synced_data(connection);
2467 CONNECTION_LOG(DEBUG, connection, "Goaway not sent, connection is closed or closing.");
2468 aws_mem_release(connection->base.alloc, pending_goaway);
2469 return;
2470 }
2471 was_cross_thread_work_scheduled = connection->synced_data.is_cross_thread_work_task_scheduled;
2472 connection->synced_data.is_cross_thread_work_task_scheduled = true;
2473 aws_linked_list_push_back(&connection->synced_data.pending_goaway_list, &pending_goaway->node);
2474 s_unlock_synced_data(connection);
2475 } /* END CRITICAL SECTION */
2476
2477 if (allow_more_streams && (http2_error != AWS_HTTP2_ERR_NO_ERROR)) {
2478 CONNECTION_LOGF(
2479 DEBUG,
2480 connection,
2481 "Send goaway with allow more streams on and non-zero error code %s(0x%x)",
2482 aws_http2_error_code_to_str(http2_error),
2483 http2_error);
2484 }
2485
2486 if (!was_cross_thread_work_scheduled) {
2487 CONNECTION_LOG(TRACE, connection, "Scheduling cross-thread work task");
2488 aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
2489 }
2490 }
2491
2492 static void s_get_settings_general(
2493 const struct aws_http_connection *connection_base,
2494 struct aws_http2_setting out_settings[AWS_HTTP2_SETTINGS_COUNT],
2495 bool local) {
2496
2497 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2498 uint32_t synced_settings[AWS_HTTP2_SETTINGS_END_RANGE];
2499 { /* BEGIN CRITICAL SECTION */
2500 s_lock_synced_data(connection);
2501 if (local) {
2502 memcpy(
2503 synced_settings, connection->synced_data.settings_self, sizeof(connection->synced_data.settings_self));
2504 } else {
2505 memcpy(
2506 synced_settings, connection->synced_data.settings_peer, sizeof(connection->synced_data.settings_peer));
2507 }
2508 s_unlock_synced_data(connection);
2509 } /* END CRITICAL SECTION */
2510 for (int i = AWS_HTTP2_SETTINGS_BEGIN_RANGE; i < AWS_HTTP2_SETTINGS_END_RANGE; i++) {
2511 /* settings range begin with 1, store them into 0-based array of aws_http2_setting */
2512 out_settings[i - 1].id = i;
2513 out_settings[i - 1].value = synced_settings[i];
2514 }
2515 return;
2516 }
2517
2518 static void s_connection_get_local_settings(
2519 const struct aws_http_connection *connection_base,
2520 struct aws_http2_setting out_settings[AWS_HTTP2_SETTINGS_COUNT]) {
2521 s_get_settings_general(connection_base, out_settings, true /*local*/);
2522 }
2523
2524 static void s_connection_get_remote_settings(
2525 const struct aws_http_connection *connection_base,
2526 struct aws_http2_setting out_settings[AWS_HTTP2_SETTINGS_COUNT]) {
2527 s_get_settings_general(connection_base, out_settings, false /*local*/);
2528 }
2529
2530 /* Send a GOAWAY with the lowest possible last-stream-id or graceful shutdown warning */
2531 static void s_send_goaway(
2532 struct aws_h2_connection *connection,
2533 uint32_t h2_error_code,
2534 bool allow_more_streams,
2535 const struct aws_byte_cursor *optional_debug_data) {
2536 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
2537
2538 uint32_t last_stream_id = allow_more_streams ? AWS_H2_STREAM_ID_MAX
2539 : aws_min_u32(
2540 connection->thread_data.latest_peer_initiated_stream_id,
2541 connection->thread_data.goaway_sent_last_stream_id);
2542
2543 if (last_stream_id > connection->thread_data.goaway_sent_last_stream_id) {
2544 CONNECTION_LOG(
2545 DEBUG,
2546 connection,
2547 "GOAWAY frame with lower last stream id has been sent, ignoring sending graceful shutdown warning.");
2548 return;
2549 }
2550
2551 struct aws_byte_cursor debug_data;
2552 AWS_ZERO_STRUCT(debug_data);
2553 if (optional_debug_data) {
2554 debug_data = *optional_debug_data;
2555 }
2556
2557 struct aws_h2_frame *goaway =
2558 aws_h2_frame_new_goaway(connection->base.alloc, last_stream_id, h2_error_code, debug_data);
2559 if (!goaway) {
2560 CONNECTION_LOGF(ERROR, connection, "Error creating GOAWAY frame, %s", aws_error_name(aws_last_error()));
2561 goto error;
2562 }
2563
2564 connection->thread_data.goaway_sent_last_stream_id = last_stream_id;
2565 { /* BEGIN CRITICAL SECTION */
2566 s_lock_synced_data(connection);
2567 connection->synced_data.goaway_sent_last_stream_id = last_stream_id;
2568 connection->synced_data.goaway_sent_http2_error_code = h2_error_code;
2569 s_unlock_synced_data(connection);
2570 } /* END CRITICAL SECTION */
2571 aws_h2_connection_enqueue_outgoing_frame(connection, goaway);
2572 return;
2573
2574 error:
2575 aws_h2_connection_shutdown_due_to_write_err(connection, aws_last_error());
2576 }
2577
2578 static int s_connection_get_sent_goaway(
2579 struct aws_http_connection *connection_base,
2580 uint32_t *out_http2_error,
2581 uint32_t *out_last_stream_id) {
2582
2583 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2584 uint32_t sent_last_stream_id;
2585 uint32_t sent_http2_error;
2586 { /* BEGIN CRITICAL SECTION */
2587 s_lock_synced_data(connection);
2588 sent_last_stream_id = connection->synced_data.goaway_sent_last_stream_id;
2589 sent_http2_error = connection->synced_data.goaway_sent_http2_error_code;
2590 s_unlock_synced_data(connection);
2591 } /* END CRITICAL SECTION */
2592
2593 uint32_t max_stream_id = AWS_H2_STREAM_ID_MAX;
2594 if (sent_last_stream_id == max_stream_id + 1) {
2595 CONNECTION_LOG(ERROR, connection, "No GOAWAY has been sent so far.");
2596 return aws_raise_error(AWS_ERROR_INVALID_STATE);
2597 }
2598
2599 *out_http2_error = sent_http2_error;
2600 *out_last_stream_id = sent_last_stream_id;
2601 return AWS_OP_SUCCESS;
2602 }
2603
2604 static int s_connection_get_received_goaway(
2605 struct aws_http_connection *connection_base,
2606 uint32_t *out_http2_error,
2607 uint32_t *out_last_stream_id) {
2608
2609 struct aws_h2_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h2_connection, base);
2610 uint32_t received_last_stream_id = 0;
2611 uint32_t received_http2_error = 0;
2612 bool goaway_not_ready = false;
2613 uint32_t max_stream_id = AWS_H2_STREAM_ID_MAX;
2614 { /* BEGIN CRITICAL SECTION */
2615 s_lock_synced_data(connection);
2616 if (connection->synced_data.goaway_received_last_stream_id == max_stream_id + 1) {
2617 goaway_not_ready = true;
2618 } else {
2619 received_last_stream_id = connection->synced_data.goaway_received_last_stream_id;
2620 received_http2_error = connection->synced_data.goaway_received_http2_error_code;
2621 }
2622 s_unlock_synced_data(connection);
2623 } /* END CRITICAL SECTION */
2624
2625 if (goaway_not_ready) {
2626 CONNECTION_LOG(ERROR, connection, "No GOAWAY has been received so far.");
2627 return aws_raise_error(AWS_ERROR_INVALID_STATE);
2628 }
2629
2630 *out_http2_error = received_http2_error;
2631 *out_last_stream_id = received_last_stream_id;
2632 return AWS_OP_SUCCESS;
2633 }
2634
2635 static int s_handler_process_read_message(
2636 struct aws_channel_handler *handler,
2637 struct aws_channel_slot *slot,
2638 struct aws_io_message *message) {
2639 (void)slot;
2640 struct aws_h2_connection *connection = handler->impl;
2641
2642 CONNECTION_LOGF(TRACE, connection, "Begin processing message of size %zu.", message->message_data.len);
2643
2644 if (connection->thread_data.is_reading_stopped) {
2645 CONNECTION_LOG(ERROR, connection, "Cannot process message because connection is shutting down.");
2646 goto clean_up;
2647 }
2648
2649 /* Any error that bubbles up from the decoder or its callbacks is treated as
2650 * a Connection Error (a GOAWAY frames is sent, and the connection is closed) */
2651 struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&message->message_data);
2652 struct aws_h2err err = aws_h2_decode(connection->thread_data.decoder, &message_cursor);
2653 if (aws_h2err_failed(err)) {
2654 CONNECTION_LOGF(
2655 ERROR,
2656 connection,
2657 "Failure while receiving frames, %s. Sending GOAWAY %s(0x%x) and closing connection",
2658 aws_error_name(err.aws_code),
2659 aws_http2_error_code_to_str(err.h2_code),
2660 err.h2_code);
2661 goto shutdown;
2662 }
2663
2664 /* HTTP/2 protocol uses WINDOW_UPDATE frames to coordinate data rates with peer,
2665 * so we can just keep the aws_channel's read-window wide open */
2666 if (aws_channel_slot_increment_read_window(slot, message->message_data.len)) {
2667 CONNECTION_LOGF(
2668 ERROR,
2669 connection,
2670 "Incrementing read window failed, error %d (%s). Closing connection",
2671 aws_last_error(),
2672 aws_error_name(aws_last_error()));
2673 err = aws_h2err_from_last_error();
2674 goto shutdown;
2675 }
2676
2677 goto clean_up;
2678
2679 shutdown:
2680 s_send_goaway(connection, err.h2_code, false /*allow_more_streams*/, NULL /*optional_debug_data*/);
2681 aws_h2_try_write_outgoing_frames(connection);
2682 s_stop(connection, true /*stop_reading*/, false /*stop_writing*/, true /*schedule_shutdown*/, err.aws_code);
2683
2684 clean_up:
2685 aws_mem_release(message->allocator, message);
2686
2687 /* Flush any outgoing frames that might have been queued as a result of decoder callbacks. */
2688 aws_h2_try_write_outgoing_frames(connection);
2689
2690 return AWS_OP_SUCCESS;
2691 }
2692
2693 static int s_handler_process_write_message(
2694 struct aws_channel_handler *handler,
2695 struct aws_channel_slot *slot,
2696 struct aws_io_message *message) {
2697
2698 (void)handler;
2699 (void)slot;
2700 (void)message;
2701 return aws_raise_error(AWS_ERROR_UNIMPLEMENTED);
2702 }
2703
2704 static int s_handler_increment_read_window(
2705 struct aws_channel_handler *handler,
2706 struct aws_channel_slot *slot,
2707 size_t size) {
2708
2709 (void)handler;
2710 (void)slot;
2711 (void)size;
2712 return aws_raise_error(AWS_ERROR_UNIMPLEMENTED);
2713 }
2714
2715 static int s_handler_shutdown(
2716 struct aws_channel_handler *handler,
2717 struct aws_channel_slot *slot,
2718 enum aws_channel_direction dir,
2719 int error_code,
2720 bool free_scarce_resources_immediately) {
2721
2722 struct aws_h2_connection *connection = handler->impl;
2723 CONNECTION_LOGF(
2724 TRACE,
2725 connection,
2726 "Channel shutting down in %s direction with error code %d (%s).",
2727 (dir == AWS_CHANNEL_DIR_READ) ? "read" : "write",
2728 error_code,
2729 aws_error_name(error_code));
2730
2731 if (dir == AWS_CHANNEL_DIR_READ) {
2732 /* This call ensures that no further streams will be created. */
2733 s_stop(connection, true /*stop_reading*/, false /*stop_writing*/, false /*schedule_shutdown*/, error_code);
2734 /* Send user requested GOAWAY, if they haven't been sent before. It's OK to access
2735 * synced_data.pending_goaway_list without holding the lock because no more user_requested GOAWAY can be added
2736 * after s_stop() has been invoked. */
2737 if (!aws_linked_list_empty(&connection->synced_data.pending_goaway_list)) {
2738 while (!aws_linked_list_empty(&connection->synced_data.pending_goaway_list)) {
2739 struct aws_linked_list_node *node =
2740 aws_linked_list_pop_front(&connection->synced_data.pending_goaway_list);
2741 struct aws_h2_pending_goaway *goaway = AWS_CONTAINER_OF(node, struct aws_h2_pending_goaway, node);
2742 s_send_goaway(connection, goaway->http2_error, goaway->allow_more_streams, &goaway->debug_data);
2743 aws_mem_release(connection->base.alloc, goaway);
2744 }
2745 aws_h2_try_write_outgoing_frames(connection);
2746 }
2747
2748 /* Send GOAWAY if none have been sent so far,
2749 * or if we've only sent a "graceful shutdown warning" that didn't name a last-stream-id */
2750 if (connection->thread_data.goaway_sent_last_stream_id == AWS_H2_STREAM_ID_MAX) {
2751 s_send_goaway(
2752 connection,
2753 error_code ? AWS_HTTP2_ERR_INTERNAL_ERROR : AWS_HTTP2_ERR_NO_ERROR,
2754 false /*allow_more_streams*/,
2755 NULL /*optional_debug_data*/);
2756 aws_h2_try_write_outgoing_frames(connection);
2757 }
2758 aws_channel_slot_on_handler_shutdown_complete(
2759 slot, AWS_CHANNEL_DIR_READ, error_code, free_scarce_resources_immediately);
2760
2761 } else /* AWS_CHANNEL_DIR_WRITE */ {
2762 connection->thread_data.channel_shutdown_error_code = error_code;
2763 connection->thread_data.channel_shutdown_immediately = free_scarce_resources_immediately;
2764 connection->thread_data.channel_shutdown_waiting_for_goaway_to_be_written = true;
2765
2766 /* We'd prefer to wait until we know GOAWAY has been written, but don't wait if... */
2767 if (free_scarce_resources_immediately /* we must finish ASAP */ ||
2768 connection->thread_data.is_writing_stopped /* write will never complete */ ||
2769 !connection->thread_data.is_outgoing_frames_task_active /* write is already complete */) {
2770
2771 s_finish_shutdown(connection);
2772 } else {
2773 CONNECTION_LOG(TRACE, connection, "HTTP/2 handler will finish shutdown once GOAWAY frame is written");
2774 }
2775 }
2776
2777 return AWS_OP_SUCCESS;
2778 }
2779
2780 static void s_finish_shutdown(struct aws_h2_connection *connection) {
2781 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
2782 AWS_PRECONDITION(connection->thread_data.channel_shutdown_waiting_for_goaway_to_be_written);
2783
2784 CONNECTION_LOG(TRACE, connection, "Finishing HTTP/2 handler shutdown");
2785
2786 connection->thread_data.channel_shutdown_waiting_for_goaway_to_be_written = false;
2787
2788 s_stop(
2789 connection,
2790 false /*stop_reading*/,
2791 true /*stop_writing*/,
2792 false /*schedule_shutdown*/,
2793 connection->thread_data.channel_shutdown_error_code);
2794
2795 /* Remove remaining streams from internal datastructures and mark them as complete. */
2796
2797 struct aws_hash_iter stream_iter = aws_hash_iter_begin(&connection->thread_data.active_streams_map);
2798 while (!aws_hash_iter_done(&stream_iter)) {
2799 struct aws_h2_stream *stream = stream_iter.element.value;
2800 aws_hash_iter_delete(&stream_iter, true);
2801 aws_hash_iter_next(&stream_iter);
2802
2803 s_stream_complete(connection, stream, AWS_ERROR_HTTP_CONNECTION_CLOSED);
2804 }
2805
2806 /* It's OK to access synced_data without holding the lock because
2807 * no more streams or user-requested control frames can be added after s_stop() has been invoked. */
2808 while (!aws_linked_list_empty(&connection->synced_data.pending_stream_list)) {
2809 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->synced_data.pending_stream_list);
2810 struct aws_h2_stream *stream = AWS_CONTAINER_OF(node, struct aws_h2_stream, node);
2811 s_stream_complete(connection, stream, AWS_ERROR_HTTP_CONNECTION_CLOSED);
2812 }
2813
2814 while (!aws_linked_list_empty(&connection->synced_data.pending_frame_list)) {
2815 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->synced_data.pending_frame_list);
2816 struct aws_h2_frame *frame = AWS_CONTAINER_OF(node, struct aws_h2_frame, node);
2817 aws_h2_frame_destroy(frame);
2818 }
2819
2820 /* invoke pending callbacks haven't moved into thread, and clean up the data */
2821 while (!aws_linked_list_empty(&connection->synced_data.pending_settings_list)) {
2822 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->synced_data.pending_settings_list);
2823 struct aws_h2_pending_settings *settings = AWS_CONTAINER_OF(node, struct aws_h2_pending_settings, node);
2824 if (settings->on_completed) {
2825 settings->on_completed(&connection->base, AWS_ERROR_HTTP_CONNECTION_CLOSED, settings->user_data);
2826 }
2827 aws_mem_release(connection->base.alloc, settings);
2828 }
2829 while (!aws_linked_list_empty(&connection->synced_data.pending_ping_list)) {
2830 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->synced_data.pending_ping_list);
2831 struct aws_h2_pending_ping *ping = AWS_CONTAINER_OF(node, struct aws_h2_pending_ping, node);
2832 if (ping->on_completed) {
2833 ping->on_completed(&connection->base, 0 /*fake rtt*/, AWS_ERROR_HTTP_CONNECTION_CLOSED, ping->user_data);
2834 }
2835 aws_mem_release(connection->base.alloc, ping);
2836 }
2837
2838 /* invoke pending callbacks moved into thread, and clean up the data */
2839 while (!aws_linked_list_empty(&connection->thread_data.pending_settings_queue)) {
2840 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->thread_data.pending_settings_queue);
2841 struct aws_h2_pending_settings *pending_settings = AWS_CONTAINER_OF(node, struct aws_h2_pending_settings, node);
2842 /* fire the user callback with error */
2843 if (pending_settings->on_completed) {
2844 pending_settings->on_completed(
2845 &connection->base, AWS_ERROR_HTTP_CONNECTION_CLOSED, pending_settings->user_data);
2846 }
2847 aws_mem_release(connection->base.alloc, pending_settings);
2848 }
2849 while (!aws_linked_list_empty(&connection->thread_data.pending_ping_queue)) {
2850 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->thread_data.pending_ping_queue);
2851 struct aws_h2_pending_ping *pending_ping = AWS_CONTAINER_OF(node, struct aws_h2_pending_ping, node);
2852 /* fire the user callback with error */
2853 if (pending_ping->on_completed) {
2854 pending_ping->on_completed(
2855 &connection->base, 0 /*fake rtt*/, AWS_ERROR_HTTP_CONNECTION_CLOSED, pending_ping->user_data);
2856 }
2857 aws_mem_release(connection->base.alloc, pending_ping);
2858 }
2859 aws_channel_slot_on_handler_shutdown_complete(
2860 connection->base.channel_slot,
2861 AWS_CHANNEL_DIR_WRITE,
2862 connection->thread_data.channel_shutdown_error_code,
2863 connection->thread_data.channel_shutdown_immediately);
2864 }
2865
2866 static size_t s_handler_initial_window_size(struct aws_channel_handler *handler) {
2867 (void)handler;
2868
2869 /* HTTP/2 protocol uses WINDOW_UPDATE frames to coordinate data rates with peer,
2870 * so we can just keep the aws_channel's read-window wide open */
2871 return SIZE_MAX;
2872 }
2873
2874 static size_t s_handler_message_overhead(struct aws_channel_handler *handler) {
2875 (void)handler;
2876
2877 /* "All frames begin with a fixed 9-octet header followed by a variable-length payload" (RFC-7540 4.1) */
2878 return 9;
2879 }
2880
2881 static void s_reset_statistics(struct aws_channel_handler *handler) {
2882 struct aws_h2_connection *connection = handler->impl;
2883 aws_crt_statistics_http2_channel_reset(&connection->thread_data.stats);
2884 if (aws_hash_table_get_entry_count(&connection->thread_data.active_streams_map) == 0) {
2885 /* Check the current state */
2886 connection->thread_data.stats.was_inactive = true;
2887 }
2888 return;
2889 }
2890
2891 static void s_gather_statistics(struct aws_channel_handler *handler, struct aws_array_list *stats) {
2892
2893 struct aws_h2_connection *connection = handler->impl;
2894 AWS_PRECONDITION(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
2895
2896 /* TODO: Need update the way we calculate statistics, to account for user-controlled pauses.
2897 * If user is adding chunks 1 by 1, there can naturally be a gap in the upload.
2898 * If the user lets the stream-window go to zero, there can naturally be a gap in the download. */
2899 uint64_t now_ns = 0;
2900 if (aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns)) {
2901 return;
2902 }
2903
2904 if (!aws_linked_list_empty(&connection->thread_data.outgoing_streams_list)) {
2905 s_add_time_measurement_to_stats(
2906 connection->thread_data.outgoing_timestamp_ns,
2907 now_ns,
2908 &connection->thread_data.stats.pending_outgoing_stream_ms);
2909
2910 connection->thread_data.outgoing_timestamp_ns = now_ns;
2911 }
2912 if (aws_hash_table_get_entry_count(&connection->thread_data.active_streams_map) != 0) {
2913 s_add_time_measurement_to_stats(
2914 connection->thread_data.incoming_timestamp_ns,
2915 now_ns,
2916 &connection->thread_data.stats.pending_incoming_stream_ms);
2917
2918 connection->thread_data.incoming_timestamp_ns = now_ns;
2919 } else {
2920 connection->thread_data.stats.was_inactive = true;
2921 }
2922
2923 void *stats_base = &connection->thread_data.stats;
2924 aws_array_list_push_back(stats, &stats_base);
2925 }