GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.cc Lines: 1528 1620 94.3 %
Date: 2022-05-17 04:15:46 Branches: 614 861 71.3 %

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

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



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

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

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

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

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

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

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


57882
  switch (frame->hd.type) {
950
24214
    case NGHTTP2_DATA:
951
24214
      return session->HandleDataFrame(frame);
952
24709
    case NGHTTP2_PUSH_PROMISE:
953
      // Intentional fall-through, handled just like headers frames
954
    case NGHTTP2_HEADERS:
955
24709
      session->HandleHeadersFrame(frame);
956
24709
      break;
957
3012
    case NGHTTP2_SETTINGS:
958
3012
      session->HandleSettingsFrame(frame);
959
3012
      break;
960
16
    case NGHTTP2_PRIORITY:
961
16
      session->HandlePriorityFrame(frame);
962
16
      break;
963
318
    case NGHTTP2_GOAWAY:
964
318
      session->HandleGoawayFrame(frame);
965
318
      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
33668
  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
2194
void Http2Session::DecrefHeaders(const nghttp2_frame* frame) {
1015
2194
  int32_t id = GetFrameID(frame);
1016
4388
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1017
1018


2194
  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
2194
}
1026
1027
2
uint32_t TranslateNghttp2ErrorCode(const int libErrorCode) {
1028

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

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

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

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

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

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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

1389
  SET_FUNCTION(0, error)
3140

1389
  SET_FUNCTION(1, priority)
3141

1389
  SET_FUNCTION(2, settings)
3142

1389
  SET_FUNCTION(3, ping)
3143

1389
  SET_FUNCTION(4, headers)
3144

1389
  SET_FUNCTION(5, frame_error)
3145

1389
  SET_FUNCTION(6, goaway_data)
3146

1389
  SET_FUNCTION(7, altsvc)
3147

1389
  SET_FUNCTION(8, origin)
3148

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