GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.cc Lines: 1558 1639 95.1 %
Date: 2022-12-07 04:23:16 Branches: 631 885 71.3 %

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

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



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

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

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

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

32198
  CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
823
824
32198
  if (is_receive_paused()) {
825
560
    CHECK(is_reading_stopped());
826
827
560
    CHECK_GT(ret, 0);
828
560
    CHECK_LE(static_cast<size_t>(ret), read_len);
829
830
    // Mark the remainder of the data as available for later consumption.
831
    // Even if all bytes were received, a paused stream may delay the
832
    // nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
833
560
    stream_buf_offset_ += ret;
834
560
    goto done;
835
  }
836
837
  // We are done processing the current input chunk.
838
31638
  DecrementCurrentSessionMemory(stream_buf_.len);
839
31638
  stream_buf_offset_ = 0;
840
31638
  stream_buf_ab_.Reset();
841
31638
  stream_buf_allocation_.reset();
842
31638
  stream_buf_ = uv_buf_init(nullptr, 0);
843
844
  // Send any data that was queued up while processing the received data.
845

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

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

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


56201
  switch (frame->hd.type) {
959
24237
    case NGHTTP2_DATA:
960
24237
      return session->HandleDataFrame(frame);
961
23659
    case NGHTTP2_PUSH_PROMISE:
962
      // Intentional fall-through, handled just like headers frames
963
    case NGHTTP2_HEADERS:
964
23659
      session->HandleHeadersFrame(frame);
965
23657
      break;
966
2349
    case NGHTTP2_SETTINGS:
967
2349
      session->HandleSettingsFrame(frame);
968
2349
      break;
969
16
    case NGHTTP2_PRIORITY:
970
16
      session->HandlePriorityFrame(frame);
971
16
      break;
972
325
    case NGHTTP2_GOAWAY:
973
325
      session->HandleGoawayFrame(frame);
974
325
      break;
975
1021
    case NGHTTP2_PING:
976
1021
      session->HandlePingFrame(frame);
977
1021
      break;
978
4
    case NGHTTP2_ALTSVC:
979
4
      session->HandleAltSvcFrame(frame);
980
4
      break;
981
5
    case NGHTTP2_ORIGIN:
982
5
      session->HandleOriginFrame(frame);
983
5
      break;
984
4585
    default:
985
4585
      break;
986
  }
987
31962
  return 0;
988
}
989
990
242
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
991
                                 const nghttp2_frame* frame,
992
                                 int lib_error_code,
993
                                 void* user_data) {
994
242
  Http2Session* session = static_cast<Http2Session*>(user_data);
995
242
  const uint32_t max_invalid_frames = session->js_fields_->max_invalid_frames;
996
997
  Debug(session,
998
        "invalid frame received (%u/%u), code: %d",
999
242
        session->invalid_frame_count_,
1000
        max_invalid_frames,
1001
        lib_error_code);
1002
242
  if (session->invalid_frame_count_++ > max_invalid_frames) {
1003
2
    session->custom_recv_error_code_ = "ERR_HTTP2_TOO_MANY_INVALID_FRAMES";
1004
2
    return 1;
1005
  }
1006
1007
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
1008

480
  if (nghttp2_is_fatal(lib_error_code) ||
1009
240
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
1010
1
    Environment* env = session->env();
1011
1
    Isolate* isolate = env->isolate();
1012
2
    HandleScope scope(isolate);
1013
1
    Local<Context> context = env->context();
1014
1
    Context::Scope context_scope(context);
1015
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
1016
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1017
  }
1018
240
  return 0;
1019
}
1020
1021
// Remove the headers reference.
1022
// Implicitly calls nghttp2_rcbuf_decref
1023
2193
void Http2Session::DecrefHeaders(const nghttp2_frame* frame) {
1024
2193
  int32_t id = GetFrameID(frame);
1025
4386
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1026
1027


2193
  if (stream && !stream->is_destroyed() && stream->headers_count() > 0) {
1028
1
    Debug(this, "freeing headers for stream %d", id);
1029
1
    stream->ClearHeaders();
1030
1
    CHECK_EQ(stream->headers_count(), 0);
1031
1
    DecrementCurrentSessionMemory(stream->current_headers_length_);
1032
1
    stream->current_headers_length_ = 0;
1033
  }
1034
2193
}
1035
1036
2
uint32_t TranslateNghttp2ErrorCode(const int libErrorCode) {
1037

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

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

36664
  if (!stream || stream->is_destroyed())
1125
57
    return 0;
1126
1127
  // Don't close synchronously in case there's pending data to be written. This
1128
  // may happen when writing trailing headers.
1129

49644
  if (code == NGHTTP2_NO_ERROR && nghttp2_session_want_write(handle) &&
1130
13037
      !env->is_stopping()) {
1131
13031
    env->SetImmediate([handle, id, code, user_data](Environment* env) {
1132
13031
      OnStreamClose(handle, id, code, user_data);
1133
13031
    });
1134
1135
13031
    return 0;
1136
  }
1137
1138
23576
  stream->Close(code);
1139
1140
  // It is possible for the stream close to occur before the stream is
1141
  // ever passed on to the javascript side. If that happens, the callback
1142
  // will return false.
1143
23576
  if (env->can_call_into_js()) {
1144
23570
    Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1145
23570
    MaybeLocal<Value> answer = stream->MakeCallback(
1146
23570
        env->http2session_on_stream_close_function(), 1, &arg);
1147

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

13844
  if (!stream || stream->is_destroyed())
1198
1
    return 0;
1199
1200
13843
  stream->statistics_.received_bytes += len;
1201
1202
  // Repeatedly ask the stream's owner for memory, and copy the read data
1203
  // into those buffers.
1204
  // The typical case is actually the exception here; Http2StreamListeners
1205
  // know about the HTTP2 session associated with this stream, so they know
1206
  // about the larger from-socket read buffer, so they do not require copying.
1207
  do {
1208
13843
    uv_buf_t buf = stream->EmitAlloc(len);
1209
13843
    ssize_t avail = len;
1210
13843
    if (static_cast<ssize_t>(buf.len) < avail)
1211
      avail = buf.len;
1212
1213
    // `buf.base == nullptr` is the default Http2StreamListener's way
1214
    // of saying that it wants a pointer to the raw original.
1215
    // Since it has access to the original socket buffer from which the data
1216
    // was read in the first place, it can use that to minimize ArrayBuffer
1217
    // allocations.
1218
13843
    if (LIKELY(buf.base == nullptr))
1219
13843
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1220
    else
1221
      memcpy(buf.base, data, avail);
1222
13843
    data += avail;
1223
13843
    len -= avail;
1224
13843
    stream->EmitRead(avail, buf);
1225
1226
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1227
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1228
    // more data is being requested.
1229
13843
    if (stream->is_reading())
1230
12729
      nghttp2_session_consume_stream(handle, id, avail);
1231
    else
1232
1114
      stream->inbound_consumed_data_while_paused_ += avail;
1233
1234
    // If we have a gathered a lot of data for output, try sending it now.
1235

27686
    if (session->outgoing_length_ > 4096 ||
1236
13843
        stream->available_outbound_length_ > 4096) {
1237
5
      session->SendPendingData();
1238
    }
1239
13843
  } while (len != 0);
1240
1241
  // If we are currently waiting for a write operation to finish, we should
1242
  // tell nghttp2 that we want to wait before we process more input data.
1243
13843
  if (session->is_write_in_progress()) {
1244
560
    CHECK(session->is_reading_stopped());
1245
560
    session->set_receive_paused();
1246
    Debug(session, "receive paused");
1247
560
    return NGHTTP2_ERR_PAUSE;
1248
  }
1249
1250
13283
  return 0;
1251
}
1252
1253
// Called by nghttp2 when it needs to determine how much padding to use in
1254
// a DATA or HEADERS frame.
1255
3
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1256
                                      const nghttp2_frame* frame,
1257
                                      size_t maxPayloadLen,
1258
                                      void* user_data) {
1259
3
  Http2Session* session = static_cast<Http2Session*>(user_data);
1260
3
  ssize_t padding = frame->hd.length;
1261
1262

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

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

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


2879
      !is_write_in_progress() &&
1607
1436
      nghttp2_session_want_read(session_.get())) {
1608
1392
    set_reading_stopped(false);
1609
1392
    stream_->ReadStart();
1610
  }
