forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_http2.cc
More file actions
2278 lines (1891 loc) · 77.5 KB
/
node_http2.cc
File metadata and controls
2278 lines (1891 loc) · 77.5 KB
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 "node.h"
#include "node_buffer.h"
#include "node_http2.h"
#include "node_http2_state.h"
#include <queue>
#include <algorithm>
namespace node {
using v8::Boolean;
using v8::Context;
using v8::Float64Array;
using v8::Function;
using v8::Integer;
using v8::Number;
using v8::ObjectTemplate;
using v8::String;
using v8::Uint32;
using v8::Uint32Array;
using v8::Undefined;
namespace http2 {
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
Callbacks(false),
Callbacks(true)};
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
Http2Scope::Http2Scope(Http2Session* session) {
if (session->flags_ & (SESSION_STATE_HAS_SCOPE |
SESSION_STATE_WRITE_SCHEDULED)) {
// There is another scope further below on the stack, or it is already
// known that a write is scheduled. In either case, there is nothing to do.
return;
}
session->flags_ |= SESSION_STATE_HAS_SCOPE;
session_ = session;
}
Http2Scope::~Http2Scope() {
if (session_ == nullptr)
return;
session_->flags_ &= ~SESSION_STATE_HAS_SCOPE;
session_->MaybeScheduleWrite();
}
Http2Options::Http2Options(Environment* env) {
nghttp2_option_new(&options_);
nghttp2_option_set_no_auto_window_update(options_, 1);
AliasedBuffer<uint32_t, v8::Uint32Array>& buffer =
env->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(
options_,
buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
}
if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
nghttp2_option_set_max_reserved_remote_streams(
options_,
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(
options_,
buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
}
// Recommended default
nghttp2_option_set_peer_max_concurrent_streams(options_, 100);
if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
nghttp2_option_set_peer_max_concurrent_streams(
options_,
buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
}
if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
padding_strategy_type strategy =
static_cast<padding_strategy_type>(
buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
SetPaddingStrategy(strategy);
}
if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS)) {
SetMaxHeaderPairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
}
if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS)) {
SetMaxOutstandingPings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
}
}
Http2Settings::Http2Settings(Environment* env) : env_(env) {
entries_.AllocateSufficientStorage(IDX_SETTINGS_COUNT);
AliasedBuffer<uint32_t, v8::Uint32Array>& buffer =
env->http2_state()->settings_buffer;
uint32_t flags = buffer[IDX_SETTINGS_COUNT];
size_t n = 0;
if (flags & (1 << IDX_SETTINGS_HEADER_TABLE_SIZE)) {
uint32_t val = buffer[IDX_SETTINGS_HEADER_TABLE_SIZE];
DEBUG_HTTP2("Http2Settings: setting header table size: %d\n", val);
entries_[n].settings_id = NGHTTP2_SETTINGS_HEADER_TABLE_SIZE;
entries_[n].value = val;
n++;
}
if (flags & (1 << IDX_SETTINGS_MAX_CONCURRENT_STREAMS)) {
uint32_t val = buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS];
DEBUG_HTTP2("Http2Settings: setting max concurrent streams: %d\n", val);
entries_[n].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
entries_[n].value = val;
n++;
}
if (flags & (1 << IDX_SETTINGS_MAX_FRAME_SIZE)) {
uint32_t val = buffer[IDX_SETTINGS_MAX_FRAME_SIZE];
DEBUG_HTTP2("Http2Settings: setting max frame size: %d\n", val);
entries_[n].settings_id = NGHTTP2_SETTINGS_MAX_FRAME_SIZE;
entries_[n].value = val;
n++;
}
if (flags & (1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE)) {
uint32_t val = buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE];
DEBUG_HTTP2("Http2Settings: setting initial window size: %d\n", val);
entries_[n].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
entries_[n].value = val;
n++;
}
if (flags & (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE)) {
uint32_t val = buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE];
DEBUG_HTTP2("Http2Settings: setting max header list size: %d\n", val);
entries_[n].settings_id = NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE;
entries_[n].value = val;
n++;
}
if (flags & (1 << IDX_SETTINGS_ENABLE_PUSH)) {
uint32_t val = buffer[IDX_SETTINGS_ENABLE_PUSH];
DEBUG_HTTP2("Http2Settings: setting enable push: %d\n", val);
entries_[n].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH;
entries_[n].value = val;
n++;
}
count_ = n;
}
inline Local<Value> Http2Settings::Pack() {
const size_t len = count_ * 6;
Local<Value> buf = Buffer::New(env_, len).ToLocalChecked();
ssize_t ret =
nghttp2_pack_settings_payload(
reinterpret_cast<uint8_t*>(Buffer::Data(buf)), len,
*entries_, count_);
if (ret >= 0)
return buf;
else
return Undefined(env_->isolate());
}
inline void Http2Settings::Update(Environment* env,
Http2Session* session,
get_setting fn) {
AliasedBuffer<uint32_t, v8::Uint32Array>& buffer =
env->http2_state()->settings_buffer;
buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
fn(session->session(), NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
fn(session->session(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
fn(session->session(), NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
fn(session->session(), NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
fn(session->session(), NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
buffer[IDX_SETTINGS_ENABLE_PUSH] =
fn(session->session(), NGHTTP2_SETTINGS_ENABLE_PUSH);
}
inline void Http2Settings::RefreshDefaults(Environment* env) {
AliasedBuffer<uint32_t, v8::Uint32Array>& buffer =
env->http2_state()->settings_buffer;
buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
DEFAULT_SETTINGS_HEADER_TABLE_SIZE;
buffer[IDX_SETTINGS_ENABLE_PUSH] =
DEFAULT_SETTINGS_ENABLE_PUSH;
buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE;
buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
DEFAULT_SETTINGS_MAX_FRAME_SIZE;
buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
buffer[IDX_SETTINGS_COUNT] =
(1 << IDX_SETTINGS_HEADER_TABLE_SIZE) |
(1 << IDX_SETTINGS_ENABLE_PUSH) |
(1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE) |
(1 << IDX_SETTINGS_MAX_FRAME_SIZE) |
(1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE);
}
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->BooleanValue(context).ToChecked();
DEBUG_HTTP2("Http2Priority: parent: %d, weight: %d, exclusive: %d\n",
parent_, weight_, exclusive_);
nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0);
}
inline const char* Http2Session::TypeName() {
switch (session_type_) {
case NGHTTP2_SESSION_SERVER: return "server";
case NGHTTP2_SESSION_CLIENT: return "client";
default:
// This should never happen
ABORT();
}
}
Headers::Headers(Isolate* isolate,
Local<Context> context,
Local<Array> headers) {
Local<Value> header_string = headers->Get(context, 0).ToLocalChecked();
Local<Value> header_count = headers->Get(context, 1).ToLocalChecked();
count_ = header_count.As<Uint32>()->Value();
int header_string_len = header_string.As<String>()->Length();
if (count_ == 0) {
CHECK_EQ(header_string_len, 0);
return;
}
// Allocate a single buffer with count_ nghttp2_nv structs, followed
// by the raw header data as passed from JS. This looks like:
// | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents |
buf_.AllocateSufficientStorage((alignof(nghttp2_nv) - 1) +
count_ * sizeof(nghttp2_nv) +
header_string_len);
// Make sure the start address is aligned appropriately for an nghttp2_nv*.
char* start = reinterpret_cast<char*>(
ROUND_UP(reinterpret_cast<uintptr_t>(*buf_), alignof(nghttp2_nv)));
char* header_contents = start + (count_ * sizeof(nghttp2_nv));
nghttp2_nv* const nva = reinterpret_cast<nghttp2_nv*>(start);
CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length());
CHECK_EQ(header_string.As<String>()
->WriteOneByte(reinterpret_cast<uint8_t*>(header_contents),
0, header_string_len,
String::NO_NULL_TERMINATION),
header_string_len);
size_t n = 0;
char* p;
for (p = header_contents; p < header_contents + header_string_len; n++) {
if (n >= count_) {
// This can happen if a passed header contained a null byte. In that
// case, just provide nghttp2 with an invalid header to make it reject
// the headers list.
static uint8_t zero = '\0';
nva[0].name = nva[0].value = &zero;
nva[0].namelen = nva[0].valuelen = 1;
count_ = 1;
return;
}
nva[n].flags = NGHTTP2_NV_FLAG_NONE;
nva[n].name = reinterpret_cast<uint8_t*>(p);
nva[n].namelen = strlen(p);
p += nva[n].namelen + 1;
nva[n].value = reinterpret_cast<uint8_t*>(p);
nva[n].valuelen = strlen(p);
p += nva[n].valuelen + 1;
}
}
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0);
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);
if (kHasGetPaddingCallback) {
nghttp2_session_callbacks_set_select_padding_callback(
callbacks, OnSelectPadding);
}
}
Http2Session::Callbacks::~Callbacks() {
nghttp2_session_callbacks_del(callbacks);
}
Http2Session::Http2Session(Environment* env,
Local<Object> wrap,
nghttp2_session_type type)
: AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
session_type_(type) {
MakeWeak<Http2Session>(this);
Http2Options opts(env);
int32_t maxHeaderPairs = opts.GetMaxHeaderPairs();
max_header_pairs_ =
type == NGHTTP2_SESSION_SERVER
? std::max(maxHeaderPairs, 4) // minimum # of request headers
: std::max(maxHeaderPairs, 1); // minimum # of response headers
max_outstanding_pings_ = opts.GetMaxOutstandingPings();
padding_strategy_ = opts.GetPaddingStrategy();
bool hasGetPaddingCallback =
padding_strategy_ == PADDING_STRATEGY_MAX ||
padding_strategy_ == PADDING_STRATEGY_CALLBACK;
nghttp2_session_callbacks* callbacks
= callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks;
auto fn = type == NGHTTP2_SESSION_SERVER ?
nghttp2_session_server_new2 :
nghttp2_session_client_new2;
// 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.
CHECK_EQ(fn(&session_, callbacks, this, *opts), 0);
}
Http2Session::~Http2Session() {
CHECK(persistent().IsEmpty());
Close();
}
void Http2Session::Close() {
DEBUG_HTTP2SESSION(this, "closing session");
if (!object().IsEmpty())
ClearWrap(object());
persistent().Reset();
if (session_ == nullptr)
return;
CHECK_EQ(nghttp2_session_terminate_session(session_, NGHTTP2_NO_ERROR), 0);
nghttp2_session_del(session_);
session_ = nullptr;
while (!outstanding_pings_.empty()) {
Http2Session::Http2Ping* ping = PopPing();
// Since this method may be called from GC, calling into JS directly
// is not allowed.
env()->SetImmediate([](Environment* env, void* data) {
static_cast<Http2Session::Http2Ping*>(data)->Done(false);
}, static_cast<void*>(ping));
}
}
inline Http2Stream* Http2Session::FindStream(int32_t id) {
auto s = streams_.find(id);
return s != streams_.end() ? s->second : nullptr;
}
inline void Http2Session::AddStream(Http2Stream* stream) {
streams_[stream->id()] = stream;
}
inline void Http2Session::RemoveStream(int32_t id) {
streams_.erase(id);
}
inline ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
size_t maxPayloadLen) {
DEBUG_HTTP2SESSION2(this, "using max frame size padding: %d", maxPayloadLen);
return maxPayloadLen;
}
inline ssize_t Http2Session::OnCallbackPadding(size_t frameLen,
size_t maxPayloadLen) {
DEBUG_HTTP2SESSION(this, "using callback to determine padding");
Isolate* isolate = env()->isolate();
HandleScope handle_scope(isolate);
Local<Context> context = env()->context();
Context::Scope context_scope(context);
#if defined(DEBUG) && DEBUG
CHECK(object()->Has(context, env()->ongetpadding_string()).FromJust());
#endif
AliasedBuffer<uint32_t, v8::Uint32Array>& buffer =
env()->http2_state()->padding_buffer;
buffer[PADDING_BUF_FRAME_LENGTH] = frameLen;
buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen;
buffer[PADDING_BUF_RETURN_VALUE] = frameLen;
MakeCallback(env()->ongetpadding_string(), 0, nullptr);
uint32_t retval = buffer[PADDING_BUF_RETURN_VALUE];
retval = std::min(retval, static_cast<uint32_t>(maxPayloadLen));
retval = std::max(retval, static_cast<uint32_t>(frameLen));
DEBUG_HTTP2SESSION2(this, "using padding size %d", retval);
return retval;
}
// Submits a graceful shutdown notice to nghttp
// See: https://nghttp2.org/documentation/nghttp2_submit_shutdown_notice.html
inline void Http2Session::SubmitShutdownNotice() {
// Only an HTTP2 Server is permitted to send a shutdown notice
if (session_type_ == NGHTTP2_SESSION_CLIENT)
return;
DEBUG_HTTP2SESSION(this, "sending shutdown notice");
// The only situation where this should fail is if the system is
// out of memory, which will cause other problems. Go ahead and crash
// in that case.
CHECK_EQ(nghttp2_submit_shutdown_notice(session_), 0);
}
// Note: This *must* send a SETTINGS frame even if niv == 0
inline void Http2Session::Settings(const nghttp2_settings_entry iv[],
size_t niv) {
DEBUG_HTTP2SESSION2(this, "submitting %d settings", niv);
Http2Scope h2scope(this);
// This will fail either if the system is out of memory, or if the settings
// values are not within the appropriate range. We should be catching the
// latter before it gets this far so crash in either case.
CHECK_EQ(nghttp2_submit_settings(session_, NGHTTP2_FLAG_NONE, iv, niv), 0);
}
// Write data received from the i/o stream to the underlying nghttp2_session.
inline ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) {
size_t total = 0;
// Note that nghttp2_session_mem_recv is a synchronous operation that
// will trigger a number of other callbacks. Those will, in turn have
// multiple side effects.
for (size_t n = 0; n < nbufs; n++) {
ssize_t ret =
nghttp2_session_mem_recv(session_,
reinterpret_cast<uint8_t*>(bufs[n].base),
bufs[n].len);
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
if (ret < 0)
return ret;
total += ret;
}
// Send any data that was queued up while processing the received data.
SendPendingData();
return total;
}
inline 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;
}
inline 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_HTTP2SESSION2(session, "beginning headers for stream %d", id);
Http2Stream* stream = session->FindStream(id);
if (stream == nullptr) {
new Http2Stream(session, id, frame->headers.cat);
} else {
stream->StartHeaders(frame->headers.cat);
}
return 0;
}
inline 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);
Http2Stream* stream = session->FindStream(id);
if (!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;
}
inline int Http2Session::OnFrameReceive(nghttp2_session* handle,
const nghttp2_frame* frame,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
DEBUG_HTTP2SESSION2(session, "complete frame received: type: %d",
frame->hd.type);
switch (frame->hd.type) {
case NGHTTP2_DATA:
session->HandleDataFrame(frame);
break;
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);
default:
break;
}
return 0;
}
inline 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_HTTP2SESSION2(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) {
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->onframeerror_string(), arraysize(argv), argv);
}
return 0;
}
inline 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_HTTP2SESSION2(session, "stream %d closed with code: %d", id, code);
Http2Stream* stream = session->FindStream(id);
// Intentionally ignore the callback if the stream does not exist
if (stream != nullptr) {
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, ignore this.
Local<Value> fn =
stream->object()->Get(context, env->onstreamclose_string())
.ToLocalChecked();
if (fn->IsFunction()) {
Local<Value> argv[1] = { Integer::NewFromUnsigned(isolate, code) };
stream->MakeCallback(fn.As<Function>(), arraysize(argv), argv);
}
}
return 0;
}
inline int Http2Session::OnInvalidHeader(nghttp2_session* session,
const nghttp2_frame* frame,
nghttp2_rcbuf* name,
nghttp2_rcbuf* value,
uint8_t flags,
void* user_data) {
// Ignore invalid header fields by default.
return 0;
}
inline int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
uint8_t flags,
int32_t id,
const uint8_t* data,
size_t len,
void* user_data) {
Http2Session* session = static_cast<Http2Session*>(user_data);
DEBUG_HTTP2SESSION2(session, "buffering data chunk for stream %d, size: "
"%d, flags: %d", id, len, flags);
// We should never actually get a 0-length chunk so this check is
// only a precaution at this point.
if (len > 0) {
CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
Http2Stream* stream = session->FindStream(id);
stream->AddChunk(data, len);
}
return 0;
}
inline ssize_t Http2Session::OnSelectPadding(nghttp2_session* session,
const nghttp2_frame* frame,
size_t maxPayloadLen,
void* user_data) {
Http2Session* handle = static_cast<Http2Session*>(user_data);
ssize_t padding = frame->hd.length;
return handle->padding_strategy_ == PADDING_STRATEGY_MAX
? handle->OnMaxFrameSizePadding(padding, maxPayloadLen)
: handle->OnCallbackPadding(padding, maxPayloadLen);
}
#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we " \
"expected SETTINGS frame. Perhaps, peer does not " \
"support HTTP/2 properly."
inline int Http2Session::OnNghttpError(nghttp2_session* handle,
const char* message,
size_t len,
void* user_data) {
// Unfortunately, this is currently the only way for us to know if
// the session errored because the peer is not an http2 peer.
Http2Session* session = static_cast<Http2Session*>(user_data);
DEBUG_HTTP2SESSION2(session, "Error '%.*s'", len, message);
if (strncmp(message, BAD_PEER_MESSAGE, len) == 0) {
Environment* env = session->env();
Isolate* isolate = env->isolate();
HandleScope scope(isolate);
Local<Context> context = env->context();
Context::Scope context_scope(context);
Local<Value> argv[1] = {
Integer::New(isolate, NGHTTP2_ERR_PROTO),
};
session->MakeCallback(env->error_string(), arraysize(argv), argv);
}
return 0;
}
inline void Http2Session::GetTrailers(Http2Stream* stream, uint32_t* flags) {
if (stream->HasTrailers()) {
Http2Stream::SubmitTrailers submit_trailers{this, stream, flags};
stream->OnTrailers(submit_trailers);
}
}
Http2Stream::SubmitTrailers::SubmitTrailers(
Http2Session* session,
Http2Stream* stream,
uint32_t* flags)
: session_(session), stream_(stream), flags_(flags) { }
inline void Http2Stream::SubmitTrailers::Submit(nghttp2_nv* trailers,
size_t length) const {
Http2Scope h2scope(session_);
if (length == 0)
return;
DEBUG_HTTP2SESSION2(session_, "sending trailers for stream %d, count: %d",
stream_->id(), length);
*flags_ |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
CHECK_EQ(
nghttp2_submit_trailer(**session_, stream_->id(), trailers, length), 0);
}
inline void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local<Context> context = env()->context();
Context::Scope context_scope(context);
int32_t id = GetFrameID(frame);
DEBUG_HTTP2SESSION2(this, "handle headers frame for stream %d", id);
Http2Stream* stream = FindStream(id);
nghttp2_header* headers = stream->headers();
size_t count = stream->headers_count();
Local<String> name_str;
Local<String> value_str;
Local<Array> holder = Array::New(isolate);
Local<Function> fn = env()->push_values_to_array_function();
Local<Value> argv[NODE_PUSH_VAL_TO_ARRAY_MAX * 2];
// The headers are passed in above as a queue of nghttp2_header structs.
// The following converts that into a JS array with the structure:
// [name1, value1, name2, value2, name3, value3, name3, value4] and so on.
// That array is passed up to the JS layer and converted into an Object form
// like {name1: value1, name2: value2, name3: [value3, value4]}. We do it
// this way for performance reasons (it's faster to generate and pass an
// array than it is to generate and pass the object).
size_t n = 0;
while (count > 0) {
size_t j = 0;
while (count > 0 && j < arraysize(argv) / 2) {
nghttp2_header item = headers[n++];
// The header name and value are passed as external one-byte strings
name_str =
ExternalHeader::New<true>(env(), item.name).ToLocalChecked();
value_str =
ExternalHeader::New<false>(env(), item.value).ToLocalChecked();
argv[j * 2] = name_str;
argv[j * 2 + 1] = value_str;
count--;
j++;
}
// For performance, we pass name and value pairs to array.protototype.push
// in batches of size NODE_PUSH_VAL_TO_ARRAY_MAX * 2 until there are no
// more items to push.
if (j > 0) {
fn->Call(env()->context(), holder, j * 2, argv).ToLocalChecked();
}
}
Local<Value> args[5] = {
stream->object(),
Integer::New(isolate, id),
Integer::New(isolate, stream->headers_category()),
Integer::New(isolate, frame->hd.flags),
holder
};
MakeCallback(env()->onheaders_string(), arraysize(args), args);
}
inline void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local<Context> context = env()->context();
Context::Scope context_scope(context);
nghttp2_priority priority_frame = frame->priority;
int32_t id = GetFrameID(frame);
DEBUG_HTTP2SESSION2(this, "handle priority frame for stream %d", id);
// Priority frame stream ID should never be <= 0. nghttp2 handles this for us
nghttp2_priority_spec spec = priority_frame.pri_spec;
Local<Value> argv[4] = {
Integer::New(isolate, id),
Integer::New(isolate, spec.stream_id),
Integer::New(isolate, spec.weight),
Boolean::New(isolate, spec.exclusive)
};
MakeCallback(env()->onpriority_string(), arraysize(argv), argv);
}
inline void Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
int32_t id = GetFrameID(frame);
DEBUG_HTTP2SESSION2(this, "handling data frame for stream %d", id);
Http2Stream* stream = FindStream(id);
if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
stream->AddChunk(nullptr, 0);
}
if (stream->IsReading())
stream->FlushDataChunks();
}
inline void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local<Context> context = env()->context();
Context::Scope context_scope(context);
nghttp2_goaway goaway_frame = frame->goaway;
DEBUG_HTTP2SESSION(this, "handling goaway frame");
Local<Value> argv[3] = {
Integer::NewFromUnsigned(isolate, goaway_frame.error_code),
Integer::New(isolate, goaway_frame.last_stream_id),
Undefined(isolate)
};
size_t length = goaway_frame.opaque_data_len;
if (length > 0) {
argv[2] = Buffer::Copy(isolate,
reinterpret_cast<char*>(goaway_frame.opaque_data),
length).ToLocalChecked();
}
MakeCallback(env()->ongoawaydata_string(), arraysize(argv), argv);
}
inline void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
if (ack) {
Http2Ping* ping = PopPing();
if (ping != nullptr)
ping->Done(true, frame->ping.opaque_data);
}
}
inline void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local<Context> context = env()->context();
Context::Scope context_scope(context);
bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
Local<Value> argv[1] = { Boolean::New(isolate, ack) };
MakeCallback(env()->onsettings_string(), arraysize(argv), argv);
}
void Http2Session::MaybeScheduleWrite() {
CHECK_EQ(flags_ & SESSION_STATE_WRITE_SCHEDULED, 0);
if (session_ != nullptr && nghttp2_session_want_write(session_)) {
flags_ |= SESSION_STATE_WRITE_SCHEDULED;
env()->SetImmediate([](Environment* env, void* data) {
Http2Session* session = static_cast<Http2Session*>(data);
if (session->session_ == nullptr ||
!(session->flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
// This can happen e.g. when a stream was reset before this turn
// of the event loop, in which case SendPendingData() is called early,
// or the session was destroyed in the meantime.
return;
}
// Sending data may call arbitrary JS code, so keep track of
// async context.
InternalCallbackScope callback_scope(session);
session->SendPendingData();
}, static_cast<void*>(this), object());
}
}
void Http2Session::SendPendingData() {
DEBUG_HTTP2SESSION(this, "sending pending data");
// Do not attempt to send data on the socket if the destroying flag has
// been set. That means everything is shutting down and the socket
// will not be usable.
if (IsDestroying())
return;
flags_ &= ~SESSION_STATE_WRITE_SCHEDULED;
WriteWrap* req = nullptr;
char* dest = nullptr;
size_t destRemaining = 0;
size_t destLength = 0; // amount of data stored in dest
size_t destOffset = 0; // current write offset of dest
const uint8_t* src; // pointer to the serialized data
ssize_t srcLength = 0; // length of serialized data chunk
// While srcLength is greater than zero
while ((srcLength = nghttp2_session_mem_send(session_, &src)) > 0) {
if (req == nullptr) {
req = AllocateSend();
destRemaining = req->ExtraSize();
dest = req->Extra();
}
DEBUG_HTTP2SESSION2(this, "nghttp2 has %d bytes to send", srcLength);
size_t srcRemaining = srcLength;
size_t srcOffset = 0;
// The amount of data we have to copy is greater than the space
// remaining. Copy what we can into the remaining space, send it,
// the proceed with the rest.
while (srcRemaining > destRemaining) {
DEBUG_HTTP2SESSION2(this, "pushing %d bytes to the socket",
destLength + destRemaining);
memcpy(dest + destOffset, src + srcOffset, destRemaining);
destLength += destRemaining;
Send(req, dest, destLength);
destOffset = 0;
destLength = 0;
srcRemaining -= destRemaining;
srcOffset += destRemaining;
req = AllocateSend();
destRemaining = req->ExtraSize();
dest = req->Extra();
}
if (srcRemaining > 0) {
memcpy(dest + destOffset, src + srcOffset, srcRemaining);
destLength += srcRemaining;
destOffset += srcRemaining;
destRemaining -= srcRemaining;
srcRemaining = 0;
srcOffset = 0;
}
}
CHECK_NE(srcLength, NGHTTP2_ERR_NOMEM);
if (destLength > 0) {
DEBUG_HTTP2SESSION2(this, "pushing %d bytes to the socket", destLength);
Send(req, dest, destLength);
}
}
inline Http2Stream* Http2Session::SubmitRequest(
nghttp2_priority_spec* prispec,
nghttp2_nv* nva,
size_t len,
int32_t* ret,
int options) {
DEBUG_HTTP2SESSION(this, "submitting request");
Http2Scope h2scope(this);
Http2Stream* stream = nullptr;
Http2Stream::Provider::Stream prov(options);
*ret = nghttp2_submit_request(session_, prispec, nva, len, *prov, nullptr);
CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
if (*ret > 0)
stream = new Http2Stream(this, *ret, NGHTTP2_HCAT_HEADERS, options);
return stream;
}
inline void Http2Session::SetChunksSinceLastWrite(size_t n) {
chunks_sent_since_last_write_ = n;
}
WriteWrap* Http2Session::AllocateSend() {
HandleScope scope(env()->isolate());
auto AfterWrite = [](WriteWrap* req, int status) {
req->Dispose();
};
Local<Object> obj =
env()->write_wrap_constructor_function()
->NewInstance(env()->context()).ToLocalChecked();
// Base the amount allocated on the remote peers max frame size
uint32_t size =
nghttp2_session_get_remote_settings(
session(),
NGHTTP2_SETTINGS_MAX_FRAME_SIZE);