GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.cc Lines: 1523 1603 95.0 %
Date: 2022-02-23 04:14:54 Branches: 612 854 71.7 %

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

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



703
  HTTP2_SETTINGS(V)
227
#undef V
228
229
703
  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
686
Http2Settings::Http2Settings(Http2Session* session,
237
                             Local<Object> obj,
238
                             Local<Function> callback,
239
686
                             uint64_t start_time)
240
    : AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
241
      session_(session),
242
686
      startTime_(start_time) {
243
686
  callback_.Reset(env()->isolate(), callback);
244
686
  count_ = Init(session->http2_state(), entries_);
245
686
}
246
247
548
Local<Function> Http2Settings::callback() const {
248
1096
  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
571
void Http2Settings::Update(Http2Session* session, get_setting fn) {
292
571
  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
571
  HTTP2_SETTINGS(V)
298
#undef V
299
571
}
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
684
void Http2Settings::Send() {
319
1368
  Http2Scope h2scope(session_.get());
320
684
  CHECK_EQ(nghttp2_submit_settings(
321
      session_->session(),
322
      NGHTTP2_FLAG_NONE,
323
      &entries_[0],
324
      count_), 0);
325
684
}
326
327
548
void Http2Settings::Done(bool ack) {
328
548
  uint64_t end = uv_hrtime();
329
548
  double duration = (end - startTime_) / 1e6;
330
331
  Local<Value> argv[] = {
332
548
    ack ? True(env()->isolate()) : False(env()->isolate()),
333
    Number::New(env()->isolate(), duration)
334
1096
  };
335
548
  MakeCallback(callback(), arraysize(argv), argv);
336
548
}
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
11777
Http2Priority::Http2Priority(Environment* env,
342
                             Local<Value> parent,
343
                             Local<Value> weight,
344
11777
                             Local<Value> exclusive) {
345
11777
  Local<Context> context = env->context();
346
23554
  int32_t parent_ = parent->Int32Value(context).ToChecked();
347
23554
  int32_t weight_ = weight->Int32Value(context).ToChecked();
348
11777
  bool exclusive_ = exclusive->IsTrue();
349
  Debug(env, DebugCategory::HTTP2STREAM,
350
        "Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
351
11777
        parent_, weight_, exclusive_ ? "yes" : "no");
352
11777
  nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
353
11777
}
354
355
356
117
const char* Http2Session::TypeName() const {
357
117
  switch (session_type_) {
358
59
    case NGHTTP2_SESSION_SERVER: return "server";
359
58
    case NGHTTP2_SESSION_CLIENT: return "client";
360
    default:
361
      // This should never happen
362
      ABORT();
363
  }
364
}
365
366
5
Origins::Origins(
367
    Environment* env,
368
    Local<String> origin_string,
369
5
    size_t origin_count)
370
5
    : count_(origin_count) {
371
5
  int origin_string_len = origin_string->Length();
372
5
  if (count_ == 0) {
373
    CHECK_EQ(origin_string_len, 0);
374
    return;
375
  }
376
377
  {
378
5
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
379
10
    bs_ = ArrayBuffer::NewBackingStore(env->isolate(),
380
                                       alignof(nghttp2_origin_entry) - 1 +
381
5
                                       count_ * sizeof(nghttp2_origin_entry) +
382
5
                                       origin_string_len);
383
  }
384
385
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
386
5
  char* start = AlignUp(static_cast<char*>(bs_->Data()),
387
                        alignof(nghttp2_origin_entry));
388
5
  char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
389
5
  nghttp2_origin_entry* const nva =
390
      reinterpret_cast<nghttp2_origin_entry*>(start);
391
392
5
  CHECK_LE(origin_contents + origin_string_len,
393
           static_cast<char*>(bs_->Data()) + bs_->ByteLength());
394
5
  CHECK_EQ(origin_string->WriteOneByte(
395
               env->isolate(),
396
               reinterpret_cast<uint8_t*>(origin_contents),
397
               0,
398
               origin_string_len,
399
               String::NO_NULL_TERMINATION),
400
           origin_string_len);
401
402
5
  size_t n = 0;
403
  char* p;
404
14
  for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
405
9
    if (n >= count_) {
406
      static uint8_t zero = '\0';
407
      nva[0].origin = &zero;
408
      nva[0].origin_len = 1;
409
      count_ = 1;
410
      return;
411
    }
412
413
9
    nva[n].origin = reinterpret_cast<uint8_t*>(p);
414
9
    nva[n].origin_len = strlen(p);
415
9
    p += nva[n].origin_len + 1;
416
  }
417
}
418
419
// Sets the various callback functions that nghttp2 will use to notify us
420
// about significant events while processing http2 stuff.
421
10030
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
422
  nghttp2_session_callbacks* callbacks_;
