GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.cc Lines: 1528 1620 94.3 %
Date: 2022-03-04 04:14:58 Branches: 613 861 71.2 %

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

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



705
  HTTP2_SETTINGS(V)
227
#undef V
228
229
705
  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
688
Http2Settings::Http2Settings(Http2Session* session,
237
                             Local<Object> obj,
238
                             Local<Function> callback,
239
688
                             uint64_t start_time)
240
    : AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
241
      session_(session),
242
688
      startTime_(start_time) {
243
688
  callback_.Reset(env()->isolate(), callback);
244
688
  count_ = Init(session->http2_state(), entries_);
245
688
}
246
247
550
Local<Function> Http2Settings::callback() const {
248
1100
  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
573
void Http2Settings::Update(Http2Session* session, get_setting fn) {
292
573
  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
573
  HTTP2_SETTINGS(V)
298
#undef V
299
573
}
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
686
void Http2Settings::Send() {
319
1372
  Http2Scope h2scope(session_.get());
320
686
  CHECK_EQ(nghttp2_submit_settings(
321
      session_->session(),
322
      NGHTTP2_FLAG_NONE,
323
      &entries_[0],
324
      count_), 0);
325
686
}
326
327
550
void Http2Settings::Done(bool ack) {
328
550
  uint64_t end = uv_hrtime();
329
550
  double duration = (end - startTime_) / 1e6;
330
331
  Local<Value> argv[] = {
332
550
    ack ? True(env()->isolate()) : False(env()->isolate()),
333
    Number::New(env()->isolate(), duration)
334
1100
  };
335
550
  MakeCallback(callback(), arraysize(argv), argv);
336
550
}
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
11773
Http2Priority::Http2Priority(Environment* env,
342
                             Local<Value> parent,
343
                             Local<Value> weight,
344
11773
                             Local<Value> exclusive) {
345
11773
  Local<Context> context = env->context();
346
23546
  int32_t parent_ = parent->Int32Value(context).ToChecked();
347
23546
  int32_t weight_ = weight->Int32Value(context).ToChecked();
348
11773
  bool exclusive_ = exclusive->IsTrue();
349
  Debug(env, DebugCategory::HTTP2STREAM,
350
        "Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
351
11773
        parent_, weight_, exclusive_ ? "yes" : "no");
352
11773
  nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
353
11773
}
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
10034
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
422
  nghttp2_session_callbacks* callbacks_;
423
10034
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
424
10034
  callbacks.reset(callbacks_);
425
426
10034
  nghttp2_session_callbacks_set_on_begin_headers_callback(
427
    callbacks_, OnBeginHeadersCallback);
428
10034
  nghttp2_session_callbacks_set_on_header_callback2(
429
    callbacks_, OnHeaderCallback);
430
10034
  nghttp2_session_callbacks_set_on_frame_recv_callback(
431
    callbacks_, OnFrameReceive);
432
10034
  nghttp2_session_callbacks_set_on_stream_close_callback(
433
    callbacks_, OnStreamClose);
434
10034
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
435
    callbacks_, OnDataChunkReceived);
436
10034
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
437
    callbacks_, OnFrameNotSent);
438
10034
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
439
    callbacks_, OnInvalidHeader);
440
10034
  nghttp2_session_callbacks_set_error_callback(
441
    callbacks_, OnNghttpError);
442
10034
  nghttp2_session_callbacks_set_send_data_callback(
443
    callbacks_, OnSendData);
444
10034
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
445
    callbacks_, OnInvalidFrame);
446
10034
  nghttp2_session_callbacks_set_on_frame_send_callback(
447
    callbacks_, OnFrameSent);
448
449
10034
  if (kHasGetPaddingCallback) {
450
5017
    nghttp2_session_callbacks_set_select_padding_callback(
451
      callbacks_, OnSelectPadding);
452
  }
453
10034
}
454
455
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
456
  StopTrackingMemory(buf);
457
}
458
459
203063
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
460
203063
  CHECK_GE(current_nghttp2_memory_, previous_size);
