GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.cc Lines: 1532 1624 94.3 %
Date: 2022-09-29 04:23:51 Branches: 616 865 71.2 %

Line Branch Exec Source
1
#include "node_http2.h"
2
#include "aliased_buffer.h"
3
#include "aliased_struct-inl.h"
4
#include "debug_utils-inl.h"
5
#include "histogram-inl.h"
6
#include "memory_tracker-inl.h"
7
#include "node.h"
8
#include "node_buffer.h"
9
#include "node_http_common-inl.h"
10
#include "node_mem-inl.h"
11
#include "node_perf.h"
12
#include "node_revert.h"
13
#include "stream_base-inl.h"
14
#include "util-inl.h"
15
16
#include <algorithm>
17
18
namespace node {
19
20
using v8::Array;
21
using v8::ArrayBuffer;
22
using v8::ArrayBufferView;
23
using v8::BackingStore;
24
using v8::Boolean;
25
using v8::Context;
26
using v8::EscapableHandleScope;
27
using v8::False;
28
using v8::Function;
29
using v8::FunctionCallbackInfo;
30
using v8::FunctionTemplate;
31
using v8::HandleScope;
32
using v8::Integer;
33
using v8::Isolate;
34
using v8::Local;
35
using v8::MaybeLocal;
36
using v8::NewStringType;
37
using v8::Number;
38
using v8::Object;
39
using v8::ObjectTemplate;
40
using v8::String;
41
using v8::True;
42
using v8::Uint8Array;
43
using v8::Undefined;
44
using v8::Value;
45
46
namespace http2 {
47
48
namespace {
49
50
const char zero_bytes_256[256] = {};
51
52
24350
bool HasHttp2Observer(Environment* env) {
53
24350
  AliasedUint32Array& observers = env->performance_state()->observers;
54
24350
  return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
55
}
56
57
}  // anonymous namespace
58
59
// These configure the callbacks required by nghttp2 itself. There are
60
// two sets of callback functions, one that is used if a padding callback
61
// is set, and other that does not include the padding callback.
62
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
63
    Callbacks(false),
64
    Callbacks(true)};
65
66
// The Http2Scope object is used to queue a write to the i/o stream. It is
67
// used whenever any action is take on the underlying nghttp2 API that may
68
// push data into nghttp2 outbound data queue.
69
//
70
// For example:
71
//
72
// Http2Scope h2scope(session);
73
// nghttp2_submit_ping(session->session(), ... );
74
//
75
// When the Http2Scope passes out of scope and is deconstructed, it will
76
// call Http2Session::MaybeScheduleWrite().
77
64275
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
78
79
109474
Http2Scope::Http2Scope(Http2Session* session) : session_(session) {
80
109474
  if (!session_) return;
81
82
  // If there is another scope further below on the stack, or
83
  // a write is already scheduled, there's nothing to do.
84

109474
  if (session_->is_in_scope() || session_->is_write_scheduled()) {
85
76219
    session_.reset();
86
76219
    return;
87
  }
88
33255
  session_->set_in_scope();
89
}
90
91
109472
Http2Scope::~Http2Scope() {
92
109472
  if (!session_) return;
93
33253
  session_->set_in_scope(false);
94
33253
  if (!session_->is_write_scheduled())
95
33253
    session_->MaybeScheduleWrite();
96
109472
}
97
98
// The Http2Options object is used during the construction of Http2Session
99
// instances to configure an appropriate nghttp2_options struct. The class
100
// uses a single TypedArray instance that is shared with the JavaScript side
101
// to more efficiently pass values back and forth.
102
770
Http2Options::Http2Options(Http2State* http2_state, SessionType type) {
103
  nghttp2_option* option;
104
770
  CHECK_EQ(nghttp2_option_new(&option), 0);
105
770
  CHECK_NOT_NULL(option);
106
770
  options_.reset(option);
107
108
  // Make sure closed connections aren't kept around, taking up memory.
109
  // Note that this breaks the priority tree, which we don't use.
110
770
  nghttp2_option_set_no_closed_streams(option, 1);
111
112
  // We manually handle flow control within a session in order to
113
  // implement backpressure -- that is, we only send WINDOW_UPDATE
114
  // frames to the remote peer as data is actually consumed by user
115
  // code. This ensures that the flow of data over the connection
116
  // does not move too quickly and limits the amount of data we
117
  // are required to buffer.
118
770
  nghttp2_option_set_no_auto_window_update(option, 1);
119
120
  // Enable built in support for receiving ALTSVC and ORIGIN frames (but
121
  // only on client side sessions
122
770
  if (type == NGHTTP2_SESSION_CLIENT) {
123
377
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ALTSVC);
124
377
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ORIGIN);
125
  }
126
127
770
  AliasedUint32Array& buffer = http2_state->options_buffer;
128
770
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
129
130
770
  if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) {
131
    nghttp2_option_set_max_deflate_dynamic_table_size(
132
        option,
133
        buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
134
  }
135
136
770
  if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
137
1
    nghttp2_option_set_max_reserved_remote_streams(
138
        option,
139
        buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]);
140
  }
141
142
770
  if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) {
143
3
    nghttp2_option_set_max_send_header_block_length(
144
        option,
145
6
        buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
146
  }
147
148
  // Recommended default
149
770
  nghttp2_option_set_peer_max_concurrent_streams(option, 100);
150
770
  if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
151
    nghttp2_option_set_peer_max_concurrent_streams(
152
        option,
153
        buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
154
  }
155
156
  // The padding strategy sets the mechanism by which we determine how much
157
  // additional frame padding to apply to DATA and HEADERS frames. Currently
158
  // this is set on a per-session basis, but eventually we may switch to
159
  // a per-stream setting, giving users greater control
160
770
  if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
161
    PaddingStrategy strategy =
162
        static_cast<PaddingStrategy>(
163
2
            buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
164
2
    set_padding_strategy(strategy);
165
  }
166
167
  // The max header list pairs option controls the maximum number of
168
  // header pairs the session may accept. This is a hard limit.. that is,
169
  // if the remote peer sends more than this amount, the stream will be
170
  // automatically closed with an RST_STREAM.
171
770
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS))
172
1
    set_max_header_pairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
173
174
  // The HTTP2 specification places no limits on the number of HTTP2
175
  // PING frames that can be sent. In order to prevent PINGS from being
176
  // abused as an attack vector, however, we place a strict upper limit
177
  // on the number of unacknowledged PINGS that can be sent at any given
178
  // time.
179
770
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS))
180
2
    set_max_outstanding_pings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
181
182
  // The HTTP2 specification places no limits on the number of HTTP2
183
  // SETTINGS frames that can be sent. In order to prevent PINGS from being
184
  // abused as an attack vector, however, we place a strict upper limit
185
  // on the number of unacknowledged SETTINGS that can be sent at any given
186
  // time.
187
770
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS))
188
2
    set_max_outstanding_settings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
189
190
  // The HTTP2 specification places no limits on the amount of memory
191
  // that a session can consume. In order to prevent abuse, we place a
192
  // cap on the amount of memory a session can consume at any given time.
193
  // this is a credit based system. Existing streams may cause the limit
194
  // to be temporarily exceeded but once over the limit, new streams cannot
195
  // created.
196
  // Important: The maxSessionMemory option in javascript is expressed in
197
  //            terms of MB increments (i.e. the value 1 == 1 MB)
198
770
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY))
199
8
    set_max_session_memory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] *
200
8
                           static_cast<uint64_t>(1000000));
201
202
770
  if (flags & (1 << IDX_OPTIONS_MAX_SETTINGS)) {
203
1
    nghttp2_option_set_max_settings(
204
        option,
205
2
        static_cast<size_t>(buffer[IDX_OPTIONS_MAX_SETTINGS]));
206
  }
207
770
}
208
209
#define GRABSETTING(entries, count, name)                                      \
210
  do {                                                                         \
211
    if (flags & (1 << IDX_SETTINGS_ ## name)) {                                \
212
      uint32_t val = buffer[IDX_SETTINGS_ ## name];                            \
213
      entries[count++] =                                                       \
214
          nghttp2_settings_entry {NGHTTP2_SETTINGS_ ## name, val};             \
215
    } } while (0)
216
217
797
size_t Http2Settings::Init(
218
    Http2State* http2_state,
219
    nghttp2_settings_entry* entries) {
220
797
  AliasedUint32Array& buffer = http2_state->settings_buffer;
221
797
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
222
223
797
  size_t count = 0;
224
225
#define V(name) GRABSETTING(entries, count, name);
226



797
  HTTP2_SETTINGS(V)
227
#undef V
228
229
797
  return count;
230
}
231
#undef GRABSETTING
232
233
// The Http2Settings class is used to configure a SETTINGS frame that is
234
// to be sent to the connected peer. The settings are set using a TypedArray
235
// that is shared with the JavaScript side.
236
780
Http2Settings::Http2Settings(Http2Session* session,
237
                             Local<Object> obj,
238
                             Local<Function> callback,
239
780
                             uint64_t start_time)
240
    : AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
241
      session_(session),
242
780
      startTime_(start_time) {
243
780
  callback_.Reset(env()->isolate(), callback);
244
780
  count_ = Init(session->http2_state(), entries_);
245
780
}
246
247
635
Local<Function> Http2Settings::callback() const {
248
1270
  return callback_.Get(env()->isolate());
249
}
250
251
void Http2Settings::MemoryInfo(MemoryTracker* tracker) const {
252
  tracker->TrackField("callback", callback_);
253
}
254
255
// Generates a Buffer that contains the serialized payload of a SETTINGS
256
// frame. This can be used, for instance, to create the Base64-encoded
257
// content of an Http2-Settings header field.
258
Local<Value> Http2Settings::Pack() {
259
  return Pack(session_->env(), count_, entries_);
260
}
261
262
17
Local<Value> Http2Settings::Pack(Http2State* state) {
263
  nghttp2_settings_entry entries[IDX_SETTINGS_COUNT];
264
17
  size_t count = Init(state, entries);
265
17
  return Pack(state->env(), count, entries);
266
}
267
268
17
Local<Value> Http2Settings::Pack(
269
    Environment* env,
270
    size_t count,
271
    const nghttp2_settings_entry* entries) {
272
17
  EscapableHandleScope scope(env->isolate());
273
17
  std::unique_ptr<BackingStore> bs;
274
  {
275
17
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
276
17
    bs = ArrayBuffer::NewBackingStore(env->isolate(), count * 6);
277
  }
278
17
  if (nghttp2_pack_settings_payload(static_cast<uint8_t*>(bs->Data()),
279
                                    bs->ByteLength(),
280
                                    entries,
281
17
                                    count) < 0) {
282
2
    return scope.Escape(Undefined(env->isolate()));
283
  }
284
16
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
285
16
  return scope.Escape(Buffer::New(env, ab, 0, ab->ByteLength())
286
32
                          .FromMaybe(Local<Value>()));
287
}
288
289
// Updates the shared TypedArray with the current remote or local settings for
290
// the session.
291
658
void Http2Settings::Update(Http2Session* session, get_setting fn) {
292
658
  AliasedUint32Array& buffer = session->http2_state()->settings_buffer;
293
294
#define V(name)                                                                \
295
  buffer[IDX_SETTINGS_ ## name] =                                              \
296
      fn(session->session(), NGHTTP2_SETTINGS_ ## name);
297
658
  HTTP2_SETTINGS(V)
298
#undef V
299
658
}
300
301
// Initializes the shared TypedArray with the default settings values.
302
6
void Http2Settings::RefreshDefaults(Http2State* http2_state) {
303
6
  AliasedUint32Array& buffer = http2_state->settings_buffer;
304
6
  uint32_t flags = 0;
305
306
#define V(name)                                                            \
307
  do {                                                                     \
308
    buffer[IDX_SETTINGS_ ## name] = DEFAULT_SETTINGS_ ## name;             \
309
    flags |= 1 << IDX_SETTINGS_ ## name;                                   \
310
  } while (0);
311
6
  HTTP2_SETTINGS(V)
312
#undef V
313
314
6
  buffer[IDX_SETTINGS_COUNT] = flags;
315
6
}
316
317
318
778
void Http2Settings::Send() {
319
1556
  Http2Scope h2scope(session_.get());
320
778
  CHECK_EQ(nghttp2_submit_settings(
321
      session_->session(),
322
      NGHTTP2_FLAG_NONE,
323
      &entries_[0],
324
      count_), 0);
325
778
}
326
327
635
void Http2Settings::Done(bool ack) {
328
635
  uint64_t end = uv_hrtime();
329
635
  double duration = (end - startTime_) / 1e6;
330
331
  Local<Value> argv[] = {
332
635
    ack ? True(env()->isolate()) : False(env()->isolate()),
333
    Number::New(env()->isolate(), duration)
334
1270
  };
335
635
  MakeCallback(callback(), arraysize(argv), argv);
336
635
}
337
338
// The Http2Priority class initializes an appropriate nghttp2_priority_spec
339
// struct used when either creating a stream or updating its priority
340
// settings.
341
12110
Http2Priority::Http2Priority(Environment* env,
342
                             Local<Value> parent,
343
                             Local<Value> weight,
344
12110
                             Local<Value> exclusive) {
345
12110
  Local<Context> context = env->context();
346
24220
  int32_t parent_ = parent->Int32Value(context).ToChecked();
347
24220
  int32_t weight_ = weight->Int32Value(context).ToChecked();
348
12110
  bool exclusive_ = exclusive->IsTrue();
349
  Debug(env, DebugCategory::HTTP2STREAM,
350
        "Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
351
12110
        parent_, weight_, exclusive_ ? "yes" : "no");
352
12110
  nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
353
12110
}
354
355
356
117
const char* Http2Session::TypeName() const {
357
117
  switch (session_type_) {
358
59
    case NGHTTP2_SESSION_SERVER: return "server";
359
58
    case NGHTTP2_SESSION_CLIENT: return "client";
360
    default:
361
      // This should never happen
362
      ABORT();
363
  }
364
}
365
366
5
Origins::Origins(
367
    Environment* env,
368
    Local<String> origin_string,
369
5
    size_t origin_count)
370
5
    : count_(origin_count) {
371
5
  int origin_string_len = origin_string->Length();
372
5
  if (count_ == 0) {
373
    CHECK_EQ(origin_string_len, 0);
374
    return;
375
  }
376
377
  {
378
5
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
379
10
    bs_ = ArrayBuffer::NewBackingStore(env->isolate(),
380
                                       alignof(nghttp2_origin_entry) - 1 +
381
5
                                       count_ * sizeof(nghttp2_origin_entry) +
382
5
                                       origin_string_len);
383
  }
384
385
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
386
5
  char* start = AlignUp(static_cast<char*>(bs_->Data()),
387
                        alignof(nghttp2_origin_entry));
388
5
  char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
389
5
  nghttp2_origin_entry* const nva =
390
      reinterpret_cast<nghttp2_origin_entry*>(start);
391
392
5
  CHECK_LE(origin_contents + origin_string_len,
393
           static_cast<char*>(bs_->Data()) + bs_->ByteLength());
394
5
  CHECK_EQ(origin_string->WriteOneByte(
395
               env->isolate(),
396
               reinterpret_cast<uint8_t*>(origin_contents),
397
               0,
398
               origin_string_len,
399
               String::NO_NULL_TERMINATION),
400
           origin_string_len);
401
402
5
  size_t n = 0;
403
  char* p;
404
14
  for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
405
9
    if (n >= count_) {
406
      static uint8_t zero = '\0';
407
      nva[0].origin = &zero;
408
      nva[0].origin_len = 1;
409
      count_ = 1;
410
      return;
411
    }
412
413
9
    nva[n].origin = reinterpret_cast<uint8_t*>(p);
414
9
    nva[n].origin_len = strlen(p);
415
9
    p += nva[n].origin_len + 1;
416
  }
417
}
418
419
// Sets the various callback functions that nghttp2 will use to notify us
420
// about significant events while processing http2 stuff.
421
11200
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
422
  nghttp2_session_callbacks* callbacks_;
423
11200
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
424
11200
  callbacks.reset(callbacks_);
425
426
11200
  nghttp2_session_callbacks_set_on_begin_headers_callback(
427
    callbacks_, OnBeginHeadersCallback);
428
11200
  nghttp2_session_callbacks_set_on_header_callback2(
429
    callbacks_, OnHeaderCallback);
430
11200
  nghttp2_session_callbacks_set_on_frame_recv_callback(
431
    callbacks_, OnFrameReceive);
432
11200
  nghttp2_session_callbacks_set_on_stream_close_callback(
433
    callbacks_, OnStreamClose);
434
11200
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
435
    callbacks_, OnDataChunkReceived);
436
11200
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
437
    callbacks_, OnFrameNotSent);
438
11200
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
439
    callbacks_, OnInvalidHeader);
440
11200
  nghttp2_session_callbacks_set_error_callback(
441
    callbacks_, OnNghttpError);
442
11200
  nghttp2_session_callbacks_set_send_data_callback(
443
    callbacks_, OnSendData);
444
11200
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
445
    callbacks_, OnInvalidFrame);
446
11200
  nghttp2_session_callbacks_set_on_frame_send_callback(
447
    callbacks_, OnFrameSent);
448
449
11200
  if (kHasGetPaddingCallback) {
450
5600
    nghttp2_session_callbacks_set_select_padding_callback(
451
      callbacks_, OnSelectPadding);
452
  }
453
11200
}
454
455
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
456
  StopTrackingMemory(buf);