423
10030
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
424
10030
  callbacks.reset(callbacks_);
425
426
10030
  nghttp2_session_callbacks_set_on_begin_headers_callback(
427
    callbacks_, OnBeginHeadersCallback);
428
10030
  nghttp2_session_callbacks_set_on_header_callback2(
429
    callbacks_, OnHeaderCallback);
430
10030
  nghttp2_session_callbacks_set_on_frame_recv_callback(
431
    callbacks_, OnFrameReceive);
432
10030
  nghttp2_session_callbacks_set_on_stream_close_callback(
433
    callbacks_, OnStreamClose);
434
10030
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
435
    callbacks_, OnDataChunkReceived);
436
10030
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
437
    callbacks_, OnFrameNotSent);
438
10030
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
439
    callbacks_, OnInvalidHeader);
440
10030
  nghttp2_session_callbacks_set_error_callback(
441
    callbacks_, OnNghttpError);
442
10030
  nghttp2_session_callbacks_set_send_data_callback(
443
    callbacks_, OnSendData);
444
10030
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
445
    callbacks_, OnInvalidFrame);
446
10030
  nghttp2_session_callbacks_set_on_frame_send_callback(
447
    callbacks_, OnFrameSent);
448
449
10030
  if (kHasGetPaddingCallback) {
450
5015
    nghttp2_session_callbacks_set_select_padding_callback(
451
      callbacks_, OnSelectPadding);
452
  }
453
10030
}
454
455
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
456
  StopTrackingMemory(buf);
457
}
458
459
203050
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
460
203050
  CHECK_GE(current_nghttp2_memory_, previous_size);
461
203050
}
462
463
102490
void Http2Session::IncreaseAllocatedSize(size_t size) {
464
102490
  current_nghttp2_memory_ += size;
465
102490
}
466
467
125602
void Http2Session::DecreaseAllocatedSize(size_t size) {
468
125602
  current_nghttp2_memory_ -= size;
469
125602
}
470
471
676
Http2Session::Http2Session(Http2State* http2_state,
472
                           Local<Object> wrap,
473
676
                           SessionType type)
474
    : AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
475
      js_fields_(http2_state->env()->isolate()),
476
      session_type_(type),
477
676
      http2_state_(http2_state) {
478
676
  MakeWeak();
479
676
  statistics_.session_type = type;
480
676
  statistics_.start_time = uv_hrtime();
481
482
  // Capture the configuration options for this session
483
676
  Http2Options opts(http2_state, type);
484
485
676
  max_session_memory_ = opts.max_session_memory();
486
487
676
  uint32_t maxHeaderPairs = opts.max_header_pairs();
488
1352
  max_header_pairs_ =
489
      type == NGHTTP2_SESSION_SERVER
490
346
          ? GetServerMaxHeaderPairs(maxHeaderPairs)
491
330
          : GetClientMaxHeaderPairs(maxHeaderPairs);
492
493
676
  max_outstanding_pings_ = opts.max_outstanding_pings();
494
676
  max_outstanding_settings_ = opts.max_outstanding_settings();
495
496
676
  padding_strategy_ = opts.padding_strategy();
497
498
676
  bool hasGetPaddingCallback =
499
676
      padding_strategy_ != PADDING_STRATEGY_NONE;
500
501
676
  auto fn = type == NGHTTP2_SESSION_SERVER ?
502
      nghttp2_session_server_new3 :
503
      nghttp2_session_client_new3;
504
505
676
  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

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

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

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

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

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

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

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


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

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


2193
  if (stream && !stream->is_destroyed() && stream->headers_count() > 0) {
1019
1
    Debug(this, "freeing headers for stream %d", id);
1020
1
    stream->ClearHeaders();
1021
1
    CHECK_EQ(stream->headers_count(), 0);
1022
1
    DecrementCurrentSessionMemory(stream->current_headers_length_);
1023
1
    stream->current_headers_length_ = 0;
1024
  }
1025
2193
}
1026
1027
// If nghttp2 is unable to send a queued up frame, it will call this callback
1028
// to let us know. If the failure occurred because we are in the process of
1029
// closing down the session or stream, we go ahead and ignore it. We don't
1030
// really care about those and there's nothing we can reasonably do about it
1031
// anyway. Other types of failures are reported up to JavaScript. This should
1032
// be exceedingly rare.
1033
2194
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1034
                                 const nghttp2_frame* frame,