1611
1612
1443
  if (is_destroyed()) {
1613
44
    HandleScope scope(env()->isolate());
1614
44
    MakeCallback(env()->ondone_string(), 0, nullptr);
1615
44
    if (stream_ != nullptr) {
1616
      // Start reading again to detect the other end finishing.
1617
44
      set_reading_stopped(false);
1618
44
      stream_->ReadStart();
1619
    }
1620
44
    return;
1621
  }
1622
1623
  // If there is more incoming data queued up, consume it.
1624
1399
  if (stream_buf_offset_ > 0) {
1625
298
    ConsumeHTTP2Data();
1626
  }
1627
1628

1399
  if (!is_write_scheduled() && !is_destroyed()) {
1629
    // Schedule a new write if nghttp2 wants to send data.
1630
1218
    MaybeScheduleWrite();
1631
  }
1632
}
1633
1634
// If the underlying nghttp2_session struct has data pending in its outbound
1635
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1636
// on the next iteration of the Node.js event loop (using the SetImmediate
1637
// queue), but only if a write has not already been scheduled.
1638
35017
void Http2Session::MaybeScheduleWrite() {
1639
35017
  CHECK(!is_write_scheduled());
1640
35017
  if (UNLIKELY(!session_))
1641
    return;
1642
1643
35017
  if (nghttp2_session_want_write(session_.get())) {
1644
3474
    HandleScope handle_scope(env()->isolate());
1645
1737
    Debug(this, "scheduling write");
1646
1737
    set_write_scheduled();
1647
1737
    BaseObjectPtr<Http2Session> strong_ref{this};
1648
1737
    env()->SetImmediate([this, strong_ref](Environment* env) {
1649

1736
      if (!session_ || !is_write_scheduled()) {
1650
        // This can happen e.g. when a stream was reset before this turn
1651
        // of the event loop, in which case SendPendingData() is called early,
1652
        // or the session was destroyed in the meantime.
1653
379
        return;
1654
      }
1655
1656
      // Sending data may call arbitrary JS code, so keep track of
1657
      // async context.
1658
1357
      if (env->can_call_into_js()) {
1659
2572
        HandleScope handle_scope(env->isolate());
1660
2572
        InternalCallbackScope callback_scope(this);
1661
1286
        SendPendingData();
1662
      }
1663
    });
1664
  }
1665
}
1666
1667
63405
void Http2Session::MaybeStopReading() {
1668
  // If the session is already closing we don't want to stop reading as we want
1669
  // to detect when the other peer is actually closed.
1670

63405
  if (is_reading_stopped() || is_closing()) return;
1671
60273
  int want_read = nghttp2_session_want_read(session_.get());
1672
60273
  Debug(this, "wants read? %d", want_read);
1673

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


65
    if (wr.req_wrap && WriteWrap::FromObject(wr.req_wrap)->stream() == stream)
1984
1
      return true;
1985
  }
1986
23635
  return false;
1987
}
1988
1989
// Every Http2Session session is tightly bound to a single i/o StreamBase
1990
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1991
// tightly coupled with all data transfer between the two happening at the
1992
// C++ layer via the StreamBase API.
1993
774
void Http2Session::Consume(Local<Object> stream_obj) {
1994
774
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1995
774
  stream->PushStreamListener(this);
1996
774
  Debug(this, "i/o stream consumed");
1997
774
}
1998
1999
// Allow injecting of data from JS
2000
// This is used when the socket has already some data received
2001
// before our listener was attached
2002
// https://github.com/nodejs/node/issues/35475
2003
2
void Http2Session::Receive(const FunctionCallbackInfo<Value>& args) {
2004
  Http2Session* session;
2005
2
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2006
2
  CHECK(args[0]->IsObject());
2007
2008
2
  ArrayBufferViewContents<char> buffer(args[0]);
2009
2
  const char* data = buffer.data();
2010
2
  size_t len = buffer.length();
2011
2
  Debug(session, "Receiving %zu bytes injected from JS", len);
2012
2013
  // Copy given buffer
2014
4
  while (len > 0) {
2015
2
    uv_buf_t buf = session->OnStreamAlloc(len);
2016
2
    size_t copy = buf.len > len ? len : buf.len;
2017
2
    memcpy(buf.base, data, copy);
2018
2
    buf.len = copy;
2019
2
    session->OnStreamRead(copy, buf);
2020
2021
2
    data += copy;
2022
2
    len -= copy;
2023
  }
2024
}
2025
2026
24312
Http2Stream* Http2Stream::New(Http2Session* session,
2027
                              int32_t id,
2028
                              nghttp2_headers_category category,
2029
                              int options) {
2030
  Local<Object> obj;
2031
48624
  if (!session->env()
2032
24312
           ->http2stream_constructor_template()
2033
24312
           ->NewInstance(session->env()->context())
2034
24312
           .ToLocal(&obj)) {
2035
    return nullptr;
2036
  }
2037
24312
  return new Http2Stream(session, obj, id, category, options);
2038
}
2039
2040
24312
Http2Stream::Http2Stream(Http2Session* session,
2041
                         Local<Object> obj,
2042
                         int32_t id,
2043
                         nghttp2_headers_category category,
2044
24312
                         int options)