461
203063
}
462
463
102495
void Http2Session::IncreaseAllocatedSize(size_t size) {
464
102495
  current_nghttp2_memory_ += size;
465
102495
}
466
467
125597
void Http2Session::DecreaseAllocatedSize(size_t size) {
468
125597
  current_nghttp2_memory_ -= size;
469
125597
}
470
471
678
Http2Session::Http2Session(Http2State* http2_state,
472
                           Local<Object> wrap,
473
678
                           SessionType type)
474
    : AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
475
      js_fields_(http2_state->env()->isolate()),
476
      session_type_(type),
477
678
      http2_state_(http2_state) {
478
678
  MakeWeak();
479
678
  statistics_.session_type = type;
480
678
  statistics_.start_time = uv_hrtime();
481
482
  // Capture the configuration options for this session
483
678
  Http2Options opts(http2_state, type);
484
485
678
  max_session_memory_ = opts.max_session_memory();
486
487
678
  uint32_t maxHeaderPairs = opts.max_header_pairs();
488
1356
  max_header_pairs_ =
489
      type == NGHTTP2_SESSION_SERVER
490
347
          ? GetServerMaxHeaderPairs(maxHeaderPairs)
491
331
          : GetClientMaxHeaderPairs(maxHeaderPairs);
492
493
678
  max_outstanding_pings_ = opts.max_outstanding_pings();
494
678
  max_outstanding_settings_ = opts.max_outstanding_settings();
495
496
678
  padding_strategy_ = opts.padding_strategy();
497
498
678
  bool hasGetPaddingCallback =
499
678
      padding_strategy_ != PADDING_STRATEGY_NONE;
500
501
678
  auto fn = type == NGHTTP2_SESSION_SERVER ?
502
      nghttp2_session_server_new3 :
503
      nghttp2_session_client_new3;
504
505
678
  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

678
  CHECK_EQ(fn(
514
      &session,
515
      callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks.get(),
516
      this,
517
      *opts,
518
      &alloc_info), 0);
519
678
  session_.reset(session);
520
521
678
  outgoing_storage_.reserve(1024);
522
678
  outgoing_buffers_.reserve(32);
523
524
  Local<Uint8Array> uint8_arr =
525
678
      Uint8Array::New(js_fields_.GetArrayBuffer(), 0, kSessionUint8FieldCount);
526
1356
  USE(wrap->Set(env()->context(), env()->fields_string(), uint8_arr));
527
678
}
528
529
4068
Http2Session::~Http2Session() {
530
1356
  CHECK(!is_in_scope());
531
1356
  Debug(this, "freeing nghttp2 session");
532
  // Explicitly reset session_ so the subsequent
533
  // current_nghttp2_memory_ check passes.
534
1356
  session_.reset();
535
1356
  CHECK_EQ(current_nghttp2_memory_, 0);
536
2712
}
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
23641
void Http2Stream::EmitStatistics() {
633
23641
  CHECK_NOT_NULL(session());
634
23641
  if (LIKELY(!HasHttp2Observer(env())))
635
23633
    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
          start,
644
          duration,
645
8
          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
658
void Http2Session::EmitStatistics() {
654
658
  if (LIKELY(!HasHttp2Observer(env())))
655
651
    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
          start,
664
          duration,
665
7
          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
658
void Http2Session::Close(uint32_t code, bool socket_closed) {
675
658
  Debug(this, "closing session");
676
677
658
  if (is_closing())
678
    return;
679
658
  set_closing();
680
681
  // Stop reading on the i/o stream
682
658
  if (stream_ != nullptr) {
683
644
    set_reading_stopped();
684
644
    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
658
  if (!socket_closed) {
692
612
    Debug(this, "terminating session with code %d", code);
693
612
    CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
694
612
    SendPendingData();
695
46
  } else if (stream_ != nullptr) {
696
32
    stream_->RemoveStreamListener(this);
697
  }
698
699
658
  set_destroyed();
700
701
  // If we are writing we will get to make the callback in OnStreamAfterWrite.
702
658
  if (!is_write_in_progress()) {
703
614
    Debug(this, "make done session callback");
704
1228
    HandleScope scope(env()->isolate());
705
614
    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
659
  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
658
  statistics_.end_time = uv_hrtime();
720
658
  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
248000
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
726
248000
  auto s = streams_.find(id);
727
248000
  return s != streams_.end() ? s->second : BaseObjectPtr<Http2Stream>();
728
}
729
730
11977
bool Http2Session::CanAddStream() {
731
  uint32_t maxConcurrentStreams =
732
11977
      nghttp2_session_get_local_settings(
733
          session_.get(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
734
  size_t maxSize =
735
11977
      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

23954
  return streams_.size() < maxSize &&
739
23954
         has_available_session_memory(sizeof(Http2Stream));
740
}
741
742
23751
void Http2Session::AddStream(Http2Stream* stream) {
743
23751
  CHECK_GE(++statistics_.stream_count, 0);
744
23751
  streams_[stream->id()] = BaseObjectPtr<Http2Stream>(stream);
745
23751
  size_t size = streams_.size();
746
23751
  if (size > statistics_.max_concurrent_streams)
747
1434
    statistics_.max_concurrent_streams = size;
748
23751
  IncrementCurrentSessionMemory(sizeof(*stream));
749
23751
}
750
751
752
23641
BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
753
23641
  BaseObjectPtr<Http2Stream> stream;
754
23641
  if (streams_.empty())
755
    return stream;
756
23641
  stream = FindStream(id);
757
23641
  if (stream) {
758
23641
    streams_.erase(id);
759
23641
    DecrementCurrentSessionMemory(sizeof(*stream));
760
  }
761
23641
  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
31495
void Http2Session::ConsumeHTTP2Data() {
797
31495
  CHECK_NOT_NULL(stream_buf_.base);
798
31495
  CHECK_LE(stream_buf_offset_, stream_buf_.len);
799
31495
  size_t read_len = stream_buf_.len - stream_buf_offset_;
800
801
  // multiple side effects.
802
31495
  Debug(this, "receiving %d bytes [wants data? %d]",
803
        read_len,
804
31495
        nghttp2_session_want_read(session_.get()));
805
31495
  set_receive_paused(false);
806
31495
  custom_recv_error_code_ = nullptr;
807
  ssize_t ret =
808
31495
    nghttp2_session_mem_recv(session_.get(),
809
31495
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
810
31495
                                 stream_buf_offset_,
811
31495
                             read_len);
812
31495
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
813

31495
  CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
814
815
31495
  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
30928
  DecrementCurrentSessionMemory(stream_buf_.len);
830
30928
  stream_buf_offset_ = 0;
831
30928
  stream_buf_ab_.Reset();
832
30928
  stream_buf_allocation_.reset();
833
30928
  stream_buf_ = uv_buf_init(nullptr, 0);
834
835
  // Send any data that was queued up while processing the received data.
836

30928
  if (ret >= 0 && !is_destroyed()) {
837
30387
    SendPendingData();
838
  }
839
840
541
done:
841
31495
  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
31495
}
864
865
866
145241
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
145241
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
869
      frame->push_promise.promised_stream_id :
870
145241
      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
23666
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
879
                                         const nghttp2_frame* frame,
880
                                         void* user_data) {
881
23666
  Http2Session* session = static_cast<Http2Session*>(user_data);
882
23666
  int32_t id = GetFrameID(frame);
883
  Debug(session, "beginning headers for stream %d", id);
884
885
47332
  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
23666
  if (LIKELY(!stream)) {
889
23953
    if (UNLIKELY(!session->CanAddStream() ||
890
                 Http2Stream::New(session, id, frame->headers.cat) ==
891

23953
                     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
11976
    session->rejected_stream_count_ = 0;
905
11689
  } else if (!stream->is_destroyed()) {
906
11689
    stream->StartHeaders(frame->headers.cat);
907
  }
908
23665
  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
71719
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
71719
  Http2Session* session = static_cast<Http2Session*>(user_data);
921
71719
  int32_t id = GetFrameID(frame);
922
143438
  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
71719
  if (UNLIKELY(!stream))
927
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
928
929
  // If the stream has already been destroyed, ignore.
930

71719
  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
71716
  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
55761
int Http2Session::OnFrameReceive(nghttp2_session* handle,
943
                                 const nghttp2_frame* frame,
944
                                 void* user_data) {
945
55761
  Http2Session* session = static_cast<Http2Session*>(user_data);
946
55761
  session->statistics_.frame_count++;
947
  Debug(session, "complete frame received: type: %d",
948
55761
        frame->hd.type);
949


55761
  switch (frame->hd.type) {
950
24231
    case NGHTTP2_DATA:
951
24231
      return session->HandleDataFrame(frame);
952
23423
    case NGHTTP2_PUSH_PROMISE:
953
      // Intentional fall-through, handled just like headers frames
954
    case NGHTTP2_HEADERS:
955
23423
      session->HandleHeadersFrame(frame);
956
23423
      break;
957
2163
    case NGHTTP2_SETTINGS:
958
2163
      session->HandleSettingsFrame(frame);
959
2163
      break;
960
16
    case NGHTTP2_PRIORITY:
961
16
      session->HandlePriorityFrame(frame);
962
16
      break;
963
315
    case NGHTTP2_GOAWAY:
964
315
      session->HandleGoawayFrame(frame);
965
315
      break;
966
1020
    case NGHTTP2_PING:
967
1020
      session->HandlePingFrame(frame);
968
1020
      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
31530
  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
2193
void Http2Session::DecrefHeaders(const nghttp2_frame* frame) {
1015
2193
  int32_t id = GetFrameID(frame);
1016
4386
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1017
1018


2193
  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
2193
}
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
2195
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1055
                                 const nghttp2_frame* frame,
1056
                                 int error_code,
1057
                                 void* user_data) {
1058
2195
  Http2Session* session = static_cast<Http2Session*>(user_data);
1059
2195
  Environment* env = session->env();
1060
  Debug(session, "frame type %d was not sent, code: %d",
1061
2195
        frame->hd.type, error_code);
1062
1063
  // Do not report if the frame was not sent due to the session closing
1064
4395
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
1065
5
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1066

2203
      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
2193
    session->DecrefHeaders(frame);
1073
2193
    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
55858
int Http2Session::OnFrameSent(nghttp2_session* handle,
1093
                              const nghttp2_frame* frame,
1094
                              void* user_data) {
1095
55858
  Http2Session* session = static_cast<Http2Session*>(user_data);
1096
55858
  session->statistics_.frame_sent += 1;
1097
55858
  return 0;
1098
}
1099
1100
// Called by nghttp2 when a stream closes.
1101
23613
int Http2Session::OnStreamClose(nghttp2_session* handle,
1102
                                int32_t id,
1103
                                uint32_t code,
1104
                                void* user_data) {
1105
23613
  Http2Session* session = static_cast<Http2Session*>(user_data);
1106
23613
  Environment* env = session->env();
1107
23613
  Isolate* isolate = env->isolate();
1108
47226
  HandleScope scope(isolate);
1109
23613
  Local<Context> context = env->context();
1110
23613
  Context::Scope context_scope(context);
1111
  Debug(session, "stream %d closed with code: %d", id, code);
1112
47226
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1113
  // Intentionally ignore the callback if the stream does not exist or has
1114
  // already been destroyed
1115

23613
  if (!stream || stream->is_destroyed())
1116
53
    return 0;
1117
1118
23560
  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
23560
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1124
  MaybeLocal<Value> answer =
1125
23560
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1126
23560
                          1, &arg);
1127

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

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

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

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

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

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


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

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

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

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


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

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

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

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

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

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

27849
  if (amount == 0 && stream->is_writable()) {
2498
2667
    CHECK(stream->queue_.empty());
2499
    Debug(session, "deferring stream %d", id);
2500
2667
    stream->EmitWantsWrite(length);
2501

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

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

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

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

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

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



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

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

753
  SET_FUNCTION(0, error)
3141

753
  SET_FUNCTION(1, priority)
3142

753
  SET_FUNCTION(2, settings)
3143

753
  SET_FUNCTION(3, ping)
3144

753
  SET_FUNCTION(4, headers)
3145

753
  SET_FUNCTION(5, frame_error)
3146

753
  SET_FUNCTION(6, goaway_data)
3147

753
  SET_FUNCTION(7, altsvc)
3148

753
  SET_FUNCTION(8, origin)
3149

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