GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.cc Lines: 1544 1637 94.3 %
Date: 2022-10-31 03:21:21 Branches: 629 885 71.1 %

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

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



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

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

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

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

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

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

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

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


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

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


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

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

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

36710
  if (!stream || stream->is_destroyed())
1121
57
    return 0;
1122
1123
  // Don't close synchronously in case there's pending data to be written. This
1124
  // may happen when writing trailing headers.
1125

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

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

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

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

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

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

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


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

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

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

63513
  if (is_reading_stopped() || is_closing()) return;
1667
60363
  int want_read = nghttp2_session_want_read(session_.get());
1668
60363
  Debug(this, "wants read? %d", want_read);
1669

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


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

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

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

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

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

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

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

27234
  if (amount == 0 && stream->is_writable()) {
2526
2538
    CHECK(stream->queue_.empty());
2527
    Debug(session, "deferring stream %d", id);
2528
2538
    stream->EmitWantsWrite(length);
2529

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

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

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

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

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

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



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

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

879
  SET_FUNCTION(0, error)
3168

879
  SET_FUNCTION(1, priority)
3169

879
  SET_FUNCTION(2, settings)
3170

879
  SET_FUNCTION(3, ping)
3171

879
  SET_FUNCTION(4, headers)
3172

879
  SET_FUNCTION(5, frame_error)
3173

879
  SET_FUNCTION(6, goaway_data)
3174

879
  SET_FUNCTION(7, altsvc)
3175

879
  SET_FUNCTION(8, origin)
3176

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