2045
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
2046
      StreamBase(session->env()),
2047
      session_(session),
2048
      id_(id),
2049
24312
      current_headers_category_(category) {
2050
24312
  MakeWeak();
2051
24312
  StreamBase::AttachToObject(GetObject());
2052
24312
  statistics_.id = id;
2053
24312
  statistics_.start_time = uv_hrtime();
2054
2055
  // Limit the number of header pairs
2056
24312
  max_header_pairs_ = session->max_header_pairs();
2057
24312
  if (max_header_pairs_ == 0) {
2058
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
2059
  }
2060
24312
  current_headers_.reserve(std::min(max_header_pairs_, 12u));
2061
2062
  // Limit the number of header octets
2063
24312
  max_header_length_ =
2064
24312
      std::min(
2065
24312
        nghttp2_session_get_local_settings(
2066
          session->session(),
2067
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
2068
48624
      MAX_MAX_HEADER_LIST_SIZE);
2069
2070
24312
  if (options & STREAM_OPTION_GET_TRAILERS)
2071
2
    set_has_trailers();
2072
2073
24312
  PushStreamListener(&stream_listener_);
2074
2075
24312
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
2076
1848
    Shutdown();
2077
24312
  session->AddStream(this);
2078
24312
}
2079
2080
97228
Http2Stream::~Http2Stream() {
2081
48614
  Debug(this, "tearing down stream");
2082
97228
}
2083
2084
void Http2Stream::MemoryInfo(MemoryTracker* tracker) const {
2085
  tracker->TrackField("current_headers", current_headers_);
2086
  tracker->TrackField("queue", queue_);
2087
}
2088
2089
17
std::string Http2Stream::diagnostic_name() const {
2090
17
  const Http2Session* sess = session();
2091
  const std::string sname =
2092

17
      sess ? sess->diagnostic_name() : "session already destroyed";
2093
34
  return "HttpStream " + std::to_string(id()) + " (" +
2094
68
         std::to_string(static_cast<int64_t>(get_async_id())) + ") [" + sname +
2095
17
         "]";
2096
}
2097
2098
// Notify the Http2Stream that a new block of HEADERS is being processed.
2099
11699
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
2100
11699
  Debug(this, "starting headers, category: %d", category);
2101
11699
  CHECK(!this->is_destroyed());
2102
11699
  session_->DecrementCurrentSessionMemory(current_headers_length_);
2103
11699
  current_headers_length_ = 0;
2104
11699
  current_headers_.clear();
2105
11699
  current_headers_category_ = category;
2106
11699
}
2107
2108
2109
nghttp2_stream* Http2Stream::operator*() const { return stream(); }
2110
2111
11
nghttp2_stream* Http2Stream::stream() const {
2112
11
  return nghttp2_session_find_stream(session_->session(), id_);
2113
}
2114
2115
23576
void Http2Stream::Close(int32_t code) {
2116
23576
  CHECK(!this->is_destroyed());
2117
23576
  set_closed();
2118
23576
  code_ = code;
2119
23576
  Debug(this, "closed with code %d", code);
2120
23576
}
2121
2122
24727
ShutdownWrap* Http2Stream::CreateShutdownWrap(Local<Object> object) {
2123
  // DoShutdown() always finishes synchronously, so there's no need to create
2124
  // a structure to store asynchronous context.
2125
24727
  return nullptr;
2126
}
2127
2128
24727
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
2129
24727
  if (is_destroyed())
2130
    return UV_EPIPE;
2131
2132
  {
2133
49454
    Http2Scope h2scope(this);
2134
24727
    set_not_writable();
2135
24727
    CHECK_NE(nghttp2_session_resume_data(
2136
        session_->session(), id_),
2137
        NGHTTP2_ERR_NOMEM);
2138
24727
    Debug(this, "writable side shutdown");
2139
  }
2140
24727
  return 1;
