-
Notifications
You must be signed in to change notification settings - Fork 38
/
h1_connection.c
2213 lines (1835 loc) · 91.2 KB
/
h1_connection.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/common/clock.h>
#include <aws/common/math.h>
#include <aws/common/mutex.h>
#include <aws/common/string.h>
#include <aws/http/private/h1_connection.h>
#include <aws/http/private/h1_decoder.h>
#include <aws/http/private/h1_stream.h>
#include <aws/http/private/request_response_impl.h>
#include <aws/http/status_code.h>
#include <aws/io/event_loop.h>
#include <aws/io/logging.h>
#include <inttypes.h>
#ifdef _MSC_VER
# pragma warning(disable : 4204) /* non-constant aggregate initializer */
#endif
enum {
DECODER_INITIAL_SCRATCH_SIZE = 256,
};
static int s_handler_process_read_message(
struct aws_channel_handler *handler,
struct aws_channel_slot *slot,
struct aws_io_message *message);
static int s_handler_process_write_message(
struct aws_channel_handler *handler,
struct aws_channel_slot *slot,
struct aws_io_message *message);
static int s_handler_increment_read_window(
struct aws_channel_handler *handler,
struct aws_channel_slot *slot,
size_t size);
static int s_handler_shutdown(
struct aws_channel_handler *handler,
struct aws_channel_slot *slot,
enum aws_channel_direction dir,
int error_code,
bool free_scarce_resources_immediately);
static size_t s_handler_initial_window_size(struct aws_channel_handler *handler);
static size_t s_handler_message_overhead(struct aws_channel_handler *handler);
static void s_handler_destroy(struct aws_channel_handler *handler);
static void s_handler_installed(struct aws_channel_handler *handler, struct aws_channel_slot *slot);
static struct aws_http_stream *s_make_request(
struct aws_http_connection *client_connection,
const struct aws_http_make_request_options *options);
static struct aws_http_stream *s_new_server_request_handler_stream(
const struct aws_http_request_handler_options *options);
static int s_stream_send_response(struct aws_http_stream *stream, struct aws_http_message *response);
static void s_connection_close(struct aws_http_connection *connection_base);
static void s_connection_stop_new_request(struct aws_http_connection *connection_base);
static bool s_connection_is_open(const struct aws_http_connection *connection_base);
static bool s_connection_new_requests_allowed(const struct aws_http_connection *connection_base);
static int s_decoder_on_request(
enum aws_http_method method_enum,
const struct aws_byte_cursor *method_str,
const struct aws_byte_cursor *uri,
void *user_data);
static int s_decoder_on_response(int status_code, void *user_data);
static int s_decoder_on_header(const struct aws_h1_decoded_header *header, void *user_data);
static int s_decoder_on_body(const struct aws_byte_cursor *data, bool finished, void *user_data);
static int s_decoder_on_done(void *user_data);
static void s_reset_statistics(struct aws_channel_handler *handler);
static void s_gather_statistics(struct aws_channel_handler *handler, struct aws_array_list *stats);
static void s_write_outgoing_stream(struct aws_h1_connection *connection, bool first_try);
static int s_try_process_next_stream_read_message(struct aws_h1_connection *connection, bool *out_stop_processing);
static struct aws_http_connection_vtable s_h1_connection_vtable = {
.channel_handler_vtable =
{
.process_read_message = s_handler_process_read_message,
.process_write_message = s_handler_process_write_message,
.increment_read_window = s_handler_increment_read_window,
.shutdown = s_handler_shutdown,
.initial_window_size = s_handler_initial_window_size,
.message_overhead = s_handler_message_overhead,
.destroy = s_handler_destroy,
.reset_statistics = s_reset_statistics,
.gather_statistics = s_gather_statistics,
},
.on_channel_handler_installed = s_handler_installed,
.make_request = s_make_request,
.new_server_request_handler_stream = s_new_server_request_handler_stream,
.stream_send_response = s_stream_send_response,
.close = s_connection_close,
.stop_new_requests = s_connection_stop_new_request,
.is_open = s_connection_is_open,
.new_requests_allowed = s_connection_new_requests_allowed,
.change_settings = NULL,
.send_ping = NULL,
.send_goaway = NULL,
.get_sent_goaway = NULL,
.get_received_goaway = NULL,
.get_local_settings = NULL,
.get_remote_settings = NULL,
};
static const struct aws_h1_decoder_vtable s_h1_decoder_vtable = {
.on_request = s_decoder_on_request,
.on_response = s_decoder_on_response,
.on_header = s_decoder_on_header,
.on_body = s_decoder_on_body,
.on_done = s_decoder_on_done,
};
void aws_h1_connection_lock_synced_data(struct aws_h1_connection *connection) {
int err = aws_mutex_lock(&connection->synced_data.lock);
AWS_ASSERT(!err);
(void)err;
}
void aws_h1_connection_unlock_synced_data(struct aws_h1_connection *connection) {
int err = aws_mutex_unlock(&connection->synced_data.lock);
AWS_ASSERT(!err);
(void)err;
}
/**
* Internal function for bringing connection to a stop.
* Invoked multiple times, including when:
* - Channel is shutting down in the read direction.
* - Channel is shutting down in the write direction.
* - An error occurs.
* - User wishes to close the connection (this is the only case where the function may run off-thread).
*/
static void s_stop(
struct aws_h1_connection *connection,
bool stop_reading,
bool stop_writing,
bool schedule_shutdown,
int error_code) {
AWS_ASSERT(stop_reading || stop_writing || schedule_shutdown); /* You are required to stop at least 1 thing */
if (stop_reading) {
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
connection->thread_data.is_reading_stopped = true;
}
if (stop_writing) {
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
connection->thread_data.is_writing_stopped = true;
}
{ /* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
/* Even if we're not scheduling shutdown just yet (ex: sent final request but waiting to read final response)
* we don't consider the connection "open" anymore so user can't create more streams */
connection->synced_data.is_open = false;
connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
if (schedule_shutdown) {
AWS_LOGF_INFO(
AWS_LS_HTTP_CONNECTION,
"id=%p: Shutting down connection with error code %d (%s).",
(void *)&connection->base,
error_code,
aws_error_name(error_code));
aws_channel_shutdown(connection->base.channel_slot->channel, error_code);
}
}
static void s_shutdown_due_to_error(struct aws_h1_connection *connection, int error_code) {
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
if (!error_code) {
error_code = AWS_ERROR_UNKNOWN;
}
/* Stop reading AND writing if an error occurs.
*
* It doesn't currently seem worth the complexity to distinguish between read errors and write errors.
* The only scenarios that would benefit from this are pipelining scenarios (ex: A server
* could continue sending a response to request A if there was an error reading request B).
* But pipelining in HTTP/1.1 is known to be fragile with regards to errors, so let's just keep it simple.
*/
s_stop(connection, true /*stop_reading*/, true /*stop_writing*/, true /*schedule_shutdown*/, error_code);
}
/**
* Public function for closing connection.
*/
static void s_connection_close(struct aws_http_connection *connection_base) {
struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
/* Don't stop reading/writing immediately, let that happen naturally during the channel shutdown process. */
s_stop(connection, false /*stop_reading*/, false /*stop_writing*/, true /*schedule_shutdown*/, AWS_ERROR_SUCCESS);
}
static void s_connection_stop_new_request(struct aws_http_connection *connection_base) {
struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
{ /* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
if (!connection->synced_data.new_stream_error_code) {
connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_CONNECTION_CLOSED;
}
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
}
static bool s_connection_is_open(const struct aws_http_connection *connection_base) {
struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
bool is_open;
{ /* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
is_open = connection->synced_data.is_open;
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
return is_open;
}
static bool s_connection_new_requests_allowed(const struct aws_http_connection *connection_base) {
struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
int new_stream_error_code;
{ /* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
new_stream_error_code = connection->synced_data.new_stream_error_code;
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
return new_stream_error_code == 0;
}
static int s_stream_send_response(struct aws_http_stream *stream, struct aws_http_message *response) {
AWS_PRECONDITION(stream);
AWS_PRECONDITION(response);
struct aws_h1_stream *h1_stream = AWS_CONTAINER_OF(stream, struct aws_h1_stream, base);
return aws_h1_stream_send_response(h1_stream, response);
}
/* Calculate the desired window size for connection that has switched protocols and become a midchannel handler. */
static size_t s_calculate_midchannel_desired_connection_window(struct aws_h1_connection *connection) {
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
AWS_ASSERT(connection->thread_data.has_switched_protocols);
if (!connection->base.channel_slot->adj_right) {
/* No downstream handler installed. */
return 0;
}
/* Connection is just dumbly forwarding aws_io_messages, so try to match downstream handler. */
return aws_channel_slot_downstream_read_window(connection->base.channel_slot);
}
/* Calculate the desired window size for a connection that is processing data for aws_http_streams. */
static size_t s_calculate_stream_mode_desired_connection_window(struct aws_h1_connection *connection) {
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
AWS_ASSERT(!connection->thread_data.has_switched_protocols);
if (!connection->base.stream_manual_window_management) {
return SIZE_MAX;
}
/* Connection window should match the available space in the read-buffer */
AWS_ASSERT(
connection->thread_data.read_buffer.pending_bytes <= connection->thread_data.read_buffer.capacity &&
"This isn't fatal, but our math is off");
const size_t desired_connection_window = aws_sub_size_saturating(
connection->thread_data.read_buffer.capacity, connection->thread_data.read_buffer.pending_bytes);
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Window stats: connection=%zu+%zu stream=%" PRIu64 " buffer=%zu/%zu",
(void *)&connection->base,
connection->thread_data.connection_window,
desired_connection_window - connection->thread_data.connection_window /*increment_size*/,
connection->thread_data.incoming_stream ? connection->thread_data.incoming_stream->thread_data.stream_window
: 0,
connection->thread_data.read_buffer.pending_bytes,
connection->thread_data.read_buffer.capacity);
return desired_connection_window;
}
/* Increment connection window, if necessary */
static int s_update_connection_window(struct aws_h1_connection *connection) {
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
if (connection->thread_data.is_reading_stopped) {
return AWS_OP_SUCCESS;
}
const size_t desired_size = connection->thread_data.has_switched_protocols
? s_calculate_midchannel_desired_connection_window(connection)
: s_calculate_stream_mode_desired_connection_window(connection);
const size_t increment_size = aws_sub_size_saturating(desired_size, connection->thread_data.connection_window);
if (increment_size > 0) {
/* Update local `connection_window`. See comments at variable's declaration site
* on why we use this instead of the official `aws_channel_slot.window_size` */
connection->thread_data.connection_window += increment_size;
connection->thread_data.recent_window_increments =
aws_add_size_saturating(connection->thread_data.recent_window_increments, increment_size);
if (aws_channel_slot_increment_read_window(connection->base.channel_slot, increment_size)) {
AWS_LOGF_ERROR(
AWS_LS_HTTP_CONNECTION,
"id=%p: Failed to increment read window, error %d (%s). Closing connection.",
(void *)&connection->base,
aws_last_error(),
aws_error_name(aws_last_error()));
return AWS_OP_ERR;
}
}
return AWS_OP_SUCCESS;
}
int aws_h1_stream_activate(struct aws_http_stream *stream) {
struct aws_h1_stream *h1_stream = AWS_CONTAINER_OF(stream, struct aws_h1_stream, base);
struct aws_http_connection *base_connection = stream->owning_connection;
struct aws_h1_connection *connection = AWS_CONTAINER_OF(base_connection, struct aws_h1_connection, base);
bool should_schedule_task = false;
{ /* BEGIN CRITICAL SECTION */
/* Note: We're touching both the connection's and stream's synced_data in this section,
* which is OK because an h1_connection and all its h1_streams share a single lock. */
aws_h1_connection_lock_synced_data(connection);
if (stream->id) {
/* stream has already been activated. */
aws_h1_connection_unlock_synced_data(connection);
return AWS_OP_SUCCESS;
}
if (connection->synced_data.new_stream_error_code) {
aws_h1_connection_unlock_synced_data(connection);
AWS_LOGF_ERROR(
AWS_LS_HTTP_CONNECTION,
"id=%p: Failed to activate the stream id=%p, new streams are not allowed now. error %d (%s)",
(void *)&connection->base,
(void *)stream,
connection->synced_data.new_stream_error_code,
aws_error_name(connection->synced_data.new_stream_error_code));
return aws_raise_error(connection->synced_data.new_stream_error_code);
}
stream->id = aws_http_connection_get_next_stream_id(base_connection);
if (!stream->id) {
aws_h1_connection_unlock_synced_data(connection);
/* aws_http_connection_get_next_stream_id() raises its own error. */
return AWS_OP_ERR;
}
/* ID successfully assigned */
h1_stream->synced_data.api_state = AWS_H1_STREAM_API_STATE_ACTIVE;
aws_linked_list_push_back(&connection->synced_data.new_client_stream_list, &h1_stream->node);
if (!connection->synced_data.is_cross_thread_work_task_scheduled) {
connection->synced_data.is_cross_thread_work_task_scheduled = true;
should_schedule_task = true;
}
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
/* connection keeps activated stream alive until stream completes */
aws_atomic_fetch_add(&stream->refcount, 1);
stream->metrics.stream_id = stream->id;
if (should_schedule_task) {
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION, "id=%p: Scheduling connection cross-thread work task.", (void *)base_connection);
aws_channel_schedule_task_now(connection->base.channel_slot->channel, &connection->cross_thread_work_task);
} else {
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Connection cross-thread work task was already scheduled",
(void *)base_connection);
}
return AWS_OP_SUCCESS;
}
void aws_h1_stream_cancel(struct aws_http_stream *stream, int error_code) {
struct aws_h1_stream *h1_stream = AWS_CONTAINER_OF(stream, struct aws_h1_stream, base);
struct aws_http_connection *base_connection = stream->owning_connection;
struct aws_h1_connection *connection = AWS_CONTAINER_OF(base_connection, struct aws_h1_connection, base);
{ /* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
if (h1_stream->synced_data.api_state != AWS_H1_STREAM_API_STATE_ACTIVE ||
connection->synced_data.is_open == false) {
/* Not active, nothing to cancel. */
aws_h1_connection_unlock_synced_data(connection);
AWS_LOGF_DEBUG(AWS_LS_HTTP_STREAM, "id=%p: Stream not active, nothing to cancel.", (void *)stream);
return;
}
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
AWS_LOGF_INFO(
AWS_LS_HTTP_CONNECTION,
"id=%p: Connection shutting down due to stream=%p cancelled with error code %d (%s).",
(void *)&connection->base,
(void *)stream,
error_code,
aws_error_name(error_code));
s_stop(connection, false /*stop_reading*/, false /*stop_writing*/, true /*schedule_shutdown*/, error_code);
}
struct aws_http_stream *s_make_request(
struct aws_http_connection *client_connection,
const struct aws_http_make_request_options *options) {
struct aws_h1_stream *stream = aws_h1_stream_new_request(client_connection, options);
if (!stream) {
AWS_LOGF_ERROR(
AWS_LS_HTTP_CONNECTION,
"id=%p: Cannot create request stream, error %d (%s)",
(void *)client_connection,
aws_last_error(),
aws_error_name(aws_last_error()));
return NULL;
}
struct aws_h1_connection *connection = AWS_CONTAINER_OF(client_connection, struct aws_h1_connection, base);
/* Insert new stream into pending list, and schedule outgoing_stream_task if it's not already running. */
int new_stream_error_code;
{ /* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
new_stream_error_code = connection->synced_data.new_stream_error_code;
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
if (new_stream_error_code) {
AWS_LOGF_ERROR(
AWS_LS_HTTP_CONNECTION,
"id=%p: Cannot create request stream, error %d (%s)",
(void *)client_connection,
new_stream_error_code,
aws_error_name(new_stream_error_code));
aws_raise_error(new_stream_error_code);
goto error;
}
/* Success! */
struct aws_byte_cursor method;
aws_http_message_get_request_method(options->request, &method);
stream->base.request_method = aws_http_str_to_method(method);
struct aws_byte_cursor path;
aws_http_message_get_request_path(options->request, &path);
AWS_LOGF_DEBUG(
AWS_LS_HTTP_STREAM,
"id=%p: Created client request on connection=%p: " PRInSTR " " PRInSTR " " PRInSTR,
(void *)&stream->base,
(void *)client_connection,
AWS_BYTE_CURSOR_PRI(method),
AWS_BYTE_CURSOR_PRI(path),
AWS_BYTE_CURSOR_PRI(aws_http_version_to_str(connection->base.http_version)));
return &stream->base;
error:
/* Force destruction of the stream, avoiding ref counting */
stream->base.vtable->destroy(&stream->base);
return NULL;
}
/* Extract work items from synced_data, and perform the work on-thread. */
static void s_cross_thread_work_task(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
(void)channel_task;
struct aws_h1_connection *connection = arg;
if (status != AWS_TASK_STATUS_RUN_READY) {
return;
}
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION, "id=%p: Running connection cross-thread work task.", (void *)&connection->base);
/* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
connection->synced_data.is_cross_thread_work_task_scheduled = false;
bool has_new_client_streams = !aws_linked_list_empty(&connection->synced_data.new_client_stream_list);
aws_linked_list_move_all_back(
&connection->thread_data.stream_list, &connection->synced_data.new_client_stream_list);
aws_h1_connection_unlock_synced_data(connection);
/* END CRITICAL SECTION */
/* Kick off outgoing-stream task if necessary */
if (has_new_client_streams) {
aws_h1_connection_try_write_outgoing_stream(connection);
}
}
static bool s_aws_http_stream_was_successful_connect(struct aws_h1_stream *stream) {
struct aws_http_stream *base = &stream->base;
if (base->request_method != AWS_HTTP_METHOD_CONNECT) {
return false;
}
if (base->client_data == NULL) {
return false;
}
if (base->client_data->response_status != AWS_HTTP_STATUS_CODE_200_OK) {
return false;
}
return true;
}
/**
* Validate and perform a protocol switch on a connection. Protocol switching essentially turns the connection's
* handler into a dummy pass-through. It is valid to switch protocols to the same protocol resulting in a channel
* that has a "dead" http handler in the middle of the channel (which negotiated the CONNECT through the proxy) and
* a "live" handler on the end which takes the actual http requests. By doing this, we get the exact same
* behavior whether we're transitioning to http or any other protocol: once the CONNECT succeeds
* the first http handler is put in pass-through mode and a new protocol (which could be http) is tacked onto the end.
*/
static int s_aws_http1_switch_protocols(struct aws_h1_connection *connection) {
AWS_FATAL_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
/* Switching protocols while there are multiple streams is too complex to deal with.
* Ensure stream_list has exactly this 1 stream in it. */
if (aws_linked_list_begin(&connection->thread_data.stream_list) !=
aws_linked_list_rbegin(&connection->thread_data.stream_list)) {
AWS_LOGF_ERROR(
AWS_LS_HTTP_CONNECTION,
"id=%p: Cannot switch protocols while further streams are pending, closing connection.",
(void *)&connection->base);
return aws_raise_error(AWS_ERROR_INVALID_STATE);
}
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Connection has switched protocols, another channel handler must be installed to"
" deal with further data.",
(void *)&connection->base);
connection->thread_data.has_switched_protocols = true;
{ /* BEGIN CRITICAL SECTION */
aws_h1_connection_lock_synced_data(connection);
connection->synced_data.new_stream_error_code = AWS_ERROR_HTTP_SWITCHED_PROTOCOLS;
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
return AWS_OP_SUCCESS;
}
static void s_stream_complete(struct aws_h1_stream *stream, int error_code) {
struct aws_h1_connection *connection =
AWS_CONTAINER_OF(stream->base.owning_connection, struct aws_h1_connection, base);
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
/*
* If this is the end of a successful CONNECT request, mark ourselves as pass-through since the proxy layer
* will be tacking on a new http handler (and possibly a tls handler in-between).
*/
if (error_code == AWS_ERROR_SUCCESS && s_aws_http_stream_was_successful_connect(stream)) {
if (s_aws_http1_switch_protocols(connection)) {
error_code = AWS_ERROR_HTTP_PROTOCOL_SWITCH_FAILURE;
s_shutdown_due_to_error(connection, error_code);
}
}
if (stream->base.client_data && stream->base.client_data->response_first_byte_timeout_task.fn != NULL) {
/* There is an outstanding response timeout task, but stream completed, we can cancel it now. We are
* safe to do it as we always on connection thread to schedule the task or cancel it */
struct aws_event_loop *connection_loop = aws_channel_get_event_loop(connection->base.channel_slot->channel);
/* The task will be zeroed out within the call */
aws_event_loop_cancel_task(connection_loop, &stream->base.client_data->response_first_byte_timeout_task);
}
if (error_code != AWS_ERROR_SUCCESS) {
if (stream->base.client_data && stream->is_incoming_message_done) {
/* As a request that finished receiving the response, we ignore error and
* consider it finished successfully */
AWS_LOGF_DEBUG(
AWS_LS_HTTP_STREAM,
"id=%p: Ignoring error code %d (%s). The response has been fully received,"
"so the stream will complete successfully.",
(void *)&stream->base,
error_code,
aws_error_name(error_code));
error_code = AWS_ERROR_SUCCESS;
}
if (stream->base.server_data && stream->is_outgoing_message_done) {
/* As a server finished sending the response, but still failed with the request was not finished receiving.
* We ignore error and consider it finished successfully */
AWS_LOGF_DEBUG(
AWS_LS_HTTP_STREAM,
"id=%p: Ignoring error code %d (%s). The response has been fully sent,"
" so the stream will complete successfully",
(void *)&stream->base,
error_code,
aws_error_name(error_code));
error_code = AWS_ERROR_SUCCESS;
}
}
/* Remove stream from list. */
aws_linked_list_remove(&stream->node);
/* Nice logging */
if (error_code) {
AWS_LOGF_DEBUG(
AWS_LS_HTTP_STREAM,
"id=%p: Stream completed with error code %d (%s).",
(void *)&stream->base,
error_code,
aws_error_name(error_code));
} else if (stream->base.client_data) {
AWS_LOGF_DEBUG(
AWS_LS_HTTP_STREAM,
"id=%p: Client request complete, response status: %d (%s).",
(void *)&stream->base,
stream->base.client_data->response_status,
aws_http_status_text(stream->base.client_data->response_status));
} else {
AWS_ASSERT(stream->base.server_data);
AWS_LOGF_DEBUG(
AWS_LS_HTTP_STREAM,
"id=%p: Server response to " PRInSTR " request complete.",
(void *)&stream->base,
AWS_BYTE_CURSOR_PRI(stream->base.server_data->request_method_str));
}
/* If connection must shut down, do it BEFORE invoking stream-complete callback.
* That way, if aws_http_connection_is_open() is called from stream-complete callback, it returns false. */
if (stream->is_final_stream) {
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Closing connection due to completion of final stream.",
(void *)&connection->base);
s_connection_close(&connection->base);
}
{ /* BEGIN CRITICAL SECTION */
/* Note: We're touching the stream's synced_data here, which is OK
* because an h1_connection and all its h1_streams share a single lock. */
aws_h1_connection_lock_synced_data(connection);
/* Mark stream complete */
stream->synced_data.api_state = AWS_H1_STREAM_API_STATE_COMPLETE;
/* Move chunks out of synced data */
aws_linked_list_move_all_back(&stream->thread_data.pending_chunk_list, &stream->synced_data.pending_chunk_list);
aws_h1_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
/* Complete any leftover chunks */
while (!aws_linked_list_empty(&stream->thread_data.pending_chunk_list)) {
struct aws_linked_list_node *node = aws_linked_list_pop_front(&stream->thread_data.pending_chunk_list);
struct aws_h1_chunk *chunk = AWS_CONTAINER_OF(node, struct aws_h1_chunk, node);
aws_h1_chunk_complete_and_destroy(chunk, &stream->base, AWS_ERROR_HTTP_STREAM_HAS_COMPLETED);
}
if (stream->base.on_metrics) {
stream->base.on_metrics(&stream->base, &stream->base.metrics, stream->base.user_data);
}
/* Invoke callback and clean up stream. */
if (stream->base.on_complete) {
stream->base.on_complete(&stream->base, error_code, stream->base.user_data);
}
aws_http_stream_release(&stream->base);
}
static void s_add_time_measurement_to_stats(uint64_t start_ns, uint64_t end_ns, uint64_t *output_ms) {
if (end_ns > start_ns) {
*output_ms += aws_timestamp_convert(end_ns - start_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_MILLIS, NULL);
}
}
static void s_set_outgoing_stream_ptr(
struct aws_h1_connection *connection,
struct aws_h1_stream *next_outgoing_stream) {
struct aws_h1_stream *prev = connection->thread_data.outgoing_stream;
uint64_t now_ns = 0;
aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns);
if (prev == NULL && next_outgoing_stream != NULL) {
/* transition from nothing to write -> something to write */
connection->thread_data.outgoing_stream_timestamp_ns = now_ns;
} else if (prev != NULL && next_outgoing_stream == NULL) {
/* transition from something to write -> nothing to write */
s_add_time_measurement_to_stats(
connection->thread_data.outgoing_stream_timestamp_ns,
now_ns,
&connection->thread_data.stats.pending_outgoing_stream_ms);
}
connection->thread_data.outgoing_stream = next_outgoing_stream;
}
static void s_set_incoming_stream_ptr(
struct aws_h1_connection *connection,
struct aws_h1_stream *next_incoming_stream) {
struct aws_h1_stream *prev = connection->thread_data.incoming_stream;
uint64_t now_ns = 0;
aws_channel_current_clock_time(connection->base.channel_slot->channel, &now_ns);
if (prev == NULL && next_incoming_stream != NULL) {
/* transition from nothing to read -> something to read */
connection->thread_data.incoming_stream_timestamp_ns = now_ns;
} else if (prev != NULL && next_incoming_stream == NULL) {
/* transition from something to read -> nothing to read */
s_add_time_measurement_to_stats(
connection->thread_data.incoming_stream_timestamp_ns,
now_ns,
&connection->thread_data.stats.pending_incoming_stream_ms);
}
connection->thread_data.incoming_stream = next_incoming_stream;
}
/**
* Ensure `incoming_stream` is pointing at the correct stream, and update state if it changes.
*/
static void s_client_update_incoming_stream_ptr(struct aws_h1_connection *connection) {
struct aws_linked_list *list = &connection->thread_data.stream_list;
struct aws_h1_stream *desired;
if (connection->thread_data.is_reading_stopped) {
desired = NULL;
} else if (aws_linked_list_empty(list)) {
desired = NULL;
} else {
desired = AWS_CONTAINER_OF(aws_linked_list_begin(list), struct aws_h1_stream, node);
}
if (connection->thread_data.incoming_stream == desired) {
return;
}
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Current incoming stream is now %p.",
(void *)&connection->base,
desired ? (void *)&desired->base : NULL);
s_set_incoming_stream_ptr(connection, desired);
}
static void s_http_stream_response_first_byte_timeout_task(
struct aws_task *task,
void *arg,
enum aws_task_status status) {
(void)task;
struct aws_h1_stream *stream = arg;
struct aws_http_connection *connection_base = stream->base.owning_connection;
/* zero-out task to indicate that it's no longer scheduled */
AWS_ZERO_STRUCT(stream->base.client_data->response_first_byte_timeout_task);
if (status == AWS_TASK_STATUS_CANCELED) {
return;
}
struct aws_h1_connection *connection = AWS_CONTAINER_OF(connection_base, struct aws_h1_connection, base);
/* Timeout happened, close the connection */
uint64_t response_first_byte_timeout_ms = stream->base.client_data->response_first_byte_timeout_ms == 0
? connection_base->client_data->response_first_byte_timeout_ms
: stream->base.client_data->response_first_byte_timeout_ms;
AWS_LOGF_INFO(
AWS_LS_HTTP_CONNECTION,
"id=%p: Closing connection as timeout after request sent to the first byte received happened. "
"response_first_byte_timeout_ms is %" PRIu64 ".",
(void *)connection_base,
response_first_byte_timeout_ms);
/* Don't stop reading/writing immediately, let that happen naturally during the channel shutdown process. */
s_stop(
connection,
false /*stop_reading*/,
false /*stop_writing*/,
true /*schedule_shutdown*/,
AWS_ERROR_HTTP_RESPONSE_FIRST_BYTE_TIMEOUT);
}
static void s_set_outgoing_message_done(struct aws_h1_stream *stream) {
struct aws_http_connection *connection = stream->base.owning_connection;
struct aws_channel *channel = aws_http_connection_get_channel(connection);
AWS_ASSERT(aws_channel_thread_is_callers_thread(channel));
if (stream->is_outgoing_message_done) {
/* Already did the job */
return;
}
stream->is_outgoing_message_done = true;
AWS_ASSERT(stream->base.metrics.send_end_timestamp_ns == -1);
aws_high_res_clock_get_ticks((uint64_t *)&stream->base.metrics.send_end_timestamp_ns);
AWS_ASSERT(stream->base.metrics.send_start_timestamp_ns != -1);
AWS_ASSERT(stream->base.metrics.send_end_timestamp_ns >= stream->base.metrics.send_start_timestamp_ns);
stream->base.metrics.sending_duration_ns =
stream->base.metrics.send_end_timestamp_ns - stream->base.metrics.send_start_timestamp_ns;
if (stream->base.metrics.receive_start_timestamp_ns == -1) {
/* We haven't receive any message, schedule the response timeout task */
uint64_t response_first_byte_timeout_ms = 0;
if (stream->base.client_data != NULL && connection->client_data != NULL) {
response_first_byte_timeout_ms = stream->base.client_data->response_first_byte_timeout_ms == 0
? connection->client_data->response_first_byte_timeout_ms
: stream->base.client_data->response_first_byte_timeout_ms;
}
if (response_first_byte_timeout_ms != 0) {
/* The task should not be initialized before. */
AWS_ASSERT(stream->base.client_data->response_first_byte_timeout_task.fn == NULL);
aws_task_init(
&stream->base.client_data->response_first_byte_timeout_task,
s_http_stream_response_first_byte_timeout_task,
stream,
"http_stream_response_first_byte_timeout_task");
uint64_t now_ns = 0;
aws_channel_current_clock_time(channel, &now_ns);
struct aws_event_loop *connection_loop = aws_channel_get_event_loop(channel);
aws_event_loop_schedule_task_future(
connection_loop,
&stream->base.client_data->response_first_byte_timeout_task,
now_ns + aws_timestamp_convert(
response_first_byte_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL));
}
}
}
/**
* If necessary, update `outgoing_stream` so it is pointing at a stream
* with data to send, or NULL if all streams are done sending data.
*
* Called from event-loop thread.
* This function has lots of side effects.
*/
static struct aws_h1_stream *s_update_outgoing_stream_ptr(struct aws_h1_connection *connection) {
struct aws_h1_stream *current = connection->thread_data.outgoing_stream;
bool current_changed = false;
int err;
/* If current stream is done sending data... */
if (current && !aws_h1_encoder_is_message_in_progress(&connection->thread_data.encoder)) {
s_set_outgoing_message_done(current);
/* RFC-7230 section 6.6: Tear-down.
* If this was the final stream, don't allows any further streams to be sent */
if (current->is_final_stream) {
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Done sending final stream, no further streams will be sent.",
(void *)&connection->base);
s_stop(
connection,
false /*stop_reading*/,
true /*stop_writing*/,
false /*schedule_shutdown*/,
AWS_ERROR_SUCCESS);
}
/* If it's also done receiving data, then it's complete! */
if (current->is_incoming_message_done) {
/* Only 1st stream in list could finish receiving before it finished sending */
AWS_ASSERT(¤t->node == aws_linked_list_begin(&connection->thread_data.stream_list));
/* This removes stream from list */
s_stream_complete(current, AWS_ERROR_SUCCESS);
}
current = NULL;
current_changed = true;
}
/* If current stream is NULL, look for more work. */
if (!current && !connection->thread_data.is_writing_stopped) {
/* Look for next stream we can work on. */
for (struct aws_linked_list_node *node = aws_linked_list_begin(&connection->thread_data.stream_list);
node != aws_linked_list_end(&connection->thread_data.stream_list);
node = aws_linked_list_next(node)) {
struct aws_h1_stream *stream = AWS_CONTAINER_OF(node, struct aws_h1_stream, node);
/* If we already sent this stream's data, keep looking... */
if (stream->is_outgoing_message_done) {
continue;
}
/* STOP if we're a server, and this stream's response isn't ready to send.
* It's not like we can skip this and start on the next stream because responses must be sent in order.
* Don't need a check like this for clients because their streams always start with data to send. */
if (connection->base.server_data && !stream->thread_data.has_outgoing_response) {
break;
}
/* We found a stream to work on! */
current = stream;
current_changed = true;
break;
}
}
/* Update current incoming and outgoing streams. */
if (current_changed) {
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Current outgoing stream is now %p.",
(void *)&connection->base,
current ? (void *)¤t->base : NULL);
s_set_outgoing_stream_ptr(connection, current);
if (current) {
AWS_ASSERT(current->base.metrics.send_start_timestamp_ns == -1);
aws_high_res_clock_get_ticks((uint64_t *)¤t->base.metrics.send_start_timestamp_ns);
err = aws_h1_encoder_start_message(
&connection->thread_data.encoder, ¤t->encoder_message, ¤t->base);
(void)err;
AWS_ASSERT(connection->thread_data.encoder.state == AWS_H1_ENCODER_STATE_INIT);
AWS_ASSERT(!err);
}
/* incoming_stream update is only for client */
if (connection->base.client_data) {
s_client_update_incoming_stream_ptr(connection);
}
}
return current;
}
/* Runs after an aws_io_message containing HTTP has completed (written to the network, or failed).
* This does NOT run after switching protocols, when we're dumbly forwarding aws_io_messages
* as a midchannel handler. */
static void s_on_channel_write_complete(
struct aws_channel *channel,
struct aws_io_message *message,
int err_code,
void *user_data) {
(void)message;
struct aws_h1_connection *connection = user_data;
AWS_ASSERT(connection->thread_data.is_outgoing_stream_task_active);
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
if (err_code) {
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Message did not write to network, error %d (%s)",
(void *)&connection->base,
err_code,
aws_error_name(err_code));
s_shutdown_due_to_error(connection, err_code);
return;
}
AWS_LOGF_TRACE(
AWS_LS_HTTP_CONNECTION,
"id=%p: Message finished writing to network. Rescheduling outgoing stream task.",
(void *)&connection->base);
/* To avoid wasting memory, we only want ONE of our written aws_io_messages in the channel at a time.
* Therefore, we wait until it's written to the network before trying to send another
* by running the outgoing-stream-task again.
*
* We also want to share the network with other channels.
* Therefore, when the write completes, we SCHEDULE the outgoing-stream-task
* to run again instead of calling the function directly.
* This way, if the message completes synchronously,
* we're not hogging the network by writing message after message in a tight loop */
aws_channel_schedule_task_now(channel, &connection->outgoing_stream_task);
}
static void s_outgoing_stream_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
(void)task;
if (status != AWS_TASK_STATUS_RUN_READY) {
return;
}
struct aws_h1_connection *connection = arg;
AWS_ASSERT(connection->thread_data.is_outgoing_stream_task_active);
AWS_ASSERT(aws_channel_thread_is_callers_thread(connection->base.channel_slot->channel));
s_write_outgoing_stream(connection, false /*first_try*/);