457
}
458
459
207902
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
460
207902
  CHECK_GE(current_nghttp2_memory_, previous_size);
461
207902
}
462
463
104968
void Http2Session::IncreaseAllocatedSize(size_t size) {
464
104968
  current_nghttp2_memory_ += size;
465
104968
}
466
467
128217
void Http2Session::DecreaseAllocatedSize(size_t size) {
468
128217
  current_nghttp2_memory_ -= size;
469
128217
}
470
471
770
Http2Session::Http2Session(Http2State* http2_state,
472
                           Local<Object> wrap,
473
770
                           SessionType type)
474
    : AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
475
      js_fields_(http2_state->env()->isolate()),
476
      session_type_(type),
477
770
      http2_state_(http2_state) {
478
770
  MakeWeak();
479
770
  statistics_.session_type = type;
480
770
  statistics_.start_time = uv_hrtime();
481
482
  // Capture the configuration options for this session
483
770
  Http2Options opts(http2_state, type);
484
485
770
  max_session_memory_ = opts.max_session_memory();
486
487
770
  uint32_t maxHeaderPairs = opts.max_header_pairs();
488
1540
  max_header_pairs_ =
489
      type == NGHTTP2_SESSION_SERVER
490
393
          ? GetServerMaxHeaderPairs(maxHeaderPairs)
491
377
          : GetClientMaxHeaderPairs(maxHeaderPairs);
492
493
770
  max_outstanding_pings_ = opts.max_outstanding_pings();
494
770
  max_outstanding_settings_ = opts.max_outstanding_settings();
495
496
770
  padding_strategy_ = opts.padding_strategy();
497
498
770
  bool hasGetPaddingCallback =
499
770
      padding_strategy_ != PADDING_STRATEGY_NONE;
500
501
770
  auto fn = type == NGHTTP2_SESSION_SERVER ?
502
      nghttp2_session_server_new3 :
503
      nghttp2_session_client_new3;
504
505
770
  nghttp2_mem alloc_info = MakeAllocator();
506
507
  // This should fail only if the system is out of memory, which
508
  // is going to cause lots of other problems anyway, or if any
509
  // of the options are out of acceptable range, which we should
510
  // be catching before it gets this far. Either way, crash if this
511
  // fails.
512
  nghttp2_session* session;
513

770
  CHECK_EQ(fn(
514
      &session,
515
      callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks.get(),
516
      this,
517
      *opts,
518
      &alloc_info), 0);
519
770
  session_.reset(session);
520
521
770
  outgoing_storage_.reserve(1024);
522
770
  outgoing_buffers_.reserve(32);
523
524
  Local<Uint8Array> uint8_arr =
525
770
      Uint8Array::New(js_fields_.GetArrayBuffer(), 0, kSessionUint8FieldCount);
526
1540
  USE(wrap->Set(env()->context(), env()->fields_string(), uint8_arr));
527
770
}
528
529
4596
Http2Session::~Http2Session() {
530
1532
  CHECK(!is_in_scope());
531
1532
  Debug(this, "freeing nghttp2 session");
532
  // Explicitly reset session_ so the subsequent
533
  // current_nghttp2_memory_ check passes.
534
1532
  session_.reset();
535
1532
  CHECK_EQ(current_nghttp2_memory_, 0);
536
3064
}
537
538
void Http2Session::MemoryInfo(MemoryTracker* tracker) const {
539
  tracker->TrackField("streams", streams_);
540
  tracker->TrackField("outstanding_pings", outstanding_pings_);
541
  tracker->TrackField("outstanding_settings", outstanding_settings_);
542
  tracker->TrackField("outgoing_buffers", outgoing_buffers_);
543
  tracker->TrackFieldWithSize("stream_buf", stream_buf_.len);
544
  tracker->TrackFieldWithSize("outgoing_storage", outgoing_storage_.size());
545
  tracker->TrackFieldWithSize("pending_rst_streams",
546
                              pending_rst_streams_.size() * sizeof(int32_t));
547
  tracker->TrackFieldWithSize("nghttp2_memory", current_nghttp2_memory_);
548
}
549
550
117
std::string Http2Session::diagnostic_name() const {
551
234
  return std::string("Http2Session ") + TypeName() + " (" +
552
351
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
553
}
554
555
8
MaybeLocal<Object> Http2StreamPerformanceEntryTraits::GetDetails(
556
    Environment* env,
557
    const Http2StreamPerformanceEntry& entry) {
558
8
  Local<Object> obj = Object::New(env->isolate());
559
560
#define SET(name, val)                                                         \
561
  if (!obj->Set(                                                               \
562
          env->context(),                                                      \
563
          env->name(),                                                         \
564
          Number::New(                                                         \
565
            env->isolate(),                                                    \
566
            static_cast<double>(entry.details.val))).IsJust()) {               \
567
    return MaybeLocal<Object>();                                               \
568
  }
569
570
32
  SET(bytes_read_string, received_bytes)
571
32
  SET(bytes_written_string, sent_bytes)
572
32
  SET(id_string, id)
573
#undef SET
574
575
#define SET(name, val)                                                         \
576
  if (!obj->Set(                                                               \
577
          env->context(),                                                      \
578
          env->name(),                                                         \
579
          Number::New(                                                         \
580
              env->isolate(),                                                  \
581
              (entry.details.val - entry.details.start_time) / 1e6))           \
582
                  .IsJust()) {                                                 \
583
    return MaybeLocal<Object>();                                               \
584
  }
585
586
32
  SET(time_to_first_byte_string, first_byte)
587
32
  SET(time_to_first_byte_sent_string, first_byte_sent)
588
32
  SET(time_to_first_header_string, first_header)
589
#undef SET
590
591
8
  return obj;
592
}
593
594
7
MaybeLocal<Object> Http2SessionPerformanceEntryTraits::GetDetails(
595
    Environment* env,
596
    const Http2SessionPerformanceEntry& entry) {
597
7
  Local<Object> obj = Object::New(env->isolate());
598
599
#define SET(name, val)                                                         \
600
  if (!obj->Set(                                                               \
601
          env->context(),                                                      \
602
          env->name(),                                                         \
603
          Number::New(                                                         \
604
            env->isolate(),                                                    \
605
            static_cast<double>(entry.details.val))).IsJust()) {               \
606
    return MaybeLocal<Object>();                                               \
607
  }
608
609
28
  SET(bytes_written_string, data_sent)
610
28
  SET(bytes_read_string, data_received)
611
28
  SET(frames_received_string, frame_count)
612
28
  SET(frames_sent_string, frame_sent)
613
28
  SET(max_concurrent_streams_string, max_concurrent_streams)
614
28
  SET(ping_rtt_string, ping_rtt)
615
28
  SET(stream_average_duration_string, stream_average_duration)
616
28
  SET(stream_count_string, stream_count)
617
618
14
  if (!obj->Set(
619
          env->context(),
620
          env->type_string(),
621
          OneByteString(
622
              env->isolate(),
623
7
              (entry.details.session_type == NGHTTP2_SESSION_SERVER)
624

28
                  ? "server" : "client")).IsJust()) {
625
    return MaybeLocal<Object>();
626
  }
627
628
#undef SET
629
7
  return obj;
630
}
631
632
23662
void Http2Stream::EmitStatistics() {
633
23662
  CHECK_NOT_NULL(session());
634
23662
  if (LIKELY(!HasHttp2Observer(env())))
635
23654
    return;
636
637
8
  double start = statistics_.start_time / 1e6;
638
8
  double duration = (PERFORMANCE_NOW() / 1e6) - start;
639
640
  std::unique_ptr<Http2StreamPerformanceEntry> entry =
641
      std::make_unique<Http2StreamPerformanceEntry>(
642
          "Http2Stream",
643
8
          start - (env()->time_origin() / 1e6),
644
          duration,
645
16
          statistics_);
646
647
8
  env()->SetImmediate([entry = move(entry)](Environment* env) {
648
8
    if (HasHttp2Observer(env))
649
8
      entry->Notify(env);
650
8
  });
651
}
652
653
673
void Http2Session::EmitStatistics() {
654
673
  if (LIKELY(!HasHttp2Observer(env())))
655
666
    return;
656
657
7
  double start = statistics_.start_time / 1e6;
658
7
  double duration = (PERFORMANCE_NOW() / 1e6) - start;
659
660
  std::unique_ptr<Http2SessionPerformanceEntry> entry =
661
      std::make_unique<Http2SessionPerformanceEntry>(
662
          "Http2Session",
663
7
          start - (env()->time_origin() / 1e6),
664
          duration,
665
14
          statistics_);
666
667
7
  env()->SetImmediate([entry = std::move(entry)](Environment* env) {
668
7
    if (HasHttp2Observer(env))
669
7
      entry->Notify(env);
670
7
  });
671
}
672
673
// Closes the session and frees the associated resources
674
673
void Http2Session::Close(uint32_t code, bool socket_closed) {
675
673
  Debug(this, "closing session");
676
677
673
  if (is_closing())
678
    return;
679
673
  set_closing();
680
681
  // Stop reading on the i/o stream
682
673
  if (stream_ != nullptr) {
683
659
    set_reading_stopped();
684
659
    stream_->ReadStop();
685
  }
686
687
  // If the socket is not closed, then attempt to send a closing GOAWAY
688
  // frame. There is no guarantee that this GOAWAY will be received by
689
  // the peer but the HTTP/2 spec recommends sending it anyway. We'll
690
  // make a best effort.
691
673
  if (!socket_closed) {
692
625
    Debug(this, "terminating session with code %d", code);
693
625
    CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
694
625
    SendPendingData();
695
48
  } else if (stream_ != nullptr) {
696
34
    stream_->RemoveStreamListener(this);
697
  }
698
699
673
  set_destroyed();
700
701
  // If we are writing we will get to make the callback in OnStreamAfterWrite.
702
673
  if (!is_write_in_progress()) {
703
629
    Debug(this, "make done session callback");
704
1258
    HandleScope scope(env()->isolate());
705
629
    MakeCallback(env()->ondone_string(), 0, nullptr);
706
  }
707
708
  // If there are outstanding pings, those will need to be canceled, do
709
  // so on the next iteration of the event loop to avoid calling out into
710
  // javascript since this may be called during garbage collection.
711
674
  while (BaseObjectPtr<Http2Ping> ping = PopPing()) {
712
1
    ping->DetachFromSession();
713
2
    env()->SetImmediate(
714
1
        [ping = std::move(ping)](Environment* env) {
715
1
          ping->Done(false);
716
1
        });
717
1
  }
718
719
673
  statistics_.end_time = uv_hrtime();
720
673
  EmitStatistics();
721
}
722
723
// Locates an existing known stream by ID. nghttp2 has a similar method
724
// but this is faster and does not fail if the stream is not found.
725
249469
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
726
249469
  auto s = streams_.find(id);
727
249469
  return s != streams_.end() ? s->second : BaseObjectPtr<Http2Stream>();
728
}
729
730
12207
bool Http2Session::CanAddStream() {
731
  uint32_t maxConcurrentStreams =
732
12207
      nghttp2_session_get_local_settings(
733
          session_.get(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
734
  size_t maxSize =
735
12207
      std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
736
  // We can add a new stream so long as we are less than the current
737
  // maximum on concurrent streams and there's enough available memory
738

24414
  return streams_.size() < maxSize &&
739
24414
         has_available_session_memory(sizeof(Http2Stream));
740
}
741
742
24318
void Http2Session::AddStream(Http2Stream* stream) {
743
24318
  CHECK_GE(++statistics_.stream_count, 0);
744
24318
  streams_[stream->id()] = BaseObjectPtr<Http2Stream>(stream);
745
24318
  size_t size = streams_.size();
746
24318
  if (size > statistics_.max_concurrent_streams)
747
1993
    statistics_.max_concurrent_streams = size;
748
24318
  IncrementCurrentSessionMemory(sizeof(*stream));
749
24318
}
750
751
752
23662
BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
753
23662
  BaseObjectPtr<Http2Stream> stream;
754
23662
  if (streams_.empty())
755
    return stream;
756
23662
  stream = FindStream(id);
757
23662
  if (stream) {
758
23662
    streams_.erase(id);
759
23662
    DecrementCurrentSessionMemory(sizeof(*stream));
760
  }
761
23662
  return stream;
762
}
763
764
// Used as one of the Padding Strategy functions. Will attempt to ensure
765
// that the total frame size, including header bytes, are 8-byte aligned.
766
// If maxPayloadLen is smaller than the number of bytes necessary to align,
767
// will return maxPayloadLen instead.
768
3
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
769
                                            size_t maxPayloadLen) {
770
3
  size_t r = (frameLen + 9) % 8;
771
3
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
772
773
3
  size_t pad = frameLen + (8 - r);
774
775
  // If maxPayloadLen happens to be less than the calculated pad length,
776
  // use the max instead, even tho this means the frame will not be
777
  // aligned.
778
3
  pad = std::min(maxPayloadLen, pad);
779
3
  Debug(this, "using frame size padding: %d", pad);
780
3
  return pad;
781
}
782
783
// Used as one of the Padding Strategy functions. Uses the maximum amount
784
// of padding allowed for the current frame.
785
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
786
                                            size_t maxPayloadLen) {
787
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
788
  return maxPayloadLen;
789
}
790
791
// Write data received from the i/o stream to the underlying nghttp2_session.
792
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
793
// various callback functions. Each of these will typically result in a call
794
// out to JavaScript so this particular function is rather hot and can be
795
// quite expensive. This is a potential performance optimization target later.
796
31939
void Http2Session::ConsumeHTTP2Data() {
797
31939
  CHECK_NOT_NULL(stream_buf_.base);
798
31939
  CHECK_LE(stream_buf_offset_, stream_buf_.len);
799
31939
  size_t read_len = stream_buf_.len - stream_buf_offset_;
800
801
  // multiple side effects.
802
31939
  Debug(this, "receiving %d bytes [wants data? %d]",
803
        read_len,
804
31939
        nghttp2_session_want_read(session_.get()));
805
31939
  set_receive_paused(false);
806
31939
  custom_recv_error_code_ = nullptr;
807
  ssize_t ret =
808
31939
    nghttp2_session_mem_recv(session_.get(),
809
31939
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
810
31939
                                 stream_buf_offset_,
811
31937
                             read_len);
812
31937
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
813

31937
  CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
814
815
31937
  if (is_receive_paused()) {
816
567
    CHECK(is_reading_stopped());
817
818
567
    CHECK_GT(ret, 0);
819
567
    CHECK_LE(static_cast<size_t>(ret), read_len);
820
821
    // Mark the remainder of the data as available for later consumption.
822
    // Even if all bytes were received, a paused stream may delay the
823
    // nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
824
567
    stream_buf_offset_ += ret;
825
567
    goto done;
826
  }
827
828
  // We are done processing the current input chunk.
829
31370
  DecrementCurrentSessionMemory(stream_buf_.len);
830
31370
  stream_buf_offset_ = 0;
831
31370
  stream_buf_ab_.Reset();
832
31370
  stream_buf_allocation_.reset();
833
31370
  stream_buf_ = uv_buf_init(nullptr, 0);
834
835
  // Send any data that was queued up while processing the received data.
836

31370
  if (ret >= 0 && !is_destroyed()) {
837
30817
    SendPendingData();
838
  }
839
840
553
done:
841
31937
  if (UNLIKELY(ret < 0)) {
842
7
    Isolate* isolate = env()->isolate();
843
7
    Debug(this,
844
        "fatal error receiving data: %d (%s)",
845
        ret,
846
7
        custom_recv_error_code_ != nullptr ?
847
            custom_recv_error_code_ : "(no custom error code)");
848
    Local<Value> args[] = {
849
      Integer::New(isolate, static_cast<int32_t>(ret)),
850
      Null(isolate)
851
14
    };
852
7
    if (custom_recv_error_code_ != nullptr) {
853
3
      args[1] = String::NewFromUtf8(
854
          isolate,
855
          custom_recv_error_code_,
856
3
          NewStringType::kInternalized).ToLocalChecked();
857
    }
858
    MakeCallback(
859
        env()->http2session_on_error_function(),
860
7
        arraysize(args),
861
7
        args);
862
  }
863
31937
}
864
865
866
146667
int32_t GetFrameID(const nghttp2_frame* frame) {
867
  // If this is a push promise, we want to grab the id of the promised stream
868
146667
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
869
      frame->push_promise.promised_stream_id :
870
146667
      frame->hd.stream_id;
871
}
872
873
874
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
875
// callback to determine if a new stream is being created or if we are simply
876
// adding a new block of headers to an existing stream. The header pairs
877
// themselves are set in the OnHeaderCallback
878
23910
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
879
                                         const nghttp2_frame* frame,