2141
}
2142
2143
// Destroy the Http2Stream and render it unusable. Actual resources for the
2144
// Stream will not be freed until the next tick of the Node.js event loop
2145
// using the SetImmediate queue.
2146
23655
void Http2Stream::Destroy() {
2147
  // Do nothing if this stream instance is already destroyed
2148
23655
  if (is_destroyed())
2149
    return;
2150
23655
  if (session_->has_pending_rststream(id_))
2151
8
    FlushRstStream();
2152
23655
  set_destroyed();
2153
2154
23655
  Debug(this, "destroying stream");
2155
2156
  // Wait until the start of the next loop to delete because there
2157
  // may still be some pending operations queued for this stream.
2158
47310
  BaseObjectPtr<Http2Stream> strong_ref = session_->RemoveStream(id_);
2159
23655
  if (strong_ref) {
2160
23655
    env()->SetImmediate([this, strong_ref = std::move(strong_ref)](
2161
118257
        Environment* env) {
2162
      // Free any remaining outgoing data chunks here. This should be done
2163
      // here because it's possible for destroy to have been called while
2164
      // we still have queued outbound writes.
2165
23662
      while (!queue_.empty()) {
2166
7
        NgHttp2StreamWrite& head = queue_.front();
2167
7
        if (head.req_wrap)
2168
7
          WriteWrap::FromObject(head.req_wrap)->Done(UV_ECANCELED);
2169
7
        queue_.pop();
2170
      }
2171
2172
      // We can destroy the stream now if there are no writes for it
2173
      // already on the socket. Otherwise, we'll wait for the garbage collector
2174
      // to take care of cleaning up.
2175

47291
      if (session() == nullptr ||
2176
23636
          !session()->HasWritesOnSocketForStream(this)) {
2177
        // Delete once strong_ref goes out of scope.
2178
23654
        Detach();
2179
      }
2180
23655
    });
2181
  }
2182
2183
23655
  statistics_.end_time = uv_hrtime();
2184
47310
  session_->statistics_.stream_average_duration =
2185
47310
      ((statistics_.end_time - statistics_.start_time) /
2186
23655
          session_->statistics_.stream_count) / 1e6;
2187
23655
  EmitStatistics();
2188
}
2189
2190
2191
// Initiates a response on the Http2Stream using data provided via the
2192
// StreamBase Streams API.
2193
11802
int Http2Stream::SubmitResponse(const Http2Headers& headers, int options) {
2194
11802
  CHECK(!this->is_destroyed());
2195
23604
  Http2Scope h2scope(this);
2196
11802
  Debug(this, "submitting response");
2197
11802
  if (options & STREAM_OPTION_GET_TRAILERS)
2198
157
    set_has_trailers();
2199
2200
11802
  if (!is_writable())
2201
10125
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2202
2203
11802
  Http2Stream::Provider::Stream prov(this, options);
2204
11802
  int ret = nghttp2_submit_response(
2205
      session_->session(),
2206
      id_,
2207
      headers.data(),
2208
      headers.length(),
2209
11802
      *prov);
2210
11802
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2211
11802
  return ret;
2212
}
2213
2214
2215
// Submit informational headers for a stream.
2216
9
int Http2Stream::SubmitInfo(const Http2Headers& headers) {
2217
9
  CHECK(!this->is_destroyed());
2218
9
  Http2Scope h2scope(this);
2219
9
  Debug(this, "sending %d informational headers", headers.length());
2220
9
  int ret = nghttp2_submit_headers(
2221
      session_->session(),
2222
      NGHTTP2_FLAG_NONE,
2223
      id_,
2224
      nullptr,
2225
      headers.data(),
2226
      headers.length(),
2227
9
      nullptr);
2228
9
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2229
9
  return ret;
2230
}
2231
2232
43
void Http2Stream::OnTrailers() {
2233
43
  Debug(this, "let javascript know we are ready for trailers");
2234
43
  CHECK(!this->is_destroyed());
2235
43
  Isolate* isolate = env()->isolate();
2236
86
  HandleScope scope(isolate);
2237
43
  Local<Context> context = env()->context();
2238
43
  Context::Scope context_scope(context);
2239
43
  set_has_trailers(false);
2240
43
  MakeCallback(env()->http2session_on_stream_trailers_function(), 0, nullptr);
2241
43
}
2242
2243
// Submit informational headers for a stream.
2244
38
int Http2Stream::SubmitTrailers(const Http2Headers& headers) {
2245
38
  CHECK(!this->is_destroyed());
2246
38
  Http2Scope h2scope(this);
2247
38
  Debug(this, "sending %d trailers", headers.length());
2248
  int ret;
2249
  // Sending an empty trailers frame poses problems in Safari, Edge & IE.
2250
  // Instead we can just send an empty data frame with NGHTTP2_FLAG_END_STREAM
2251
  // to indicate that the stream is ready to be closed.
2252
38
  if (headers.length() == 0) {
2253
31
    Http2Stream::Provider::Stream prov(this, 0);
2254
31
    ret = nghttp2_submit_data(
2255
        session_->session(),
2256
        NGHTTP2_FLAG_END_STREAM,
2257
        id_,
2258
31
        *prov);
2259
  } else {
2260
7
    ret = nghttp2_submit_trailer(
2261
        session_->session(),
2262
        id_,
2263
        headers.data(),
2264
        headers.length());
2265
  }
2266
38
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2267
38
  return ret;
2268
}
2269
2270
// Submit a PRIORITY frame to the connected peer.
2271
6
int Http2Stream::SubmitPriority(const Http2Priority& priority,
2272
                                bool silent) {
2273
6
  CHECK(!this->is_destroyed());
2274
6
  Http2Scope h2scope(this);
2275
6
  Debug(this, "sending priority spec");
2276
6
  int ret = silent ?
2277
      nghttp2_session_change_stream_priority(
2278
          session_->session(),
2279
          id_,
2280
          &priority) :
2281
6
      nghttp2_submit_priority(
2282
          session_->session(),
2283
          NGHTTP2_FLAG_NONE,
2284
6
          id_, &priority);
2285
6
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2286
6
  return ret;
2287
}
2288
2289
// Closes the Http2Stream by submitting an RST_STREAM frame to the connected
2290
// peer.
2291
130
void Http2Stream::SubmitRstStream(const uint32_t code) {
2292
130
  CHECK(!this->is_destroyed());
2293
130
  code_ = code;
2294
2295
73
  auto is_stream_cancel = [](const uint32_t code) {
2296
73
    return code == NGHTTP2_CANCEL;
2297
  };
2298
2299
  // If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
2300
  // add it to the pending list and don't force purge the data. It is
2301
  // to avoids the double free error due to unwanted behavior of nghttp2.
2302
2303
  // Add stream to the pending list only if it is received with scope
2304
  // below in the stack. The pending list may not get processed
2305
  // if RST_STREAM received is not in scope and added to the list
2306
  // causing endpoint to hang.
2307

130
  if (session_->is_in_scope() && is_stream_cancel(code)) {
2308
1
      session_->AddPendingRstStream(id_);
2309
11
      return;
2310
  }
2311
2312
2313
  // If possible, force a purge of any currently pending data here to make sure
2314
  // it is sent before closing the stream. If it returns non-zero then we need
2315
  // to wait until the current write finishes and try again to avoid nghttp2
2316
  // behaviour where it prioritizes RstStream over everything else.
2317
129
  if (session_->SendPendingData() != 0) {
2318
10
    session_->AddPendingRstStream(id_);
2319
10
    return;
2320
  }
2321
2322
119
  FlushRstStream();
2323
}
2324
2325
130
void Http2Stream::FlushRstStream() {
2326
130
  if (is_destroyed())
2327
    return;
2328
260
  Http2Scope h2scope(this);
2329
130
  CHECK_EQ(nghttp2_submit_rst_stream(
2330
      session_->session(),
2331
      NGHTTP2_FLAG_NONE,
2332
      id_,
2333
      code_), 0);
2334
}
2335
2336
2337
// Submit a push promise and create the associated Http2Stream if successful.
2338
9
Http2Stream* Http2Stream::SubmitPushPromise(const Http2Headers& headers,
2339
                                            int32_t* ret,
2340
                                            int options) {
2341
9
  CHECK(!this->is_destroyed());
2342
9
  Http2Scope h2scope(this);
2343
9
  Debug(this, "sending push promise");
2344
9
  *ret = nghttp2_submit_push_promise(
2345
      session_->session(),
2346
      NGHTTP2_FLAG_NONE,
2347
      id_,
2348
      headers.data(),
2349
      headers.length(),
2350
      nullptr);
2351
9
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
2352
9
  Http2Stream* stream = nullptr;
2353
9
  if (*ret > 0) {
2354
9
    stream = Http2Stream::New(
2355
        session_.get(), *ret, NGHTTP2_HCAT_HEADERS, options);
2356
  }
2357
2358
9
  return stream;
2359
}
2360
2361
// Switch the StreamBase into flowing mode to begin pushing chunks of data
2362
// out to JS land.
2363
23497
int Http2Stream::ReadStart() {
2364
23497
  Http2Scope h2scope(this);
2365
23497
  CHECK(!this->is_destroyed());
2366
23497
  set_reading();
2367
2368
23497
  Debug(this, "reading starting");
2369
2370
  // Tell nghttp2 about our consumption of the data that was handed
2371
  // off to JS land.
2372
23497
  nghttp2_session_consume_stream(
2373
      session_->session(),
2374
      id_,
2375
      inbound_consumed_data_while_paused_);
2376
23497
  inbound_consumed_data_while_paused_ = 0;
2377
2378
23497
  return 0;
2379
}
2380
2381
// Switch the StreamBase into paused mode.
2382
5112
int Http2Stream::ReadStop() {
2383
5112
  CHECK(!this->is_destroyed());
2384
5112
  if (!is_reading())
2385
115
    return 0;
2386
4997
  set_paused();
2387
4997
  Debug(this, "reading stopped");
2388
4997
  return 0;
2389
}
2390
2391
// The Http2Stream class is a subclass of StreamBase. The DoWrite method
2392
// receives outbound chunks of data to send as outbound DATA frames. These
2393
// are queued in an internal linked list of uv_buf_t structs that are sent
2394
// when nghttp2 is ready to serialize the data frame.
2395
//
2396
// Queue the given set of uv_but_t handles for writing to an
2397
// nghttp2_stream. The WriteWrap's Done callback will be invoked once the
2398
// chunks of data have been flushed to the underlying nghttp2_session.
2399
// Note that this does *not* mean that the data has been flushed
2400
// to the socket yet.
2401
3887
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2402
                         uv_buf_t* bufs,