1035
                                 int error_code,
1036
                                 void* user_data) {
1037
2194
  Http2Session* session = static_cast<Http2Session*>(user_data);
1038
2194
  Environment* env = session->env();
1039
  Debug(session, "frame type %d was not sent, code: %d",
1040
2194
        frame->hd.type, error_code);
1041
1042
  // Do not report if the frame was not sent due to the session closing
1043
4392
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
1044
4
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1045

2200
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
1046
2
      session->js_fields_->frame_error_listener_count == 0) {
1047
    // Nghttp2 contains header limit of 65536. When this value is exceeded the
1048
    // pipeline is stopped and we should remove the current headers reference
1049
    // to destroy the session completely.
1050
    // Further information see: https://github.com/nodejs/node/issues/35233
1051
2193
    session->DecrefHeaders(frame);
1052
2193
    return 0;
1053
  }
1054
1055
1
  Isolate* isolate = env->isolate();
1056
2
  HandleScope scope(isolate);
1057
1
  Local<Context> context = env->context();
1058
1
  Context::Scope context_scope(context);
1059
1060
  Local<Value> argv[3] = {
1061
1
    Integer::New(isolate, frame->hd.stream_id),
1062
1
    Integer::New(isolate, frame->hd.type),
1063
    Integer::New(isolate, error_code)
1064
3
  };
1065
  session->MakeCallback(
1066
      env->http2session_on_frame_error_function(),
1067
1
      arraysize(argv), argv);
1068
1
  return 0;
1069
}
1070
1071
55729
int Http2Session::OnFrameSent(nghttp2_session* handle,
1072
                              const nghttp2_frame* frame,
1073
                              void* user_data) {
1074
55729
  Http2Session* session = static_cast<Http2Session*>(user_data);
1075
55729
  session->statistics_.frame_sent += 1;
1076
55729
  return 0;
1077
}
1078
1079
// Called by nghttp2 when a stream closes.
1080
23621
int Http2Session::OnStreamClose(nghttp2_session* handle,
1081
                                int32_t id,
1082
                                uint32_t code,
1083
                                void* user_data) {
1084
23621
  Http2Session* session = static_cast<Http2Session*>(user_data);
1085
23621
  Environment* env = session->env();
1086
23621
  Isolate* isolate = env->isolate();
1087
47242
  HandleScope scope(isolate);
1088
23621
  Local<Context> context = env->context();
1089
23621
  Context::Scope context_scope(context);
1090
  Debug(session, "stream %d closed with code: %d", id, code);
1091
47242
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1092
  // Intentionally ignore the callback if the stream does not exist or has
1093
  // already been destroyed
1094

23621
  if (!stream || stream->is_destroyed())
1095
53
    return 0;
1096
1097
23568
  stream->Close(code);
1098
1099
  // It is possible for the stream close to occur before the stream is
1100
  // ever passed on to the javascript side. If that happens, the callback
1101
  // will return false.
1102
23568
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1103
  MaybeLocal<Value> answer =
1104
23568
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1105
23568
                          1, &arg);
1106

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

13822
  if (!stream || stream->is_destroyed())
1156
1
    return 0;
1157
1158
13821
  stream->statistics_.received_bytes += len;
1159
1160
  // Repeatedly ask the stream's owner for memory, and copy the read data
1161
  // into those buffers.
1162
  // The typical case is actually the exception here; Http2StreamListeners
1163
  // know about the HTTP2 session associated with this stream, so they know
1164
  // about the larger from-socket read buffer, so they do not require copying.
