GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.cc Lines: 1512 1592 95.0 %
Date: 2022-01-06 04:14:11 Branches: 604 844 71.6 %

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

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



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

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

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

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

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

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

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


55739
  switch (frame->hd.type) {
950
24232
    case NGHTTP2_DATA:
951
24232
      return session->HandleDataFrame(frame);
952
23416
    case NGHTTP2_PUSH_PROMISE:
953
      // Intentional fall-through, handled just like headers frames
954
    case NGHTTP2_HEADERS:
955
23416
      session->HandleHeadersFrame(frame);
956
23416
      break;
957
2150
    case NGHTTP2_SETTINGS:
958
2150
      session->HandleSettingsFrame(frame);
959
2150
      break;
960
16
    case NGHTTP2_PRIORITY:
961
16
      session->HandlePriorityFrame(frame);
962
16
      break;
963
312
    case NGHTTP2_GOAWAY:
964
312
      session->HandleGoawayFrame(frame);
965
312
      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
31507
  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
// If nghttp2 is unable to send a queued up frame, it will call this callback
1013
// to let us know. If the failure occurred because we are in the process of
1014
// closing down the session or stream, we go ahead and ignore it. We don't
1015
// really care about those and there's nothing we can reasonably do about it
1016
// anyway. Other types of failures are reported up to JavaScript. This should
1017
// be exceedingly rare.
1018
2191
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1019
                                 const nghttp2_frame* frame,
1020
                                 int error_code,
1021
                                 void* user_data) {
1022
2191
  Http2Session* session = static_cast<Http2Session*>(user_data);
1023
2191
  Environment* env = session->env();
1024
  Debug(session, "frame type %d was not sent, code: %d",
1025
2191
        frame->hd.type, error_code);
1026
1027
  // Do not report if the frame was not sent due to the session closing
1028
4386
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
1029
4
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1030

2197
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
1031
2
      session->js_fields_->frame_error_listener_count == 0) {
1032
2190
    return 0;
1033
  }
1034
1035
1
  Isolate* isolate = env->isolate();
1036
2
  HandleScope scope(isolate);
1037
1
  Local<Context> context = env->context();
1038
1
  Context::Scope context_scope(context);
1039
1040
  Local<Value> argv[3] = {
1041
1
    Integer::New(isolate, frame->hd.stream_id),
1042
1
    Integer::New(isolate, frame->hd.type),
1043
    Integer::New(isolate, error_code)
1044
3
  };
1045
  session->MakeCallback(
1046
      env->http2session_on_frame_error_function(),
1047
1
      arraysize(argv), argv);
1048
1
  return 0;
1049
}
1050
1051
55814
int Http2Session::OnFrameSent(nghttp2_session* handle,
1052
                              const nghttp2_frame* frame,
1053
                              void* user_data) {
1054
55814
  Http2Session* session = static_cast<Http2Session*>(user_data);
1055
55814
  session->statistics_.frame_sent += 1;
1056
55814
  return 0;
1057
}
1058
1059
// Called by nghttp2 when a stream closes.
1060
23607
int Http2Session::OnStreamClose(nghttp2_session* handle,
1061
                                int32_t id,
1062
                                uint32_t code,
1063
                                void* user_data) {
1064
23607
  Http2Session* session = static_cast<Http2Session*>(user_data);
1065
23607
  Environment* env = session->env();
1066
23607
  Isolate* isolate = env->isolate();
1067
47214
  HandleScope scope(isolate);
1068
23607
  Local<Context> context = env->context();
1069
23607
  Context::Scope context_scope(context);
1070
  Debug(session, "stream %d closed with code: %d", id, code);
1071
47214
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1072
  // Intentionally ignore the callback if the stream does not exist or has
1073
  // already been destroyed
1074

23607
  if (!stream || stream->is_destroyed())
1075
53
    return 0;
1076
1077
23554
  stream->Close(code);
1078
1079
  // It is possible for the stream close to occur before the stream is
1080
  // ever passed on to the javascript side. If that happens, the callback
1081
  // will return false.
1082
23554
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1083
  MaybeLocal<Value> answer =
1084
23554
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1085
23554
                          1, &arg);
1086

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

13842
  if (!stream || stream->is_destroyed())
1136
1
    return 0;
1137
1138
13841
  stream->statistics_.received_bytes += len;
1139
1140
  // Repeatedly ask the stream's owner for memory, and copy the read data
1141
  // into those buffers.
1142
  // The typical case is actually the exception here; Http2StreamListeners
1143
  // know about the HTTP2 session associated with this stream, so they know