2403
                         size_t nbufs,
2404
                         uv_stream_t* send_handle) {
2405
3887
  CHECK_NULL(send_handle);
2406
7774
  Http2Scope h2scope(this);
2407

3887
  if (!is_writable() || is_destroyed()) {
2408
    return UV_EOF;
2409
  }
2410
3887
  Debug(this, "queuing %d buffers to send", nbufs);
2411
31521
  for (size_t i = 0; i < nbufs; ++i) {
2412
    // Store the req_wrap on the last write info in the queue, so that it is
2413
    // only marked as finished once all buffers associated with it are finished.
2414
27634
    queue_.emplace(NgHttp2StreamWrite {
2415
55268
      BaseObjectPtr<AsyncWrap>(
2416
3887
          i == nbufs - 1 ? req_wrap->GetAsyncWrap() : nullptr),
2417
27634
      bufs[i]
2418
55268
    });
2419
27634
    IncrementAvailableOutboundLength(bufs[i].len);
2420
  }
2421
3887
  CHECK_NE(nghttp2_session_resume_data(
2422
      session_->session(),
2423
      id_), NGHTTP2_ERR_NOMEM);
2424
3887
  return 0;
2425
}
2426
2427
// Ads a header to the Http2Stream. Note that the header name and value are
2428
// provided using a buffer structure provided by nghttp2 that allows us to
2429
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2430
// is incremented here and are decremented when the header name and values
2431
// are garbage collected later.
2432
72647
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2433
                            nghttp2_rcbuf* value,
2434
                            uint8_t flags) {
2435
72647
  CHECK(!this->is_destroyed());
2436
2437
72647
  if (Http2RcBufferPointer::IsZeroLength(name))
2438
    return true;  // Ignore empty headers.
2439
2440
145294
  Http2Header header(env(), name, value, flags);
2441
72647
  size_t length = header.length() + 32;
2442
  // A header can only be added if we have not exceeded the maximum number
2443
  // of headers and the session has memory available for it.
2444
72647
  if (!session_->has_available_session_memory(length) ||
2445

145293
      current_headers_.size() == max_header_pairs_ ||
2446
72646
      current_headers_length_ + length > max_header_length_) {
2447
3
    return false;
2448
  }
2449
2450
72644
  if (statistics_.first_header == 0)
2451
23643
    statistics_.first_header = uv_hrtime();
2452
2453
72644
  current_headers_.push_back(std::move(header));
2454
2455
72644
  current_headers_length_ += length;
2456
72644
  session_->IncrementCurrentSessionMemory(length);
2457
72644
  return true;
2458
}
2459
2460
// A Provider is the thing that provides outbound DATA frame data.
2461
11833
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2462
11833
  CHECK(!stream->is_destroyed());
2463
11833
  provider_.source.ptr = stream;
2464
11833
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2465
11833
}
2466
2467
12101
Http2Stream::Provider::Provider(int options) {
2468
12101
  provider_.source.ptr = nullptr;
2469
12101
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2470
12101
}
2471
2472
95736
Http2Stream::Provider::~Provider() {
2473
47868
  provider_.source.ptr = nullptr;
2474
}
2475
2476
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2477
// built via the StreamBase API and the Streams js API.
2478
12101
Http2Stream::Provider::Stream::Stream(int options)
2479
12101
    : Http2Stream::Provider(options) {
2480
12101
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2481
12101
}
2482
2483
11833
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2484
11833
    : Http2Stream::Provider(stream, options) {
2485
11833
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2486
11833
}
2487
2488
26785
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2489
                                              int32_t id,