880
                                         void* user_data) {
881
23910
  Http2Session* session = static_cast<Http2Session*>(user_data);
882
23910
  int32_t id = GetFrameID(frame);
883
  Debug(session, "beginning headers for stream %d", id);
884
885
47820
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
886
  // The common case is that we're creating a new stream. The less likely
887
  // case is that we're receiving a set of trailers
888
23910
  if (LIKELY(!stream)) {
889
24413
    if (UNLIKELY(!session->CanAddStream() ||
890
                 Http2Stream::New(session, id, frame->headers.cat) ==
891

24413
                     nullptr)) {
892
2
      if (session->rejected_stream_count_++ >
893
1
          session->js_fields_->max_rejected_streams)
894
        return NGHTTP2_ERR_CALLBACK_FAILURE;
895
      // Too many concurrent streams being opened
896
1
      nghttp2_submit_rst_stream(
897
          session->session(),
898
          NGHTTP2_FLAG_NONE,
899
          id,
900
          NGHTTP2_ENHANCE_YOUR_CALM);
901
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
902
    }
903
904
12206
    session->rejected_stream_count_ = 0;
905
11703
  } else if (!stream->is_destroyed()) {
906
11703
    stream->StartHeaders(frame->headers.cat);
907
  }
908
23909
  return 0;
909
}
910
911
// Called by nghttp2 for each header name/value pair in a HEADERS block.
912
// This had to have been preceded by a call to OnBeginHeadersCallback so
913
// the Http2Stream is guaranteed to already exist.
914
72668
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
915
                                   const nghttp2_frame* frame,
916
                                   nghttp2_rcbuf* name,
917
                                   nghttp2_rcbuf* value,
918
                                   uint8_t flags,
919
                                   void* user_data) {
920
72668
  Http2Session* session = static_cast<Http2Session*>(user_data);
921
72668
  int32_t id = GetFrameID(frame);
922
145336
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
923
  // If stream is null at this point, either something odd has happened
924
  // or the stream was closed locally while header processing was occurring.
925
  // either way, do not proceed and close the stream.
926
72668
  if (UNLIKELY(!stream))
927
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
928
929
  // If the stream has already been destroyed, ignore.
930

72668
  if (!stream->is_destroyed() && !stream->AddHeader(name, value, flags)) {
931
    // This will only happen if the connected peer sends us more
932
    // than the allowed number of header items at any given time
933
3
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
934
3
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
935
  }
936
72665
  return 0;
937
}
938
939
940
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
941
// only a handful of frame types that we care about handling here.
942
56176
int Http2Session::OnFrameReceive(nghttp2_session* handle,
943
                                 const nghttp2_frame* frame,
944
                                 void* user_data) {
945
56176
  Http2Session* session = static_cast<Http2Session*>(user_data);
946
56176
  session->statistics_.frame_count++;
947
  Debug(session, "complete frame received: type: %d",
948
56176
        frame->hd.type);
949


56176
  switch (frame->hd.type) {
950
24219
    case NGHTTP2_DATA:
951
24219
      return session->HandleDataFrame(frame);
952
23666
    case NGHTTP2_PUSH_PROMISE:
953
      // Intentional fall-through, handled just like headers frames
954
    case NGHTTP2_HEADERS:
955
23666
      session->HandleHeadersFrame(frame);
956
23664
      break;
957
2339
    case NGHTTP2_SETTINGS:
958
2339
      session->HandleSettingsFrame(frame);
959
2339
      break;
960
16
    case NGHTTP2_PRIORITY:
961
16
      session->HandlePriorityFrame(frame);
962
16
      break;
963
322
    case NGHTTP2_GOAWAY:
964
322
      session->HandleGoawayFrame(frame);
965
322
      break;
966
1021
    case NGHTTP2_PING:
967
1021
      session->HandlePingFrame(frame);
968
1021
      break;
969
4
    case NGHTTP2_ALTSVC:
970
4
      session->HandleAltSvcFrame(frame);
971
4
      break;
972
5
    case NGHTTP2_ORIGIN:
973
5
      session->HandleOriginFrame(frame);
974
5
      break;
975
4584
    default:
976
4584
      break;
977
  }
978
31955
  return 0;
979
}
980
981
242
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
982
                                 const nghttp2_frame* frame,
983
                                 int lib_error_code,
984
                                 void* user_data) {
985
242
  Http2Session* session = static_cast<Http2Session*>(user_data);
986
242
  const uint32_t max_invalid_frames = session->js_fields_->max_invalid_frames;
987
988
  Debug(session,
989
        "invalid frame received (%u/%u), code: %d",
990
242
        session->invalid_frame_count_,
991
        max_invalid_frames,
992
        lib_error_code);
993
242
  if (session->invalid_frame_count_++ > max_invalid_frames) {
994
2
    session->custom_recv_error_code_ = "ERR_HTTP2_TOO_MANY_INVALID_FRAMES";
995
2
    return 1;
996
  }
997
998
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
999

480
  if (nghttp2_is_fatal(lib_error_code) ||
1000
240
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
1001
1
    Environment* env = session->env();
1002
1
    Isolate* isolate = env->isolate();
1003
2
    HandleScope scope(isolate);
1004
1
    Local<Context> context = env->context();
1005
1
    Context::Scope context_scope(context);
1006
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
1007
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1008
  }
1009
240
  return 0;
1010
}
1011
1012
// Remove the headers reference.
1013
// Implicitly calls nghttp2_rcbuf_decref
1014
2195
void Http2Session::DecrefHeaders(const nghttp2_frame* frame) {
1015
2195
  int32_t id = GetFrameID(frame);
1016
4390
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1017
1018


2195
  if (stream && !stream->is_destroyed() && stream->headers_count() > 0) {
1019
1
    Debug(this, "freeing headers for stream %d", id);
1020
1
    stream->ClearHeaders();
1021
1
    CHECK_EQ(stream->headers_count(), 0);
1022
1
    DecrementCurrentSessionMemory(stream->current_headers_length_);
1023
1
    stream->current_headers_length_ = 0;
1024
  }
1025
2195
}
1026
1027
2
uint32_t TranslateNghttp2ErrorCode(const int libErrorCode) {
1028

2
  switch (libErrorCode) {
1029
  case NGHTTP2_ERR_STREAM_CLOSED:
1030
    return NGHTTP2_STREAM_CLOSED;
1031
  case NGHTTP2_ERR_HEADER_COMP:
1032
    return NGHTTP2_COMPRESSION_ERROR;
1033
2
  case NGHTTP2_ERR_FRAME_SIZE_ERROR:
1034
2
    return NGHTTP2_FRAME_SIZE_ERROR;
1035
  case NGHTTP2_ERR_FLOW_CONTROL:
1036
    return NGHTTP2_FLOW_CONTROL_ERROR;
1037
  case NGHTTP2_ERR_REFUSED_STREAM:
1038
    return NGHTTP2_REFUSED_STREAM;
1039
  case NGHTTP2_ERR_PROTO:
1040
  case NGHTTP2_ERR_HTTP_HEADER:
1041
  case NGHTTP2_ERR_HTTP_MESSAGING:
1042
    return NGHTTP2_PROTOCOL_ERROR;
1043
  default:
1044
    return NGHTTP2_INTERNAL_ERROR;
1045
  }
1046
}
1047
1048
// If nghttp2 is unable to send a queued up frame, it will call this callback
1049
// to let us know. If the failure occurred because we are in the process of
1050
// closing down the session or stream, we go ahead and ignore it. We don't
1051
// really care about those and there's nothing we can reasonably do about it
1052
// anyway. Other types of failures are reported up to JavaScript. This should
1053
// be exceedingly rare.
1054
2197
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1055
                                 const nghttp2_frame* frame,
1056
                                 int error_code,
1057
                                 void* user_data) {
1058
2197
  Http2Session* session = static_cast<Http2Session*>(user_data);
1059
2197
  Environment* env = session->env();
1060
  Debug(session, "frame type %d was not sent, code: %d",
1061
2197
        frame->hd.type, error_code);
1062
1063
  // Do not report if the frame was not sent due to the session closing
1064
4399
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
1065
5
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1066

2205
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
1067
3
      session->js_fields_->frame_error_listener_count == 0) {
1068
    // Nghttp2 contains header limit of 65536. When this value is exceeded the
1069
    // pipeline is stopped and we should remove the current headers reference
1070
    // to destroy the session completely.
1071
    // Further information see: https://github.com/nodejs/node/issues/35233
1072
2195
    session->DecrefHeaders(frame);
1073
2195
    return 0;
1074
  }
1075
1076
2
  Isolate* isolate = env->isolate();
1077
4
  HandleScope scope(isolate);
1078
2
  Local<Context> context = env->context();
1079
2
  Context::Scope context_scope(context);
1080
1081
  Local<Value> argv[3] = {
1082
2
    Integer::New(isolate, frame->hd.stream_id),
1083
2
    Integer::New(isolate, frame->hd.type),
1084
2
    Integer::New(isolate, TranslateNghttp2ErrorCode(error_code))
1085
6
  };
1086
  session->MakeCallback(
1087
      env->http2session_on_frame_error_function(),
1088
2
      arraysize(argv), argv);
1089
2
  return 0;
1090
}
1091
1092
56330
int Http2Session::OnFrameSent(nghttp2_session* handle,
1093
                              const nghttp2_frame* frame,
1094
                              void* user_data) {
1095
56330
  Http2Session* session = static_cast<Http2Session*>(user_data);
1096
56330
  session->statistics_.frame_sent += 1;
1097
56330
  return 0;
1098
}
1099
1100
// Called by nghttp2 when a stream closes.
1101
23640
int Http2Session::OnStreamClose(nghttp2_session* handle,
1102
                                int32_t id,
1103
                                uint32_t code,
1104
                                void* user_data) {
1105
23640
  Http2Session* session = static_cast<Http2Session*>(user_data);
1106
23640
  Environment* env = session->env();
1107
23640
  Isolate* isolate = env->isolate();
1108
47280
  HandleScope scope(isolate);
1109
23640
  Local<Context> context = env->context();
1110
23640
  Context::Scope context_scope(context);
1111
  Debug(session, "stream %d closed with code: %d", id, code);
1112
47280
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1113
  // Intentionally ignore the callback if the stream does not exist or has
1114
  // already been destroyed
1115

23640
  if (!stream || stream->is_destroyed())
1116
53
    return 0;
1117
1118
23587
  stream->Close(code);
1119
1120
  // It is possible for the stream close to occur before the stream is
1121
  // ever passed on to the javascript side. If that happens, the callback
1122
  // will return false.
1123
23587
  if (env->can_call_into_js()) {
1124
23587
    Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1125
23587
    MaybeLocal<Value> answer = stream->MakeCallback(
1126
23587
        env->http2session_on_stream_close_function(), 1, &arg);
1127

47174
    if (answer.IsEmpty() || answer.ToLocalChecked()->IsFalse()) {
1128
      // Skip to destroy
1129
138
      stream->Destroy();
1130
    }
1131
  }
1132
23587
  return 0;
1133
}
1134
1135
// Called by nghttp2 when an invalid header has been received. For now, we
1136
// ignore these. If this callback was not provided, nghttp2 would handle
1137
// invalid headers strictly and would shut down the stream. We are intentionally
1138
// being more lenient here although we may want to revisit this choice later.
1139
4
int Http2Session::OnInvalidHeader(nghttp2_session* session,
1140
                                  const nghttp2_frame* frame,
1141
                                  nghttp2_rcbuf* name,
1142
                                  nghttp2_rcbuf* value,
1143
                                  uint8_t flags,
1144
                                  void* user_data) {
1145
  // Ignore invalid header fields by default.
1146
4
  return 0;
1147
}
1148
1149
// When nghttp2 receives a DATA frame, it will deliver the data payload to
1150
// us in discrete chunks. We push these into a linked list stored in the
1151
// Http2Sttream which is flushed out to JavaScript as quickly as possible.
1152
// This can be a particularly hot path.
1153
13824
int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
1154
                                      uint8_t flags,
1155
                                      int32_t id,
1156
                                      const uint8_t* data,
1157
                                      size_t len,
1158
                                      void* user_data) {
1159
13824
  Http2Session* session = static_cast<Http2Session*>(user_data);
1160
  Debug(session, "buffering data chunk for stream %d, size: "
1161
        "%d, flags: %d", id, len, flags);
1162
13824
  Environment* env = session->env();
1163
27648
  HandleScope scope(env->isolate());
1164
1165
  // We should never actually get a 0-length chunk so this check is
1166
  // only a precaution at this point.
1167
13824
  if (len == 0)
1168
    return 0;
1169
1170
  // Notify nghttp2 that we've consumed a chunk of data on the connection
1171
  // so that it can send a WINDOW_UPDATE frame. This is a critical part of
1172
  // the flow control process in http2
1173
13824
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1174
27648
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1175
1176
  // If the stream has been destroyed, ignore this chunk
1177

13824
  if (!stream || stream->is_destroyed())
1178
1
    return 0;
1179
1180
13823
  stream->statistics_.received_bytes += len;
1181
1182
  // Repeatedly ask the stream's owner for memory, and copy the read data
1183
  // into those buffers.
1184
  // The typical case is actually the exception here; Http2StreamListeners
1185
  // know about the HTTP2 session associated with this stream, so they know
1186
  // about the larger from-socket read buffer, so they do not require copying.
1187
  do {
1188
13823
    uv_buf_t buf = stream->EmitAlloc(len);
1189
13823
    ssize_t avail = len;
1190
13823
    if (static_cast<ssize_t>(buf.len) < avail)
1191
      avail = buf.len;
1192
1193
    // `buf.base == nullptr` is the default Http2StreamListener's way
1194
    // of saying that it wants a pointer to the raw original.
1195
    // Since it has access to the original socket buffer from which the data
1196
    // was read in the first place, it can use that to minimize ArrayBuffer
1197
    // allocations.
1198
13823
    if (LIKELY(buf.base == nullptr))
1199
13823
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1200
    else
1201
      memcpy(buf.base, data, avail);
1202
13823
    data += avail;
1203
13823
    len -= avail;
1204
13823
    stream->EmitRead(avail, buf);
1205
1206
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1207
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1208
    // more data is being requested.
1209
13823
    if (stream->is_reading())
1210
12715
      nghttp2_session_consume_stream(handle, id, avail);
1211
    else
1212
1108
      stream->inbound_consumed_data_while_paused_ += avail;
1213
1214
    // If we have a gathered a lot of data for output, try sending it now.
1215

27643
    if (session->outgoing_length_ > 4096 ||
1216
13820
        stream->available_outbound_length_ > 4096) {
1217
10
      session->SendPendingData();
1218
    }
1219
13823
  } while (len != 0);
1220
1221
  // If we are currently waiting for a write operation to finish, we should
1222
  // tell nghttp2 that we want to wait before we process more input data.
1223
13823
  if (session->is_write_in_progress()) {
1224
567
    CHECK(session->is_reading_stopped());
1225
567
    session->set_receive_paused();
1226
    Debug(session, "receive paused");
1227
567
    return NGHTTP2_ERR_PAUSE;
1228
  }
1229
1230
13256
  return 0;
1231
}
1232
1233
// Called by nghttp2 when it needs to determine how much padding to use in
1234
// a DATA or HEADERS frame.
1235
3
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1236
                                      const nghttp2_frame* frame,
1237
                                      size_t maxPayloadLen,
1238
                                      void* user_data) {
1239
3
  Http2Session* session = static_cast<Http2Session*>(user_data);
1240
3
  ssize_t padding = frame->hd.length;
1241
1242

3
  switch (session->padding_strategy_) {
1243
    case PADDING_STRATEGY_NONE:
1244
      // Fall-through
1245
      break;
1246
    case PADDING_STRATEGY_MAX:
1247
      padding = session->OnMaxFrameSizePadding(padding, maxPayloadLen);
1248
      break;
1249
3
    case PADDING_STRATEGY_ALIGNED:
1250
3
      padding = session->OnDWordAlignedPadding(padding, maxPayloadLen);
1251
3
      break;
1252
  }
1253
3
  return padding;
1254
}
1255
1256
#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we "     \
1257
                         "expected SETTINGS frame.  Perhaps, peer does not "  \
1258
                         "support HTTP/2 properly."
1259
1260
// We use this currently to determine when an attempt is made to use the http2
1261
// protocol with a non-http2 peer.
1262
241
int Http2Session::OnNghttpError(nghttp2_session* handle,
1263
                                const char* message,
1264
                                size_t len,
1265
                                void* user_data) {
1266
  // Unfortunately, this is currently the only way for us to know if
1267
  // the session errored because the peer is not an http2 peer.
1268
241
  Http2Session* session = static_cast<Http2Session*>(user_data);
1269
  Debug(session, "Error '%s'", message);
1270
241
  if (strncmp(message, BAD_PEER_MESSAGE, len) == 0) {
1271
1
    Environment* env = session->env();
1272
1
    Isolate* isolate = env->isolate();
1273
2
    HandleScope scope(isolate);
1274
1
    Local<Context> context = env->context();
1275
1
    Context::Scope context_scope(context);
1276
1
    Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1277
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1278
  }
1279
241
  return 0;
1280
}
1281
1282
13823
uv_buf_t Http2StreamListener::OnStreamAlloc(size_t size) {
1283
  // See the comments in Http2Session::OnDataChunkReceived
1284
  // (which is the only possible call site for this method).
1285
13823
  return uv_buf_init(nullptr, size);
1286
}
1287
1288
26491
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1289
26491
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1290
26491
  Http2Session* session = stream->session();