1165
  do {
1166
13821
    uv_buf_t buf = stream->EmitAlloc(len);
1167
13821
    ssize_t avail = len;
1168
13821
    if (static_cast<ssize_t>(buf.len) < avail)
1169
      avail = buf.len;
1170
1171
    // `buf.base == nullptr` is the default Http2StreamListener's way
1172
    // of saying that it wants a pointer to the raw original.
1173
    // Since it has access to the original socket buffer from which the data
1174
    // was read in the first place, it can use that to minimize ArrayBuffer
1175
    // allocations.
1176
13821
    if (LIKELY(buf.base == nullptr))
1177
13821
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1178
    else
1179
      memcpy(buf.base, data, avail);
1180
13821
    data += avail;
1181
13821
    len -= avail;
1182
13821
    stream->EmitRead(avail, buf);
1183
1184
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1185
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1186
    // more data is being requested.
1187
13821
    if (stream->is_reading())
1188
12712
      nghttp2_session_consume_stream(handle, id, avail);
1189
    else
1190
1109
      stream->inbound_consumed_data_while_paused_ += avail;
1191
1192
    // If we have a gathered a lot of data for output, try sending it now.
1193

27639
    if (session->outgoing_length_ > 4096 ||
1194
13818
        stream->available_outbound_length_ > 4096) {
1195
10
      session->SendPendingData();
1196
    }
1197
13821
  } while (len != 0);
1198
1199
  // If we are currently waiting for a write operation to finish, we should
1200
  // tell nghttp2 that we want to wait before we process more input data.
1201
13821
  if (session->is_write_in_progress()) {
1202
567
    CHECK(session->is_reading_stopped());
1203
567
    session->set_receive_paused();
1204
    Debug(session, "receive paused");
1205
567
    return NGHTTP2_ERR_PAUSE;
1206
  }
1207
1208
13254
  return 0;
1209
}
1210
1211
// Called by nghttp2 when it needs to determine how much padding to use in
1212
// a DATA or HEADERS frame.
1213
3
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1214
                                      const nghttp2_frame* frame,
1215
                                      size_t maxPayloadLen,
1216
                                      void* user_data) {
1217
3
  Http2Session* session = static_cast<Http2Session*>(user_data);
1218
3
  ssize_t padding = frame->hd.length;
1219
1220

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

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

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


2956
      !is_write_in_progress() &&
1565
1475
      nghttp2_session_want_read(session_.get())) {
1566
1432
    set_reading_stopped(false);
1567
1432
    stream_->ReadStart();
1568
  }
1569
1570
1481
  if (is_destroyed()) {
1571
43
    HandleScope scope(env()->isolate());
1572
43
    MakeCallback(env()->ondone_string(), 0, nullptr);
1573
43
    return;
1574
  }
1575
1576
  // If there is more incoming data queued up, consume it.
1577
1438
  if (stream_buf_offset_ > 0) {
1578
303
    ConsumeHTTP2Data();
1579
  }
1580
1581

1438
  if (!is_write_scheduled() && !is_destroyed()) {
1582
    // Schedule a new write if nghttp2 wants to send data.
1583
1330
    MaybeScheduleWrite();
1584
  }
1585
}
1586
1587
// If the underlying nghttp2_session struct has data pending in its outbound
1588
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1589
// on the next iteration of the Node.js event loop (using the SetImmediate
1590
// queue), but only if a write has not already been scheduled.
1591
33980
void Http2Session::MaybeScheduleWrite() {
1592
33980
  CHECK(!is_write_scheduled());
1593
33980
  if (UNLIKELY(!session_))
1594
    return;
1595
1596
33980
  if (nghttp2_session_want_write(session_.get())) {
1597
3404
    HandleScope handle_scope(env()->isolate());
1598
1702
    Debug(this, "scheduling write");
1599
1702
    set_write_scheduled();
1600
1702
    BaseObjectPtr<Http2Session> strong_ref{this};
1601
1702
    env()->SetImmediate([this, strong_ref](Environment* env) {
1602

1702
      if (!session_ || !is_write_scheduled()) {
1603
        // This can happen e.g. when a stream was reset before this turn
1604
        // of the event loop, in which case SendPendingData() is called early,
1605
        // or the session was destroyed in the meantime.
1606
300
        return;
1607
      }
1608
1609
      // Sending data may call arbitrary JS code, so keep track of
1610
      // async context.
1611
2804
      HandleScope handle_scope(env->isolate());
1612
2804
      InternalCallbackScope callback_scope(this);
1613
1402
      SendPendingData();
1614
    });
1615
  }
1616
}
1617
1618
62559
void Http2Session::MaybeStopReading() {
1619
62559
  if (is_reading_stopped()) return;
1620
59861
  int want_read = nghttp2_session_want_read(session_.get());
1621
59861
  Debug(this, "wants read? %d", want_read);
1622

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


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

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

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

3959
  if (!is_writable() || is_destroyed()) {
2354
    req_wrap->Done(UV_EOF);
2355
    return 0;
2356
  }
2357
3959
  Debug(this, "queuing %d buffers to send", nbufs);
2358
31672
  for (size_t i = 0; i < nbufs; ++i) {
2359
    // Store the req_wrap on the last write info in the queue, so that it is
2360
    // only marked as finished once all buffers associated with it are finished.
2361
27713
    queue_.emplace(NgHttp2StreamWrite {
2362
55426
      BaseObjectPtr<AsyncWrap>(
2363
3959
          i == nbufs - 1 ? req_wrap->GetAsyncWrap() : nullptr),
2364
27713
      bufs[i]
2365
55426
    });
2366
27713
    IncrementAvailableOutboundLength(bufs[i].len);
2367
  }
2368
3959
  CHECK_NE(nghttp2_session_resume_data(
2369
      session_->session(),
2370
      id_), NGHTTP2_ERR_NOMEM);
2371
3959
  return 0;
2372
}
2373
2374
// Ads a header to the Http2Stream. Note that the header name and value are
2375
// provided using a buffer structure provided by nghttp2 that allows us to
2376
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2377
// is incremented here and are decremented when the header name and values
2378
// are garbage collected later.
2379
71743
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2380
                            nghttp2_rcbuf* value,