1144
  // about the larger from-socket read buffer, so they do not require copying.
1145
  do {
1146
13841
    uv_buf_t buf = stream->EmitAlloc(len);
1147
13841
    ssize_t avail = len;
1148
13841
    if (static_cast<ssize_t>(buf.len) < avail)
1149
      avail = buf.len;
1150
1151
    // `buf.base == nullptr` is the default Http2StreamListener's way
1152
    // of saying that it wants a pointer to the raw original.
1153
    // Since it has access to the original socket buffer from which the data
1154
    // was read in the first place, it can use that to minimize ArrayBuffer
1155
    // allocations.
1156
13841
    if (LIKELY(buf.base == nullptr))
1157
13841
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1158
    else
1159
      memcpy(buf.base, data, avail);
1160
13841
    data += avail;
1161
13841
    len -= avail;
1162
13841
    stream->EmitRead(avail, buf);
1163
1164
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1165
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1166
    // more data is being requested.
1167
13841
    if (stream->is_reading())
1168
12731
      nghttp2_session_consume_stream(handle, id, avail);
1169
    else
1170
1110
      stream->inbound_consumed_data_while_paused_ += avail;
1171
1172
    // If we have a gathered a lot of data for output, try sending it now.
1173

27679
    if (session->outgoing_length_ > 4096 ||
1174
13838
        stream->available_outbound_length_ > 4096) {
1175
10
      session->SendPendingData();
1176
    }
1177
13841
  } while (len != 0);
1178
1179
  // If we are currently waiting for a write operation to finish, we should
1180
  // tell nghttp2 that we want to wait before we process more input data.
1181
13841
  if (session->is_write_in_progress()) {
1182
567
    CHECK(session->is_reading_stopped());
1183
567
    session->set_receive_paused();
1184
    Debug(session, "receive paused");
1185
567
    return NGHTTP2_ERR_PAUSE;
1186
  }
1187
1188
13274
  return 0;
1189
}
1190
1191
// Called by nghttp2 when it needs to determine how much padding to use in
1192
// a DATA or HEADERS frame.
1193
3
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1194
                                      const nghttp2_frame* frame,
1195
                                      size_t maxPayloadLen,
1196
                                      void* user_data) {
1197
3
  Http2Session* session = static_cast<Http2Session*>(user_data);
1198
3
  ssize_t padding = frame->hd.length;
1199
1200

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

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

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


3008
      !is_write_in_progress() &&
1545
1501
      nghttp2_session_want_read(session_.get())) {
1546
1458
    set_reading_stopped(false);
1547
1458
    stream_->ReadStart();
1548
  }
1549
1550
1507
  if (is_destroyed()) {
1551
43
    HandleScope scope(env()->isolate());
1552
43
    MakeCallback(env()->ondone_string(), 0, nullptr);
1553
43
    return;
1554
  }
1555
1556
  // If there is more incoming data queued up, consume it.
1557
1464
  if (stream_buf_offset_ > 0) {
1558
303
    ConsumeHTTP2Data();
1559
  }
1560
1561

1464
  if (!is_write_scheduled() && !is_destroyed()) {
1562
    // Schedule a new write if nghttp2 wants to send data.
1563
1356
    MaybeScheduleWrite();
1564
  }