1291
26491
  Environment* env = stream->env();
1292
26491
  HandleScope handle_scope(env->isolate());
1293
26491
  Context::Scope context_scope(env->context());
1294
1295
26491
  if (nread < 0) {
1296
12668
    PassReadErrorToPreviousListener(nread);
1297
12668
    return;
1298
  }
1299
1300
  Local<ArrayBuffer> ab;
1301
13823
  if (session->stream_buf_ab_.IsEmpty()) {
1302
    ab = ArrayBuffer::New(env->isolate(),
1303
5626
                          std::move(session->stream_buf_allocation_));
1304
5626
    session->stream_buf_ab_.Reset(env->isolate(), ab);
1305
  } else {
1306
8197
    ab = PersistentToLocal::Strong(session->stream_buf_ab_);
1307
  }
1308
1309
  // There is a single large array buffer for the entire data read from the
1310
  // network; create a slice of that array buffer and emit it as the
1311
  // received data buffer.
1312
13823
  size_t offset = buf.base - session->stream_buf_.base;
1313
1314
  // Verify that the data offset is inside the current read buffer.
1315
13823
  CHECK_GE(offset, session->stream_buf_offset_);
1316
13823
  CHECK_LE(offset, session->stream_buf_.len);
1317
13823
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1318
1319
13823
  stream->CallJSOnreadMethod(nread, ab, offset);
1320
}
1321
1322
1323
// Called by OnFrameReceived to notify JavaScript land that a complete
1324
// HEADERS frame has been received and processed. This method converts the
1325
// received headers into a JavaScript array and pushes those out to JS.
1326
23666
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1327
23666
  Isolate* isolate = env()->isolate();
1328
23666
  HandleScope scope(isolate);
1329
23666
  Local<Context> context = env()->context();
1330
23666
  Context::Scope context_scope(context);
1331
1332
23666
  int32_t id = GetFrameID(frame);
1333
23666
  Debug(this, "handle headers frame for stream %d", id);
1334
23666
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1335
1336
  // If the stream has already been destroyed, ignore.
1337

23666
  if (!stream || stream->is_destroyed())
1338
    return;
1339
1340
  // The headers are stored as a vector of Http2Header instances.
1341
  // The following converts that into a JS array with the structure:
1342
  // [name1, value1, name2, value2, name3, value3, name3, value4] and so on.
1343
  // That array is passed up to the JS layer and converted into an Object form
1344
  // like {name1: value1, name2: value2, name3: [value3, value4]}. We do it
1345
  // this way for performance reasons (it's faster to generate and pass an
1346
  // array than it is to generate and pass the object).
1347
1348
47330
  MaybeStackBuffer<Local<Value>, 64> headers_v(stream->headers_count() * 2);
1349
47330
  MaybeStackBuffer<Local<Value>, 32> sensitive_v(stream->headers_count());
1350
23666
  size_t sensitive_count = 0;
1351
1352
23666
  stream->TransferHeaders([&](const Http2Header& header, size_t i) {
1353
145296
    headers_v[i * 2] = header.GetName(this).ToLocalChecked();
1354
145296
    headers_v[i * 2 + 1] = header.GetValue(this).ToLocalChecked();
1355
72648
    if (header.flags() & NGHTTP2_NV_FLAG_NO_INDEX)
1356
29
      sensitive_v[sensitive_count++] = headers_v[i * 2];
1357
72648
  });
1358
23666
  CHECK_EQ(stream->headers_count(), 0);
1359
1360
23666
  DecrementCurrentSessionMemory(stream->current_headers_length_);
1361
23666
  stream->current_headers_length_ = 0;
1362
1363
  Local<Value> args[] = {
1364
23666
    stream->object(),
1365
    Integer::New(isolate, id),
1366
23666
    Integer::New(isolate, stream->headers_category()),
1367
23666
    Integer::New(isolate, frame->hd.flags),
1368
    Array::New(isolate, headers_v.out(), headers_v.length()),
1369
    Array::New(isolate, sensitive_v.out(), sensitive_count),
1370
165662
  };
1371
  MakeCallback(env()->http2session_on_headers_function(),
1372
23666
               arraysize(args), args);
1373
}
1374
1375
1376
// Called by OnFrameReceived when a complete PRIORITY frame has been
1377
// received. Notifies JS land about the priority change. Note that priorities
1378
// are considered advisory only, so this has no real effect other than to
1379
// simply let user code know that the priority has changed.
1380
16
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
1381
16
  if (js_fields_->priority_listener_count == 0) return;
1382
5
  Isolate* isolate = env()->isolate();
1383
10
  HandleScope scope(isolate);
1384
5
  Local<Context> context = env()->context();
1385
5
  Context::Scope context_scope(context);
1386
1387
5
  nghttp2_priority priority_frame = frame->priority;
1388
5
  int32_t id = GetFrameID(frame);
1389
5
  Debug(this, "handle priority frame for stream %d", id);
1390
  // Priority frame stream ID should never be <= 0. nghttp2 handles this for us
1391
5
  nghttp2_priority_spec spec = priority_frame.pri_spec;
1392
1393
  Local<Value> argv[4] = {
1394
    Integer::New(isolate, id),
1395
    Integer::New(isolate, spec.stream_id),
1396
    Integer::New(isolate, spec.weight),
1397
5
    Boolean::New(isolate, spec.exclusive)
1398
20
  };
1399
  MakeCallback(env()->http2session_on_priority_function(),
1400
5
               arraysize(argv), argv);
1401
}
1402
1403
1404
// Called by OnFrameReceived when a complete DATA frame has been received.
1405
// If we know that this was the last DATA frame (because the END_STREAM flag
1406
// is set), then we'll terminate the readable side of the StreamBase.
1407
24219
int Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1408
24219
  int32_t id = GetFrameID(frame);
1409
24219
  Debug(this, "handling data frame for stream %d", id);
1410
48438
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1411
1412
48438
  if (stream &&
1413

48438
      !stream->is_destroyed() &&
1414
24219
      frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1415
12668
    stream->EmitRead(UV_EOF);
1416
11551
  } else if (frame->hd.length == 0) {
1417
5
    if (invalid_frame_count_++ > js_fields_->max_invalid_frames) {
1418
1
      custom_recv_error_code_ = "ERR_HTTP2_TOO_MANY_INVALID_FRAMES";
1419
1
      Debug(this, "rejecting empty-frame-without-END_STREAM flood\n");
1420
      // Consider a flood of 0-length frames without END_STREAM an error.
1421
1
      return 1;
1422
    }
1423
  }
1424
24218
  return 0;
1425
}
1426
1427
1428
// Called by OnFrameReceived when a complete GOAWAY frame has been received.
1429
322
void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
1430
322
  Isolate* isolate = env()->isolate();
1431
644
  HandleScope scope(isolate);
1432
322
  Local<Context> context = env()->context();
1433
322
  Context::Scope context_scope(context);
1434
1435
322
  nghttp2_goaway goaway_frame = frame->goaway;
1436
322
  Debug(this, "handling goaway frame");
1437
1438
  Local<Value> argv[3] = {
1439
    Integer::NewFromUnsigned(isolate, goaway_frame.error_code),
1440
    Integer::New(isolate, goaway_frame.last_stream_id),
1441
    Undefined(isolate)
1442
966
  };
1443
1444
322
  size_t length = goaway_frame.opaque_data_len;
1445
322
  if (length > 0) {
1446
    // If the copy fails for any reason here, we just ignore it.
1447
    // The additional goaway data is completely optional and we
1448
    // shouldn't fail if we're not able to process it.
1449
3
    argv[2] = Buffer::Copy(isolate,
1450
3
                           reinterpret_cast<char*>(goaway_frame.opaque_data),
1451
3
                           length).ToLocalChecked();
1452
  }
1453
1454
  MakeCallback(env()->http2session_on_goaway_data_function(),
1455
322
               arraysize(argv), argv);
1456
322
}
1457
1458
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
1459
4
void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
1460
4
  if (!(js_fields_->bitfield & (1 << kSessionHasAltsvcListeners))) return;
1461
4
  Isolate* isolate = env()->isolate();
1462
8
  HandleScope scope(isolate);
1463
4
  Local<Context> context = env()->context();
1464
4
  Context::Scope context_scope(context);
1465
1466
4
  int32_t id = GetFrameID(frame);
1467
1468
4
  nghttp2_extension ext = frame->ext;
1469
4
  nghttp2_ext_altsvc* altsvc = static_cast<nghttp2_ext_altsvc*>(ext.payload);
1470
4
  Debug(this, "handling altsvc frame");
1471
1472
  Local<Value> argv[3] = {
1473
    Integer::New(isolate, id),
1474
8
    OneByteString(isolate, altsvc->origin, altsvc->origin_len),
1475
8
    OneByteString(isolate, altsvc->field_value, altsvc->field_value_len)
1476
12
  };
1477
1478
  MakeCallback(env()->http2session_on_altsvc_function(),
1479
4
               arraysize(argv), argv);
1480
}
1481
1482
5
void Http2Session::HandleOriginFrame(const nghttp2_frame* frame) {
1483
5
  Isolate* isolate = env()->isolate();
1484
10
  HandleScope scope(isolate);
1485
5
  Local<Context> context = env()->context();
1486
5
  Context::Scope context_scope(context);
1487
1488
5
  Debug(this, "handling origin frame");
1489
1490
5
  nghttp2_extension ext = frame->ext;
1491
5
  nghttp2_ext_origin* origin = static_cast<nghttp2_ext_origin*>(ext.payload);
1492
1493
5
  size_t nov = origin->nov;
1494
10
  std::vector<Local<Value>> origin_v(nov);
1495
1496
14
  for (size_t i = 0; i < nov; ++i) {
1497
9
    const nghttp2_origin_entry& entry = origin->ov[i];
1498
18
    origin_v[i] = OneByteString(isolate, entry.origin, entry.origin_len);
1499
  }
1500
5
  Local<Value> holder = Array::New(isolate, origin_v.data(), origin_v.size());
1501
5
  MakeCallback(env()->http2session_on_origin_function(), 1, &holder);
1502
5
}
1503
1504
// Called by OnFrameReceived when a complete PING frame has been received.
1505
1021
void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
1506
1021
  Isolate* isolate = env()->isolate();
1507
1021
  HandleScope scope(isolate);
1508
1021
  Local<Context> context = env()->context();
1509
1021
  Context::Scope context_scope(context);
1510
  Local<Value> arg;
1511
1021
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1512
1021
  if (ack) {
1513
22
    BaseObjectPtr<Http2Ping> ping = PopPing();
1514
1515
11
    if (!ping) {
1516
      // PING Ack is unsolicited. Treat as a connection error. The HTTP/2
1517
      // spec does not require this, but there is no legitimate reason to
1518
      // receive an unsolicited PING ack on a connection. Either the peer
1519
      // is buggy or malicious, and we're not going to tolerate such
1520
      // nonsense.
1521
1
      arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1522
1
      MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1523
1
      return;
1524
    }
1525
1526
10
    ping->Done(true, frame->ping.opaque_data);
1527
10
    return;
1528
  }
1529
1530
1010
  if (!(js_fields_->bitfield & (1 << kSessionHasPingListeners))) return;
1531
  // Notify the session that a ping occurred
1532
2
  arg = Buffer::Copy(
1533
      env(),
1534
2
      reinterpret_cast<const char*>(frame->ping.opaque_data),
1535
2
      8).ToLocalChecked();
1536
2
  MakeCallback(env()->http2session_on_ping_function(), 1, &arg);
1537
}
1538
1539
// Called by OnFrameReceived when a complete SETTINGS frame has been received.
1540
2339
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
1541
2339
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1542
2339
  if (!ack) {
1543
1706
    js_fields_->bitfield &= ~(1 << kSessionRemoteSettingsIsUpToDate);
1544
1706
    if (!(js_fields_->bitfield & (1 << kSessionHasRemoteSettingsListeners)))
1545
2339
      return;
1546
    // This is not a SETTINGS acknowledgement, notify and return
1547
13
    MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
1548
13
    return;
1549
  }
1550
1551
  // If this is an acknowledgement, we should have an Http2Settings
1552
  // object for it.
1553
633
  BaseObjectPtr<Http2Settings> settings = PopSettings();
1554
633
  if (settings) {
1555
633
    settings->Done(true);
1556
633
    return;
1557
  }
1558
  // SETTINGS Ack is unsolicited. Treat as a connection error. The HTTP/2
1559
  // spec does not require this, but there is no legitimate reason to
1560
  // receive an unsolicited SETTINGS ack on a connection. Either the peer
1561
  // is buggy or malicious, and we're not going to tolerate such
1562
  // nonsense.
1563
  // Note that nghttp2 currently prevents this from happening for SETTINGS
1564
  // frames, so this block is purely defensive just in case that behavior
1565
  // changes. Specifically, unlike unsolicited PING acks, unsolicited
1566
  // SETTINGS acks should *never* make it this far.
1567
  Isolate* isolate = env()->isolate();
1568
  HandleScope scope(isolate);
1569
  Local<Context> context = env()->context();
1570
  Context::Scope context_scope(context);
1571
  Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1572
  MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1573
}
1574
1575
// Callback used when data has been written to the stream.
1576
1661
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
1577
1661
  Debug(this, "write finished with status %d", status);
1578
1579
1661
  CHECK(is_write_in_progress());
1580
1661
  set_write_in_progress(false);
1581
1582
  // Inform all pending writes about their completion.
1583
1661
  ClearOutgoing(status);
1584
1585
1661
  if (is_reading_stopped() &&
1586


3315
      !is_write_in_progress() &&
1587
1654
      nghttp2_session_want_read(session_.get())) {
1588
1611
    set_reading_stopped(false);
1589
1611
    stream_->ReadStart();
1590
  }
1591
1592
1661
  if (is_destroyed()) {
1593
43
    HandleScope scope(env()->isolate());
1594
43
    MakeCallback(env()->ondone_string(), 0, nullptr);
1595
43
    return;
1596
  }
1597
1598
  // If there is more incoming data queued up, consume it.
1599
1618
  if (stream_buf_offset_ > 0) {
1600
303
    ConsumeHTTP2Data();
1601
  }
1602
1603

1618
  if (!is_write_scheduled() && !is_destroyed()) {
1604
    // Schedule a new write if nghttp2 wants to send data.
1605
1438
    MaybeScheduleWrite();
1606
  }
1607
}
1608
1609
// If the underlying nghttp2_session struct has data pending in its outbound
1610
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1611
// on the next iteration of the Node.js event loop (using the SetImmediate
1612
// queue), but only if a write has not already been scheduled.
1613
34691
void Http2Session::MaybeScheduleWrite() {
1614
34691
  CHECK(!is_write_scheduled());
1615
34691
  if (UNLIKELY(!session_))
1616
    return;
1617
1618
34691
  if (nghttp2_session_want_write(session_.get())) {
1619
3898
    HandleScope handle_scope(env()->isolate());
1620
1949
    Debug(this, "scheduling write");
1621
1949
    set_write_scheduled();
1622
1949
    BaseObjectPtr<Http2Session> strong_ref{this};
1623
1949
    env()->SetImmediate([this, strong_ref](Environment* env) {
1624

1949
      if (!session_ || !is_write_scheduled()) {
1625
        // This can happen e.g. when a stream was reset before this turn
1626
        // of the event loop, in which case SendPendingData() is called early,
1627
        // or the session was destroyed in the meantime.
1628
376
        return;
1629
      }
1630
1631
      // Sending data may call arbitrary JS code, so keep track of
1632
      // async context.
1633
1573
      if (env->can_call_into_js()) {
1634
3004
        HandleScope handle_scope(env->isolate());
1635
3004
        InternalCallbackScope callback_scope(this);
1636
1502
        SendPendingData();
1637
      }
1638
    });
1639
  }
1640
}
1641
1642
63219
void Http2Session::MaybeStopReading() {
1643
63219
  if (is_reading_stopped()) return;
1644
60349
  int want_read = nghttp2_session_want_read(session_.get());
1645
60349
  Debug(this, "wants read? %d", want_read);
1646

60349
  if (want_read == 0 || is_write_in_progress()) {
1647
1627
    set_reading_stopped();
1648
1627
    stream_->ReadStop();
1649
  }
1650
}
1651
1652
// Unset the sending state, finish up all current writes, and reset
1653
// storage for data and metadata that was associated with these writes.
1654
32866
void Http2Session::ClearOutgoing(int status) {
1655
32866
  CHECK(is_sending());
1656
1657
32866
  set_sending(false);
1658
1659
32866
  if (!outgoing_buffers_.empty()) {
1660
31596
    outgoing_storage_.clear();
1661
31596
    outgoing_length_ = 0;
1662
1663
63192
    std::vector<NgHttp2StreamWrite> current_outgoing_buffers_;
1664
31596
    current_outgoing_buffers_.swap(outgoing_buffers_);
1665
125854
    for (const NgHttp2StreamWrite& wr : current_outgoing_buffers_) {
1666
188516
      BaseObjectPtr<AsyncWrap> wrap = std::move(wr.req_wrap);
1667
94258
      if (wrap) {
1668
        // TODO(addaleax): Pass `status` instead of 0, so that we actually error
1669
        // out with the error from the write to the underlying protocol,
1670
        // if one occurred.
1671
3983
        WriteWrap::FromObject(wrap)->Done(0);
1672
      }
1673
    }
1674
  }
1675
1676
  // Now that we've finished sending queued data, if there are any pending
1677
  // RstStreams we should try sending again and then flush them one by one.
1678
32866
  if (!pending_rst_streams_.empty()) {
1679
18
    std::vector<int32_t> current_pending_rst_streams;
1680
9
    pending_rst_streams_.swap(current_pending_rst_streams);
1681
1682
9
    SendPendingData();
1683
1684
20
    for (int32_t stream_id : current_pending_rst_streams) {
1685
22
      BaseObjectPtr<Http2Stream> stream = FindStream(stream_id);
1686
11
      if (LIKELY(stream))
1687
3
        stream->FlushRstStream();
1688
    }
1689
  }
1690
32866
}
1691
1692
94285
void Http2Session::PushOutgoingBuffer(NgHttp2StreamWrite&& write) {
1693
94285
  outgoing_length_ += write.buf.len;
1694
94285
  outgoing_buffers_.emplace_back(std::move(write));
1695
94285
}
1696
1697
// Queue a given block of data for sending. This always creates a copy,
1698
// so it is used for the cases in which nghttp2 requests sending of a
1699
// small chunk of data.
1700
56715
void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
1701
56715
  size_t offset = outgoing_storage_.size();