2490
                                              uint8_t* buf,
2491
                                              size_t length,
2492
                                              uint32_t* flags,
2493
                                              nghttp2_data_source* source,
2494
                                              void* user_data) {
2495
26785
  Http2Session* session = static_cast<Http2Session*>(user_data);
2496
  Debug(session, "reading outbound data for stream %d", id);
2497
53570
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
2498
26785
  if (!stream) return 0;
2499
26785
  if (stream->statistics_.first_byte_sent == 0)
2500
12751
    stream->statistics_.first_byte_sent = uv_hrtime();
2501
26785
  CHECK_EQ(id, stream->id());
2502
2503
26785
  size_t amount = 0;          // amount of data being sent in this data frame.
2504
2505
  // Remove all empty chunks from the head of the queue.
2506
  // This is done here so that .write('', cb) is still a meaningful way to
2507
  // find out when the HTTP2 stream wants to consume data, and because the
2508
  // StreamBase API allows empty input chunks.
2509

26796
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2510
    BaseObjectPtr<AsyncWrap> finished =
2511
22
        std::move(stream->queue_.front().req_wrap);
2512
11
    stream->queue_.pop();
2513
11
    if (finished)
2514
9
      WriteWrap::FromObject(finished)->Done(0);
2515
  }
2516
2517
26785
  if (!stream->queue_.empty()) {
2518
    Debug(session, "stream %d has pending outbound data", id);
2519
12950
    amount = std::min(stream->available_outbound_length_, length);
2520
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2521
12950
    if (amount > 0) {
2522
      // Just return the length, let Http2Session::OnSendData take care of
2523
      // actually taking the buffers out of the queue.
2524
12950
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2525
12950
      stream->DecrementAvailableOutboundLength(amount);
2526
    }
2527
  }
2528
2529

26785
  if (amount == 0 && stream->is_writable()) {
2530
2452
    CHECK(stream->queue_.empty());
2531
    Debug(session, "deferring stream %d", id);
2532
2452
    stream->EmitWantsWrite(length);
2533

2452
    if (stream->available_outbound_length_ > 0 || !stream->is_writable()) {
2534
      // EmitWantsWrite() did something interesting synchronously, restart:
2535
      return OnRead(handle, id, buf, length, flags, source, user_data);
2536
    }
2537
2452
    return NGHTTP2_ERR_DEFERRED;
2538
  }
2539
2540

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

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

9
  if (ret <= 0 || stream == nullptr) {
2878
    Debug(parent, "failed to create push stream: %d", ret);
2879
    return args.GetReturnValue().Set(ret);
2880
  }
2881
18
  Debug(parent, "push stream %d created", stream->id());
2882
18
  args.GetReturnValue().Set(stream->object());
2883
}
2884
2885
// Send a PRIORITY frame
2886
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2887
6
  Environment* env = Environment::GetCurrent(args);
2888
  Http2Stream* stream;
2889
6
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2890
2891

18
  CHECK_EQ(stream->SubmitPriority(
2892
      Http2Priority(env, args[0], args[1], args[2]),
2893
      args[3]->IsTrue()), 0);
2894
6
  Debug(stream, "priority submitted");
2895
}
2896
2897
// A TypedArray shared by C++ and JS land is used to communicate state
2898
// information about the Http2Stream. This updates the values in that
2899
// TypedArray so that the state can be read by JS.
2900
11
void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
2901
  Http2Stream* stream;
2902
11
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2903
2904
11
  Debug(stream, "refreshing state");
2905
2906
11
  CHECK_NOT_NULL(stream->session());
2907
  AliasedFloat64Array& buffer =
2908
11
      stream->session()->http2_state()->stream_state_buffer;
2909
2910
11
  nghttp2_stream* str = stream->stream();
2911
11
  nghttp2_session* s = stream->session()->session();
2912
2913
11
  if (str == nullptr) {
2914
1
    buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE;
2915
    buffer[IDX_STREAM_STATE_WEIGHT] =
2916
        buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2917
        buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2918
        buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2919
1
        buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0;
2920
  } else {
2921
    buffer[IDX_STREAM_STATE] =
2922
10
        nghttp2_stream_get_state(str);
2923
    buffer[IDX_STREAM_STATE_WEIGHT] =
2924
10
        nghttp2_stream_get_weight(str);
2925
    buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2926
10
        nghttp2_stream_get_sum_dependency_weight(str);
2927
    buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2928
10
        nghttp2_session_get_stream_local_close(s, stream->id());
2929
    buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2930
10
        nghttp2_session_get_stream_remote_close(s, stream->id());
2931
    buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] =
2932
10
        nghttp2_session_get_stream_local_window_size(s, stream->id());
2933
  }
2934
}
2935
2936
5
void Http2Session::AltSvc(int32_t id,
2937
                          uint8_t* origin,
2938
                          size_t origin_len,
2939
                          uint8_t* value,
2940
                          size_t value_len) {
2941
10
  Http2Scope h2scope(this);
2942
5
  CHECK_EQ(nghttp2_submit_altsvc(session_.get(), NGHTTP2_FLAG_NONE, id,
2943
                                 origin, origin_len, value, value_len), 0);
2944
5
}
2945
2946
5
void Http2Session::Origin(const Origins& origins) {
2947
10
  Http2Scope h2scope(this);
2948
5
  CHECK_EQ(nghttp2_submit_origin(
2949
      session_.get(),
2950
      NGHTTP2_FLAG_NONE,
2951
      *origins,
2952
      origins.length()), 0);
2953
5
}
2954
2955
// Submits an AltSvc frame to be sent to the connected peer.
2956
5
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2957
5
  Environment* env = Environment::GetCurrent(args);
2958
  Http2Session* session;
2959
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2960
2961
10
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2962
2963
  // origin and value are both required to be ASCII, handle them as such.
2964
10
  Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2965
10
  Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2966
2967

10
  if (origin_str.IsEmpty() || value_str.IsEmpty())
2968
    return;
2969
2970
5
  size_t origin_len = origin_str->Length();
