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

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

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



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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

756
  SET_FUNCTION(0, error)
3141

756
  SET_FUNCTION(1, priority)
3142

756
  SET_FUNCTION(2, settings)
3143

756
  SET_FUNCTION(3, ping)
3144

756
  SET_FUNCTION(4, headers)
3145

756
  SET_FUNCTION(5, frame_error)
3146

756
  SET_FUNCTION(6, goaway_data)
3147

756
  SET_FUNCTION(7, altsvc)
3148

756
  SET_FUNCTION(8, origin)
3149

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