2381
                            uint8_t flags) {
2382
71743
  CHECK(!this->is_destroyed());
2383
2384
71743
  if (Http2RcBufferPointer::IsZeroLength(name))
2385
    return true;  // Ignore empty headers.
2386
2387
143486
  Http2Header header(env(), name, value, flags);
2388
71743
  size_t length = header.length() + 32;
2389
  // A header can only be added if we have not exceeded the maximum number
2390
  // of headers and the session has memory available for it.
2391
71743
  if (!session_->has_available_session_memory(length) ||
2392

143485
      current_headers_.size() == max_header_pairs_ ||
2393
71742
      current_headers_length_ + length > max_header_length_) {
2394
3
    return false;
2395
  }
2396
2397
71740
  if (statistics_.first_header == 0)
2398
23418
    statistics_.first_header = uv_hrtime();
2399
2400
71740
  current_headers_.push_back(std::move(header));
2401
2402
71740
  current_headers_length_ += length;
2403
71740
  session_->IncrementCurrentSessionMemory(length);
2404
71740
  return true;
2405
}
2406
2407
// A Provider is the thing that provides outbound DATA frame data.
2408
11720
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2409
11720
  CHECK(!stream->is_destroyed());
2410
11720
  provider_.source.ptr = stream;
2411
11720
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2412
11720
}
2413
2414
11771
Http2Stream::Provider::Provider(int options) {
2415
11771
  provider_.source.ptr = nullptr;
2416
11771
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2417
11771
}
2418
2419
93964
Http2Stream::Provider::~Provider() {
2420
46982
  provider_.source.ptr = nullptr;
2421
}
2422
2423
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2424
// built via the StreamBase API and the Streams js API.
2425
11771
Http2Stream::Provider::Stream::Stream(int options)
2426
11771
    : Http2Stream::Provider(options) {
2427
11771
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2428
11771
}
2429
2430
11720
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2431
11720
    : Http2Stream::Provider(stream, options) {
2432
11720
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2433
11720
}
2434
2435
27673
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2436
                                              int32_t id,
2437
                                              uint8_t* buf,
2438
                                              size_t length,
2439
                                              uint32_t* flags,
2440
                                              nghttp2_data_source* source,
2441
                                              void* user_data) {
2442
27673
  Http2Session* session = static_cast<Http2Session*>(user_data);
2443
  Debug(session, "reading outbound data for stream %d", id);
2444
55346
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
2445
27673
  if (!stream) return 0;
2446
27673
  if (stream->statistics_.first_byte_sent == 0)
2447
12737
    stream->statistics_.first_byte_sent = uv_hrtime();
2448
27673
  CHECK_EQ(id, stream->id());
2449
2450
27673
  size_t amount = 0;          // amount of data being sent in this data frame.
2451
2452
  // Remove all empty chunks from the head of the queue.
2453
  // This is done here so that .write('', cb) is still a meaningful way to
2454
  // find out when the HTTP2 stream wants to consume data, and because the
2455
  // StreamBase API allows empty input chunks.
2456

27678
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2457
    BaseObjectPtr<AsyncWrap> finished =
2458
10
        std::move(stream->queue_.front().req_wrap);
2459
5
    stream->queue_.pop();
2460
5
    if (finished)
2461
3
      WriteWrap::FromObject(finished)->Done(0);
2462
  }