1565
}
1566
1567
// If the underlying nghttp2_session struct has data pending in its outbound
1568
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1569
// on the next iteration of the Node.js event loop (using the SetImmediate
1570
// queue), but only if a write has not already been scheduled.
1571
34000
void Http2Session::MaybeScheduleWrite() {
1572
34000
  CHECK(!is_write_scheduled());
1573
34000
  if (UNLIKELY(!session_))
1574
    return;
1575
1576
34000
  if (nghttp2_session_want_write(session_.get())) {
1577
3438
    HandleScope handle_scope(env()->isolate());
1578
1719
    Debug(this, "scheduling write");
1579
1719
    set_write_scheduled();
1580
1719
    BaseObjectPtr<Http2Session> strong_ref{this};
1581
1719
    env()->SetImmediate([this, strong_ref](Environment* env) {
1582

1719
      if (!session_ || !is_write_scheduled()) {
1583
        // This can happen e.g. when a stream was reset before this turn
1584
        // of the event loop, in which case SendPendingData() is called early,
1585
        // or the session was destroyed in the meantime.
1586
298
        return;
1587
      }
1588
1589
      // Sending data may call arbitrary JS code, so keep track of
1590
      // async context.
1591
2842
      HandleScope handle_scope(env->isolate());
1592
2842
      InternalCallbackScope callback_scope(this);
1593
1421
      SendPendingData();
1594
    });
1595
  }
1596
}
1597
1598
62528
void Http2Session::MaybeStopReading() {
1599
62528
  if (is_reading_stopped()) return;
1600
59841
  int want_read = nghttp2_session_want_read(session_.get());
1601
59841
  Debug(this, "wants read? %d", want_read);
1602

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


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

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

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

4005
  if (!is_writable() || is_destroyed()) {
2334
    req_wrap->Done(UV_EOF);
2335
    return 0;
2336
  }
2337
4005
  Debug(this, "queuing %d buffers to send", nbufs);
2338
31754
  for (size_t i = 0; i < nbufs; ++i) {
2339
    // Store the req_wrap on the last write info in the queue, so that it is
2340
    // only marked as finished once all buffers associated with it are finished.
2341
27749
    queue_.emplace(NgHttp2StreamWrite {
2342
55498
      BaseObjectPtr<AsyncWrap>(
2343
4005
          i == nbufs - 1 ? req_wrap->GetAsyncWrap() : nullptr),
2344
27749
      bufs[i]
2345
55498
    });
2346
27749
    IncrementAvailableOutboundLength(bufs[i].len);
2347
  }
2348
4005
  CHECK_NE(nghttp2_session_resume_data(
2349
      session_->session(),
2350
      id_), NGHTTP2_ERR_NOMEM);
2351
4005
  return 0;
2352
}
2353
2354
// Ads a header to the Http2Stream. Note that the header name and value are
2355
// provided using a buffer structure provided by nghttp2 that allows us to
2356
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2357
// is incremented here and are decremented when the header name and values
2358
// are garbage collected later.
2359
71789
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2360
                            nghttp2_rcbuf* value,
2361
                            uint8_t flags) {
2362
71789
  CHECK(!this->is_destroyed());
2363
2364
71789
  if (Http2RcBufferPointer::IsZeroLength(name))
2365
    return true;  // Ignore empty headers.
2366
2367
143578
  Http2Header header(env(), name, value, flags);
2368
71789
  size_t length = header.length() + 32;
2369
  // A header can only be added if we have not exceeded the maximum number
2370
  // of headers and the session has memory available for it.
2371
71789
  if (!session_->has_available_session_memory(length) ||
2372

143577
      current_headers_.size() == max_header_pairs_ ||
2373
71788
      current_headers_length_ + length > max_header_length_) {
2374
3
    return false;
2375
  }
2376
2377
71786
  if (statistics_.first_header == 0)
2378
23435
    statistics_.first_header = uv_hrtime();
2379
2380
71786
  current_headers_.push_back(std::move(header));
2381
2382
71786
  current_headers_length_ += length;
2383
71786
  session_->IncrementCurrentSessionMemory(length);
2384
71786
  return true;
2385
}
2386
2387
// A Provider is the thing that provides outbound DATA frame data.
2388
11713
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2389
11713
  CHECK(!stream->is_destroyed());
2390
11713
  provider_.source.ptr = stream;
2391
11713
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2392
11713
}
2393
2394
11763
Http2Stream::Provider::Provider(int options) {
2395
11763
  provider_.source.ptr = nullptr;
2396
11763
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2397
11763
}
2398
2399
93904
Http2Stream::Provider::~Provider() {
2400
46952
  provider_.source.ptr = nullptr;
2401
}
2402
2403
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2404
// built via the StreamBase API and the Streams js API.
2405
11763
Http2Stream::Provider::Stream::Stream(int options)
2406
11763
    : Http2Stream::Provider(options) {
2407
11763
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2408
11763
}
2409
2410
11713
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2411
11713
    : Http2Stream::Provider(stream, options) {
2412
11713
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2413
11713
}
2414
2415
27840
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2416
                                              int32_t id,
2417
                                              uint8_t* buf,
2418
                                              size_t length,
2419
                                              uint32_t* flags,
2420
                                              nghttp2_data_source* source,
2421
                                              void* user_data) {
2422
27840
  Http2Session* session = static_cast<Http2Session*>(user_data);
2423
  Debug(session, "reading outbound data for stream %d", id);
2424
55680
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
2425
27840
  if (!stream) return 0;
2426
27840
  if (stream->statistics_.first_byte_sent == 0)
2427
12737
    stream->statistics_.first_byte_sent = uv_hrtime();
2428
27840
  CHECK_EQ(id, stream->id());
2429
2430
27840
  size_t amount = 0;          // amount of data being sent in this data frame.
2431
2432
  // Remove all empty chunks from the head of the queue.
2433
  // This is done here so that .write('', cb) is still a meaningful way to
2434
  // find out when the HTTP2 stream wants to consume data, and because the
2435
  // StreamBase API allows empty input chunks.
2436

27845
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2437
    BaseObjectPtr<AsyncWrap> finished =
2438
10
        std::move(stream->queue_.front().req_wrap);
2439
5
    stream->queue_.pop();
2440
5
    if (finished)
2441
3
      WriteWrap::FromObject(finished)->Done(0);
2442
  }