1702
56715
  outgoing_storage_.resize(offset + src_length);
1703
56715
  memcpy(&outgoing_storage_[offset], src, src_length);
1704
1705
  // Store with a base of `nullptr` initially, since future resizes
1706
  // of the outgoing_buffers_ vector may invalidate the pointer.
1707
  // The correct base pointers will be set later, before writing to the
1708
  // underlying socket.
1709
56715
  PushOutgoingBuffer(NgHttp2StreamWrite {
1710
    uv_buf_init(nullptr, src_length)
1711
  });
1712
56715
}
1713
1714
// Prompts nghttp2 to begin serializing it's pending data and pushes each
1715
// chunk out to the i/o socket to be sent. This is a particularly hot method
1716
// that will generally be called at least twice be event loop iteration.
1717
// This is a potential performance optimization target later.
1718
// Returns non-zero value if a write is already in progress.
1719
33089
uint8_t Http2Session::SendPendingData() {
1720
33089
  Debug(this, "sending pending data");
1721
  // Do not attempt to send data on the socket if the destroying flag has
1722
  // been set. That means everything is shutting down and the socket
1723
  // will not be usable.
1724
33089
  if (is_destroyed())
1725
40
    return 0;
1726
33049
  set_write_scheduled(false);
1727
1728
  // SendPendingData should not be called recursively.
1729
33049
  if (is_sending())
1730
177
    return 1;
1731
  // This is cleared by ClearOutgoing().
1732
32872
  set_sending();
1733
1734
  ssize_t src_length;
1735
  const uint8_t* src;
1736
1737
32872
  CHECK(outgoing_buffers_.empty());
1738
32872
  CHECK(outgoing_storage_.empty());
1739
1740
  // Part One: Gather data from nghttp2
1741
1742
75768
  while ((src_length = nghttp2_session_mem_send(session_.get(), &src)) > 0) {
1743
42896
    Debug(this, "nghttp2 has %d bytes to send", src_length);
1744
42896
    CopyDataIntoOutgoing(src, src_length);
1745
  }
1746
1747
32872
  CHECK_NE(src_length, NGHTTP2_ERR_NOMEM);
1748
1749
32872
  if (stream_ == nullptr) {
1750
    // It would seem nice to bail out earlier, but `nghttp2_session_mem_send()`
1751
    // does take care of things like closing the individual streams after
1752
    // a socket has been torn down, so we still need to call it.
1753
17
    ClearOutgoing(UV_ECANCELED);
1754
17
    return 0;
1755
  }
1756
1757
  // Part Two: Pass Data to the underlying stream
1758
1759
32855
  size_t count = outgoing_buffers_.size();
1760
32855
  if (count == 0) {
1761
1270
    ClearOutgoing(0);
1762
1270
    return 0;
1763
  }
1764
63170
  MaybeStackBuffer<uv_buf_t, 32> bufs;
1765
31585
  bufs.AllocateSufficientStorage(count);
1766
1767
  // Set the buffer base pointers for copied data that ended up in the
1768
  // sessions's own storage since it might have shifted around during gathering.
1769
  // (Those are marked by having .base == nullptr.)
1770
31585
  size_t offset = 0;
1771
31585
  size_t i = 0;
1772
125847
  for (const NgHttp2StreamWrite& write : outgoing_buffers_) {
1773
94262
    statistics_.data_sent += write.buf.len;
1774
94262
    if (write.buf.base == nullptr) {
1775
56692
      bufs[i++] = uv_buf_init(
1776
113384
          reinterpret_cast<char*>(outgoing_storage_.data() + offset),
1777
56692
          write.buf.len);
1778
56692
      offset += write.buf.len;
1779
    } else {
1780
37570
      bufs[i++] = write.buf;
1781
    }
1782
  }
1783
1784
31585
  chunks_sent_since_last_write_++;
1785
1786
31585
  CHECK(!is_write_in_progress());
1787
31585
  set_write_in_progress();
1788
31585
  StreamWriteResult res = underlying_stream()->Write(*bufs, count);
1789
31585
  if (!res.async) {
1790
29918
    set_write_in_progress(false);
1791
29918
    ClearOutgoing(res.err);
1792
  }
1793
1794
31585
  MaybeStopReading();
1795
1796
31585
  return 0;
1797
}
1798
1799
1800
// This callback is called from nghttp2 when it wants to send DATA frames for a
1801
// given Http2Stream, when we set the `NGHTTP2_DATA_FLAG_NO_COPY` flag earlier
1802
// in the Http2Stream::Provider::Stream::OnRead callback.
1803
// We take the write information directly out of the stream's data queue.
1804
13818
int Http2Session::OnSendData(
1805
      nghttp2_session* session_,
1806
      nghttp2_frame* frame,
1807
      const uint8_t* framehd,
1808
      size_t length,
1809
      nghttp2_data_source* source,
1810
      void* user_data) {
1811
13818
  Http2Session* session = static_cast<Http2Session*>(user_data);
1812
27636
  BaseObjectPtr<Http2Stream> stream = session->FindStream(frame->hd.stream_id);
1813
13818
  if (!stream) return 0;
1814
1815
  // Send the frame header + a byte that indicates padding length.
1816
13818
  session->CopyDataIntoOutgoing(framehd, 9);
1817
13818
  if (frame->data.padlen > 0) {
1818
1
    uint8_t padding_byte = frame->data.padlen - 1;
1819
1
    CHECK_EQ(padding_byte, frame->data.padlen - 1);
1820
1
    session->CopyDataIntoOutgoing(&padding_byte, 1);
1821
  }
1822
1823
  Debug(session, "nghttp2 has %d bytes to send directly", length);
1824
41554
  while (length > 0) {
1825
    // nghttp2 thinks that there is data available (length > 0), which means
1826
    // we told it so, which means that we *should* have data available.
1827
37569
    CHECK(!stream->queue_.empty());
1828
1829
37569
    NgHttp2StreamWrite& write = stream->queue_.front();
1830
37569
    if (write.buf.len <= length) {
1831
      // This write does not suffice by itself, so we can consume it completely.
1832
27736
      length -= write.buf.len;
1833
27736
      session->PushOutgoingBuffer(std::move(write));
1834
27736
      stream->queue_.pop();
1835
27736
      continue;
1836
    }
1837
1838
    // Slice off `length` bytes of the first write in the queue.
1839
9833
    session->PushOutgoingBuffer(NgHttp2StreamWrite {
1840
      uv_buf_init(write.buf.base, length)
1841
    });
1842
9833
    write.buf.base += length;
1843
9833
    write.buf.len -= length;
1844
9833
    break;
1845
  }
1846
1847
13818
  if (frame->data.padlen > 0) {
1848
    // Send padding if that was requested.
1849
1
    session->PushOutgoingBuffer(NgHttp2StreamWrite {
1850
1
      uv_buf_init(const_cast<char*>(zero_bytes_256), frame->data.padlen - 1)
1851
    });
1852
  }
1853
1854
13818
  return 0;
1855
}
1856
1857
// Creates a new Http2Stream and submits a new http2 request.
1858
12104
Http2Stream* Http2Session::SubmitRequest(
1859
    const Http2Priority& priority,
1860
    const Http2Headers& headers,
1861
    int32_t* ret,
1862
    int options) {
1863
12104
  Debug(this, "submitting request");
1864
24208
  Http2Scope h2scope(this);
1865
12104
  Http2Stream* stream = nullptr;
1866
12104
  Http2Stream::Provider::Stream prov(options);
1867
12104
  *ret = nghttp2_submit_request(
1868
      session_.get(),
1869
      &priority,
1870
      headers.data(),
1871
      headers.length(),
1872
12104
      *prov,
1873
      nullptr);
1874
12104
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
1875
12104
  if (LIKELY(*ret > 0))
1876
12103
    stream = Http2Stream::New(this, *ret, NGHTTP2_HCAT_HEADERS, options);
1877
12104
  return stream;
1878
}
1879
1880
31662
uv_buf_t Http2Session::OnStreamAlloc(size_t suggested_size) {
1881
31662
  return env()->allocate_managed_buffer(suggested_size);
1882
}
1883
1884
// Callback used to receive inbound data from the i/o stream
1885
31686
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
1886
31686
  HandleScope handle_scope(env()->isolate());
1887
31686
  Context::Scope context_scope(env()->context());
1888
31686
  Http2Scope h2scope(this);
1889
31686
  CHECK_NOT_NULL(stream_);
1890
31686
  Debug(this, "receiving %d bytes, offset %d", nread, stream_buf_offset_);
1891
31686
  std::unique_ptr<BackingStore> bs = env()->release_managed_buffer(buf_);
1892
1893
  // Only pass data on if nread > 0
1894
31686
  if (nread <= 0) {
1895
50
    if (nread < 0) {
1896
50
      PassReadErrorToPreviousListener(nread);
1897
    }
1898
50
    return;
1899
  }
1900
1901
31636
  CHECK_LE(static_cast<size_t>(nread), bs->ByteLength());
1902
1903
31636
  statistics_.data_received += nread;
1904
1905
31636
  if (LIKELY(stream_buf_offset_ == 0)) {
1906
    // Shrink to the actual amount of used data.
1907
31373
    bs = BackingStore::Reallocate(env()->isolate(), std::move(bs), nread);
1908
  } else {
1909
    // This is a very unlikely case, and should only happen if the ReadStart()
1910
    // call in OnStreamAfterWrite() immediately provides data. If that does
1911
    // happen, we concatenate the data we received with the already-stored
1912
    // pending input data, slicing off the already processed part.
1913
263
    size_t pending_len = stream_buf_.len - stream_buf_offset_;
1914
263
    std::unique_ptr<BackingStore> new_bs;
1915
    {
1916
263
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
1917
526
      new_bs = ArrayBuffer::NewBackingStore(env()->isolate(),
1918
263
                                            pending_len + nread);
1919
    }
1920
263
    memcpy(static_cast<char*>(new_bs->Data()),
1921
263
           stream_buf_.base + stream_buf_offset_,
1922
           pending_len);
1923
263
    memcpy(static_cast<char*>(new_bs->Data()) + pending_len,
1924
263
           bs->Data(),
1925
           nread);
1926
1927
263
    bs = std::move(new_bs);
1928
263
    nread = bs->ByteLength();
1929
263
    stream_buf_offset_ = 0;
1930
263
    stream_buf_ab_.Reset();
1931
1932
    // We have now fully processed the stream_buf_ input chunk (by moving the
1933
    // remaining part into buf, which will be accounted for below).
1934
263
    DecrementCurrentSessionMemory(stream_buf_.len);
1935
  }
1936
1937
31636
  IncrementCurrentSessionMemory(nread);
1938
1939
  // Remember the current buffer, so that OnDataChunkReceived knows the
1940
  // offset of a DATA frame's data into the socket read buffer.
1941
31636
  stream_buf_ = uv_buf_init(static_cast<char*>(bs->Data()),
1942
63272
                            static_cast<unsigned int>(nread));
1943
1944
  // Store this so we can create an ArrayBuffer for read data from it.
1945
  // DATA frames will be emitted as slices of that ArrayBuffer to avoid having
1946
  // to copy memory.
1947
31636
  stream_buf_allocation_ = std::move(bs);
1948
1949
31636
  ConsumeHTTP2Data();
1950
1951
31634
  MaybeStopReading();
1952
}
1953
1954
23652
bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
1955
23744
  for (const NgHttp2StreamWrite& wr : outgoing_buffers_) {
1956


93
    if (wr.req_wrap && WriteWrap::FromObject(wr.req_wrap)->stream() == stream)
1957
1
      return true;
1958
  }
1959
23651
  return false;
1960
}
1961
1962
// Every Http2Session session is tightly bound to a single i/o StreamBase
1963
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1964
// tightly coupled with all data transfer between the two happening at the
1965
// C++ layer via the StreamBase API.
1966
770
void Http2Session::Consume(Local<Object> stream_obj) {
1967
770
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1968
770
  stream->PushStreamListener(this);
1969
770
  Debug(this, "i/o stream consumed");
1970
770
}
1971
1972
// Allow injecting of data from JS
1973
// This is used when the socket has already some data received
1974
// before our listener was attached
1975
// https://github.com/nodejs/node/issues/35475
1976
2
void Http2Session::Receive(const FunctionCallbackInfo<Value>& args) {
1977
  Http2Session* session;
1978
2
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
1979
2
  CHECK(args[0]->IsObject());
1980
1981
2
  ArrayBufferViewContents<char> buffer(args[0]);
1982
2
  const char* data = buffer.data();
1983
2
  size_t len = buffer.length();
1984
2
  Debug(session, "Receiving %zu bytes injected from JS", len);
1985
1986
  // Copy given buffer
1987
4
  while (len > 0) {
1988
2
    uv_buf_t buf = session->OnStreamAlloc(len);
1989
2
    size_t copy = buf.len > len ? len : buf.len;
1990
2
    memcpy(buf.base, data, copy);
1991
2
    buf.len = copy;
1992
2
    session->OnStreamRead(copy, buf);
1993
1994
2
    data += copy;
1995
2
    len -= copy;
1996
  }
1997
}
1998
1999
24318
Http2Stream* Http2Stream::New(Http2Session* session,
2000
                              int32_t id,
2001
                              nghttp2_headers_category category,
2002
                              int options) {
2003
  Local<Object> obj;
2004
48636
  if (!session->env()
2005
24318
           ->http2stream_constructor_template()
2006
24318
           ->NewInstance(session->env()->context())
2007
24318
           .ToLocal(&obj)) {
2008
    return nullptr;
2009
  }
2010
24318
  return new Http2Stream(session, obj, id, category, options);
2011
}
2012
2013
24318
Http2Stream::Http2Stream(Http2Session* session,
2014
                         Local<Object> obj,
2015
                         int32_t id,
2016
                         nghttp2_headers_category category,
2017
24318
                         int options)
2018
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
2019
      StreamBase(session->env()),
2020
      session_(session),
2021
      id_(id),
2022
24318
      current_headers_category_(category) {
2023
24318
  MakeWeak();
2024
24318
  StreamBase::AttachToObject(GetObject());
2025
24318
  statistics_.id = id;
2026
24318
  statistics_.start_time = uv_hrtime();
2027
2028
  // Limit the number of header pairs
2029
24318
  max_header_pairs_ = session->max_header_pairs();
2030
24318
  if (max_header_pairs_ == 0) {
2031
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
2032
  }
2033
24318
  current_headers_.reserve(std::min(max_header_pairs_, 12u));
2034
2035
  // Limit the number of header octets
2036
24318
  max_header_length_ =
2037
24318
      std::min(
2038
24318
        nghttp2_session_get_local_settings(
2039
          session->session(),
2040
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
2041
48636
      MAX_MAX_HEADER_LIST_SIZE);
2042
2043
24318
  if (options & STREAM_OPTION_GET_TRAILERS)
2044
2
    set_has_trailers();
2045
2046
24318
  PushStreamListener(&stream_listener_);
2047
2048
24318
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
2049
1856
    Shutdown();
2050
24318
  session->AddStream(this);
2051
24318
}
2052
2053
97256
Http2Stream::~Http2Stream() {
2054
48628
  Debug(this, "tearing down stream");
2055
97256
}
2056
2057
void Http2Stream::MemoryInfo(MemoryTracker* tracker) const {
2058
  tracker->TrackField("current_headers", current_headers_);
2059
  tracker->TrackField("queue", queue_);
2060
}
2061
2062
17
std::string Http2Stream::diagnostic_name() const {
2063
34
  return "HttpStream " + std::to_string(id()) + " (" +
2064
68
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
2065
51
      session()->diagnostic_name() + "]";
2066
}
2067
2068
// Notify the Http2Stream that a new block of HEADERS is being processed.
2069
11703
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
2070
11703
  Debug(this, "starting headers, category: %d", category);
2071
11703
  CHECK(!this->is_destroyed());
2072
11703
  session_->DecrementCurrentSessionMemory(current_headers_length_);
2073
11703
  current_headers_length_ = 0;
2074
11703
  current_headers_.clear();
2075
11703
  current_headers_category_ = category;
2076
11703
}
2077
2078
2079
nghttp2_stream* Http2Stream::operator*() const { return stream(); }
2080
2081
11
nghttp2_stream* Http2Stream::stream() const {
2082
11
  return nghttp2_session_find_stream(session_->session(), id_);
2083
}
2084
2085
23587
void Http2Stream::Close(int32_t code) {
2086
23587
  CHECK(!this->is_destroyed());
2087
23587
  set_closed();
2088
23587
  code_ = code;
2089
23587
  Debug(this, "closed with code %d", code);
2090
23587
}
2091
2092
24739
ShutdownWrap* Http2Stream::CreateShutdownWrap(Local<Object> object) {
2093
  // DoShutdown() always finishes synchronously, so there's no need to create
2094
  // a structure to store asynchronous context.
2095
24739
  return nullptr;
2096
}
2097
2098
24739
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
2099
24739
  if (is_destroyed())