2463
2464
27673
  if (!stream->queue_.empty()) {
2465
    Debug(session, "stream %d has pending outbound data", id);
2466
13684
    amount = std::min(stream->available_outbound_length_, length);
2467
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2468
13684
    if (amount > 0) {
2469
      // Just return the length, let Http2Session::OnSendData take care of
2470
      // actually taking the buffers out of the queue.
2471
13684
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2472
13684
      stream->DecrementAvailableOutboundLength(amount);
2473
    }
2474
  }
2475
2476

27673
  if (amount == 0 && stream->is_writable()) {
2477
2622
    CHECK(stream->queue_.empty());
2478
    Debug(session, "deferring stream %d", id);
2479
2622
    stream->EmitWantsWrite(length);
2480

2622
    if (stream->available_outbound_length_ > 0 || !stream->is_writable()) {
2481
      // EmitWantsWrite() did something interesting synchronously, restart:
2482
      return OnRead(handle, id, buf, length, flags, source, user_data);
2483
    }
2484
2622
    return NGHTTP2_ERR_DEFERRED;
2485
  }
2486
2487

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

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

9
  if (ret <= 0 || stream == nullptr) {
2826
    Debug(parent, "failed to create push stream: %d", ret);
2827
    return args.GetReturnValue().Set(ret);
2828
  }
2829
18
  Debug(parent, "push stream %d created", stream->id());
2830
18
  args.GetReturnValue().Set(stream->object());
2831
}
2832
2833
// Send a PRIORITY frame
2834
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2835
6
  Environment* env = Environment::GetCurrent(args);
2836
  Http2Stream* stream;
2837
6
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2838
2839

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

10
  if (origin_str.IsEmpty() || value_str.IsEmpty())
2916
    return;
2917
2918
5
  size_t origin_len = origin_str->Length();
2919
5
  size_t value_len = value_str->Length();
2920
2921
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2922
  // Verify that origin len != 0 if stream id == 0, or
2923
  // that origin len == 0 if stream id != 0
2924



5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2925
2926
10
  MaybeStackBuffer<uint8_t> origin(origin_len);
2927
10
  MaybeStackBuffer<uint8_t> value(value_len);
2928
5
  origin_str->WriteOneByte(env->isolate(), *origin);
2929
5
  value_str->WriteOneByte(env->isolate(), *value);
2930
2931
5
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2932
}
2933
2934
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2935
5
  Environment* env = Environment::GetCurrent(args);
2936
5
  Local<Context> context = env->context();
2937
  Http2Session* session;
2938
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2939
2940
10
  Local<String> origin_string = args[0].As<String>();
2941
5
  size_t count = args[1]->Int32Value(context).ToChecked();
2942
2943
5
  session->Origin(Origins(env, origin_string, count));
2944
}
2945
2946
// Submits a PING frame to be sent to the connected peer.
2947
13
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2948
  Http2Session* session;
2949
13
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2950
2951
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2952
  // then the current hrtime will be used as the payload.
2953
13
  ArrayBufferViewContents<uint8_t, 8> payload;
2954
13
  if (args[0]->IsArrayBufferView()) {
2955
12
    payload.Read(args[0].As<ArrayBufferView>());
2956
6
    CHECK_EQ(payload.length(), 8);
2957
  }
2958
2959
13
  CHECK(args[1]->IsFunction());
2960
13
  args.GetReturnValue().Set(
2961
52
      session->AddPing(payload.data(), args[1].As<Function>()));
2962
}
2963
2964
// Submits a SETTINGS frame for the Http2Session
2965
686
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2966
  Http2Session* session;
2967
686
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2968
686
  CHECK(args[0]->IsFunction());
2969

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

750
  SET_FUNCTION(0, error)
3120

750
  SET_FUNCTION(1, priority)
3121

750
  SET_FUNCTION(2, settings)
3122

750
  SET_FUNCTION(3, ping)
3123

750
  SET_FUNCTION(4, headers)
3124

750
  SET_FUNCTION(5, frame_error)
3125

750
  SET_FUNCTION(6, goaway_data)
3126

750
  SET_FUNCTION(7, altsvc)
3127

750
  SET_FUNCTION(8, origin)
3128

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