2971
5
  size_t value_len = value_str->Length();
2972
2973
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2974
  // Verify that origin len != 0 if stream id == 0, or
2975
  // that origin len == 0 if stream id != 0
2976



5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2977
2978
10
  MaybeStackBuffer<uint8_t> origin(origin_len);
2979
10
  MaybeStackBuffer<uint8_t> value(value_len);
2980
5
  origin_str->WriteOneByte(env->isolate(), *origin);
2981
5
  value_str->WriteOneByte(env->isolate(), *value);
2982
2983
5
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2984
}
2985
2986
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2987
5
  Environment* env = Environment::GetCurrent(args);
2988
5
  Local<Context> context = env->context();
2989
  Http2Session* session;
2990
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2991
2992
10
  Local<String> origin_string = args[0].As<String>();
2993
5
  size_t count = args[1]->Int32Value(context).ToChecked();
2994
2995
5
  session->Origin(Origins(env, origin_string, count));
2996
}
2997
2998
// Submits a PING frame to be sent to the connected peer.
2999
13
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
3000
  Http2Session* session;
3001
13
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
3002
3003
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
3004
  // then the current hrtime will be used as the payload.
3005
13
  ArrayBufferViewContents<uint8_t, 8> payload;
3006
13
  if (args[0]->IsArrayBufferView()) {
3007
12
    payload.Read(args[0].As<ArrayBufferView>());
3008
6
    CHECK_EQ(payload.length(), 8);
3009
  }
3010
3011
13
  CHECK(args[1]->IsFunction());
3012
13
  args.GetReturnValue().Set(
3013
52
      session->AddPing(payload.data(), args[1].As<Function>()));
3014
}
3015
3016
// Submits a SETTINGS frame for the Http2Session
3017
784
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
3018
  Http2Session* session;
3019
784
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
3020
784
  CHECK(args[0]->IsFunction());
3021

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

879
  SET_FUNCTION(0, error)
3172

879
  SET_FUNCTION(1, priority)
3173

879
  SET_FUNCTION(2, settings)
3174

879
  SET_FUNCTION(3, ping)
3175

879
  SET_FUNCTION(4, headers)
3176

879
  SET_FUNCTION(5, frame_error)
3177

879
  SET_FUNCTION(6, goaway_data)
3178

879
  SET_FUNCTION(7, altsvc)
3179

879
  SET_FUNCTION(8, origin)
3180

879
  SET_FUNCTION(9, stream_trailers)
3181
879
  SET_FUNCTION(10, stream_close)
3182
3183
#undef SET_FUNCTION
3184
293
}
3185
3186
#ifdef NODE_DEBUG_NGHTTP2
3187
void NgHttp2Debug(const char* format, va_list args) {
3188
  vfprintf(stderr, format, args);
3189
}
3190
#endif
3191
3192
2
void Http2State::MemoryInfo(MemoryTracker* tracker) const {
3193
2
  tracker->TrackField("root_buffer", root_buffer);
3194
2
}
3195
3196
// Set up the process.binding('http2') binding.
3197
298
void Initialize(Local<Object> target,
3198
                Local<Value> unused,
3199
                Local<Context> context,
3200
                void* priv) {
3201
298
  Environment* env = Environment::GetCurrent(context);
3202
298
  Isolate* isolate = env->isolate();
3203
298
  HandleScope handle_scope(isolate);
3204
3205
298
  Http2State* const state = env->AddBindingData<Http2State>(context, target);
3206
298
  if (state == nullptr) return;
3207
3208
#define SET_STATE_TYPEDARRAY(name, field)             \
3209
  target->Set(context,                                \
3210
              FIXED_ONE_BYTE_STRING(isolate, (name)), \
3211
              (field)).FromJust()
3212
3213
  // Initialize the buffer used to store the session state
3214
1192
  SET_STATE_TYPEDARRAY(
3215
    "sessionState", state->session_state_buffer.GetJSArray());
3216
  // Initialize the buffer used to store the stream state
3217
1192
  SET_STATE_TYPEDARRAY(
3218
    "streamState", state->stream_state_buffer.GetJSArray());
3219
1192
  SET_STATE_TYPEDARRAY(
3220
    "settingsBuffer", state->settings_buffer.GetJSArray());
3221
1192
  SET_STATE_TYPEDARRAY(
3222
    "optionsBuffer", state->options_buffer.GetJSArray());
3223
1192
  SET_STATE_TYPEDARRAY(
3224
    "streamStats", state->stream_stats_buffer.GetJSArray());
3225
1192
  SET_STATE_TYPEDARRAY(
3226
    "sessionStats", state->session_stats_buffer.GetJSArray());
3227
#undef SET_STATE_TYPEDARRAY
3228
3229
894
  NODE_DEFINE_CONSTANT(target, kBitfield);
3230
894
  NODE_DEFINE_CONSTANT(target, kSessionPriorityListenerCount);
3231
894
  NODE_DEFINE_CONSTANT(target, kSessionFrameErrorListenerCount);
3232
894
  NODE_DEFINE_CONSTANT(target, kSessionMaxInvalidFrames);
3233
894
  NODE_DEFINE_CONSTANT(target, kSessionMaxRejectedStreams);
3234
894
  NODE_DEFINE_CONSTANT(target, kSessionUint8FieldCount);
3235
3236
894
  NODE_DEFINE_CONSTANT(target, kSessionHasRemoteSettingsListeners);
3237
894
  NODE_DEFINE_CONSTANT(target, kSessionRemoteSettingsIsUpToDate);
3238
894
  NODE_DEFINE_CONSTANT(target, kSessionHasPingListeners);
3239
596
  NODE_DEFINE_CONSTANT(target, kSessionHasAltsvcListeners);
3240
3241
  // Method to fetch the nghttp2 string description of an nghttp2 error code
3242
298
  SetMethod(context, target, "nghttp2ErrorString", HttpErrorString);
3243
298
  SetMethod(context, target, "refreshDefaultSettings", RefreshDefaultSettings);
3244
298
  SetMethod(context, target, "packSettings", PackSettings);
3245
298
  SetMethod(context, target, "setCallbackFunctions", SetCallbackFunctions);
3246
3247
298
  Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate());
3248
298
  ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping"));
3249
298
  ping->Inherit(AsyncWrap::GetConstructorTemplate(env));