2100
    return UV_EPIPE;
2101
2102
  {
2103
49478
    Http2Scope h2scope(this);
2104
24739
    set_not_writable();
2105
24739
    CHECK_NE(nghttp2_session_resume_data(
2106
        session_->session(), id_),
2107
        NGHTTP2_ERR_NOMEM);
2108
24739
    Debug(this, "writable side shutdown");
2109
  }
2110
24739
  return 1;
2111
}
2112
2113
// Destroy the Http2Stream and render it unusable. Actual resources for the
2114
// Stream will not be freed until the next tick of the Node.js event loop
2115
// using the SetImmediate queue.
2116
23663
void Http2Stream::Destroy() {
2117
  // Do nothing if this stream instance is already destroyed
2118
23663
  if (is_destroyed())
2119
1
    return;
2120
23662
  if (session_->has_pending_rststream(id_))
2121
8
    FlushRstStream();
2122
23662
  set_destroyed();
2123
2124
23662
  Debug(this, "destroying stream");
2125
2126
  // Wait until the start of the next loop to delete because there
2127
  // may still be some pending operations queued for this stream.
2128
47324
  BaseObjectPtr<Http2Stream> strong_ref = session_->RemoveStream(id_);
2129
23662
  if (strong_ref) {
2130
23662
    env()->SetImmediate([this, strong_ref = std::move(strong_ref)](
2131
118310
        Environment* env) {
2132
      // Free any remaining outgoing data chunks here. This should be done
2133
      // here because it's possible for destroy to have been called while
2134
      // we still have queued outbound writes.
2135
23669
      while (!queue_.empty()) {
2136
7
        NgHttp2StreamWrite& head = queue_.front();
2137
7
        if (head.req_wrap)
2138
7
          WriteWrap::FromObject(head.req_wrap)->Done(UV_ECANCELED);
2139
7
        queue_.pop();
2140
      }
2141
2142
      // We can destroy the stream now if there are no writes for it
2143
      // already on the socket. Otherwise, we'll wait for the garbage collector
2144
      // to take care of cleaning up.
2145

47314
      if (session() == nullptr ||
2146
23652
          !session()->HasWritesOnSocketForStream(this)) {
2147
        // Delete once strong_ref goes out of scope.
2148
23661
        Detach();
2149
      }
2150
23662
    });
2151
  }
2152
2153
23662
  statistics_.end_time = uv_hrtime();
2154
47324
  session_->statistics_.stream_average_duration =
2155
47324
      ((statistics_.end_time - statistics_.start_time) /
2156
23662
          session_->statistics_.stream_count) / 1e6;
2157
23662
  EmitStatistics();
2158
}
2159
2160
2161
// Initiates a response on the Http2Stream using data provided via the
2162
// StreamBase Streams API.
2163
11785
int Http2Stream::SubmitResponse(const Http2Headers& headers, int options) {
2164
11785
  CHECK(!this->is_destroyed());
2165
23570
  Http2Scope h2scope(this);
2166
11785
  Debug(this, "submitting response");
2167
11785
  if (options & STREAM_OPTION_GET_TRAILERS)
2168
162
    set_has_trailers();
2169
2170
11785
  if (!is_writable())
2171
10130
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2172
2173
11785
  Http2Stream::Provider::Stream prov(this, options);
2174
11785
  int ret = nghttp2_submit_response(
2175
      session_->session(),
2176
      id_,
2177
      headers.data(),
2178
      headers.length(),
2179
11785
      *prov);
2180
11785
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2181
11785
  return ret;
2182
}
2183
2184
2185
// Submit informational headers for a stream.
2186
9
int Http2Stream::SubmitInfo(const Http2Headers& headers) {
2187
9
  CHECK(!this->is_destroyed());
2188
9
  Http2Scope h2scope(this);
2189
9
  Debug(this, "sending %d informational headers", headers.length());
2190
9
  int ret = nghttp2_submit_headers(
2191
      session_->session(),
2192
      NGHTTP2_FLAG_NONE,
2193
      id_,
2194
      nullptr,
2195
      headers.data(),
2196
      headers.length(),
2197
9
      nullptr);
2198
9
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2199
9
  return ret;
2200
}
2201
2202
43
void Http2Stream::OnTrailers() {
2203
43
  Debug(this, "let javascript know we are ready for trailers");
2204
43
  CHECK(!this->is_destroyed());
2205
43
  Isolate* isolate = env()->isolate();
2206
86
  HandleScope scope(isolate);
2207
43
  Local<Context> context = env()->context();
2208
43
  Context::Scope context_scope(context);
2209
43
  set_has_trailers(false);
2210
43
  MakeCallback(env()->http2session_on_stream_trailers_function(), 0, nullptr);
2211
43
}
2212
2213
// Submit informational headers for a stream.
2214
37
int Http2Stream::SubmitTrailers(const Http2Headers& headers) {
2215
37
  CHECK(!this->is_destroyed());
2216
37
  Http2Scope h2scope(this);
2217
37
  Debug(this, "sending %d trailers", headers.length());
2218
  int ret;
2219
  // Sending an empty trailers frame poses problems in Safari, Edge & IE.
2220
  // Instead we can just send an empty data frame with NGHTTP2_FLAG_END_STREAM
2221
  // to indicate that the stream is ready to be closed.
2222
37
  if (headers.length() == 0) {
2223
31
    Http2Stream::Provider::Stream prov(this, 0);
2224
31
    ret = nghttp2_submit_data(
2225
        session_->session(),
2226
        NGHTTP2_FLAG_END_STREAM,
2227
        id_,
2228
31
        *prov);
2229
  } else {
2230
6
    ret = nghttp2_submit_trailer(
2231
        session_->session(),
2232
        id_,
2233
        headers.data(),
2234
        headers.length());
2235
  }
2236
37
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2237
37
  return ret;
2238
}
2239
2240
// Submit a PRIORITY frame to the connected peer.
2241
6
int Http2Stream::SubmitPriority(const Http2Priority& priority,
2242
                                bool silent) {
2243
6
  CHECK(!this->is_destroyed());
2244
6
  Http2Scope h2scope(this);
2245
6
  Debug(this, "sending priority spec");
2246
6
  int ret = silent ?
2247
      nghttp2_session_change_stream_priority(
2248
          session_->session(),
2249
          id_,
2250
          &priority) :
2251
6
      nghttp2_submit_priority(
2252
          session_->session(),
2253
          NGHTTP2_FLAG_NONE,
2254
6
          id_, &priority);
2255
6
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2256
6
  return ret;
2257
}
2258
2259
// Closes the Http2Stream by submitting an RST_STREAM frame to the connected
2260
// peer.
2261
127
void Http2Stream::SubmitRstStream(const uint32_t code) {
2262
127
  CHECK(!this->is_destroyed());
2263
127
  code_ = code;
2264
2265
71
  auto is_stream_cancel = [](const uint32_t code) {
2266
71
    return code == NGHTTP2_CANCEL;
2267
  };
2268
2269
  // If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
2270
  // add it to the pending list and don't force purge the data. It is
2271
  // to avoids the double free error due to unwanted behavior of nghttp2.
2272
2273
  // Add stream to the pending list only if it is received with scope
2274
  // below in the stack. The pending list may not get processed
2275
  // if RST_STREAM received is not in scope and added to the list
2276
  // causing endpoint to hang.
2277

127
  if (session_->is_in_scope() && is_stream_cancel(code)) {
2278
1
      session_->AddPendingRstStream(id_);
2279
11
      return;
2280
  }
2281
2282
2283
  // If possible, force a purge of any currently pending data here to make sure
2284
  // it is sent before closing the stream. If it returns non-zero then we need
2285
  // to wait until the current write finishes and try again to avoid nghttp2
2286
  // behaviour where it prioritizes RstStream over everything else.
2287
126
  if (session_->SendPendingData() != 0) {
2288
10
    session_->AddPendingRstStream(id_);
2289
10
    return;
2290
  }
2291
2292
116
  FlushRstStream();
2293
}
2294
2295
127
void Http2Stream::FlushRstStream() {
2296
127
  if (is_destroyed())
2297
1
    return;
2298
252
  Http2Scope h2scope(this);
2299
126
  CHECK_EQ(nghttp2_submit_rst_stream(
2300
      session_->session(),
2301
      NGHTTP2_FLAG_NONE,
2302
      id_,
2303
      code_), 0);
2304
}
2305
2306
2307
// Submit a push promise and create the associated Http2Stream if successful.
2308
9
Http2Stream* Http2Stream::SubmitPushPromise(const Http2Headers& headers,
2309
                                            int32_t* ret,
2310
                                            int options) {
2311
9
  CHECK(!this->is_destroyed());
2312
9
  Http2Scope h2scope(this);
2313
9
  Debug(this, "sending push promise");
2314
9
  *ret = nghttp2_submit_push_promise(
2315
      session_->session(),
2316
      NGHTTP2_FLAG_NONE,
2317
      id_,
2318
      headers.data(),
2319
      headers.length(),
2320
      nullptr);
2321
9
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
2322
9
  Http2Stream* stream = nullptr;
2323
9
  if (*ret > 0) {
2324
9
    stream = Http2Stream::New(
2325
        session_.get(), *ret, NGHTTP2_HCAT_HEADERS, options);
2326
  }
2327
2328
9
  return stream;
2329
}
2330
2331
// Switch the StreamBase into flowing mode to begin pushing chunks of data
2332
// out to JS land.
2333
23487
int Http2Stream::ReadStart() {
2334
23487
  Http2Scope h2scope(this);
2335
23487
  CHECK(!this->is_destroyed());
2336
23487
  set_reading();
2337
2338
23487
  Debug(this, "reading starting");
2339
2340
  // Tell nghttp2 about our consumption of the data that was handed
2341
  // off to JS land.
2342
23487
  nghttp2_session_consume_stream(
2343
      session_->session(),
2344
      id_,
2345
      inbound_consumed_data_while_paused_);
2346
23487
  inbound_consumed_data_while_paused_ = 0;
2347
2348
23487
  return 0;
2349
}
2350
2351
// Switch the StreamBase into paused mode.
2352
5101
int Http2Stream::ReadStop() {
2353
5101
  CHECK(!this->is_destroyed());
2354
5101
  if (!is_reading())
2355
101
    return 0;
2356
5000
  set_paused();
2357
5000
  Debug(this, "reading stopped");
2358
5000
  return 0;
2359
}
2360
2361
// The Http2Stream class is a subclass of StreamBase. The DoWrite method
2362
// receives outbound chunks of data to send as outbound DATA frames. These
2363
// are queued in an internal linked list of uv_buf_t structs that are sent
2364
// when nghttp2 is ready to serialize the data frame.
2365
//
2366
// Queue the given set of uv_but_t handles for writing to an
2367
// nghttp2_stream. The WriteWrap's Done callback will be invoked once the
2368
// chunks of data have been flushed to the underlying nghttp2_session.
2369
// Note that this does *not* mean that the data has been flushed
2370
// to the socket yet.
2371
4077
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2372
                         uv_buf_t* bufs,
2373
                         size_t nbufs,
2374
                         uv_stream_t* send_handle) {
2375
4077
  CHECK_NULL(send_handle);
2376
8154
  Http2Scope h2scope(this);
2377

4077
  if (!is_writable() || is_destroyed()) {
2378
    req_wrap->Done(UV_EOF);
2379
    return 0;
2380
  }
2381
4077
  Debug(this, "queuing %d buffers to send", nbufs);
2382
31909
  for (size_t i = 0; i < nbufs; ++i) {
2383
    // Store the req_wrap on the last write info in the queue, so that it is
2384
    // only marked as finished once all buffers associated with it are finished.
2385
27832
    queue_.emplace(NgHttp2StreamWrite {
2386
55664
      BaseObjectPtr<AsyncWrap>(
2387
4077
          i == nbufs - 1 ? req_wrap->GetAsyncWrap() : nullptr),
2388
27832
      bufs[i]
2389
55664
    });
2390
27832
    IncrementAvailableOutboundLength(bufs[i].len);
2391
  }
2392
4077
  CHECK_NE(nghttp2_session_resume_data(
2393
      session_->session(),
2394
      id_), NGHTTP2_ERR_NOMEM);
2395
4077
  return 0;
2396
}
2397
2398
// Ads a header to the Http2Stream. Note that the header name and value are
2399
// provided using a buffer structure provided by nghttp2 that allows us to
2400
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2401
// is incremented here and are decremented when the header name and values
2402
// are garbage collected later.
2403
72668
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2404
                            nghttp2_rcbuf* value,
2405
                            uint8_t flags) {
2406
72668
  CHECK(!this->is_destroyed());
2407
2408
72668
  if (Http2RcBufferPointer::IsZeroLength(name))
2409
    return true;  // Ignore empty headers.
2410
2411
145336
  Http2Header header(env(), name, value, flags);
2412
72668
  size_t length = header.length() + 32;
2413
  // A header can only be added if we have not exceeded the maximum number
2414
  // of headers and the session has memory available for it.
2415
72668
  if (!session_->has_available_session_memory(length) ||
2416

145335
      current_headers_.size() == max_header_pairs_ ||
2417
72667
      current_headers_length_ + length > max_header_length_) {
2418
3
    return false;
2419
  }
2420
2421
72665
  if (statistics_.first_header == 0)
2422
23651
    statistics_.first_header = uv_hrtime();
2423
2424
72665
  current_headers_.push_back(std::move(header));
2425
2426
72665
  current_headers_length_ += length;
2427
72665
  session_->IncrementCurrentSessionMemory(length);
2428
72665
  return true;
2429
}
2430
2431
// A Provider is the thing that provides outbound DATA frame data.
2432
11816
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2433
11816
  CHECK(!stream->is_destroyed());
2434
11816
  provider_.source.ptr = stream;
2435
11816
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2436
11816
}
2437
2438
12104
Http2Stream::Provider::Provider(int options) {
2439
12104
  provider_.source.ptr = nullptr;
2440
12104
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2441
12104
}
2442
2443
95680
Http2Stream::Provider::~Provider() {
2444
47840
  provider_.source.ptr = nullptr;
2445
}
2446
2447
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2448
// built via the StreamBase API and the Streams js API.
2449
12104
Http2Stream::Provider::Stream::Stream(int options)
2450
12104
    : Http2Stream::Provider(options) {
2451
12104
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2452
12104
}
2453
2454
11816
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2455
11816
    : Http2Stream::Provider(stream, options) {
2456
11816
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2457
11816
}
2458
2459
27856
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2460
                                              int32_t id,
2461
                                              uint8_t* buf,
2462
                                              size_t length,
2463
                                              uint32_t* flags,
2464
                                              nghttp2_data_source* source,
2465
                                              void* user_data) {
2466
27856
  Http2Session* session = static_cast<Http2Session*>(user_data);
2467
  Debug(session, "reading outbound data for stream %d", id);
2468
55712
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
2469
27856
  if (!stream) return 0;
2470
27856
  if (stream->statistics_.first_byte_sent == 0)
2471
12750
    stream->statistics_.first_byte_sent = uv_hrtime();
2472
27856
  CHECK_EQ(id, stream->id());
2473
2474
27856
  size_t amount = 0;          // amount of data being sent in this data frame.
2475
2476
  // Remove all empty chunks from the head of the queue.
2477
  // This is done here so that .write('', cb) is still a meaningful way to
2478
  // find out when the HTTP2 stream wants to consume data, and because the
2479
  // StreamBase API allows empty input chunks.
2480

27867
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2481
    BaseObjectPtr<AsyncWrap> finished =
2482
22
        std::move(stream->queue_.front().req_wrap);
2483
11
    stream->queue_.pop();
2484
11
    if (finished)
2485
9
      WriteWrap::FromObject(finished)->Done(0);
2486
  }
2487
2488
27856
  if (!stream->queue_.empty()) {
2489
    Debug(session, "stream %d has pending outbound data", id);
2490
13818
    amount = std::min(stream->available_outbound_length_, length);
2491
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2492
13818
    if (amount > 0) {
2493
      // Just return the length, let Http2Session::OnSendData take care of
2494
      // actually taking the buffers out of the queue.
2495
13818
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2496
13818
      stream->DecrementAvailableOutboundLength(amount);
2497
    }
2498
  }