2443
2444
27840
  if (!stream->queue_.empty()) {
2445
    Debug(session, "stream %d has pending outbound data", id);
2446
13808
    amount = std::min(stream->available_outbound_length_, length);
2447
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2448
13808
    if (amount > 0) {
2449
      // Just return the length, let Http2Session::OnSendData take care of
2450
      // actually taking the buffers out of the queue.
2451
13808
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2452
13808
      stream->DecrementAvailableOutboundLength(amount);
2453
    }
2454
  }
2455
2456

27840
  if (amount == 0 && stream->is_writable()) {
2457
2666
    CHECK(stream->queue_.empty());
2458
    Debug(session, "deferring stream %d", id);
2459
2666
    stream->EmitWantsWrite(length);
2460

2666
    if (stream->available_outbound_length_ > 0 || !stream->is_writable()) {
2461
      // EmitWantsWrite() did something interesting synchronously, restart:
2462
      return OnRead(handle, id, buf, length, flags, source, user_data);
2463
    }
2464
2666
    return NGHTTP2_ERR_DEFERRED;
2465
  }
2466
2467

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

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

9
  if (ret <= 0 || stream == nullptr) {
2806
    Debug(parent, "failed to create push stream: %d", ret);
2807
    return args.GetReturnValue().Set(ret);
2808
  }
2809
18
  Debug(parent, "push stream %d created", stream->id());
2810
18
  args.GetReturnValue().Set(stream->object());
2811
}
2812
2813
// Send a PRIORITY frame
2814
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2815
6
  Environment* env = Environment::GetCurrent(args);
2816
  Http2Stream* stream;
2817
6
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2818
2819

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

10
  if (origin_str.IsEmpty() || value_str.IsEmpty())
2896
    return;
2897
2898
5
  size_t origin_len = origin_str->Length();
2899
5
  size_t value_len = value_str->Length();
2900
2901
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2902
  // Verify that origin len != 0 if stream id == 0, or
2903
  // that origin len == 0 if stream id != 0
2904



5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2905
2906
10
  MaybeStackBuffer<uint8_t> origin(origin_len);
2907
10
  MaybeStackBuffer<uint8_t> value(value_len);
2908
5
  origin_str->WriteOneByte(env->isolate(), *origin);
2909
5
  value_str->WriteOneByte(env->isolate(), *value);
2910
2911
5
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2912
}
2913
2914
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2915
5
  Environment* env = Environment::GetCurrent(args);
2916
5
  Local<Context> context = env->context();
2917
  Http2Session* session;
2918
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2919
2920
10
  Local<String> origin_string = args[0].As<String>();
2921
5
  size_t count = args[1]->Int32Value(context).ToChecked();
2922
2923
5
  session->Origin(Origins(env, origin_string, count));
2924
}
2925
2926
// Submits a PING frame to be sent to the connected peer.
2927
13
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2928
  Http2Session* session;
2929
13
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2930
2931
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2932
  // then the current hrtime will be used as the payload.
2933
13
  ArrayBufferViewContents<uint8_t, 8> payload;
2934
13
  if (args[0]->IsArrayBufferView()) {
2935
12
    payload.Read(args[0].As<ArrayBufferView>());
2936
6
    CHECK_EQ(payload.length(), 8);
2937
  }
2938
2939
13
  CHECK(args[1]->IsFunction());
2940
13
  args.GetReturnValue().Set(
2941
52
      session->AddPing(payload.data(), args[1].As<Function>()));
2942
}
2943
2944
// Submits a SETTINGS frame for the Http2Session
2945
680
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2946
  Http2Session* session;
2947
680
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2948
680
  CHECK(args[0]->IsFunction());
2949

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

747
  SET_FUNCTION(0, error)
3100

747
  SET_FUNCTION(1, priority)
3101

747
  SET_FUNCTION(2, settings)
3102

747
  SET_FUNCTION(3, ping)
3103

747
  SET_FUNCTION(4, headers)
3104

747
  SET_FUNCTION(5, frame_error)
3105

747
  SET_FUNCTION(6, goaway_data)
3106

747
  SET_FUNCTION(7, altsvc)
3107

747
  SET_FUNCTION(8, origin)
3108

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