-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
node_http2.cc
3120 lines (2682 loc) Β· 110 KB
/
node_http2.cc
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
#include "aliased_buffer.h"
#include "allocated_buffer-inl.h"
#include "aliased_struct-inl.h"
#include "debug_utils-inl.h"
#include "memory_tracker-inl.h"
#include "node.h"
#include "node_buffer.h"
#include "node_http2.h"
#include "node_http_common-inl.h"
#include "node_mem-inl.h"
#include "node_perf.h"
#include "node_revert.h"
#include "stream_base-inl.h"
#include "util-inl.h"
#include <algorithm>
namespace node {
using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::Boolean;
using v8::Context;
using v8::EscapableHandleScope;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::String;
using v8::Uint8Array;
using v8::Undefined;
using v8::Value;
using node::performance::PerformanceEntry;
namespace http2 {
namespace {
const char zero_bytes_256[256] = {};
bool HasHttp2Observer(Environment* env) {
AliasedUint32Array& observers = env->performance_state()->observers;
return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
}
} // anonymous namespace
// These configure the callbacks required by nghttp2 itself. There are
// two sets of callback functions, one that is used if a padding callback
// is set, and other that does not include the padding callback.
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
Callbacks(false),
Callbacks(true)};
// The Http2Scope object is used to queue a write to the i/o stream. It is
// used whenever any action is take on the underlying nghttp2 API that may
// push data into nghttp2 outbound data queue.
//
// For example:
//
// Http2Scope h2scope(session);
// nghttp2_submit_ping(session->session(), ... );
//
// When the Http2Scope passes out of scope and is deconstructed, it will
// call Http2Session::MaybeScheduleWrite().
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
Http2Scope::Http2Scope(Http2Session* session) : session_(session) {
if (!session_) return;
// If there is another scope further below on the stack, or
// a write is already scheduled, there's nothing to do.
if (session_->is_in_scope() || session_->is_write_scheduled()) {
session_.reset();
return;
}
session_->set_in_scope();
}
Http2Scope::~Http2Scope() {
if (!session_) return;
session_->set_in_scope(false);
session_->MaybeScheduleWrite();
}
// The Http2Options object is used during the construction of Http2Session
// instances to configure an appropriate nghttp2_options struct. The class
// uses a single TypedArray instance that is shared with the JavaScript side
// to more efficiently pass values back and forth.
Http2Options::Http2Options(Http2State* http2_state, SessionType type) {
nghttp2_option* option;
CHECK_EQ(nghttp2_option_new(&option), 0);
CHECK_NOT_NULL(option);
options_.reset(option);
// Make sure closed connections aren't kept around, taking up memory.
// Note that this breaks the priority tree, which we don't use.
nghttp2_option_set_no_closed_streams(option, 1);
// We manually handle flow control within a session in order to
// implement backpressure -- that is, we only send WINDOW_UPDATE
// frames to the remote peer as data is actually consumed by user
// code. This ensures that the flow of data over the connection
// does not move too quickly and limits the amount of data we
// are required to buffer.
nghttp2_option_set_no_auto_window_update(option, 1);
// Enable built in support for receiving ALTSVC and ORIGIN frames (but
// only on client side sessions
if (type == NGHTTP2_SESSION_CLIENT) {
nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ALTSVC);
nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ORIGIN);
}
AliasedUint32Array& buffer = http2_state->options_buffer;
uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) {
nghttp2_option_set_max_deflate_dynamic_table_size(
option,
buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
}
if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
nghttp2_option_set_max_reserved_remote_streams(
option,
buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]);
}
if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) {
nghttp2_option_set_max_send_header_block_length(
option,
buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
}
// Recommended default
nghttp2_option_set_peer_max_concurrent_streams(option, 100);
if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
nghttp2_option_set_peer_max_concurrent_streams(
option,
buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
}
// The padding strategy sets the mechanism by which we determine how much
// additional frame padding to apply to DATA and HEADERS frames. Currently
// this is set on a per-session basis, but eventually we may switch to
// a per-stream setting, giving users greater control
if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
PaddingStrategy strategy =
static_cast<PaddingStrategy>(
buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
set_padding_strategy(strategy);
}
// The max header list pairs option controls the maximum number of
// header pairs the session may accept. This is a hard limit.. that is,
// if the remote peer sends more than this amount, the stream will be
// automatically closed with an RST_STREAM.
if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS))
set_max_header_pairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
// The HTTP2 specification places no limits on the number of HTTP2
// PING frames that can be sent. In order to prevent PINGS from being
// abused as an attack vector, however, we place a strict upper limit
// on the number of unacknowledged PINGS that can be sent at any given
// time.
if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS))
set_max_outstanding_pings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
// The HTTP2 specification places no limits on the number of HTTP2
// SETTINGS frames that can be sent. In order to prevent PINGS from being
// abused as an attack vector, however, we place a strict upper limit
// on the number of unacknowledged SETTINGS that can be sent at any given
// time.
if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS))
set_max_outstanding_settings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
// The HTTP2 specification places no limits on the amount of memory
// that a session can consume. In order to prevent abuse, we place a
// cap on the amount of memory a session can consume at any given time.
// this is a credit based system. Existing streams may cause the limit
// to be temporarily exceeded but once over the limit, new streams cannot
// created.
// Important: The maxSessionMemory option in javascript is expressed in
// terms of MB increments (i.e. the value 1 == 1 MB)
if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY))
set_max_session_memory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1000000);
if (flags & (1 << IDX_OPTIONS_MAX_SETTINGS)) {
nghttp2_option_set_max_settings(
option,
static_cast<size_t>(buffer[IDX_OPTIONS_MAX_SETTINGS]));
}
}
#define GRABSETTING(entries, count, name) \
do { \
if (flags & (1 << IDX_SETTINGS_ ## name)) { \
uint32_t val = buffer[IDX_SETTINGS_ ## name]; \
entries[count++] = \
nghttp2_settings_entry {NGHTTP2_SETTINGS_ ## name, val}; \
} } while (0)
size_t Http2Settings::Init(
Http2State* http2_state,
nghttp2_settings_entry* entries) {
AliasedUint32Array& buffer = http2_state->settings_buffer;
uint32_t flags = buffer[IDX_SETTINGS_COUNT];
size_t count = 0;
#define V(name) GRABSETTING(entries, count, name);
HTTP2_SETTINGS(V)
#undef V
return count;
}
#undef GRABSETTING
// The Http2Settings class is used to configure a SETTINGS frame that is
// to be sent to the connected peer. The settings are set using a TypedArray
// that is shared with the JavaScript side.
Http2Settings::Http2Settings(Http2Session* session,
Local<Object> obj,
Local<Function> callback,
uint64_t start_time)
: AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
session_(session),
startTime_(start_time) {
callback_.Reset(env()->isolate(), callback);
count_ = Init(session->http2_state(), entries_);
}
Local<Function> Http2Settings::callback() const {
return callback_.Get(env()->isolate());
}
void Http2Settings::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("callback", callback_);
}
// Generates a Buffer that contains the serialized payload of a SETTINGS
// frame. This can be used, for instance, to create the Base64-encoded
// content of an Http2-Settings header field.
Local<Value> Http2Settings::Pack() {
return Pack(session_->env(), count_, entries_);
}
Local<Value> Http2Settings::Pack(Http2State* state) {
nghttp2_settings_entry entries[IDX_SETTINGS_COUNT];
size_t count = Init(state, entries);
return Pack(state->env(), count, entries);
}
Local<Value> Http2Settings::Pack(
Environment* env,
size_t count,
const nghttp2_settings_entry* entries) {
EscapableHandleScope scope(env->isolate());
const size_t size = count * 6;
AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
ssize_t ret =
nghttp2_pack_settings_payload(
reinterpret_cast<uint8_t*>(buffer.data()),
size,
entries,
count);
Local<Value> buf = Undefined(env->isolate());
if (ret >= 0) buf = buffer.ToBuffer().ToLocalChecked();
return scope.Escape(buf);
}
// Updates the shared TypedArray with the current remote or local settings for
// the session.
void Http2Settings::Update(Http2Session* session, get_setting fn) {
AliasedUint32Array& buffer = session->http2_state()->settings_buffer;
#define V(name) \
buffer[IDX_SETTINGS_ ## name] = \
fn(session->session(), NGHTTP2_SETTINGS_ ## name);
HTTP2_SETTINGS(V)
#undef V
}
// Initializes the shared TypedArray with the default settings values.
void Http2Settings::RefreshDefaults(Http2State* http2_state) {
AliasedUint32Array& buffer = http2_state->settings_buffer;
uint32_t flags = 0;
#define V(name) \
do { \
buffer[IDX_SETTINGS_ ## name] = DEFAULT_SETTINGS_ ## name; \
flags |= 1 << IDX_SETTINGS_ ## name; \
} while (0);
HTTP2_SETTINGS(V)
#undef V
buffer[IDX_SETTINGS_COUNT] = flags;
}
void Http2Settings::Send() {
Http2Scope h2scope(session_.get());
CHECK_EQ(nghttp2_submit_settings(
session_->session(),
NGHTTP2_FLAG_NONE,
&entries_[0],
count_), 0);
}
void Http2Settings::Done(bool ack) {
uint64_t end = uv_hrtime();
double duration = (end - startTime_) / 1e6;
Local<Value> argv[] = {
ack ? v8::True(env()->isolate()) : v8::False(env()->isolate()),
Number::New(env()->isolate(), duration)
};
MakeCallback(callback(), arraysize(argv), argv);
}
// The Http2Priority class initializes an appropriate nghttp2_priority_spec
// struct used when either creating a stream or updating its priority
// settings.
Http2Priority::Http2Priority(Environment* env,
Local<Value> parent,
Local<Value> weight,
Local<Value> exclusive) {
Local<Context> context = env->context();
int32_t parent_ = parent->Int32Value(context).ToChecked();
int32_t weight_ = weight->Int32Value(context).ToChecked();
bool exclusive_ = exclusive->IsTrue();
Debug(env, DebugCategory::HTTP2STREAM,
"Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
parent_, weight_, exclusive_ ? "yes" : "no");
nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
}
const char* Http2Session::TypeName() const {
switch (session_type_) {
case NGHTTP2_SESSION_SERVER: return "server";
case NGHTTP2_SESSION_CLIENT: return "client";
default:
// This should never happen
ABORT();
}
}
Origins::Origins(
Environment* env,
Local<String> origin_string,
size_t origin_count)
: count_(origin_count) {
int origin_string_len = origin_string->Length();
if (count_ == 0) {
CHECK_EQ(origin_string_len, 0);
return;
}
buf_ = AllocatedBuffer::AllocateManaged(
env,
(alignof(nghttp2_origin_entry) - 1) +
count_ * sizeof(nghttp2_origin_entry) +
origin_string_len);
// Make sure the start address is aligned appropriately for an nghttp2_nv*.
char* start = AlignUp(buf_.data(), alignof(nghttp2_origin_entry));
char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
nghttp2_origin_entry* const nva =
reinterpret_cast<nghttp2_origin_entry*>(start);
CHECK_LE(origin_contents + origin_string_len, buf_.data() + buf_.size());
CHECK_EQ(origin_string->WriteOneByte(
env->isolate(),
reinterpret_cast<uint8_t*>(origin_contents),
0,
origin_string_len,
String::NO_NULL_TERMINATION),
origin_string_len);
size_t n = 0;
char* p;
for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
if (n >= count_) {
static uint8_t zero = '\0';
nva[0].origin = &zero;
nva[0].origin_len = 1;
count_ = 1;
return;
}
nva[n].origin = reinterpret_cast<uint8_t*>(p);
nva[n].origin_len = strlen(p);
p += nva[n].origin_len + 1;
}
}
// Sets the various callback functions that nghttp2 will use to notify us
// about significant events while processing http2 stuff.
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
nghttp2_session_callbacks* callbacks_;
CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
callbacks.reset(callbacks_);
nghttp2_session_callbacks_set_on_begin_headers_callback(
callbacks_, OnBeginHeadersCallback);
nghttp2_session_callbacks_set_on_header_callback2(
callbacks_, OnHeaderCallback);
nghttp2_session_callbacks_set_on_frame_recv_callback(
callbacks_, OnFrameReceive);
nghttp2_session_callbacks_set_on_stream_close_callback(
callbacks_, OnStreamClose);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
callbacks_, OnDataChunkReceived);
nghttp2_session_callbacks_set_on_frame_not_send_callback(
callbacks_, OnFrameNotSent);
nghttp2_session_callbacks_set_on_invalid_header_callback2(
callbacks_, OnInvalidHeader);
nghttp2_session_callbacks_set_error_callback(
callbacks_, OnNghttpError);
nghttp2_session_callbacks_set_send_data_callback(
callbacks_, OnSendData);
nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
callbacks_, OnInvalidFrame);
nghttp2_session_callbacks_set_on_frame_send_callback(
callbacks_, OnFrameSent);
if (kHasGetPaddingCallback) {
nghttp2_session_callbacks_set_select_padding_callback(
callbacks_, OnSelectPadding);
}
}
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
StopTrackingMemory(buf);
}
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
CHECK_GE(current_nghttp2_memory_, previous_size);
}
void Http2Session::IncreaseAllocatedSize(size_t size) {
current_nghttp2_memory_ += size;
}
void Http2Session::DecreaseAllocatedSize(size_t size) {
current_nghttp2_memory_ -= size;
}
Http2Session::Http2Session(Http2State* http2_state,
Local<Object> wrap,
SessionType type)
: AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
js_fields_(http2_state->env()->isolate()),
session_type_(type),
http2_state_(http2_state) {
MakeWeak();
statistics_.start_time = uv_hrtime();
// Capture the configuration options for this session
Http2Options opts(http2_state, type);
max_session_memory_ = opts.max_session_memory();
uint32_t maxHeaderPairs = opts.max_header_pairs();
max_header_pairs_ =
type == NGHTTP2_SESSION_SERVER
? GetServerMaxHeaderPairs(maxHeaderPairs)
: GetClientMaxHeaderPairs(maxHeaderPairs);
max_outstanding_pings_ = opts.max_outstanding_pings();
max_outstanding_settings_ = opts.max_outstanding_settings();
padding_strategy_ = opts.padding_strategy();
bool hasGetPaddingCallback =
padding_strategy_ != PADDING_STRATEGY_NONE;
auto fn = type == NGHTTP2_SESSION_SERVER ?
nghttp2_session_server_new3 :
nghttp2_session_client_new3;
nghttp2_mem alloc_info = MakeAllocator();
// This should fail only if the system is out of memory, which
// is going to cause lots of other problems anyway, or if any
// of the options are out of acceptable range, which we should
// be catching before it gets this far. Either way, crash if this
// fails.
nghttp2_session* session;
CHECK_EQ(fn(
&session,
callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks.get(),
this,
*opts,
&alloc_info), 0);
session_.reset(session);
outgoing_storage_.reserve(1024);
outgoing_buffers_.reserve(32);
Local<Uint8Array> uint8_arr =
Uint8Array::New(js_fields_.GetArrayBuffer(), 0, kSessionUint8FieldCount);
USE(wrap->Set(env()->context(), env()->fields_string(), uint8_arr));
}
Http2Session::~Http2Session() {
CHECK(!is_in_scope());
Debug(this, "freeing nghttp2 session");
// Explicitly reset session_ so the subsequent
// current_nghttp2_memory_ check passes.
session_.reset();
CHECK_EQ(current_nghttp2_memory_, 0);
}
void Http2Session::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("streams", streams_);
tracker->TrackField("outstanding_pings", outstanding_pings_);
tracker->TrackField("outstanding_settings", outstanding_settings_);
tracker->TrackField("outgoing_buffers", outgoing_buffers_);
tracker->TrackFieldWithSize("stream_buf", stream_buf_.len);
tracker->TrackFieldWithSize("outgoing_storage", outgoing_storage_.size());
tracker->TrackFieldWithSize("pending_rst_streams",
pending_rst_streams_.size() * sizeof(int32_t));
tracker->TrackFieldWithSize("nghttp2_memory", current_nghttp2_memory_);
}
std::string Http2Session::diagnostic_name() const {
return std::string("Http2Session ") + TypeName() + " (" +
std::to_string(static_cast<int64_t>(get_async_id())) + ")";
}
void Http2Stream::EmitStatistics() {
CHECK_NOT_NULL(session());
if (!HasHttp2Observer(env()))
return;
auto entry =
std::make_unique<Http2StreamPerformanceEntry>(
session()->http2_state(), id_, statistics_);
env()->SetImmediate([entry = move(entry)](Environment* env) {
if (!HasHttp2Observer(env))
return;
HandleScope handle_scope(env->isolate());
AliasedFloat64Array& buffer = entry->http2_state()->stream_stats_buffer;
buffer[IDX_STREAM_STATS_ID] = entry->id();
if (entry->first_byte() != 0) {
buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] =
(entry->first_byte() - entry->startTimeNano()) / 1e6;
} else {
buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0;
}
if (entry->first_header() != 0) {
buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] =
(entry->first_header() - entry->startTimeNano()) / 1e6;
} else {
buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0;
}
if (entry->first_byte_sent() != 0) {
buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] =
(entry->first_byte_sent() - entry->startTimeNano()) / 1e6;
} else {
buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0;
}
buffer[IDX_STREAM_STATS_SENTBYTES] =
static_cast<double>(entry->sent_bytes());
buffer[IDX_STREAM_STATS_RECEIVEDBYTES] =
static_cast<double>(entry->received_bytes());
Local<Object> obj;
if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
});
}
void Http2Session::EmitStatistics() {
if (!HasHttp2Observer(env()))
return;
auto entry = std::make_unique<Http2SessionPerformanceEntry>(
http2_state(), statistics_, session_type_);
env()->SetImmediate([entry = std::move(entry)](Environment* env) {
if (!HasHttp2Observer(env))
return;
HandleScope handle_scope(env->isolate());
AliasedFloat64Array& buffer = entry->http2_state()->session_stats_buffer;
buffer[IDX_SESSION_STATS_TYPE] = entry->type();
buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6;
buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count();
buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent();
buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count();
buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] =
entry->stream_average_duration();
buffer[IDX_SESSION_STATS_DATA_SENT] =
static_cast<double>(entry->data_sent());
buffer[IDX_SESSION_STATS_DATA_RECEIVED] =
static_cast<double>(entry->data_received());
buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] =
static_cast<double>(entry->max_concurrent_streams());
Local<Object> obj;
if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
});
}
// Closes the session and frees the associated resources
void Http2Session::Close(uint32_t code, bool socket_closed) {
Debug(this, "closing session");
if (is_closing())
return;
set_closing();
// Stop reading on the i/o stream
if (stream_ != nullptr) {
set_reading_stopped();
stream_->ReadStop();
}
// If the socket is not closed, then attempt to send a closing GOAWAY
// frame. There is no guarantee that this GOAWAY will be received by
// the peer but the HTTP/2 spec recommends sending it anyway. We'll
// make a best effort.
if (!socket_closed) {
Debug(this, "terminating session with code %d", code);
CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
SendPendingData();
} else if (stream_ != nullptr) {
stream_->RemoveStreamListener(this);
}
set_destroyed();
// If we are writing we will get to make the callback in OnStreamAfterWrite.
if (!is_write_in_progress()) {
Debug(this, "make done session callback");
HandleScope scope(env()->isolate());
MakeCallback(env()->ondone_string(), 0, nullptr);
}
// If there are outstanding pings, those will need to be canceled, do
// so on the next iteration of the event loop to avoid calling out into
// javascript since this may be called during garbage collection.
while (BaseObjectPtr<Http2Ping> ping = PopPing()) {
ping->DetachFromSession();
env()->SetImmediate(
[ping = std::move(ping)](Environment* env) {
ping->Done(false);
});
}
statistics_.end_time = uv_hrtime();
EmitStatistics();
}
// Locates an existing known stream by ID. nghttp2 has a similar method
// but this is faster and does not fail if the stream is not found.
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
auto s = streams_.find(id);
return s != streams_.end() ? s->second : BaseObjectPtr<Http2Stream>();
}
bool Http2Session::CanAddStream() {
uint32_t maxConcurrentStreams =
nghttp2_session_get_local_settings(
session_.get(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
size_t maxSize =
std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
// We can add a new stream so long as we are less than the current
// maximum on concurrent streams and there's enough available memory
return streams_.size() < maxSize &&
has_available_session_memory(sizeof(Http2Stream));
}
void Http2Session::AddStream(Http2Stream* stream) {
CHECK_GE(++statistics_.stream_count, 0);
streams_[stream->id()] = BaseObjectPtr<Http2Stream>(stream);
size_t size = streams_.size();
if (size > statistics_.max_concurrent_streams)
statistics_.max_concurrent_streams = size;
IncrementCurrentSessionMemory(sizeof(*stream));
}
BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
BaseObjectPtr<Http2Stream> stream;
if (streams_.empty())
return stream;
stream = FindStream(id);
if (stream) {
streams_.erase(id);
DecrementCurrentSessionMemory(sizeof(*stream));
}
return stream;
}
// Used as one of the Padding Strategy functions. Will attempt to ensure
// that the total frame size, including header bytes, are 8-byte aligned.
// If maxPayloadLen is smaller than the number of bytes necessary to align,
// will return maxPayloadLen instead.
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
size_t maxPayloadLen) {
size_t r = (frameLen + 9) % 8;
if (r == 0) return frameLen; // If already a multiple of 8, return.
size_t pad = frameLen + (8 - r);
// If maxPayloadLen happens to be less than the calculated pad length,
// use the max instead, even tho this means the frame will not be
// aligned.
pad = std::min(maxPayloadLen, pad);
Debug(this, "using frame size padding: %d", pad);
return pad;
}
// Used as one of the Padding Strategy functions. Uses the maximum amount
// of padding allowed for the current frame.
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
size_t maxPayloadLen) {
Debug(this, "using max frame size padding: %d", maxPayloadLen);
return maxPayloadLen;
}
// Write data received from the i/o stream to the underlying nghttp2_session.
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
// various callback functions. Each of these will typically result in a call
// out to JavaScript so this particular function is rather hot and can be
// quite expensive. This is a potential performance optimization target later.
ssize_t Http2Session::ConsumeHTTP2Data() {
CHECK_NOT_NULL(stream_buf_.base);
CHECK_LT(stream_buf_offset_, stream_buf_.len);
size_t read_len = stream_buf_.len - stream_buf_offset_;
// multiple side effects.
Debug(this, "receiving %d bytes [wants data? %d]",
read_len,
nghttp2_session_want_read(session_.get()));
set_receive_paused(false);
ssize_t ret =
nghttp2_session_mem_recv(session_.get(),
reinterpret_cast<uint8_t*>(stream_buf_.base) +
stream_buf_offset_,
read_len);
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
if (is_receive_paused()) {
CHECK(is_reading_stopped());
CHECK_GT(ret, 0);
CHECK_LE(static_cast<size_t>(ret), read_len);
if (static_cast<size_t>(ret) < read_len) {
// Mark the remainder of the data as available for later consumption.
stream_buf_offset_ += ret;
return ret;
}
}
// We are done processing the current input chunk.
DecrementCurrentSessionMemory(stream_buf_.len);
stream_buf_offset_ = 0;
stream_buf_ab_.Reset();
stream_buf_allocation_.clear();
stream_buf_ = uv_buf_init(nullptr, 0);
if (ret < 0)
return ret;
// Send any data that was queued up while processing the received data.
if (!is_destroyed()) {
SendPendingData();
}
return ret;
}
int32_t GetFrameID(const nghttp2_frame* frame) {
// If this is a push promise, we want to grab the id of the promised stream
return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
frame->push_promise.promised_stream_id :
frame->hd.stream_id;
}
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
// callback to determine if a new stream is being created or if we are simply
// adding a new block of headers to an existing stream. The header pairs
// themselves are set in the OnHeaderCallback
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
const nghttp2_frame* frame,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
int32_t id = GetFrameID(frame);
Debug(session, "beginning headers for stream %d", id);
BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
// The common case is that we're creating a new stream. The less likely
// case is that we're receiving a set of trailers
if (LIKELY(!stream)) {
if (UNLIKELY(!session->CanAddStream() ||
Http2Stream::New(session, id, frame->headers.cat) ==
nullptr)) {
if (session->rejected_stream_count_++ >
session->js_fields_->max_rejected_streams)
return NGHTTP2_ERR_CALLBACK_FAILURE;
// Too many concurrent streams being opened
nghttp2_submit_rst_stream(
session->session(),
NGHTTP2_FLAG_NONE,
id,
NGHTTP2_ENHANCE_YOUR_CALM);
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
session->rejected_stream_count_ = 0;
} else if (!stream->is_destroyed()) {
stream->StartHeaders(frame->headers.cat);
}
return 0;
}
// Called by nghttp2 for each header name/value pair in a HEADERS block.
// This had to have been preceded by a call to OnBeginHeadersCallback so
// the Http2Stream is guaranteed to already exist.
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
const nghttp2_frame* frame,
nghttp2_rcbuf* name,
nghttp2_rcbuf* value,
uint8_t flags,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
int32_t id = GetFrameID(frame);
BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
// If stream is null at this point, either something odd has happened
// or the stream was closed locally while header processing was occurring.
// either way, do not proceed and close the stream.
if (UNLIKELY(!stream))
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
// If the stream has already been destroyed, ignore.
if (!stream->is_destroyed() && !stream->AddHeader(name, value, flags)) {
// This will only happen if the connected peer sends us more
// than the allowed number of header items at any given time
stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
return 0;
}
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
// only a handful of frame types that we care about handling here.
int Http2Session::OnFrameReceive(nghttp2_session* handle,
const nghttp2_frame* frame,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
session->statistics_.frame_count++;
Debug(session, "complete frame received: type: %d",
frame->hd.type);
switch (frame->hd.type) {
case NGHTTP2_DATA:
return session->HandleDataFrame(frame);
case NGHTTP2_PUSH_PROMISE:
// Intentional fall-through, handled just like headers frames
case NGHTTP2_HEADERS:
session->HandleHeadersFrame(frame);
break;
case NGHTTP2_SETTINGS:
session->HandleSettingsFrame(frame);
break;
case NGHTTP2_PRIORITY:
session->HandlePriorityFrame(frame);
break;
case NGHTTP2_GOAWAY:
session->HandleGoawayFrame(frame);
break;
case NGHTTP2_PING:
session->HandlePingFrame(frame);
break;
case NGHTTP2_ALTSVC:
session->HandleAltSvcFrame(frame);
break;
case NGHTTP2_ORIGIN:
session->HandleOriginFrame(frame);
break;
default:
break;
}
return 0;
}
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
const nghttp2_frame* frame,
int lib_error_code,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
Debug(session,
"invalid frame received (%u/%u), code: %d",
session->invalid_frame_count_,
session->js_fields_->max_invalid_frames,
lib_error_code);
if (session->invalid_frame_count_++ > session->js_fields_->max_invalid_frames)
return 1;
// If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
if (nghttp2_is_fatal(lib_error_code) ||
lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
Environment* env = session->env();
Isolate* isolate = env->isolate();
HandleScope scope(isolate);
Local<Context> context = env->context();
Context::Scope context_scope(context);
Local<Value> arg = Integer::New(isolate, lib_error_code);
session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
}
return 0;
}
// If nghttp2 is unable to send a queued up frame, it will call this callback
// to let us know. If the failure occurred because we are in the process of
// closing down the session or stream, we go ahead and ignore it. We don't
// really care about those and there's nothing we can reasonably do about it
// anyway. Other types of failures are reported up to JavaScript. This should
// be exceedingly rare.
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
const nghttp2_frame* frame,
int error_code,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
Environment* env = session->env();
Debug(session, "frame type %d was not sent, code: %d",
frame->hd.type, error_code);
// Do not report if the frame was not sent due to the session closing
if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
error_code == NGHTTP2_ERR_STREAM_CLOSED ||
error_code == NGHTTP2_ERR_STREAM_CLOSING ||
session->js_fields_->frame_error_listener_count == 0) {
return 0;
}
Isolate* isolate = env->isolate();
HandleScope scope(isolate);
Local<Context> context = env->context();
Context::Scope context_scope(context);
Local<Value> argv[3] = {
Integer::New(isolate, frame->hd.stream_id),
Integer::New(isolate, frame->hd.type),
Integer::New(isolate, error_code)
};
session->MakeCallback(
env->http2session_on_frame_error_function(),
arraysize(argv), argv);
return 0;
}
int Http2Session::OnFrameSent(nghttp2_session* handle,
const nghttp2_frame* frame,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
session->statistics_.frame_sent += 1;
return 0;
}
// Called by nghttp2 when a stream closes.
int Http2Session::OnStreamClose(nghttp2_session* handle,
int32_t id,
uint32_t code,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
Environment* env = session->env();
Isolate* isolate = env->isolate();
HandleScope scope(isolate);
Local<Context> context = env->context();
Context::Scope context_scope(context);
Debug(session, "stream %d closed with code: %d", id, code);
BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
// Intentionally ignore the callback if the stream does not exist or has
// already been destroyed
if (!stream || stream->is_destroyed())
return 0;
stream->Close(code);
// It is possible for the stream close to occur before the stream is
// ever passed on to the javascript side. If that happens, the callback
// will return false.
Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
MaybeLocal<Value> answer =
stream->MakeCallback(env->http2session_on_stream_close_function(),
1, &arg);
if (answer.IsEmpty() || answer.ToLocalChecked()->IsFalse()) {
// Skip to destroy
stream->Destroy();