2499
2500

27856
  if (amount == 0 && stream->is_writable()) {
2501
2655
    CHECK(stream->queue_.empty());
2502
    Debug(session, "deferring stream %d", id);
2503
2655
    stream->EmitWantsWrite(length);
2504

2655
    if (stream->available_outbound_length_ > 0 || !stream->is_writable()) {
2505
      // EmitWantsWrite() did something interesting synchronously, restart:
2506
      return OnRead(handle, id, buf, length, flags, source, user_data);
2507
    }
2508
2655
    return NGHTTP2_ERR_DEFERRED;
2509
  }
2510
2511

25201
  if (stream->available_outbound_length_ == 0 && !stream->is_writable()) {
2512
    Debug(session, "no more data for stream %d", id);
2513
12743
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2514
12743
    if (stream->has_trailers()) {
2515
43
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2516
43
      stream->OnTrailers();
2517
    }
2518
  }
2519
2520
25201
  stream->statistics_.sent_bytes += amount;
2521
25201
  return amount;
2522
}
2523
2524
27832
void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2525
27832
  available_outbound_length_ += amount;
2526
27832
  session_->IncrementCurrentSessionMemory(amount);
2527
27832
}
2528
2529
13818
void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2530
13818
  available_outbound_length_ -= amount;
2531
13818
  session_->DecrementCurrentSessionMemory(amount);
2532
13818
}
2533
2534
2535
// Implementation of the JavaScript API
2536
2537
// Fetches the string description of a nghttp2 error code and passes that
2538
// back to JS land
2539
62
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2540
62
  Environment* env = Environment::GetCurrent(args);
2541
124
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2542
62
  args.GetReturnValue().Set(
2543
      OneByteString(
2544
          env->isolate(),
2545
62
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val))));
2546
62
}
2547
2548
2549
// Serializes the settings object into a Buffer instance that
2550
// would be suitable, for instance, for creating the Base64
2551
// output for an HTTP2-Settings header field.
2552
17
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2553
17
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2554
17
  args.GetReturnValue().Set(Http2Settings::Pack(state));
2555
17
}
2556
2557
// A TypedArray instance is shared between C++ and JS land to contain the
2558
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2559
// default values.
2560
6
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2561
6
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2562
6
  Http2Settings::RefreshDefaults(state);
2563
6
}
2564
2565
// Sets the next stream ID the Http2Session. If successful, returns true.
2566
1
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2567
1
  Environment* env = Environment::GetCurrent(args);
2568
  Http2Session* session;
2569
1
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2570
1
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2571
1
  if (nghttp2_session_set_next_stream_id(session->session(), id) < 0) {
2572
    Debug(session, "failed to set next stream id to %d", id);
2573
    return args.GetReturnValue().Set(false);
2574
  }
2575
1
  args.GetReturnValue().Set(true);
2576
1
  Debug(session, "set next stream id to %d", id);
2577
}
2578
2579
// Set local window size (local endpoints's window size) to the given
2580
// window_size for the stream denoted by 0.
2581
// This function returns 0 if it succeeds, or one of a negative codes
2582
3
void Http2Session::SetLocalWindowSize(
2583
    const FunctionCallbackInfo<Value>& args) {
2584
3
  Environment* env = Environment::GetCurrent(args);
2585
  Http2Session* session;
2586
3
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2587
2588
3
  int32_t window_size = args[0]->Int32Value(env->context()).ToChecked();
2589
2590
3
  int result = nghttp2_session_set_local_window_size(
2591
      session->session(), NGHTTP2_FLAG_NONE, 0, window_size);
2592
2593
3
  args.GetReturnValue().Set(result);
2594
2595
3
  Debug(session, "set local window size to %d", window_size);
2596
}
2597
2598
// A TypedArray instance is shared between C++ and JS land to contain the
2599
// SETTINGS (either remote or local). RefreshSettings updates the current
2600
// values established for each of the settings so those can be read in JS land.
2601
template <get_setting fn>
2602
1316
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2603
  Http2Session* session;
2604
1316
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2605
1316
  Http2Settings::Update(session, fn);
2606
1316
  Debug(session, "settings refreshed for session");
2607
}
2608
2609
// A TypedArray instance is shared between C++ and JS land to contain state
2610
// information of the current Http2Session. This updates the values in the
2611
// TypedArray so those can be read in JS land.
2612
12
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2613
  Http2Session* session;
2614
12
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2615
12
  Debug(session, "refreshing state");
2616
2617
12
  AliasedFloat64Array& buffer = session->http2_state()->session_state_buffer;
2618
2619
12
  nghttp2_session* s = session->session();
2620
2621
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2622
12
      nghttp2_session_get_effective_local_window_size(s);
2623
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2624
12
      nghttp2_session_get_effective_recv_data_length(s);
2625
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2626
12
      nghttp2_session_get_next_stream_id(s);
2627
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2628
12
      nghttp2_session_get_local_window_size(s);
2629
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2630
12
      nghttp2_session_get_last_proc_stream_id(s);
2631
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2632
12
      nghttp2_session_get_remote_window_size(s);
2633
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2634
12
      static_cast<double>(nghttp2_session_get_outbound_queue_size(s));
2635
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2636
12
      static_cast<double>(nghttp2_session_get_hd_deflate_dynamic_table_size(s));
2637
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2638
12
      static_cast<double>(nghttp2_session_get_hd_inflate_dynamic_table_size(s));
2639
}
2640
2641
2642
// Constructor for new Http2Session instances.
2643
770
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2644
770
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2645
770
  Environment* env = state->env();
2646
770
  CHECK(args.IsConstructCall());
2647
  SessionType type =
2648
      static_cast<SessionType>(
2649
1540
          args[0]->Int32Value(env->context()).ToChecked());
2650
770
  Http2Session* session = new Http2Session(state, args.This(), type);
2651
  Debug(session, "session created");
2652
770
}
2653
2654
2655
// Binds the Http2Session with a StreamBase used for i/o
2656
770
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2657
  Http2Session* session;
2658
770
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2659
770
  CHECK(args[0]->IsObject());
2660
2310
  session->Consume(args[0].As<Object>());
2661
}
2662
2663
// Destroys the Http2Session instance and renders it unusable
2664
673
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2665
  Http2Session* session;
2666
673
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2667
673
  Debug(session, "destroying session");
2668
673
  Environment* env = Environment::GetCurrent(args);
2669
673
  Local<Context> context = env->context();
2670
2671
673
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2672
1346
  session->Close(code, args[1]->IsTrue());
2673
}
2674
2675
// Submits a new request on the Http2Session and returns either an error code
2676
// or the Http2Stream object.
2677
12104
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2678
  Http2Session* session;
2679
12105
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2680
12104
  Environment* env = session->env();
2681
2682
24208
  Local<Array> headers = args[0].As<Array>();
2683
12104
  int32_t options = args[1]->Int32Value(env->context()).ToChecked();
2684
2685
12104
  Debug(session, "request submitted");
2686
2687
12104
  int32_t ret = 0;
2688
  Http2Stream* stream =
2689
12104
      session->Http2Session::SubmitRequest(
2690
12104
          Http2Priority(env, args[2], args[3], args[4]),
2691
24208
          Http2Headers(env, headers),
2692
          &ret,
2693
          static_cast<int>(options));
2694
2695

12104
  if (ret <= 0 || stream == nullptr) {
2696
2
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2697
2
    return args.GetReturnValue().Set(ret);
2698
  }
2699
2700
24206
  Debug(session, "request submitted, new stream id %d", stream->id());
2701
24206
  args.GetReturnValue().Set(stream->object());
2702
}
2703
2704
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2705
// of shutting down. Note that this function does not actually alter the
2706
// state of the Http2Session, it's simply a notification.
2707
610
void Http2Session::Goaway(uint32_t code,
2708
                          int32_t lastStreamID,
2709
                          const uint8_t* data,
2710
                          size_t len) {
2711
610
  if (is_destroyed())
2712
    return;
2713
2714
1220
  Http2Scope h2scope(this);
2715
  // the last proc stream id is the most recently created Http2Stream.
2716
610
  if (lastStreamID <= 0)
2717
610
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_.get());
2718
610
  Debug(this, "submitting goaway");
2719
610
  nghttp2_submit_goaway(session_.get(), NGHTTP2_FLAG_NONE,
2720
                        lastStreamID, code, data, len);
2721
}
2722
2723
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2724
// of shutting down. The opaque data argument is an optional TypedArray that
2725
// can be used to send debugging data to the connected peer.
2726
610
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2727
610
  Environment* env = Environment::GetCurrent(args);
2728
610
  Local<Context> context = env->context();
2729
  Http2Session* session;
2730
610
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2731
2732
1220
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2733
610
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2734
610
  ArrayBufferViewContents<uint8_t> opaque_data;
2735
2736
610
  if (args[2]->IsArrayBufferView()) {
2737
2
    opaque_data.Read(args[2].As<ArrayBufferView>());
2738
  }
2739
2740
610
  session->Goaway(code, lastStreamID, opaque_data.data(), opaque_data.length());
2741
}
2742
2743
// Update accounting of data chunks. This is used primarily to manage timeout
2744
// logic when using the FD Provider.
2745
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2746
10
  Environment* env = Environment::GetCurrent(args);
2747
10
  Isolate* isolate = env->isolate();
2748
10
  HandleScope scope(isolate);
2749
  Http2Session* session;
2750
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2751
2752
10
  uint32_t length = session->chunks_sent_since_last_write_;
2753
2754
10
  session->object()->Set(env->context(),
2755
                         env->chunks_sent_since_last_write_string(),
2756
40
                         Integer::NewFromUnsigned(isolate, length)).Check();
2757
2758
20
  args.GetReturnValue().Set(length);
2759
}
2760
2761
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2762
// this *WILL* alter the state of the stream, causing the OnStreamClose
2763
// callback to the triggered.
2764
124
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2765
124
  Environment* env = Environment::GetCurrent(args);
2766
124
  Local<Context> context = env->context();
2767
  Http2Stream* stream;
2768
124
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2769
124
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2770
124
  Debug(stream, "sending rst_stream with code %d", code);
2771
124
  stream->SubmitRstStream(code);
2772
}
2773
2774
// Initiates a response on the Http2Stream using the StreamBase API to provide
2775
// outbound DATA frames.
2776
11785
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2777
11785
  Environment* env = Environment::GetCurrent(args);
2778
  Http2Stream* stream;
2779
11785
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2780
2781
23570
  Local<Array> headers = args[0].As<Array>();
2782
23570
  int32_t options = args[1]->Int32Value(env->context()).ToChecked();
2783
2784
11785
  args.GetReturnValue().Set(
2785
      stream->SubmitResponse(
2786
23570
          Http2Headers(env, headers),
2787
          static_cast<int>(options)));
2788
11785
  Debug(stream, "response submitted");
2789
}
2790
2791
2792
// Submits informational headers on the Http2Stream
2793
9
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2794
9
  Environment* env = Environment::GetCurrent(args);
2795
  Http2Stream* stream;
2796
9
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2797
2798
18
  Local<Array> headers = args[0].As<Array>();
2799
2800
18
  args.GetReturnValue().Set(stream->SubmitInfo(Http2Headers(env, headers)));
2801
}
2802
2803
// Submits trailing headers on the Http2Stream
2804
37
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2805
37
  Environment* env = Environment::GetCurrent(args);
2806
  Http2Stream* stream;
2807
37
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2808
2809
74
  Local<Array> headers = args[0].As<Array>();
2810
2811
37
  args.GetReturnValue().Set(
2812
74
      stream->SubmitTrailers(Http2Headers(env, headers)));
2813
}
2814
2815
// Grab the numeric id of the Http2Stream
2816
12112
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2817
  Http2Stream* stream;
2818
12112
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2819
24224
  args.GetReturnValue().Set(stream->id());
2820
}
2821
2822
// Destroy the Http2Stream, rendering it no longer usable
2823
23525
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2824
  Http2Stream* stream;
2825
23525
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2826
23525
  Debug(stream, "destroying stream");
2827
23525
  stream->Destroy();
2828
}
2829
2830
// Initiate a Push Promise and create the associated Http2Stream
2831
9
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2832
9
  Environment* env = Environment::GetCurrent(args);
2833
  Http2Stream* parent;
2834
9
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2835
2836
18
  Local<Array> headers = args[0].As<Array>();
2837
9
  int32_t options = args[1]->Int32Value(env->context()).ToChecked();
2838
2839
9
  Debug(parent, "creating push promise");
2840
2841
9
  int32_t ret = 0;
2842
  Http2Stream* stream =
2843
9
      parent->SubmitPushPromise(
2844
18
          Http2Headers(env, headers),
2845
          &ret,
2846
          static_cast<int>(options));
2847
2848

9
  if (ret <= 0 || stream == nullptr) {
2849
    Debug(parent, "failed to create push stream: %d", ret);
2850
    return args.GetReturnValue().Set(ret);
2851
  }
2852
18
  Debug(parent, "push stream %d created", stream->id());
2853
18
  args.GetReturnValue().Set(stream->object());
2854
}
2855
2856
// Send a PRIORITY frame
2857
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2858
6
  Environment* env = Environment::GetCurrent(args);
2859
  Http2Stream* stream;
2860
6
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2861
2862

18
  CHECK_EQ(stream->SubmitPriority(
2863
      Http2Priority(env, args[0], args[1], args[2]),
2864
      args[3]->IsTrue()), 0);
2865
6
  Debug(stream, "priority submitted");
2866
}
2867
2868
// A TypedArray shared by C++ and JS land is used to communicate state
2869
// information about the Http2Stream. This updates the values in that
2870
// TypedArray so that the state can be read by JS.
2871
11
void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
2872
  Http2Stream* stream;
2873
11
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2874
2875
11
  Debug(stream, "refreshing state");
2876
2877
11
  CHECK_NOT_NULL(stream->session());
2878
  AliasedFloat64Array& buffer =
2879
11
      stream->session()->http2_state()->stream_state_buffer;
2880
2881
11
  nghttp2_stream* str = stream->stream();
2882
11
  nghttp2_session* s = stream->session()->session();
2883
2884
11
  if (str == nullptr) {
2885
1
    buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE;
2886
    buffer[IDX_STREAM_STATE_WEIGHT] =
2887
        buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2888
        buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2889
        buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2890
1
        buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0;
2891
  } else {
2892
    buffer[IDX_STREAM_STATE] =
2893
10
        nghttp2_stream_get_state(str);
2894
    buffer[IDX_STREAM_STATE_WEIGHT] =
2895
10
        nghttp2_stream_get_weight(str);
2896
    buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2897
10
        nghttp2_stream_get_sum_dependency_weight(str);
2898
    buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2899
10
        nghttp2_session_get_stream_local_close(s, stream->id());
2900
    buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2901
10
        nghttp2_session_get_stream_remote_close(s, stream->id());
2902
    buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] =
2903
10
        nghttp2_session_get_stream_local_window_size(s, stream->id());
2904
  }
2905
}
2906
2907
5
void Http2Session::AltSvc(int32_t id,
2908
                          uint8_t* origin,
2909
                          size_t origin_len,
2910
                          uint8_t* value,
2911
                          size_t value_len) {
2912
10
  Http2Scope h2scope(this);
2913
5
  CHECK_EQ(nghttp2_submit_altsvc(session_.get(), NGHTTP2_FLAG_NONE, id,
2914
                                 origin, origin_len, value, value_len), 0);
2915
5
}
2916
2917
5
void Http2Session::Origin(const Origins& origins) {
2918
10
  Http2Scope h2scope(this);
2919
5
  CHECK_EQ(nghttp2_submit_origin(
2920
      session_.get(),
2921
      NGHTTP2_FLAG_NONE,
2922
      *origins,
2923
      origins.length()), 0);
2924
5
}
2925
2926
// Submits an AltSvc frame to be sent to the connected peer.
2927
5
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2928
5
  Environment* env = Environment::GetCurrent(args);
2929
  Http2Session* session;
2930
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2931
2932
10
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2933
2934
  // origin and value are both required to be ASCII, handle them as such.
2935
10
  Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2936
10
  Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2937
2938

10
  if (origin_str.IsEmpty() || value_str.IsEmpty())
2939
    return;
2940
2941
5
  size_t origin_len = origin_str->Length();
2942
5
  size_t value_len = value_str->Length();
2943
2944
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2945
  // Verify that origin len != 0 if stream id == 0, or
2946
  // that origin len == 0 if stream id != 0
2947



5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2948
2949
10
  MaybeStackBuffer<uint8_t> origin(origin_len);
2950
10
  MaybeStackBuffer<uint8_t> value(value_len);
2951
5
  origin_str->WriteOneByte(env->isolate(), *origin);
2952
5
  value_str->WriteOneByte(env->isolate(), *value);
2953
2954
5
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2955
}
2956
2957
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2958
5
  Environment* env = Environment::GetCurrent(args);
2959
5
  Local<Context> context = env->context();
2960
  Http2Session* session;
2961
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2962
2963
10
  Local<String> origin_string = args[0].As<String>();
2964
5
  size_t count = args[1]->Int32Value(context).ToChecked();