3250
298
  Local<ObjectTemplate> pingt = ping->InstanceTemplate();
3251
298
  pingt->SetInternalFieldCount(Http2Ping::kInternalFieldCount);
3252
298
  env->set_http2ping_constructor_template(pingt);
3253
3254
298
  Local<FunctionTemplate> setting = FunctionTemplate::New(env->isolate());
3255
298
  setting->Inherit(AsyncWrap::GetConstructorTemplate(env));
3256
298
  Local<ObjectTemplate> settingt = setting->InstanceTemplate();
3257
298
  settingt->SetInternalFieldCount(AsyncWrap::kInternalFieldCount);
3258
298
  env->set_http2settings_constructor_template(settingt);
3259
3260
298
  Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
3261
298
  SetProtoMethod(isolate, stream, "id", Http2Stream::GetID);
3262
298
  SetProtoMethod(isolate, stream, "destroy", Http2Stream::Destroy);
3263
298
  SetProtoMethod(isolate, stream, "priority", Http2Stream::Priority);
3264
298
  SetProtoMethod(isolate, stream, "pushPromise", Http2Stream::PushPromise);
3265
298
  SetProtoMethod(isolate, stream, "info", Http2Stream::Info);
3266
298
  SetProtoMethod(isolate, stream, "trailers", Http2Stream::Trailers);
3267
298
  SetProtoMethod(isolate, stream, "respond", Http2Stream::Respond);
3268
298
  SetProtoMethod(isolate, stream, "rstStream", Http2Stream::RstStream);
3269
298
  SetProtoMethod(isolate, stream, "refreshState", Http2Stream::RefreshState);
3270
298
  stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
3271
298
  StreamBase::AddMethods(env, stream);
3272
298
  Local<ObjectTemplate> streamt = stream->InstanceTemplate();
3273
298
  streamt->SetInternalFieldCount(StreamBase::kInternalFieldCount);
3274
298
  env->set_http2stream_constructor_template(streamt);
3275
298
  SetConstructorFunction(context, target, "Http2Stream", stream);
3276
3277
  Local<FunctionTemplate> session =
3278
298
      NewFunctionTemplate(isolate, Http2Session::New);
3279
596
  session->InstanceTemplate()->SetInternalFieldCount(
3280
      Http2Session::kInternalFieldCount);
3281
298
  session->Inherit(AsyncWrap::GetConstructorTemplate(env));
3282
298
  SetProtoMethod(isolate, session, "origin", Http2Session::Origin);
3283
298
  SetProtoMethod(isolate, session, "altsvc", Http2Session::AltSvc);
3284
298
  SetProtoMethod(isolate, session, "ping", Http2Session::Ping);
3285
298
  SetProtoMethod(isolate, session, "consume", Http2Session::Consume);
3286
298
  SetProtoMethod(isolate, session, "receive", Http2Session::Receive);
3287
298
  SetProtoMethod(isolate, session, "destroy", Http2Session::Destroy);
3288
298
  SetProtoMethod(isolate, session, "goaway", Http2Session::Goaway);
3289
298
  SetProtoMethod(isolate, session, "settings", Http2Session::Settings);
3290
298
  SetProtoMethod(isolate, session, "request", Http2Session::Request);
3291
298
  SetProtoMethod(
3292
      isolate, session, "setNextStreamID", Http2Session::SetNextStreamID);
3293
298
  SetProtoMethod(
3294
      isolate, session, "setLocalWindowSize", Http2Session::SetLocalWindowSize);
3295
298
  SetProtoMethod(
3296
      isolate, session, "updateChunksSent", Http2Session::UpdateChunksSent);
3297
298
  SetProtoMethod(isolate, session, "refreshState", Http2Session::RefreshState);
3298
298
  SetProtoMethod(
3299
      isolate,
3300
      session,
3301
      "localSettings",
3302
      Http2Session::RefreshSettings<nghttp2_session_get_local_settings>);
3303
298
  SetProtoMethod(
3304
      isolate,
3305
      session,
3306
      "remoteSettings",
3307
      Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>);
3308
298
  SetConstructorFunction(context, target, "Http2Session", session);
3309
3310
298
  Local<Object> constants = Object::New(isolate);
3311
3312
  // This does allocate one more slot than needed but it's not used.
3313
#define V(name) FIXED_ONE_BYTE_STRING(isolate, #name),
3314
  Local<Value> error_code_names[] = {
3315
    HTTP2_ERROR_CODES(V)
3316
4172
  };
3317
#undef V
3318
3319
  Local<Array> name_for_error_code =
3320
      Array::New(
3321
          isolate,
3322
          error_code_names,
3323
298
          arraysize(error_code_names));
3324
3325
298
  target->Set(context,
3326
              FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"),
3327
894
              name_for_error_code).Check();
3328
3329
#define V(constant) NODE_DEFINE_HIDDEN_CONSTANT(constants, constant);
3330
8046
  HTTP2_HIDDEN_CONSTANTS(V)
3331
#undef V
3332
3333
#define V(constant) NODE_DEFINE_CONSTANT(constants, constant);
3334
30694
  HTTP2_CONSTANTS(V)
3335
#undef V
3336
3337
  // NGHTTP2_DEFAULT_WEIGHT is a macro and not a regular define
3338
  // it won't be set properly on the constants object if included
3339
  // in the HTTP2_CONSTANTS macro.
3340
894
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_DEFAULT_WEIGHT);
3341
3342
#define V(NAME, VALUE)                                          \
3343
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE);
3344
77182
  HTTP_KNOWN_HEADERS(V)
3345
#undef V
3346
3347
#define V(NAME, VALUE)                                          \
3348
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE);
3349
35164
  HTTP_KNOWN_METHODS(V)
3350
#undef V
3351
3352
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
3353
37846
  HTTP_STATUS_CODES(V)
3354
#undef V
3355
3356
894
  target->Set(context, env->constants_string(), constants).Check();
3357
3358
#ifdef NODE_DEBUG_NGHTTP2
3359
  nghttp2_set_debug_vprintf_callback(NgHttp2Debug);
3360
#endif
3361
}
3362
}  // namespace http2
3363
}  // namespace node
3364
3365
5710
NODE_BINDING_CONTEXT_AWARE_INTERNAL(http2, node::http2::Initialize)