2965
2966
5
  session->Origin(Origins(env, origin_string, count));
2967
}
2968
2969
// Submits a PING frame to be sent to the connected peer.
2970
13
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2971
  Http2Session* session;
2972
13
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2973
2974
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2975
  // then the current hrtime will be used as the payload.
2976
13
  ArrayBufferViewContents<uint8_t, 8> payload;
2977
13
  if (args[0]->IsArrayBufferView()) {
2978
12
    payload.Read(args[0].As<ArrayBufferView>());
2979
6
    CHECK_EQ(payload.length(), 8);
2980
  }
2981
2982
13
  CHECK(args[1]->IsFunction());
2983
13
  args.GetReturnValue().Set(
2984
52
      session->AddPing(payload.data(), args[1].As<Function>()));
2985
}
2986
2987
// Submits a SETTINGS frame for the Http2Session
2988
780
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2989
  Http2Session* session;
2990
780
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2991
780
  CHECK(args[0]->IsFunction());
2992

3120
  args.GetReturnValue().Set(session->AddSettings(args[0].As<Function>()));
2993
}
2994
2995
685
BaseObjectPtr<Http2Ping> Http2Session::PopPing() {
2996
685
  BaseObjectPtr<Http2Ping> ping;
2997
685
  if (!outstanding_pings_.empty()) {
2998
11
    ping = std::move(outstanding_pings_.front());
2999
11
    outstanding_pings_.pop();
3000
11
    DecrementCurrentSessionMemory(sizeof(*ping));
3001
  }
3002
685
  return ping;
3003
}
3004
3005
13
bool Http2Session::AddPing(const uint8_t* payload, Local<Function> callback) {
3006
  Local<Object> obj;
3007
13
  if (!env()->http2ping_constructor_template()
3008
13
          ->NewInstance(env()->context())
3009
13
              .ToLocal(&obj)) {
3010
    return false;
3011
  }
3012
3013
  BaseObjectPtr<Http2Ping> ping =
3014
26
      MakeDetachedBaseObject<Http2Ping>(this, obj, callback);
3015
13
  if (!ping)
3016
    return false;
3017
3018
13
  if (outstanding_pings_.size() == max_outstanding_pings_) {
3019
2
    ping->Done(false);
3020
2
    return false;
3021
  }
3022
3023
11
  IncrementCurrentSessionMemory(sizeof(*ping));
3024
  // The Ping itself is an Async resource. When the acknowledgement is received,
3025
  // the callback will be invoked and a notification sent out to JS land. The
3026
  // notification will include the duration of the ping, allowing the round
3027
  // trip to be measured.
3028
11
  ping->Send(payload);
3029
3030
11
  outstanding_pings_.emplace(std::move(ping));
3031
11
  return true;
3032
}
3033
3034
633
BaseObjectPtr<Http2Settings> Http2Session::PopSettings() {
3035
633
  BaseObjectPtr<Http2Settings> settings;
3036
633
  if (!outstanding_settings_.empty()) {
3037
633
    settings = std::move(outstanding_settings_.front());
3038
633
    outstanding_settings_.pop();
3039
633
    DecrementCurrentSessionMemory(sizeof(*settings));
3040
  }
3041
633
  return settings;
3042
}
3043
3044
780
bool Http2Session::AddSettings(Local<Function> callback) {
3045
  Local<Object> obj;
3046
780
  if (!env()->http2settings_constructor_template()
3047
780
          ->NewInstance(env()->context())
3048
780
              .ToLocal(&obj)) {
3049
    return false;
3050
  }
3051
3052
  BaseObjectPtr<Http2Settings> settings =
3053
1560
      MakeDetachedBaseObject<Http2Settings>(this, obj, callback, 0);
3054
780
  if (!settings)
3055
    return false;
3056
3057
780
  if (outstanding_settings_.size() == max_outstanding_settings_) {
3058
2
    settings->Done(false);
3059
2
    return false;
3060
  }
3061
3062
778
  IncrementCurrentSessionMemory(sizeof(*settings));
3063
778
  settings->Send();
3064
778
  outstanding_settings_.emplace(std::move(settings));
3065
778
  return true;
3066
}
3067
3068
13
Http2Ping::Http2Ping(
3069
    Http2Session* session,
3070
    Local<Object> obj,
3071
13
    Local<Function> callback)
3072
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2PING),
3073
      session_(session),
3074
13
      startTime_(uv_hrtime()) {
3075
13
  callback_.Reset(env()->isolate(), callback);
3076
13
}
3077
3078
void Http2Ping::MemoryInfo(MemoryTracker* tracker) const {
3079
  tracker->TrackField("callback", callback_);
3080
}
3081
3082
13
Local<Function> Http2Ping::callback() const {
3083
26
  return callback_.Get(env()->isolate());
3084
}
3085
3086
11
void Http2Ping::Send(const uint8_t* payload) {
3087
11
  CHECK(session_);
3088
  uint8_t data[8];
3089
11
  if (payload == nullptr) {
3090
5
    memcpy(&data, &startTime_, arraysize(data));
3091
5
    payload = data;
3092
  }
3093
22
  Http2Scope h2scope(session_.get());
3094
11
  CHECK_EQ(nghttp2_submit_ping(
3095
      session_->session(),
3096
      NGHTTP2_FLAG_NONE,
3097
      payload), 0);
3098
11
}
3099
3100
13
void Http2Ping::Done(bool ack, const uint8_t* payload) {
3101
13
  uint64_t duration_ns = uv_hrtime() - startTime_;
3102
13
  double duration_ms = duration_ns / 1e6;
3103
13
  if (session_) session_->statistics_.ping_rtt = duration_ns;
3104
3105
13
  Isolate* isolate = env()->isolate();
3106
26
  HandleScope handle_scope(isolate);
3107
26
  Context::Scope context_scope(env()->context());
3108
3109
13
  Local<Value> buf = Undefined(isolate);
3110
13
  if (payload != nullptr) {
3111
10
    buf = Buffer::Copy(isolate,
3112
                       reinterpret_cast<const char*>(payload),
3113
10
                       8).ToLocalChecked();
3114
  }
3115
3116
  Local<Value> argv[] = {
3117
    ack ? True(isolate) : False(isolate),
3118
    Number::New(isolate, duration_ms),
3119
    buf
3120
26
  };
3121
13
  MakeCallback(callback(), arraysize(argv), argv);
3122
13
}
3123
3124
1
void Http2Ping::DetachFromSession() {
3125
1
  session_.reset();
3126
1
}
3127
3128
void NgHttp2StreamWrite::MemoryInfo(MemoryTracker* tracker) const {
3129
  if (req_wrap)
3130
    tracker->TrackField("req_wrap", req_wrap);
3131
  tracker->TrackField("buf", buf);
3132
}
3133
3134
292
void SetCallbackFunctions(const FunctionCallbackInfo<Value>& args) {
3135
292
  Environment* env = Environment::GetCurrent(args);
3136
292
  CHECK_EQ(args.Length(), 11);
3137
3138
#define SET_FUNCTION(arg, name)                                               \
3139
  CHECK(args[arg]->IsFunction());                                             \
3140
  env->set_http2session_on_ ## name ## _function(args[arg].As<Function>());
3141
3142

876
  SET_FUNCTION(0, error)
3143

876
  SET_FUNCTION(1, priority)
3144

876
  SET_FUNCTION(2, settings)
3145

876
  SET_FUNCTION(3, ping)
3146

876
  SET_FUNCTION(4, headers)
3147

876
  SET_FUNCTION(5, frame_error)
3148

876
  SET_FUNCTION(6, goaway_data)
3149

876
  SET_FUNCTION(7, altsvc)
3150

876
  SET_FUNCTION(8, origin)
3151

876
  SET_FUNCTION(9, stream_trailers)
3152
876
  SET_FUNCTION(10, stream_close)
3153
3154
#undef SET_FUNCTION
3155
292
}
3156
3157
2
void Http2State::MemoryInfo(MemoryTracker* tracker) const {
3158
2
  tracker->TrackField("root_buffer", root_buffer);
3159
2
}
3160
3161
// Set up the process.binding('http2') binding.
3162
297
void Initialize(Local<Object> target,
3163
                Local<Value> unused,
3164
                Local<Context> context,
3165
                void* priv) {
3166
297
  Environment* env = Environment::GetCurrent(context);
3167
297
  Isolate* isolate = env->isolate();
3168
297
  HandleScope handle_scope(isolate);
3169
3170
297
  Http2State* const state = env->AddBindingData<Http2State>(context, target);
3171
297
  if (state == nullptr) return;
3172
3173
#define SET_STATE_TYPEDARRAY(name, field)             \
3174
  target->Set(context,                                \
3175
              FIXED_ONE_BYTE_STRING(isolate, (name)), \
3176
              (field)).FromJust()
3177
3178
  // Initialize the buffer used to store the session state
3179
1188
  SET_STATE_TYPEDARRAY(
3180
    "sessionState", state->session_state_buffer.GetJSArray());
3181
  // Initialize the buffer used to store the stream state
3182
1188
  SET_STATE_TYPEDARRAY(
3183
    "streamState", state->stream_state_buffer.GetJSArray());
3184
1188
  SET_STATE_TYPEDARRAY(
3185
    "settingsBuffer", state->settings_buffer.GetJSArray());
3186
1188
  SET_STATE_TYPEDARRAY(
3187
    "optionsBuffer", state->options_buffer.GetJSArray());
3188
1188
  SET_STATE_TYPEDARRAY(
3189
    "streamStats", state->stream_stats_buffer.GetJSArray());
3190
1188
  SET_STATE_TYPEDARRAY(
3191
    "sessionStats", state->session_stats_buffer.GetJSArray());
3192
#undef SET_STATE_TYPEDARRAY
3193
3194
891
  NODE_DEFINE_CONSTANT(target, kBitfield);
3195
891
  NODE_DEFINE_CONSTANT(target, kSessionPriorityListenerCount);
3196
891
  NODE_DEFINE_CONSTANT(target, kSessionFrameErrorListenerCount);
3197
891
  NODE_DEFINE_CONSTANT(target, kSessionMaxInvalidFrames);
3198
891
  NODE_DEFINE_CONSTANT(target, kSessionMaxRejectedStreams);
3199
891
  NODE_DEFINE_CONSTANT(target, kSessionUint8FieldCount);
3200
3201
891
  NODE_DEFINE_CONSTANT(target, kSessionHasRemoteSettingsListeners);
3202
891
  NODE_DEFINE_CONSTANT(target, kSessionRemoteSettingsIsUpToDate);
3203
891
  NODE_DEFINE_CONSTANT(target, kSessionHasPingListeners);
3204
594
  NODE_DEFINE_CONSTANT(target, kSessionHasAltsvcListeners);
3205
3206
  // Method to fetch the nghttp2 string description of an nghttp2 error code
3207
297
  SetMethod(context, target, "nghttp2ErrorString", HttpErrorString);
3208
297
  SetMethod(context, target, "refreshDefaultSettings", RefreshDefaultSettings);
3209
297
  SetMethod(context, target, "packSettings", PackSettings);
3210
297
  SetMethod(context, target, "setCallbackFunctions", SetCallbackFunctions);
3211
3212
297
  Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate());
3213
297
  ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping"));
3214
297
  ping->Inherit(AsyncWrap::GetConstructorTemplate(env));
3215
297
  Local<ObjectTemplate> pingt = ping->InstanceTemplate();
3216
297
  pingt->SetInternalFieldCount(Http2Ping::kInternalFieldCount);
3217
297
  env->set_http2ping_constructor_template(pingt);
3218
3219
297
  Local<FunctionTemplate> setting = FunctionTemplate::New(env->isolate());
3220
297
  setting->Inherit(AsyncWrap::GetConstructorTemplate(env));
3221
297
  Local<ObjectTemplate> settingt = setting->InstanceTemplate();
3222
297
  settingt->SetInternalFieldCount(AsyncWrap::kInternalFieldCount);
3223
297
  env->set_http2settings_constructor_template(settingt);
3224
3225
297
  Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
3226
297
  SetProtoMethod(isolate, stream, "id", Http2Stream::GetID);
3227
297
  SetProtoMethod(isolate, stream, "destroy", Http2Stream::Destroy);
3228
297
  SetProtoMethod(isolate, stream, "priority", Http2Stream::Priority);
3229
297
  SetProtoMethod(isolate, stream, "pushPromise", Http2Stream::PushPromise);
3230
297
  SetProtoMethod(isolate, stream, "info", Http2Stream::Info);
3231
297
  SetProtoMethod(isolate, stream, "trailers", Http2Stream::Trailers);
3232
297
  SetProtoMethod(isolate, stream, "respond", Http2Stream::Respond);
3233
297
  SetProtoMethod(isolate, stream, "rstStream", Http2Stream::RstStream);
3234
297
  SetProtoMethod(isolate, stream, "refreshState", Http2Stream::RefreshState);
3235
297
  stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
3236
297
  StreamBase::AddMethods(env, stream);
3237
297
  Local<ObjectTemplate> streamt = stream->InstanceTemplate();
3238
297
  streamt->SetInternalFieldCount(StreamBase::kInternalFieldCount);
3239
297
  env->set_http2stream_constructor_template(streamt);
3240
297
  SetConstructorFunction(context, target, "Http2Stream", stream);
3241
3242
  Local<FunctionTemplate> session =
3243
297
      NewFunctionTemplate(isolate, Http2Session::New);
3244
594
  session->InstanceTemplate()->SetInternalFieldCount(
3245
      Http2Session::kInternalFieldCount);
3246
297
  session->Inherit(AsyncWrap::GetConstructorTemplate(env));
3247
297
  SetProtoMethod(isolate, session, "origin", Http2Session::Origin);
3248
297
  SetProtoMethod(isolate, session, "altsvc", Http2Session::AltSvc);
3249
297
  SetProtoMethod(isolate, session, "ping", Http2Session::Ping);
3250
297
  SetProtoMethod(isolate, session, "consume", Http2Session::Consume);
3251
297
  SetProtoMethod(isolate, session, "receive", Http2Session::Receive);
3252
297
  SetProtoMethod(isolate, session, "destroy", Http2Session::Destroy);
3253
297
  SetProtoMethod(isolate, session, "goaway", Http2Session::Goaway);
3254
297
  SetProtoMethod(isolate, session, "settings", Http2Session::Settings);
3255
297
  SetProtoMethod(isolate, session, "request", Http2Session::Request);
3256
297
  SetProtoMethod(
3257
      isolate, session, "setNextStreamID", Http2Session::SetNextStreamID);
3258
297
  SetProtoMethod(
3259
      isolate, session, "setLocalWindowSize", Http2Session::SetLocalWindowSize);
3260
297
  SetProtoMethod(
3261
      isolate, session, "updateChunksSent", Http2Session::UpdateChunksSent);
3262
297
  SetProtoMethod(isolate, session, "refreshState", Http2Session::RefreshState);
3263
297
  SetProtoMethod(
3264
      isolate,
3265
      session,
3266
      "localSettings",
3267
      Http2Session::RefreshSettings<nghttp2_session_get_local_settings>);
3268
297
  SetProtoMethod(
3269
      isolate,
3270
      session,
3271
      "remoteSettings",
3272
      Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>);
3273
297
  SetConstructorFunction(context, target, "Http2Session", session);
3274
3275
297
  Local<Object> constants = Object::New(isolate);
3276
3277
  // This does allocate one more slot than needed but it's not used.
3278
#define V(name) FIXED_ONE_BYTE_STRING(isolate, #name),
3279
  Local<Value> error_code_names[] = {
3280
    HTTP2_ERROR_CODES(V)
3281
4158
  };
3282
#undef V
3283
3284
  Local<Array> name_for_error_code =
3285
      Array::New(
3286
          isolate,
3287
          error_code_names,
3288
297
          arraysize(error_code_names));
3289
3290
297
  target->Set(context,
3291
              FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"),
3292
891
              name_for_error_code).Check();
3293
3294
#define V(constant) NODE_DEFINE_HIDDEN_CONSTANT(constants, constant);
3295
8019
  HTTP2_HIDDEN_CONSTANTS(V)
3296
#undef V
3297
3298
#define V(constant) NODE_DEFINE_CONSTANT(constants, constant);
3299
30591
  HTTP2_CONSTANTS(V)
3300
#undef V
3301
3302
  // NGHTTP2_DEFAULT_WEIGHT is a macro and not a regular define
3303
  // it won't be set properly on the constants object if included
3304
  // in the HTTP2_CONSTANTS macro.
3305
891
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_DEFAULT_WEIGHT);
3306
3307
#define V(NAME, VALUE)                                          \
3308
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE);
3309
76032
  HTTP_KNOWN_HEADERS(V)
3310
#undef V
3311
3312
#define V(NAME, VALUE)                                          \
3313
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE);
3314
35046
  HTTP_KNOWN_METHODS(V)
3315
#undef V
3316
3317
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
3318
37719
  HTTP_STATUS_CODES(V)
3319
#undef V
3320
3321
891
  target->Set(context, env->constants_string(), constants).Check();
3322
}
3323
}  // namespace http2
3324
}  // namespace node
3325
3326
5600
NODE_MODULE_CONTEXT_AWARE_INTERNAL(http2, node::http2::Initialize)