GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_http2.cc Lines: 1561 1630 95.8 %
Date: 2020-11-20 19:51:53 Branches: 559 766 73.0 %

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

107728
  if (session_->is_in_scope() || session_->is_write_scheduled()) {
82
74999
    session_.reset();
83
74999
    return;
84
  }
85
32729
  session_->set_in_scope();
86
}
87
88
215456
Http2Scope::~Http2Scope() {
89
107728
  if (!session_) return;
90
32729
  session_->set_in_scope(false);
91
32729
  session_->MaybeScheduleWrite();
92
107728
}
93
94
// The Http2Options object is used during the construction of Http2Session
95
// instances to configure an appropriate nghttp2_options struct. The class
96
// uses a single TypedArray instance that is shared with the JavaScript side
97
// to more efficiently pass values back and forth.
98
658
Http2Options::Http2Options(Http2State* http2_state, SessionType type) {
99
  nghttp2_option* option;
100
658
  CHECK_EQ(nghttp2_option_new(&option), 0);
101
658
  CHECK_NOT_NULL(option);
102
658
  options_.reset(option);
103
104
  // Make sure closed connections aren't kept around, taking up memory.
105
  // Note that this breaks the priority tree, which we don't use.
106
658
  nghttp2_option_set_no_closed_streams(option, 1);
107
108
  // We manually handle flow control within a session in order to
109
  // implement backpressure -- that is, we only send WINDOW_UPDATE
110
  // frames to the remote peer as data is actually consumed by user
111
  // code. This ensures that the flow of data over the connection
112
  // does not move too quickly and limits the amount of data we
113
  // are required to buffer.
114
658
  nghttp2_option_set_no_auto_window_update(option, 1);
115
116
  // Enable built in support for receiving ALTSVC and ORIGIN frames (but
117
  // only on client side sessions
118
658
  if (type == NGHTTP2_SESSION_CLIENT) {
119
320
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ALTSVC);
120
320
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ORIGIN);
121
  }
122
123
658
  AliasedUint32Array& buffer = http2_state->options_buffer;
124
658
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
125
126
658
  if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) {
127
    nghttp2_option_set_max_deflate_dynamic_table_size(
128
        option,
129
        buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
130
  }
131
132
658
  if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
133
2
    nghttp2_option_set_max_reserved_remote_streams(
134
        option,
135
1
        buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]);
136
  }
137
138
658
  if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) {
139
1
    nghttp2_option_set_max_send_header_block_length(
140
        option,
141
2
        buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
142
  }
143
144
  // Recommended default
145
658
  nghttp2_option_set_peer_max_concurrent_streams(option, 100);
146
658
  if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
147
    nghttp2_option_set_peer_max_concurrent_streams(
148
        option,
149
        buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
150
  }
151
152
  // The padding strategy sets the mechanism by which we determine how much
153
  // additional frame padding to apply to DATA and HEADERS frames. Currently
154
  // this is set on a per-session basis, but eventually we may switch to
155
  // a per-stream setting, giving users greater control
156
658
  if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
157
    PaddingStrategy strategy =
158
        static_cast<PaddingStrategy>(
159
2
            buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
160
2
    set_padding_strategy(strategy);
161
  }
162
163
  // The max header list pairs option controls the maximum number of
164
  // header pairs the session may accept. This is a hard limit.. that is,
165
  // if the remote peer sends more than this amount, the stream will be
166
  // automatically closed with an RST_STREAM.
167
658
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS))
168
1
    set_max_header_pairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
169
170
  // The HTTP2 specification places no limits on the number of HTTP2
171
  // PING frames that can be sent. In order to prevent PINGS from being
172
  // abused as an attack vector, however, we place a strict upper limit
173
  // on the number of unacknowledged PINGS that can be sent at any given
174
  // time.
175
658
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS))
176
2
    set_max_outstanding_pings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
177
178
  // The HTTP2 specification places no limits on the number of HTTP2
179
  // SETTINGS frames that can be sent. In order to prevent PINGS from being
180
  // abused as an attack vector, however, we place a strict upper limit
181
  // on the number of unacknowledged SETTINGS that can be sent at any given
182
  // time.
183
658
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS))
184
2
    set_max_outstanding_settings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
185
186
  // The HTTP2 specification places no limits on the amount of memory
187
  // that a session can consume. In order to prevent abuse, we place a
188
  // cap on the amount of memory a session can consume at any given time.
189
  // this is a credit based system. Existing streams may cause the limit
190
  // to be temporarily exceeded but once over the limit, new streams cannot
191
  // created.
192
  // Important: The maxSessionMemory option in javascript is expressed in
193
  //            terms of MB increments (i.e. the value 1 == 1 MB)
194
658
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY))
195
6
    set_max_session_memory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1000000);
196
197
658
  if (flags & (1 << IDX_OPTIONS_MAX_SETTINGS)) {
198
1
    nghttp2_option_set_max_settings(
199
        option,
200
2
        static_cast<size_t>(buffer[IDX_OPTIONS_MAX_SETTINGS]));
201
  }
202
658
}
203
204
#define GRABSETTING(entries, count, name)                                      \
205
  do {                                                                         \
206
    if (flags & (1 << IDX_SETTINGS_ ## name)) {                                \
207
      uint32_t val = buffer[IDX_SETTINGS_ ## name];                            \
208
      entries[count++] =                                                       \
209
          nghttp2_settings_entry {NGHTTP2_SETTINGS_ ## name, val};             \
210
    } } while (0)
211
212
685
size_t Http2Settings::Init(
213
    Http2State* http2_state,
214
    nghttp2_settings_entry* entries) {
215
685
  AliasedUint32Array& buffer = http2_state->settings_buffer;
216
685
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
217
218
685
  size_t count = 0;
219
220
#define V(name) GRABSETTING(entries, count, name);
221
685
  HTTP2_SETTINGS(V)
222
6
#undef V
223
12
224
697
  return count;
225
8
}
226
685
#undef GRABSETTING
227
18
228
6
// The Http2Settings class is used to configure a SETTINGS frame that is
229
6
// to be sent to the connected peer. The settings are set using a TypedArray
230
10
// that is shared with the JavaScript side.
231
1353
Http2Settings::Http2Settings(Http2Session* session,
232
6
                             Local<Object> obj,
233
                             Local<Function> callback,
234
668
                             uint64_t start_time)
235
    : AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
236
      session_(session),
237
1336
      startTime_(start_time) {
238
668
  callback_.Reset(env()->isolate(), callback);
239
668
  count_ = Init(session->http2_state(), entries_);
240
668
}
241
242
538
Local<Function> Http2Settings::callback() const {
243
1076
  return callback_.Get(env()->isolate());
244
}
245
246
4
void Http2Settings::MemoryInfo(MemoryTracker* tracker) const {
247
4
  tracker->TrackField("callback", callback_);
248
4
}
249
250
// Generates a Buffer that contains the serialized payload of a SETTINGS
251
// frame. This can be used, for instance, to create the Base64-encoded
252
// content of an Http2-Settings header field.
253
Local<Value> Http2Settings::Pack() {
254
  return Pack(session_->env(), count_, entries_);
255
}
256
257
17
Local<Value> Http2Settings::Pack(Http2State* state) {
258
  nghttp2_settings_entry entries[IDX_SETTINGS_COUNT];
259
17
  size_t count = Init(state, entries);
260
17
  return Pack(state->env(), count, entries);
261
}
262
263
17
Local<Value> Http2Settings::Pack(
264
    Environment* env,
265
    size_t count,
266
    const nghttp2_settings_entry* entries) {
267
17
  EscapableHandleScope scope(env->isolate());
268
17
  const size_t size = count * 6;
269
34
  AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
270
  ssize_t ret =
271
      nghttp2_pack_settings_payload(
272
17
          reinterpret_cast<uint8_t*>(buffer.data()),
273
          size,
274
          entries,
275
17
          count);
276
17
  Local<Value> buf = Undefined(env->isolate());
277
33
  if (ret >= 0) buf = buffer.ToBuffer().ToLocalChecked();
278
17
  return scope.Escape(buf);
279
}
280
281
// Updates the shared TypedArray with the current remote or local settings for
282
// the session.
283
561
void Http2Settings::Update(Http2Session* session, get_setting fn) {
284
561
  AliasedUint32Array& buffer = session->http2_state()->settings_buffer;
285
286
#define V(name)                                                                \
287
  buffer[IDX_SETTINGS_ ## name] =                                              \
288
      fn(session->session(), NGHTTP2_SETTINGS_ ## name);
289
561
  HTTP2_SETTINGS(V)
290
1122
#undef V
291
2244
}
292
1122
293
561
// Initializes the shared TypedArray with the default settings values.
294
567
void Http2Settings::RefreshDefaults(Http2State* http2_state) {
295
6
  AliasedUint32Array& buffer = http2_state->settings_buffer;
296
6
  uint32_t flags = 0;
297
298
#define V(name)                                                            \
299
  do {                                                                     \
300
    buffer[IDX_SETTINGS_ ## name] = DEFAULT_SETTINGS_ ## name;             \
301
    flags |= 1 << IDX_SETTINGS_ ## name;                                   \
302
  } while (0);
303
6
  HTTP2_SETTINGS(V)
304
6
#undef V
305
6
306
12
  buffer[IDX_SETTINGS_COUNT] = flags;
307
18
}
308
18
309
12
310
672
void Http2Settings::Send() {
311
1332
  Http2Scope h2scope(session_.get());
312
666
  CHECK_EQ(nghttp2_submit_settings(
313
      session_->session(),
314
      NGHTTP2_FLAG_NONE,
315
      &entries_[0],
316
      count_), 0);
317
666
}
318
319
538
void Http2Settings::Done(bool ack) {
320
538
  uint64_t end = uv_hrtime();
321
538
  double duration = (end - startTime_) / 1e6;
322
323
  Local<Value> argv[] = {
324
538
    ack ? v8::True(env()->isolate()) : v8::False(env()->isolate()),
325
    Number::New(env()->isolate(), duration)
326
1614
  };
327
538
  MakeCallback(callback(), arraysize(argv), argv);
328
538
}
329
330
// The Http2Priority class initializes an appropriate nghttp2_priority_spec
331
// struct used when either creating a stream or updating its priority
332
// settings.
333
11784
Http2Priority::Http2Priority(Environment* env,
334
                             Local<Value> parent,
335
                             Local<Value> weight,
336
11784
                             Local<Value> exclusive) {
337
11784
  Local<Context> context = env->context();
338
23568
  int32_t parent_ = parent->Int32Value(context).ToChecked();
339
23568
  int32_t weight_ = weight->Int32Value(context).ToChecked();
340
11784
  bool exclusive_ = exclusive->IsTrue();
341
  Debug(env, DebugCategory::HTTP2STREAM,
342
        "Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
343
23568
        parent_, weight_, exclusive_ ? "yes" : "no");
344
11784
  nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
345
11784
}
346
347
348
118
const char* Http2Session::TypeName() const {
349
118
  switch (session_type_) {
350
59
    case NGHTTP2_SESSION_SERVER: return "server";
351
59
    case NGHTTP2_SESSION_CLIENT: return "client";
352
    default:
353
      // This should never happen
354
      ABORT();
355
  }
356
}
357
358
5
Origins::Origins(
359
    Environment* env,
360
    Local<String> origin_string,
361
5
    size_t origin_count)
362
5
    : count_(origin_count) {
363
5
  int origin_string_len = origin_string->Length();
364
5
  if (count_ == 0) {
365
    CHECK_EQ(origin_string_len, 0);
366
    return;
367
  }
368
369
10
  buf_ = AllocatedBuffer::AllocateManaged(
370
      env,
371
      (alignof(nghttp2_origin_entry) - 1) +
372
5
       count_ * sizeof(nghttp2_origin_entry) +
373
5
                              origin_string_len);
374
375
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
376
5
  char* start = AlignUp(buf_.data(), alignof(nghttp2_origin_entry));
377
5
  char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
378
  nghttp2_origin_entry* const nva =
379
5
      reinterpret_cast<nghttp2_origin_entry*>(start);
380
381
5
  CHECK_LE(origin_contents + origin_string_len, buf_.data() + buf_.size());
382
10
  CHECK_EQ(origin_string->WriteOneByte(
383
               env->isolate(),
384
               reinterpret_cast<uint8_t*>(origin_contents),
385
               0,
386
               origin_string_len,
387
               String::NO_NULL_TERMINATION),
388
           origin_string_len);
389
390
5
  size_t n = 0;
391
  char* p;
392
14
  for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
393
9
    if (n >= count_) {
394
      static uint8_t zero = '\0';
395
      nva[0].origin = &zero;
396
      nva[0].origin_len = 1;
397
      count_ = 1;
398
      return;
399
    }
400
401
9
    nva[n].origin = reinterpret_cast<uint8_t*>(p);
402
9
    nva[n].origin_len = strlen(p);
403
9
    p += nva[n].origin_len + 1;
404
  }
405
}
406
407
// Sets the various callback functions that nghttp2 will use to notify us
408
// about significant events while processing http2 stuff.
409
9356
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
410
  nghttp2_session_callbacks* callbacks_;
411
9356
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
412
9356
  callbacks.reset(callbacks_);
413
414
  nghttp2_session_callbacks_set_on_begin_headers_callback(
415
9356
    callbacks_, OnBeginHeadersCallback);
416
  nghttp2_session_callbacks_set_on_header_callback2(
417
9356
    callbacks_, OnHeaderCallback);
418
  nghttp2_session_callbacks_set_on_frame_recv_callback(
419
9356
    callbacks_, OnFrameReceive);
420
  nghttp2_session_callbacks_set_on_stream_close_callback(
421
9356
    callbacks_, OnStreamClose);
422
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
423
9356
    callbacks_, OnDataChunkReceived);
424
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
425
9356
    callbacks_, OnFrameNotSent);
426
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
427
9356
    callbacks_, OnInvalidHeader);
428
  nghttp2_session_callbacks_set_error_callback(
429
9356
    callbacks_, OnNghttpError);
430
  nghttp2_session_callbacks_set_send_data_callback(
431
9356
    callbacks_, OnSendData);
432
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
433
9356
    callbacks_, OnInvalidFrame);
434
  nghttp2_session_callbacks_set_on_frame_send_callback(
435
9356
    callbacks_, OnFrameSent);
436
437
9356
  if (kHasGetPaddingCallback) {
438
    nghttp2_session_callbacks_set_select_padding_callback(
439
4678
      callbacks_, OnSelectPadding);
440
  }
441
9356
}
442
443
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
444
  StopTrackingMemory(buf);
445
}
446
447
202535
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
448
202535
  CHECK_GE(current_nghttp2_memory_, previous_size);
449
202535
}
450
451
102216
void Http2Session::IncreaseAllocatedSize(size_t size) {
452
102216
  current_nghttp2_memory_ += size;
453
102216
}
454
455
125461
void Http2Session::DecreaseAllocatedSize(size_t size) {
456
125461
  current_nghttp2_memory_ -= size;
457
125461
}
458
459
658
Http2Session::Http2Session(Http2State* http2_state,
460
                           Local<Object> wrap,
461
658
                           SessionType type)
462
    : AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
463
      js_fields_(http2_state->env()->isolate()),
464
      session_type_(type),
465
1316
      http2_state_(http2_state) {
466
658
  MakeWeak();
467
658
  statistics_.start_time = uv_hrtime();
468
469
  // Capture the configuration options for this session
470
1316
  Http2Options opts(http2_state, type);
471
472
658
  max_session_memory_ = opts.max_session_memory();
473
474
658
  uint32_t maxHeaderPairs = opts.max_header_pairs();
475
658
  max_header_pairs_ =
476
      type == NGHTTP2_SESSION_SERVER
477
338
          ? GetServerMaxHeaderPairs(maxHeaderPairs)
478
996
          : GetClientMaxHeaderPairs(maxHeaderPairs);
479
480
658
  max_outstanding_pings_ = opts.max_outstanding_pings();
481
658
  max_outstanding_settings_ = opts.max_outstanding_settings();
482
483
658
  padding_strategy_ = opts.padding_strategy();
484
485
  bool hasGetPaddingCallback =
486
658
      padding_strategy_ != PADDING_STRATEGY_NONE;
487
488
658
  auto fn = type == NGHTTP2_SESSION_SERVER ?
489
      nghttp2_session_server_new3 :
490
658
      nghttp2_session_client_new3;
491
492
658
  nghttp2_mem alloc_info = MakeAllocator();
493
494
  // This should fail only if the system is out of memory, which
495
  // is going to cause lots of other problems anyway, or if any
496
  // of the options are out of acceptable range, which we should
497
  // be catching before it gets this far. Either way, crash if this
498
  // fails.
499
  nghttp2_session* session;
500

658
  CHECK_EQ(fn(
501
      &session,
502
      callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks.get(),
503
      this,
504
      *opts,
505
      &alloc_info), 0);
506
658
  session_.reset(session);
507
508
658
  outgoing_storage_.reserve(1024);
509
658
  outgoing_buffers_.reserve(32);
510
511
  Local<Uint8Array> uint8_arr =
512
658
      Uint8Array::New(js_fields_.GetArrayBuffer(), 0, kSessionUint8FieldCount);
513
1974
  USE(wrap->Set(env()->context(), env()->fields_string(), uint8_arr));
514
658
}
515
516
2632
Http2Session::~Http2Session() {
517
658
  CHECK(!is_in_scope());
518
658
  Debug(this, "freeing nghttp2 session");
519
  // Explicitly reset session_ so the subsequent
520
  // current_nghttp2_memory_ check passes.
521
658
  session_.reset();
522
658
  CHECK_EQ(current_nghttp2_memory_, 0);
523
1316
}
524
525
4
void Http2Session::MemoryInfo(MemoryTracker* tracker) const {
526
4
  tracker->TrackField("streams", streams_);
527
4
  tracker->TrackField("outstanding_pings", outstanding_pings_);
528
4
  tracker->TrackField("outstanding_settings", outstanding_settings_);
529
4
  tracker->TrackField("outgoing_buffers", outgoing_buffers_);
530
4
  tracker->TrackFieldWithSize("stream_buf", stream_buf_.len);
531
4
  tracker->TrackFieldWithSize("outgoing_storage", outgoing_storage_.size());
532
4
  tracker->TrackFieldWithSize("pending_rst_streams",
533
8
                              pending_rst_streams_.size() * sizeof(int32_t));
534
4
  tracker->TrackFieldWithSize("nghttp2_memory", current_nghttp2_memory_);
535
4
}
536
537
118
std::string Http2Session::diagnostic_name() const {
538
236
  return std::string("Http2Session ") + TypeName() + " (" +
539
354
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
540
}
541
542
23666
void Http2Stream::EmitStatistics() {
543
23666
  CHECK_NOT_NULL(session());
544
23666
  if (!HasHttp2Observer(env()))
545
23658
    return;
546
  auto entry =
547
      std::make_unique<Http2StreamPerformanceEntry>(
548
16
          session()->http2_state(), id_, statistics_);
549
48
  env()->SetImmediate([entry = move(entry)](Environment* env) {
550
8
    if (!HasHttp2Observer(env))
551
      return;
552
16
    HandleScope handle_scope(env->isolate());
553
8
    AliasedFloat64Array& buffer = entry->http2_state()->stream_stats_buffer;
554
8
    buffer[IDX_STREAM_STATS_ID] = entry->id();
555
8
    if (entry->first_byte() != 0) {
556
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] =
557
          (entry->first_byte() - entry->startTimeNano()) / 1e6;
558
    } else {
559
8
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0;
560
    }
561
8
    if (entry->first_header() != 0) {
562
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] =
563
8
          (entry->first_header() - entry->startTimeNano()) / 1e6;
564
    } else {
565
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0;
566
    }
567
8
    if (entry->first_byte_sent() != 0) {
568
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] =
569
4
          (entry->first_byte_sent() - entry->startTimeNano()) / 1e6;
570
    } else {
571
4
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0;
572
    }
573
    buffer[IDX_STREAM_STATS_SENTBYTES] =
574
8
        static_cast<double>(entry->sent_bytes());
575
    buffer[IDX_STREAM_STATS_RECEIVEDBYTES] =
576
8
        static_cast<double>(entry->received_bytes());
577
    Local<Object> obj;
578
24
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
579
8
  });
580
}
581
582
639
void Http2Session::EmitStatistics() {
583
639
  if (!HasHttp2Observer(env()))
584
632
    return;
585
  auto entry = std::make_unique<Http2SessionPerformanceEntry>(
586
14
      http2_state(), statistics_, session_type_);
587
42
  env()->SetImmediate([entry = std::move(entry)](Environment* env) {
588
7
    if (!HasHttp2Observer(env))
589
      return;
590
14
    HandleScope handle_scope(env->isolate());
591
7
    AliasedFloat64Array& buffer = entry->http2_state()->session_stats_buffer;
592
7
    buffer[IDX_SESSION_STATS_TYPE] = entry->type();
593
7
    buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6;
594
7
    buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count();
595
7
    buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent();
596
7
    buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count();
597
    buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] =
598
7
        entry->stream_average_duration();
599
    buffer[IDX_SESSION_STATS_DATA_SENT] =
600
7
        static_cast<double>(entry->data_sent());
601
    buffer[IDX_SESSION_STATS_DATA_RECEIVED] =
602
7
        static_cast<double>(entry->data_received());
603
    buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] =
604
7
        static_cast<double>(entry->max_concurrent_streams());
605
    Local<Object> obj;
606
21
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
607
7
  });
608
}
609
610
// Closes the session and frees the associated resources
611
639
void Http2Session::Close(uint32_t code, bool socket_closed) {
612
639
  Debug(this, "closing session");
613
614
639
  if (is_closing())
615
    return;
616
639
  set_closing();
617
618
  // Stop reading on the i/o stream
619
639
  if (stream_ != nullptr) {
620
629
    set_reading_stopped();
621
629
    stream_->ReadStop();
622
  }
623
624
  // If the socket is not closed, then attempt to send a closing GOAWAY
625
  // frame. There is no guarantee that this GOAWAY will be received by
626
  // the peer but the HTTP/2 spec recommends sending it anyway. We'll
627
  // make a best effort.
628
639
  if (!socket_closed) {
629
596
    Debug(this, "terminating session with code %d", code);
630
596
    CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
631
596
    SendPendingData();
632
43
  } else if (stream_ != nullptr) {
633
33
    stream_->RemoveStreamListener(this);
634
  }
635
636
639
  set_destroyed();
637
638
  // If we are writing we will get to make the callback in OnStreamAfterWrite.
639
639
  if (!is_write_in_progress()) {
640
597
    Debug(this, "make done session callback");
641
1194
    HandleScope scope(env()->isolate());
642
597
    MakeCallback(env()->ondone_string(), 0, nullptr);
643
  }
644
645
  // If there are outstanding pings, those will need to be canceled, do
646
  // so on the next iteration of the event loop to avoid calling out into
647
  // javascript since this may be called during garbage collection.
648
641
  while (BaseObjectPtr<Http2Ping> ping = PopPing()) {
649
1
    ping->DetachFromSession();
650
2
    env()->SetImmediate(
651
5
        [ping = std::move(ping)](Environment* env) {
652
1
          ping->Done(false);
653
2
        });
654
1
  }
655
656
639
  statistics_.end_time = uv_hrtime();
657
639
  EmitStatistics();
658
}
659
660
// Locates an existing known stream by ID. nghttp2 has a similar method
661
// but this is faster and does not fail if the stream is not found.
662
246351
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
663
246351
  auto s = streams_.find(id);
664
246351
  return s != streams_.end() ? s->second : BaseObjectPtr<Http2Stream>();
665
}
666
667
11990
bool Http2Session::CanAddStream() {
668
  uint32_t maxConcurrentStreams =
669
11990
      nghttp2_session_get_local_settings(
670
11990
          session_.get(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
671
  size_t maxSize =
672
11990
      std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
673
  // We can add a new stream so long as we are less than the current
674
  // maximum on concurrent streams and there's enough available memory
675

23980
  return streams_.size() < maxSize &&
676
23980
         has_available_session_memory(sizeof(Http2Stream));
677
}
678
679
23775
void Http2Session::AddStream(Http2Stream* stream) {
680
23775
  CHECK_GE(++statistics_.stream_count, 0);
681
23775
  streams_[stream->id()] = BaseObjectPtr<Http2Stream>(stream);
682
23775
  size_t size = streams_.size();
683
23775
  if (size > statistics_.max_concurrent_streams)
684
1417
    statistics_.max_concurrent_streams = size;
685
23775
  IncrementCurrentSessionMemory(sizeof(*stream));
686
23775
}
687
688
689
23666
BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
690
23666
  BaseObjectPtr<Http2Stream> stream;
691
23666
  if (streams_.empty())
692
    return stream;
693
23666
  stream = FindStream(id);
694
23666
  if (stream) {
695
23666
    streams_.erase(id);
696
23666
    DecrementCurrentSessionMemory(sizeof(*stream));
697
  }
698
23666
  return stream;
699
}
700
701
// Used as one of the Padding Strategy functions. Will attempt to ensure
702
// that the total frame size, including header bytes, are 8-byte aligned.
703
// If maxPayloadLen is smaller than the number of bytes necessary to align,
704
// will return maxPayloadLen instead.
705
3
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
706
                                            size_t maxPayloadLen) {
707
3
  size_t r = (frameLen + 9) % 8;
708
3
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
709
710
3
  size_t pad = frameLen + (8 - r);
711
712
  // If maxPayloadLen happens to be less than the calculated pad length,
713
  // use the max instead, even tho this means the frame will not be
714
  // aligned.
715
3
  pad = std::min(maxPayloadLen, pad);
716
3
  Debug(this, "using frame size padding: %d", pad);
717
3
  return pad;
718
}
719
720
// Used as one of the Padding Strategy functions. Uses the maximum amount
721
// of padding allowed for the current frame.
722
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
723
                                            size_t maxPayloadLen) {
724
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
725
  return maxPayloadLen;
726
}
727
728
// Write data received from the i/o stream to the underlying nghttp2_session.
729
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
730
// various callback functions. Each of these will typically result in a call
731
// out to JavaScript so this particular function is rather hot and can be
732
// quite expensive. This is a potential performance optimization target later.
733
31514
ssize_t Http2Session::ConsumeHTTP2Data() {
734
31514
  CHECK_NOT_NULL(stream_buf_.base);
735
31514
  CHECK_LE(stream_buf_offset_, stream_buf_.len);
736
31514
  size_t read_len = stream_buf_.len - stream_buf_offset_;
737
738
  // multiple side effects.
739
31514
  Debug(this, "receiving %d bytes [wants data? %d]",
740
        read_len,
741
63028
        nghttp2_session_want_read(session_.get()));
742
31514
  set_receive_paused(false);
743
  ssize_t ret =
744
63028
    nghttp2_session_mem_recv(session_.get(),
745
31514
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
746
31514
                                 stream_buf_offset_,
747
31514
                             read_len);
748
31514
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
749
750
31514
  if (is_receive_paused()) {
751
558
    CHECK(is_reading_stopped());
752
753
558
    CHECK_GT(ret, 0);
754
558
    CHECK_LE(static_cast<size_t>(ret), read_len);
755
756
    // Mark the remainder of the data as available for later consumption.
757
    // Even if all bytes were received, a paused stream may delay the
758
    // nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
759
558
    stream_buf_offset_ += ret;
760
558
    return ret;
761
  }
762
763
  // We are done processing the current input chunk.
764
30956
  DecrementCurrentSessionMemory(stream_buf_.len);
765
30956
  stream_buf_offset_ = 0;
766
30956
  stream_buf_ab_.Reset();
767
30956
  stream_buf_allocation_.clear();
768
30956
  stream_buf_ = uv_buf_init(nullptr, 0);
769
770
30956
  if (ret < 0)
771
6
    return ret;
772
773
  // Send any data that was queued up while processing the received data.
774
30950
  if (!is_destroyed()) {
775
30426
    SendPendingData();
776
  }
777
30950
  return ret;
778
}
779
780
781
143194
int32_t GetFrameID(const nghttp2_frame* frame) {
782
  // If this is a push promise, we want to grab the id of the promised stream
783
143194
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
784
      frame->push_promise.promised_stream_id :
785
143194
      frame->hd.stream_id;
786
}
787
788
789
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
790
// callback to determine if a new stream is being created or if we are simply
791
// adding a new block of headers to an existing stream. The header pairs
792
// themselves are set in the OnHeaderCallback
793
23692
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
794
                                         const nghttp2_frame* frame,
795
                                         void* user_data) {
796
23692
  Http2Session* session = static_cast<Http2Session*>(user_data);
797
23692
  int32_t id = GetFrameID(frame);
798
  Debug(session, "beginning headers for stream %d", id);
799
800
47384
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
801
  // The common case is that we're creating a new stream. The less likely
802
  // case is that we're receiving a set of trailers
803
23692
  if (LIKELY(!stream)) {
804

11990
    if (UNLIKELY(!session->CanAddStream() ||
805
                 Http2Stream::New(session, id, frame->headers.cat) ==
806
                     nullptr)) {
807
2
      if (session->rejected_stream_count_++ >
808
1
          session->js_fields_->max_rejected_streams)
809
        return NGHTTP2_ERR_CALLBACK_FAILURE;
810
      // Too many concurrent streams being opened
811
1
      nghttp2_submit_rst_stream(
812
          session->session(),
813
          NGHTTP2_FLAG_NONE,
814
          id,
815
2
          NGHTTP2_ENHANCE_YOUR_CALM);
816
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
817
    }
818
819
11989
    session->rejected_stream_count_ = 0;
820
11702
  } else if (!stream->is_destroyed()) {
821
11702
    stream->StartHeaders(frame->headers.cat);
822
  }
823
23691
  return 0;
824
}
825
826
// Called by nghttp2 for each header name/value pair in a HEADERS block.
827
// This had to have been preceded by a call to OnBeginHeadersCallback so
828
// the Http2Stream is guaranteed to already exist.
829
71872
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
830
                                   const nghttp2_frame* frame,
831
                                   nghttp2_rcbuf* name,
832
                                   nghttp2_rcbuf* value,
833
                                   uint8_t flags,
834
                                   void* user_data) {
835
71872
  Http2Session* session = static_cast<Http2Session*>(user_data);
836
71872
  int32_t id = GetFrameID(frame);
837
143744
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
838
  // If stream is null at this point, either something odd has happened
839
  // or the stream was closed locally while header processing was occurring.
840
  // either way, do not proceed and close the stream.
841
71872
  if (UNLIKELY(!stream))
842
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
843
844
  // If the stream has already been destroyed, ignore.
845

71872
  if (!stream->is_destroyed() && !stream->AddHeader(name, value, flags)) {
846
    // This will only happen if the connected peer sends us more
847
    // than the allowed number of header items at any given time
848
3
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
849
3
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
850
  }
851
71869
  return 0;
852
}
853
854
855
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
856
// only a handful of frame types that we care about handling here.
857
55689
int Http2Session::OnFrameReceive(nghttp2_session* handle,
858
                                 const nghttp2_frame* frame,
859
                                 void* user_data) {
860
55689
  Http2Session* session = static_cast<Http2Session*>(user_data);
861
55689
  session->statistics_.frame_count++;
862
55689
  Debug(session, "complete frame received: type: %d",
863
        frame->hd.type);
864


55689
  switch (frame->hd.type) {
865
    case NGHTTP2_DATA:
866
24171
      return session->HandleDataFrame(frame);
867
    case NGHTTP2_PUSH_PROMISE:
868
      // Intentional fall-through, handled just like headers frames
869
    case NGHTTP2_HEADERS:
870
23450
      session->HandleHeadersFrame(frame);
871
23450
      break;
872
    case NGHTTP2_SETTINGS:
873
2135
      session->HandleSettingsFrame(frame);
874
2135
      break;
875
    case NGHTTP2_PRIORITY:
876
16
      session->HandlePriorityFrame(frame);
877
16
      break;
878
    case NGHTTP2_GOAWAY:
879
306
      session->HandleGoawayFrame(frame);
880
306
      break;
881
    case NGHTTP2_PING:
882
1020
      session->HandlePingFrame(frame);
883
1020
      break;
884
    case NGHTTP2_ALTSVC:
885
4
      session->HandleAltSvcFrame(frame);
886
4
      break;
887
    case NGHTTP2_ORIGIN:
888
5
      session->HandleOriginFrame(frame);
889
5
      break;
890
    default:
891
4582
      break;
892
  }
893
31518
  return 0;
894
}
895
896
242
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
897
                                 const nghttp2_frame* frame,
898
                                 int lib_error_code,
899
                                 void* user_data) {
900
242
  Http2Session* session = static_cast<Http2Session*>(user_data);
901
902
242
  Debug(session,
903
        "invalid frame received (%u/%u), code: %d",
904
        session->invalid_frame_count_,
905
242
        session->js_fields_->max_invalid_frames,
906
        lib_error_code);
907
242
  if (session->invalid_frame_count_++ > session->js_fields_->max_invalid_frames)
908
2
    return 1;
909
910
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
911

480
  if (nghttp2_is_fatal(lib_error_code) ||
912
240
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
913
1
    Environment* env = session->env();
914
1
    Isolate* isolate = env->isolate();
915
2
    HandleScope scope(isolate);
916
1
    Local<Context> context = env->context();
917
    Context::Scope context_scope(context);
918
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
919
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
920
  }
921
240
  return 0;
922
}
923
924
// If nghttp2 is unable to send a queued up frame, it will call this callback
925
// to let us know. If the failure occurred because we are in the process of
926
// closing down the session or stream, we go ahead and ignore it. We don't
927
// really care about those and there's nothing we can reasonably do about it
928
// anyway. Other types of failures are reported up to JavaScript. This should
929
// be exceedingly rare.
930
2187
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
931
                                 const nghttp2_frame* frame,
932
                                 int error_code,
933
                                 void* user_data) {
934
2187
  Http2Session* session = static_cast<Http2Session*>(user_data);
935
2187
  Environment* env = session->env();
936
2187
  Debug(session, "frame type %d was not sent, code: %d",
937
        frame->hd.type, error_code);
938
939
  // Do not report if the frame was not sent due to the session closing
940

4378
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
941
7
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
942

2192
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
943
2
      session->js_fields_->frame_error_listener_count == 0) {
944
2186
    return 0;
945
  }
946
947
1
  Isolate* isolate = env->isolate();
948
2
  HandleScope scope(isolate);
949
1
  Local<Context> context = env->context();
950
  Context::Scope context_scope(context);
951
952
  Local<Value> argv[3] = {
953
1
    Integer::New(isolate, frame->hd.stream_id),
954
1
    Integer::New(isolate, frame->hd.type),
955
    Integer::New(isolate, error_code)
956
6
  };
957
  session->MakeCallback(
958
      env->http2session_on_frame_error_function(),
959
1
      arraysize(argv), argv);
960
1
  return 0;
961
}
962
963
55991
int Http2Session::OnFrameSent(nghttp2_session* handle,
964
                              const nghttp2_frame* frame,
965
                              void* user_data) {
966
55991
  Http2Session* session = static_cast<Http2Session*>(user_data);
967
55991
  session->statistics_.frame_sent += 1;
968
55991
  return 0;
969
}
970
971
// Called by nghttp2 when a stream closes.
972
23637
int Http2Session::OnStreamClose(nghttp2_session* handle,
973
                                int32_t id,
974
                                uint32_t code,
975
                                void* user_data) {
976
23637
  Http2Session* session = static_cast<Http2Session*>(user_data);
977
23637
  Environment* env = session->env();
978
23637
  Isolate* isolate = env->isolate();
979
47274
  HandleScope scope(isolate);
980
23637
  Local<Context> context = env->context();
981
  Context::Scope context_scope(context);
982
  Debug(session, "stream %d closed with code: %d", id, code);
983
47274
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
984
  // Intentionally ignore the callback if the stream does not exist or has
985
  // already been destroyed
986

23637
  if (!stream || stream->is_destroyed())
987
55
    return 0;
988
989
23582
  stream->Close(code);
990
991
  // It is possible for the stream close to occur before the stream is
992
  // ever passed on to the javascript side. If that happens, the callback
993
  // will return false.
994
23582
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
995
  MaybeLocal<Value> answer =
996
23582
    stream->MakeCallback(env->http2session_on_stream_close_function(),
997
47164
                          1, &arg);
998

70746
  if (answer.IsEmpty() || answer.ToLocalChecked()->IsFalse()) {
999
    // Skip to destroy
1000
138
    stream->Destroy();
1001
  }
1002
23582
  return 0;
1003
}
1004
1005
// Called by nghttp2 when an invalid header has been received. For now, we
1006
// ignore these. If this callback was not provided, nghttp2 would handle
1007
// invalid headers strictly and would shut down the stream. We are intentionally
1008
// being more lenient here although we may want to revisit this choice later.
1009
4
int Http2Session::OnInvalidHeader(nghttp2_session* session,
1010
                                  const nghttp2_frame* frame,
1011
                                  nghttp2_rcbuf* name,
1012
                                  nghttp2_rcbuf* value,
1013
                                  uint8_t flags,
1014
                                  void* user_data) {
1015
  // Ignore invalid header fields by default.
1016
4
  return 0;
1017
}
1018
1019
// When nghttp2 receives a DATA frame, it will deliver the data payload to
1020
// us in discrete chunks. We push these into a linked list stored in the
1021
// Http2Sttream which is flushed out to JavaScript as quickly as possible.
1022
// This can be a particularly hot path.
1023
13782
int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
1024
                                      uint8_t flags,
1025
                                      int32_t id,
1026
                                      const uint8_t* data,
1027
                                      size_t len,
1028
                                      void* user_data) {
1029
13782
  Http2Session* session = static_cast<Http2Session*>(user_data);
1030
  Debug(session, "buffering data chunk for stream %d, size: "
1031
        "%d, flags: %d", id, len, flags);
1032
13782
  Environment* env = session->env();
1033
27564
  HandleScope scope(env->isolate());
1034
1035
  // We should never actually get a 0-length chunk so this check is
1036
  // only a precaution at this point.
1037
13782
  if (len == 0)
1038
    return 0;
1039
1040
  // Notify nghttp2 that we've consumed a chunk of data on the connection
1041
  // so that it can send a WINDOW_UPDATE frame. This is a critical part of
1042
  // the flow control process in http2
1043
13782
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1044
27564
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1045
1046
  // If the stream has been destroyed, ignore this chunk
1047

13782
  if (!stream || stream->is_destroyed())
1048
1
    return 0;
1049
1050
13781
  stream->statistics_.received_bytes += len;
1051
1052
  // Repeatedly ask the stream's owner for memory, and copy the read data
1053
  // into those buffers.
1054
  // The typical case is actually the exception here; Http2StreamListeners
1055
  // know about the HTTP2 session associated with this stream, so they know
1056
  // about the larger from-socket read buffer, so they do not require copying.
1057
  do {
1058
13781
    uv_buf_t buf = stream->EmitAlloc(len);
1059
13781
    ssize_t avail = len;
1060
13781
    if (static_cast<ssize_t>(buf.len) < avail)
1061
      avail = buf.len;
1062
1063
    // `buf.base == nullptr` is the default Http2StreamListener's way
1064
    // of saying that it wants a pointer to the raw original.
1065
    // Since it has access to the original socket buffer from which the data
1066
    // was read in the first place, it can use that to minimize ArrayBuffer
1067
    // allocations.
1068
13781
    if (LIKELY(buf.base == nullptr))
1069
13781
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1070
    else
1071
      memcpy(buf.base, data, avail);
1072
13781
    data += avail;
1073
13781
    len -= avail;
1074
13781
    stream->EmitRead(avail, buf);
1075
1076
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1077
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1078
    // more data is being requested.
1079
13781
    if (stream->is_reading())
1080
12670
      nghttp2_session_consume_stream(handle, id, avail);
1081
    else
1082
1111
      stream->inbound_consumed_data_while_paused_ += avail;
1083
1084
    // If we have a gathered a lot of data for output, try sending it now.
1085

27562
    if (session->outgoing_length_ > 4096 ||
1086
13781
        stream->available_outbound_length_ > 4096) {
1087
4
      session->SendPendingData();
1088
    }
1089
13781
  } while (len != 0);
1090
1091
  // If we are currently waiting for a write operation to finish, we should
1092
  // tell nghttp2 that we want to wait before we process more input data.
1093
13781
  if (session->is_write_in_progress()) {
1094
558
    CHECK(session->is_reading_stopped());
1095
558
    session->set_receive_paused();
1096
    Debug(session, "receive paused");
1097
558
    return NGHTTP2_ERR_PAUSE;
1098
  }
1099
1100
13223
  return 0;
1101
}
1102
1103
// Called by nghttp2 when it needs to determine how much padding to use in
1104
// a DATA or HEADERS frame.
1105
3
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1106
                                      const nghttp2_frame* frame,
1107
                                      size_t maxPayloadLen,
1108
                                      void* user_data) {
1109
3
  Http2Session* session = static_cast<Http2Session*>(user_data);
1110
3
  ssize_t padding = frame->hd.length;
1111
1112

3
  switch (session->padding_strategy_) {
1113
    case PADDING_STRATEGY_NONE:
1114
      // Fall-through
1115
      break;
1116
    case PADDING_STRATEGY_MAX:
1117
      padding = session->OnMaxFrameSizePadding(padding, maxPayloadLen);
1118
      break;
1119
    case PADDING_STRATEGY_ALIGNED:
1120
3
      padding = session->OnDWordAlignedPadding(padding, maxPayloadLen);
1121
3
      break;
1122
  }
1123
3
  return padding;
1124
}
1125
1126
#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we "     \
1127
                         "expected SETTINGS frame.  Perhaps, peer does not "  \
1128
                         "support HTTP/2 properly."
1129
1130
// We use this currently to determine when an attempt is made to use the http2
1131
// protocol with a non-http2 peer.
1132
239
int Http2Session::OnNghttpError(nghttp2_session* handle,
1133
                                const char* message,
1134
                                size_t len,
1135
                                void* user_data) {
1136
  // Unfortunately, this is currently the only way for us to know if
1137
  // the session errored because the peer is not an http2 peer.
1138
239
  Http2Session* session = static_cast<Http2Session*>(user_data);
1139
  Debug(session, "Error '%s'", message);
1140
239
  if (strncmp(message, BAD_PEER_MESSAGE, len) == 0) {
1141
1
    Environment* env = session->env();
1142
1
    Isolate* isolate = env->isolate();
1143
2
    HandleScope scope(isolate);
1144
1
    Local<Context> context = env->context();
1145
    Context::Scope context_scope(context);
1146
1
    Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1147
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1148
  }
1149
239
  return 0;
1150
}
1151
1152
13781
uv_buf_t Http2StreamListener::OnStreamAlloc(size_t size) {
1153
  // See the comments in Http2Session::OnDataChunkReceived
1154
  // (which is the only possible call site for this method).
1155
13781
  return uv_buf_init(nullptr, size);
1156
}
1157
1158
26443
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1159
26443
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1160
26443
  Http2Session* session = stream->session();
1161
26443
  Environment* env = stream->env();
1162
40224
  HandleScope handle_scope(env->isolate());
1163
40224
  Context::Scope context_scope(env->context());
1164
1165
26443
  if (nread < 0) {
1166
12662
    PassReadErrorToPreviousListener(nread);
1167
12662
    return;
1168
  }
1169
1170
  Local<ArrayBuffer> ab;
1171
27562
  if (session->stream_buf_ab_.IsEmpty()) {
1172
5625
    ab = session->stream_buf_allocation_.ToArrayBuffer();
1173
5625
    session->stream_buf_ab_.Reset(env->isolate(), ab);
1174
  } else {
1175
8156
    ab = PersistentToLocal::Strong(session->stream_buf_ab_);
1176
  }
1177
1178
  // There is a single large array buffer for the entire data read from the
1179
  // network; create a slice of that array buffer and emit it as the
1180
  // received data buffer.
1181
13781
  size_t offset = buf.base - session->stream_buf_.base;
1182
1183
  // Verify that the data offset is inside the current read buffer.
1184
13781
  CHECK_GE(offset, session->stream_buf_offset_);
1185
13781
  CHECK_LE(offset, session->stream_buf_.len);
1186
13781
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1187
1188
13781
  stream->CallJSOnreadMethod(nread, ab, offset);
1189
}
1190
1191
1192
// Called by OnFrameReceived to notify JavaScript land that a complete
1193
// HEADERS frame has been received and processed. This method converts the
1194
// received headers into a JavaScript array and pushes those out to JS.
1195
23450
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1196
23450
  Isolate* isolate = env()->isolate();
1197
46900
  HandleScope scope(isolate);
1198
23450
  Local<Context> context = env()->context();
1199
23450
  Context::Scope context_scope(context);
1200
1201
23450
  int32_t id = GetFrameID(frame);
1202
23450
  Debug(this, "handle headers frame for stream %d", id);
1203
46900
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1204
1205
  // If the stream has already been destroyed, ignore.
1206

23450
  if (!stream || stream->is_destroyed())
1207
    return;
1208
1209
  // The headers are stored as a vector of Http2Header instances.
1210
  // The following converts that into a JS array with the structure:
1211
  // [name1, value1, name2, value2, name3, value3, name3, value4] and so on.
1212
  // That array is passed up to the JS layer and converted into an Object form
1213
  // like {name1: value1, name2: value2, name3: [value3, value4]}. We do it
1214
  // this way for performance reasons (it's faster to generate and pass an
1215
  // array than it is to generate and pass the object).
1216
1217
46900
  MaybeStackBuffer<Local<Value>, 64> headers_v(stream->headers_count() * 2);
1218
46900
  MaybeStackBuffer<Local<Value>, 32> sensitive_v(stream->headers_count());
1219
23450
  size_t sensitive_count = 0;
1220
1221
118658
  stream->TransferHeaders([&](const Http2Header& header, size_t i) {
1222
287037
    headers_v[i * 2] = header.GetName(this).ToLocalChecked();
1223
287032
    headers_v[i * 2 + 1] = header.GetValue(this).ToLocalChecked();
1224
71758
    if (header.flags() & NGHTTP2_NV_FLAG_NO_INDEX)
1225
10
      sensitive_v[sensitive_count++] = headers_v[i * 2];
1226
95208
  });
1227
23450
  CHECK_EQ(stream->headers_count(), 0);
1228
1229
23450
  DecrementCurrentSessionMemory(stream->current_headers_length_);
1230
23450
  stream->current_headers_length_ = 0;
1231
1232
  Local<Value> args[] = {
1233
23450
    stream->object(),
1234
    Integer::New(isolate, id),
1235
23450
    Integer::New(isolate, stream->headers_category()),
1236
23450
    Integer::New(isolate, frame->hd.flags),
1237
    Array::New(isolate, headers_v.out(), headers_v.length()),
1238
    Array::New(isolate, sensitive_v.out(), sensitive_count),
1239
234500
  };
1240
  MakeCallback(env()->http2session_on_headers_function(),
1241
23450
               arraysize(args), args);
1242
}
1243
1244
1245
// Called by OnFrameReceived when a complete PRIORITY frame has been
1246
// received. Notifies JS land about the priority change. Note that priorities
1247
// are considered advisory only, so this has no real effect other than to
1248
// simply let user code know that the priority has changed.
1249
16
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
1250
16
  if (js_fields_->priority_listener_count == 0) return;
1251
5
  Isolate* isolate = env()->isolate();
1252
10
  HandleScope scope(isolate);
1253
5
  Local<Context> context = env()->context();
1254
  Context::Scope context_scope(context);
1255
1256
5
  nghttp2_priority priority_frame = frame->priority;
1257
5
  int32_t id = GetFrameID(frame);
1258
5
  Debug(this, "handle priority frame for stream %d", id);
1259
  // Priority frame stream ID should never be <= 0. nghttp2 handles this for us
1260
5
  nghttp2_priority_spec spec = priority_frame.pri_spec;
1261
1262
  Local<Value> argv[4] = {
1263
    Integer::New(isolate, id),
1264
    Integer::New(isolate, spec.stream_id),
1265
    Integer::New(isolate, spec.weight),
1266
5
    Boolean::New(isolate, spec.exclusive)
1267
30
  };
1268
  MakeCallback(env()->http2session_on_priority_function(),
1269
5
               arraysize(argv), argv);
1270
}
1271
1272
1273
// Called by OnFrameReceived when a complete DATA frame has been received.
1274
// If we know that this was the last DATA frame (because the END_STREAM flag
1275
// is set), then we'll terminate the readable side of the StreamBase.
1276
24171
int Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1277
24171
  int32_t id = GetFrameID(frame);
1278
24171
  Debug(this, "handling data frame for stream %d", id);
1279
48342
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1280
1281

48342
  if (stream &&
1282

48342
      !stream->is_destroyed() &&
1283
24171
      frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1284
12662
    stream->EmitRead(UV_EOF);
1285
11509
  } else if (frame->hd.length == 0) {
1286
    return 1;  // Consider 0-length frame without END_STREAM an error.
1287
  }
1288
24171
  return 0;
1289
}
1290
1291
1292
// Called by OnFrameReceived when a complete GOAWAY frame has been received.
1293
306
void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
1294
306
  Isolate* isolate = env()->isolate();
1295
612
  HandleScope scope(isolate);
1296
306
  Local<Context> context = env()->context();
1297
  Context::Scope context_scope(context);
1298
1299
306
  nghttp2_goaway goaway_frame = frame->goaway;
1300
306
  Debug(this, "handling goaway frame");
1301
1302
  Local<Value> argv[3] = {
1303
    Integer::NewFromUnsigned(isolate, goaway_frame.error_code),
1304
    Integer::New(isolate, goaway_frame.last_stream_id),
1305
    Undefined(isolate)
1306
1224
  };
1307
1308
306
  size_t length = goaway_frame.opaque_data_len;
1309
306
  if (length > 0) {
1310
    // If the copy fails for any reason here, we just ignore it.
1311
    // The additional goaway data is completely optional and we
1312
    // shouldn't fail if we're not able to process it.
1313
9
    argv[2] = Buffer::Copy(isolate,
1314
3
                           reinterpret_cast<char*>(goaway_frame.opaque_data),
1315
3
                           length).ToLocalChecked();
1316
  }
1317
1318
  MakeCallback(env()->http2session_on_goaway_data_function(),
1319
306
               arraysize(argv), argv);
1320
306
}
1321
1322
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
1323
4
void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
1324
4
  if (!(js_fields_->bitfield & (1 << kSessionHasAltsvcListeners))) return;
1325
4
  Isolate* isolate = env()->isolate();
1326
8
  HandleScope scope(isolate);
1327
4
  Local<Context> context = env()->context();
1328
  Context::Scope context_scope(context);
1329
1330
4
  int32_t id = GetFrameID(frame);
1331
1332
4
  nghttp2_extension ext = frame->ext;
1333
4
  nghttp2_ext_altsvc* altsvc = static_cast<nghttp2_ext_altsvc*>(ext.payload);
1334
4
  Debug(this, "handling altsvc frame");
1335
1336
  Local<Value> argv[3] = {
1337
    Integer::New(isolate, id),
1338
8
    OneByteString(isolate, altsvc->origin, altsvc->origin_len),
1339
8
    OneByteString(isolate, altsvc->field_value, altsvc->field_value_len)
1340
32
  };
1341
1342
  MakeCallback(env()->http2session_on_altsvc_function(),
1343
4
               arraysize(argv), argv);
1344
}
1345
1346
5
void Http2Session::HandleOriginFrame(const nghttp2_frame* frame) {
1347
5
  Isolate* isolate = env()->isolate();
1348
10
  HandleScope scope(isolate);
1349
5
  Local<Context> context = env()->context();
1350
  Context::Scope context_scope(context);
1351
1352
5
  Debug(this, "handling origin frame");
1353
1354
5
  nghttp2_extension ext = frame->ext;
1355
5
  nghttp2_ext_origin* origin = static_cast<nghttp2_ext_origin*>(ext.payload);
1356
1357
5
  size_t nov = origin->nov;
1358
10
  std::vector<Local<Value>> origin_v(nov);
1359
1360
14
  for (size_t i = 0; i < nov; ++i) {
1361
9
    const nghttp2_origin_entry& entry = origin->ov[i];
1362
18
    origin_v[i] = OneByteString(isolate, entry.origin, entry.origin_len);
1363
  }
1364
5
  Local<Value> holder = Array::New(isolate, origin_v.data(), origin_v.size());
1365
5
  MakeCallback(env()->http2session_on_origin_function(), 1, &holder);
1366
5
}
1367
1368
// Called by OnFrameReceived when a complete PING frame has been received.
1369
1020
void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
1370
1020
  Isolate* isolate = env()->isolate();
1371
1022
  HandleScope scope(isolate);
1372
1020
  Local<Context> context = env()->context();
1373
2
  Context::Scope context_scope(context);
1374
  Local<Value> arg;
1375
1020
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1376
1020
  if (ack) {
1377
22
    BaseObjectPtr<Http2Ping> ping = PopPing();
1378
1379
11
    if (!ping) {
1380
      // PING Ack is unsolicited. Treat as a connection error. The HTTP/2
1381
      // spec does not require this, but there is no legitimate reason to
1382
      // receive an unsolicited PING ack on a connection. Either the peer
1383
      // is buggy or malicious, and we're not going to tolerate such
1384
      // nonsense.
1385
2
      arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1386
1
      MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1387
1
      return;
1388
    }
1389
1390
10
    ping->Done(true, frame->ping.opaque_data);
1391
10
    return;
1392
  }
1393
1394
1009
  if (!(js_fields_->bitfield & (1 << kSessionHasPingListeners))) return;
1395
  // Notify the session that a ping occurred
1396
6
  arg = Buffer::Copy(
1397
      env(),
1398
      reinterpret_cast<const char*>(frame->ping.opaque_data),
1399
4
      8).ToLocalChecked();
1400
2
  MakeCallback(env()->http2session_on_ping_function(), 1, &arg);
1401
}
1402
1403
// Called by OnFrameReceived when a complete SETTINGS frame has been received.
1404
2135
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
1405
2135
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1406
2135
  if (!ack) {
1407
1599
    js_fields_->bitfield &= ~(1 << kSessionRemoteSettingsIsUpToDate);
1408
1599
    if (!(js_fields_->bitfield & (1 << kSessionHasRemoteSettingsListeners)))
1409
3721
      return;
1410
    // This is not a SETTINGS acknowledgement, notify and return
1411
13
    MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
1412
13
    return;
1413
  }
1414
1415
  // If this is an acknowledgement, we should have an Http2Settings
1416
  // object for it.
1417
536
  BaseObjectPtr<Http2Settings> settings = PopSettings();
1418
536
  if (settings) {
1419
536
    settings->Done(true);
1420
536
    return;
1421
  }
1422
  // SETTINGS Ack is unsolicited. Treat as a connection error. The HTTP/2
1423
  // spec does not require this, but there is no legitimate reason to
1424
  // receive an unsolicited SETTINGS ack on a connection. Either the peer
1425
  // is buggy or malicious, and we're not going to tolerate such
1426
  // nonsense.
1427
  // Note that nghttp2 currently prevents this from happening for SETTINGS
1428
  // frames, so this block is purely defensive just in case that behavior
1429
  // changes. Specifically, unlike unsolicited PING acks, unsolicited
1430
  // SETTINGS acks should *never* make it this far.
1431
  Isolate* isolate = env()->isolate();
1432
  HandleScope scope(isolate);
1433
  Local<Context> context = env()->context();
1434
  Context::Scope context_scope(context);
1435
  Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1436
  MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1437
}
1438
1439
// Callback used when data has been written to the stream.
1440
1558
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
1441
1558
  Debug(this, "write finished with status %d", status);
1442
1443
1558
  CHECK(is_write_in_progress());
1444
1558
  set_write_in_progress(false);
1445
1446
  // Inform all pending writes about their completion.
1447
1558
  ClearOutgoing(status);
1448
1449

4672
  if (is_reading_stopped() &&
1450

3110
      !is_write_in_progress() &&
1451
1552
      nghttp2_session_want_read(session_.get())) {
1452
1512
    set_reading_stopped(false);
1453
1512
    stream_->ReadStart();
1454
  }
1455
1456
1558
  if (is_destroyed()) {
1457
82
    HandleScope scope(env()->isolate());
1458
41
    MakeCallback(env()->ondone_string(), 0, nullptr);
1459
41
    return;
1460
  }
1461
1462
  // If there is more incoming data queued up, consume it.
1463
1517
  if (stream_buf_offset_ > 0) {
1464
300
    ConsumeHTTP2Data();
1465
  }
1466
1467
1517
  if (!is_write_scheduled()) {
1468
    // Schedule a new write if nghttp2 wants to send data.
1469
1410
    MaybeScheduleWrite();
1470
  }
1471
}
1472
1473
// If the underlying nghttp2_session struct has data pending in its outbound
1474
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1475
// on the next iteration of the Node.js event loop (using the SetImmediate
1476
// queue), but only if a write has not already been scheduled.
1477
34139
void Http2Session::MaybeScheduleWrite() {
1478
34139
  CHECK(!is_write_scheduled());
1479
34139
  if (UNLIKELY(!session_))
1480
    return;
1481
1482
34139
  if (nghttp2_session_want_write(session_.get())) {
1483
3528
    HandleScope handle_scope(env()->isolate());
1484
1764
    Debug(this, "scheduling write");
1485
1764
    set_write_scheduled();
1486
3528
    BaseObjectPtr<Http2Session> strong_ref{this};
1487
15292
    env()->SetImmediate([this, strong_ref](Environment* env) {
1488

3528
      if (!session_ || !is_write_scheduled()) {
1489
        // This can happen e.g. when a stream was reset before this turn
1490
        // of the event loop, in which case SendPendingData() is called early,
1491
        // or the session was destroyed in the meantime.
1492
292
        return;
1493
      }
1494
1495
      // Sending data may call arbitrary JS code, so keep track of
1496
      // async context.
1497
2944
      HandleScope handle_scope(env->isolate());
1498
2944
      InternalCallbackScope callback_scope(this);
1499
1472
      SendPendingData();
1500
1764
    });
1501
  }
1502
}
1503
1504
62650
void Http2Session::MaybeStopReading() {
1505
62650
  if (is_reading_stopped()) return;
1506
59999
  int want_read = nghttp2_session_want_read(session_.get());
1507
59999
  Debug(this, "wants read? %d", want_read);
1508

59999
  if (want_read == 0 || is_write_in_progress()) {
1509
1523
    set_reading_stopped();
1510
1523
    stream_->ReadStop();
1511
  }
1512
}
1513
1514
// Unset the sending state, finish up all current writes, and reset
1515
// storage for data and metadata that was associated with these writes.
1516
32450
void Http2Session::ClearOutgoing(int status) {
1517
32450
  CHECK(is_sending());
1518
1519
32450
  set_sending(false);
1520
1521
32450
  if (!outgoing_buffers_.empty()) {
1522
31449
    outgoing_storage_.clear();
1523
31449
    outgoing_length_ = 0;
1524
1525
62898
    std::vector<NgHttp2StreamWrite> current_outgoing_buffers_;
1526
31449
    current_outgoing_buffers_.swap(outgoing_buffers_);
1527
125513
    for (const NgHttp2StreamWrite& wr : current_outgoing_buffers_) {
1528
188128
      BaseObjectPtr<AsyncWrap> wrap = std::move(wr.req_wrap);
1529
94064
      if (wrap) {
1530
        // TODO(addaleax): Pass `status` instead of 0, so that we actually error
1531
        // out with the error from the write to the underlying protocol,
1532
        // if one occurred.
1533
4016
        WriteWrap::FromObject(wrap)->Done(0);
1534
      }
1535
    }
1536
  }
1537
1538
  // Now that we've finished sending queued data, if there are any pending
1539
  // RstStreams we should try sending again and then flush them one by one.
1540
32450
  if (!pending_rst_streams_.empty()) {
1541
12
    std::vector<int32_t> current_pending_rst_streams;
1542
6
    pending_rst_streams_.swap(current_pending_rst_streams);
1543
1544
6
    SendPendingData();
1545
1546
14
    for (int32_t stream_id : current_pending_rst_streams) {
1547
16
      BaseObjectPtr<Http2Stream> stream = FindStream(stream_id);
1548
8
      if (LIKELY(stream))
1549
1
        stream->FlushRstStream();
1550
    }
1551
  }
1552
32450
}
1553
1554
94076
void Http2Session::PushOutgoingBuffer(NgHttp2StreamWrite&& write) {
1555
94076
  outgoing_length_ += write.buf.len;
1556
94076
  outgoing_buffers_.emplace_back(std::move(write));
1557
94076
}
1558
1559
// Queue a given block of data for sending. This always creates a copy,
1560
// so it is used for the cases in which nghttp2 requests sending of a
1561
// small chunk of data.
1562
56312
void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
1563
56312
  size_t offset = outgoing_storage_.size();
1564
56312
  outgoing_storage_.resize(offset + src_length);
1565
56312
  memcpy(&outgoing_storage_[offset], src, src_length);
1566
1567
  // Store with a base of `nullptr` initially, since future resizes
1568
  // of the outgoing_buffers_ vector may invalidate the pointer.
1569
  // The correct base pointers will be set later, before writing to the
1570
  // underlying socket.
1571
112624
  PushOutgoingBuffer(NgHttp2StreamWrite {
1572
    uv_buf_init(nullptr, src_length)
1573
56312
  });
1574
56312
}
1575
1576
// Prompts nghttp2 to begin serializing it's pending data and pushes each
1577
// chunk out to the i/o socket to be sent. This is a particularly hot method
1578
// that will generally be called at least twice be event loop iteration.
1579
// This is a potential performance optimization target later.
1580
// Returns non-zero value if a write is already in progress.
1581
32622
uint8_t Http2Session::SendPendingData() {
1582
32622
  Debug(this, "sending pending data");
1583
  // Do not attempt to send data on the socket if the destroying flag has
1584
  // been set. That means everything is shutting down and the socket
1585
  // will not be usable.
1586
32622
  if (is_destroyed())
1587
40
    return 0;
1588
32582
  set_write_scheduled(false);
1589
1590
  // SendPendingData should not be called recursively.
1591
32582
  if (is_sending())
1592
128
    return 1;
1593
  // This is cleared by ClearOutgoing().
1594
32454
  set_sending();
1595
1596
  ssize_t src_length;
1597
  const uint8_t* src;
1598
1599
32454
  CHECK(outgoing_buffers_.empty());
1600
32454
  CHECK(outgoing_storage_.empty());
1601
1602
  // Part One: Gather data from nghttp2
1603
1604
42300
  while ((src_length = nghttp2_session_mem_send(session_.get(), &src)) > 0) {
1605
42300
    Debug(this, "nghttp2 has %d bytes to send", src_length);
1606
42300
    CopyDataIntoOutgoing(src, src_length);
1607
  }
1608
1609
32454
  CHECK_NE(src_length, NGHTTP2_ERR_NOMEM);
1610
1611
32454
  if (stream_ == nullptr) {
1612
    // It would seem nice to bail out earlier, but `nghttp2_session_mem_send()`
1613
    // does take care of things like closing the individual streams after
1614
    // a socket has been torn down, so we still need to call it.
1615
11
    ClearOutgoing(UV_ECANCELED);
1616
11
    return 0;
1617
  }
1618
1619
  // Part Two: Pass Data to the underlying stream
1620
1621
32443
  size_t count = outgoing_buffers_.size();
1622
32443
  if (count == 0) {
1623
1001
    ClearOutgoing(0);
1624
1001
    return 0;
1625
  }
1626
62884
  MaybeStackBuffer<uv_buf_t, 32> bufs;
1627
31442
  bufs.AllocateSufficientStorage(count);
1628
1629
  // Set the buffer base pointers for copied data that ended up in the
1630
  // sessions's own storage since it might have shifted around during gathering.
1631
  // (Those are marked by having .base == nullptr.)
1632
31442
  size_t offset = 0;
1633
31442
  size_t i = 0;
1634
125502
  for (const NgHttp2StreamWrite& write : outgoing_buffers_) {
1635
94060
    statistics_.data_sent += write.buf.len;
1636
94060
    if (write.buf.base == nullptr) {
1637
56296
      bufs[i++] = uv_buf_init(
1638
56296
          reinterpret_cast<char*>(outgoing_storage_.data() + offset),
1639
112592
          write.buf.len);
1640
56296
      offset += write.buf.len;
1641
    } else {
1642
37764
      bufs[i++] = write.buf;
1643
    }
1644
  }
1645
1646
31442
  chunks_sent_since_last_write_++;
1647
1648
31442
  CHECK(!is_write_in_progress());
1649
31442
  set_write_in_progress();
1650
31442
  StreamWriteResult res = underlying_stream()->Write(*bufs, count);
1651
31442
  if (!res.async) {
1652
29880
    set_write_in_progress(false);
1653
29880
    ClearOutgoing(res.err);
1654
  }
1655
1656
31442
  MaybeStopReading();
1657
1658
31442
  return 0;
1659
}
1660
1661
1662
// This callback is called from nghttp2 when it wants to send DATA frames for a
1663
// given Http2Stream, when we set the `NGHTTP2_DATA_FLAG_NO_COPY` flag earlier
1664
// in the Http2Stream::Provider::Stream::OnRead callback.
1665
// We take the write information directly out of the stream's data queue.
1666
14011
int Http2Session::OnSendData(
1667
      nghttp2_session* session_,
1668
      nghttp2_frame* frame,
1669
      const uint8_t* framehd,
1670
      size_t length,
1671
      nghttp2_data_source* source,
1672
      void* user_data) {
1673
14011
  Http2Session* session = static_cast<Http2Session*>(user_data);
1674
28022
  BaseObjectPtr<Http2Stream> stream = session->FindStream(frame->hd.stream_id);
1675
14011
  if (!stream) return 0;
1676
1677
  // Send the frame header + a byte that indicates padding length.
1678
14011
  session->CopyDataIntoOutgoing(framehd, 9);
1679
14011
  if (frame->data.padlen > 0) {
1680
1
    uint8_t padding_byte = frame->data.padlen - 1;
1681
1
    CHECK_EQ(padding_byte, frame->data.padlen - 1);
1682
1
    session->CopyDataIntoOutgoing(&padding_byte, 1);
1683
  }
1684
1685
  Debug(session, "nghttp2 has %d bytes to send directly", length);
1686
69551
  while (length > 0) {
1687
    // nghttp2 thinks that there is data available (length > 0), which means
1688
    // we told it so, which means that we *should* have data available.
1689
37763
    CHECK(!stream->queue_.empty());
1690
1691
37763
    NgHttp2StreamWrite& write = stream->queue_.front();
1692
37763
    if (write.buf.len <= length) {
1693
      // This write does not suffice by itself, so we can consume it completely.
1694
27770
      length -= write.buf.len;
1695
27770
      session->PushOutgoingBuffer(std::move(write));
1696
27770
      stream->queue_.pop();
1697
27770
      continue;
1698
    }
1699
1700
    // Slice off `length` bytes of the first write in the queue.
1701
19986
    session->PushOutgoingBuffer(NgHttp2StreamWrite {
1702
      uv_buf_init(write.buf.base, length)
1703
9993
    });
1704
9993
    write.buf.base += length;
1705
9993
    write.buf.len -= length;
1706
9993
    break;
1707
  }
1708
1709
14011
  if (frame->data.padlen > 0) {
1710
    // Send padding if that was requested.
1711
2
    session->PushOutgoingBuffer(NgHttp2StreamWrite {
1712
1
      uv_buf_init(const_cast<char*>(zero_bytes_256), frame->data.padlen - 1)
1713
1
    });
1714
  }
1715
1716
14011
  return 0;
1717
}
1718
1719
// Creates a new Http2Stream and submits a new http2 request.
1720
11778
Http2Stream* Http2Session::SubmitRequest(
1721
    const Http2Priority& priority,
1722
    const Http2Headers& headers,
1723
    int32_t* ret,
1724
    int options) {
1725
11778
  Debug(this, "submitting request");
1726
23556
  Http2Scope h2scope(this);
1727
11778
  Http2Stream* stream = nullptr;
1728
23556
  Http2Stream::Provider::Stream prov(options);
1729
11778
  *ret = nghttp2_submit_request(
1730
      session_.get(),
1731
      &priority,
1732
      headers.data(),
1733
      headers.length(),
1734
11778
      *prov,
1735
      nullptr);
1736
11778
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
1737
11778
  if (LIKELY(*ret > 0))
1738
11777
    stream = Http2Stream::New(this, *ret, NGHTTP2_HCAT_HEADERS, options);
1739
23556
  return stream;
1740
}
1741
1742
31236
uv_buf_t Http2Session::OnStreamAlloc(size_t suggested_size) {
1743
31236
  return AllocatedBuffer::AllocateManaged(env(), suggested_size).release();
1744
}
1745
1746
// Callback used to receive inbound data from the i/o stream
1747
31260
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
1748
62468
  HandleScope handle_scope(env()->isolate());
1749
62468
  Context::Scope context_scope(env()->context());
1750
62468
  Http2Scope h2scope(this);
1751
31260
  CHECK_NOT_NULL(stream_);
1752
31260
  Debug(this, "receiving %d bytes, offset %d", nread, stream_buf_offset_);
1753
62468
  AllocatedBuffer buf(env(), buf_);
1754
1755
  // Only pass data on if nread > 0
1756
31260
  if (nread <= 0) {
1757
46
    if (nread < 0) {
1758
46
      PassReadErrorToPreviousListener(nread);
1759
    }
1760
46
    return;
1761
  }
1762
1763
31214
  statistics_.data_received += nread;
1764
1765
31214
  if (LIKELY(stream_buf_offset_ == 0)) {
1766
    // Shrink to the actual amount of used data.
1767
30957
    buf.Resize(nread);
1768
  } else {
1769
    // This is a very unlikely case, and should only happen if the ReadStart()
1770
    // call in OnStreamAfterWrite() immediately provides data. If that does
1771
    // happen, we concatenate the data we received with the already-stored
1772
    // pending input data, slicing off the already processed part.
1773
257
    size_t pending_len = stream_buf_.len - stream_buf_offset_;
1774
    AllocatedBuffer new_buf =
1775
514
        AllocatedBuffer::AllocateManaged(env(), pending_len + nread);
1776
257
    memcpy(new_buf.data(), stream_buf_.base + stream_buf_offset_, pending_len);
1777
257
    memcpy(new_buf.data() + pending_len, buf.data(), nread);
1778
1779
257
    buf = std::move(new_buf);
1780
257
    nread = buf.size();
1781
257
    stream_buf_offset_ = 0;
1782
257
    stream_buf_ab_.Reset();
1783
1784
    // We have now fully processed the stream_buf_ input chunk (by moving the
1785
    // remaining part into buf, which will be accounted for below).
1786
257
    DecrementCurrentSessionMemory(stream_buf_.len);
1787
  }
1788
1789
31214
  IncrementCurrentSessionMemory(nread);
1790
1791
  // Remember the current buffer, so that OnDataChunkReceived knows the
1792
  // offset of a DATA frame's data into the socket read buffer.
1793
31214
  stream_buf_ = uv_buf_init(buf.data(), static_cast<unsigned int>(nread));
1794
1795
31214
  Isolate* isolate = env()->isolate();
1796
1797
  // Store this so we can create an ArrayBuffer for read data from it.
1798
  // DATA frames will be emitted as slices of that ArrayBuffer to avoid having
1799
  // to copy memory.
1800
31214
  stream_buf_allocation_ = std::move(buf);
1801
1802
31214
  ssize_t ret = ConsumeHTTP2Data();
1803
1804
31214
  if (UNLIKELY(ret < 0)) {
1805
6
    Debug(this, "fatal error receiving data: %d", ret);
1806
6
    Local<Value> arg = Integer::New(isolate, static_cast<int32_t>(ret));
1807
6
    MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1808
6
    return;
1809
  }
1810
1811
31208
  MaybeStopReading();
1812
}
1813
1814
23656
bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
1815
23928
  for (const NgHttp2StreamWrite& wr : outgoing_buffers_) {
1816


333
    if (wr.req_wrap && WriteWrap::FromObject(wr.req_wrap)->stream() == stream)
1817
61
      return true;
1818
  }
1819
23595
  return false;
1820
}
1821
1822
// Every Http2Session session is tightly bound to a single i/o StreamBase
1823
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1824
// tightly coupled with all data transfer between the two happening at the
1825
// C++ layer via the StreamBase API.
1826
658
void Http2Session::Consume(Local<Object> stream_obj) {
1827
658
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1828
658
  stream->PushStreamListener(this);
1829
658
  Debug(this, "i/o stream consumed");
1830
658
}
1831
1832
// Allow injecting of data from JS
1833
// This is used when the socket has already some data received
1834
// before our listener was attached
1835
// https://github.com/nodejs/node/issues/35475
1836
2
void Http2Session::Receive(const FunctionCallbackInfo<Value>& args) {
1837
  Http2Session* session;
1838
2
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
1839
4
  CHECK(args[0]->IsObject());
1840
1841
2
  ArrayBufferViewContents<char> buffer(args[0]);
1842
2
  const char* data = buffer.data();
1843
2
  size_t len = buffer.length();
1844
2
  Debug(session, "Receiving %zu bytes injected from JS", len);
1845
1846
  // Copy given buffer
1847
6
  while (len > 0) {
1848
2
    uv_buf_t buf = session->OnStreamAlloc(len);
1849
2
    size_t copy = buf.len > len ? len : buf.len;
1850
2
    memcpy(buf.base, data, copy);
1851
2
    buf.len = copy;
1852
2
    session->OnStreamRead(copy, buf);
1853
1854
2
    data += copy;
1855
2
    len -= copy;
1856
  }
1857
}
1858
1859
23775
Http2Stream* Http2Stream::New(Http2Session* session,
1860
                              int32_t id,
1861
                              nghttp2_headers_category category,
1862
                              int options) {
1863
  Local<Object> obj;
1864
47550
  if (!session->env()
1865
47550
           ->http2stream_constructor_template()
1866
71325
           ->NewInstance(session->env()->context())
1867
23775
           .ToLocal(&obj)) {
1868
    return nullptr;
1869
  }
1870
23775
  return new Http2Stream(session, obj, id, category, options);
1871
}
1872
1873
23775
Http2Stream::Http2Stream(Http2Session* session,
1874
                         Local<Object> obj,
1875
                         int32_t id,
1876
                         nghttp2_headers_category category,
1877
23775
                         int options)
1878
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
1879
      StreamBase(session->env()),
1880
      session_(session),
1881
      id_(id),
1882
23775
      current_headers_category_(category) {
1883
23775
  MakeWeak();
1884
23775
  StreamBase::AttachToObject(GetObject());
1885
23775
  statistics_.start_time = uv_hrtime();
1886
1887
  // Limit the number of header pairs
1888
23775
  max_header_pairs_ = session->max_header_pairs();
1889
23775
  if (max_header_pairs_ == 0) {
1890
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1891
  }
1892
23775
  current_headers_.reserve(std::min(max_header_pairs_, 12u));
1893
1894
  // Limit the number of header octets
1895
23775
  max_header_length_ =
1896
23775
      std::min(
1897
47550
        nghttp2_session_get_local_settings(
1898
          session->session(),
1899
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1900
71325
      MAX_MAX_HEADER_LIST_SIZE);
1901
1902
23775
  if (options & STREAM_OPTION_GET_TRAILERS)
1903
2
    set_has_trailers();
1904
1905
23775
  PushStreamListener(&stream_listener_);
1906
1907
23775
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1908
604
    Shutdown();
1909
23775
  session->AddStream(this);
1910
23775
}
1911
1912
71325
Http2Stream::~Http2Stream() {
1913
23775
  Debug(this, "tearing down stream");
1914
47550
}
1915
1916
void Http2Stream::MemoryInfo(MemoryTracker* tracker) const {
1917
  tracker->TrackField("current_headers", current_headers_);
1918
  tracker->TrackField("queue", queue_);
1919
}
1920
1921
18
std::string Http2Stream::diagnostic_name() const {
1922
36
  return "HttpStream " + std::to_string(id()) + " (" +
1923
72
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
1924
54
      session()->diagnostic_name() + "]";
1925
}
1926
1927
// Notify the Http2Stream that a new block of HEADERS is being processed.
1928
11702
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
1929
11702
  Debug(this, "starting headers, category: %d", category);
1930
11702
  CHECK(!this->is_destroyed());
1931
11702
  session_->DecrementCurrentSessionMemory(current_headers_length_);
1932
11702
  current_headers_length_ = 0;
1933
11702
  current_headers_.clear();
1934
11702
  current_headers_category_ = category;
1935
11702
}
1936
1937
1938
nghttp2_stream* Http2Stream::operator*() const { return stream(); }
1939
1940
11
nghttp2_stream* Http2Stream::stream() const {
1941
11
  return nghttp2_session_find_stream(session_->session(), id_);
1942
}
1943
1944
23582
void Http2Stream::Close(int32_t code) {
1945
23582
  CHECK(!this->is_destroyed());
1946
23582
  set_closed();
1947
23582
  code_ = code;
1948
23582
  Debug(this, "closed with code %d", code);
1949
23582
}
1950
1951
24088
ShutdownWrap* Http2Stream::CreateShutdownWrap(v8::Local<v8::Object> object) {
1952
  // DoShutdown() always finishes synchronously, so there's no need to create
1953
  // a structure to store asynchronous context.
1954
24088
  return nullptr;
1955
}
1956
1957
24088
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
1958
24088
  if (is_destroyed())
1959
    return UV_EPIPE;
1960
1961
  {
1962
48176
    Http2Scope h2scope(this);
1963
24088
    set_not_writable();
1964
24088
    CHECK_NE(nghttp2_session_resume_data(
1965
        session_->session(), id_),
1966
        NGHTTP2_ERR_NOMEM);
1967
24088
    Debug(this, "writable side shutdown");
1968
  }
1969
24088
  return 1;
1970
}
1971
1972
// Destroy the Http2Stream and render it unusable. Actual resources for the
1973
// Stream will not be freed until the next tick of the Node.js event loop
1974
// using the SetImmediate queue.
1975
23667
void Http2Stream::Destroy() {
1976
  // Do nothing if this stream instance is already destroyed
1977
23667
  if (is_destroyed())
1978
1
    return;
1979
23666
  if (session_->has_pending_rststream(id_))
1980
7
    FlushRstStream();
1981
23666
  set_destroyed();
1982
1983
23666
  Debug(this, "destroying stream");
1984
1985
  // Wait until the start of the next loop to delete because there
1986
  // may still be some pending operations queued for this stream.
1987
47332
  BaseObjectPtr<Http2Stream> strong_ref = session_->RemoveStream(id_);
1988
23666
  if (strong_ref) {
1989
118330
    env()->SetImmediate([this, strong_ref = std::move(strong_ref)](
1990
94608
        Environment* env) {
1991
      // Free any remaining outgoing data chunks here. This should be done
1992
      // here because it's possible for destroy to have been called while
1993
      // we still have queued outbound writes.
1994
23676
      while (!queue_.empty()) {
1995
5
        NgHttp2StreamWrite& head = queue_.front();
1996
5
        if (head.req_wrap)
1997
5
          WriteWrap::FromObject(head.req_wrap)->Done(UV_ECANCELED);
1998
5
        queue_.pop();
1999
      }
2000
2001
      // We can destroy the stream now if there are no writes for it
2002
      // already on the socket. Otherwise, we'll wait for the garbage collector
2003
      // to take care of cleaning up.
2004

47322
      if (session() == nullptr ||
2005
23656
          !session()->HasWritesOnSocketForStream(this)) {
2006
        // Delete once strong_ref goes out of scope.
2007
23605
        Detach();
2008
      }
2009
47332
    });
2010
  }
2011
2012
23666
  statistics_.end_time = uv_hrtime();
2013
47332
  session_->statistics_.stream_average_duration =
2014
47332
      ((statistics_.end_time - statistics_.start_time) /
2015
47332
          session_->statistics_.stream_count) / 1e6;
2016
23666
  EmitStatistics();
2017
}
2018
2019
2020
// Initiates a response on the Http2Stream using data provided via the
2021
// StreamBase Streams API.
2022
11703
int Http2Stream::SubmitResponse(const Http2Headers& headers, int options) {
2023
11703
  CHECK(!this->is_destroyed());
2024
23406
  Http2Scope h2scope(this);
2025
11703
  Debug(this, "submitting response");
2026
11703
  if (options & STREAM_OPTION_GET_TRAILERS)
2027
168
    set_has_trailers();
2028
2029
11703
  if (!is_writable())
2030
10142
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2031
2032
23406
  Http2Stream::Provider::Stream prov(this, options);
2033
11703
  int ret = nghttp2_submit_response(
2034
      session_->session(),
2035
      id_,
2036
      headers.data(),
2037
      headers.length(),
2038
23406
      *prov);
2039
11703
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2040
23406
  return ret;
2041
}
2042
2043
2044
// Submit informational headers for a stream.
2045
5
int Http2Stream::SubmitInfo(const Http2Headers& headers) {
2046
5
  CHECK(!this->is_destroyed());
2047
10
  Http2Scope h2scope(this);
2048
10
  Debug(this, "sending %d informational headers", headers.length());
2049
5
  int ret = nghttp2_submit_headers(
2050
      session_->session(),
2051
      NGHTTP2_FLAG_NONE,
2052
      id_,
2053
      nullptr,
2054
      headers.data(),
2055
      headers.length(),
2056
5
      nullptr);
2057
5
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2058
10
  return ret;
2059
}
2060
2061
37
void Http2Stream::OnTrailers() {
2062
37
  Debug(this, "let javascript know we are ready for trailers");
2063
37
  CHECK(!this->is_destroyed());
2064
37
  Isolate* isolate = env()->isolate();
2065
74
  HandleScope scope(isolate);
2066
37
  Local<Context> context = env()->context();
2067
  Context::Scope context_scope(context);
2068
37
  set_has_trailers(false);
2069
37
  MakeCallback(env()->http2session_on_stream_trailers_function(), 0, nullptr);
2070
37
}
2071
2072
// Submit informational headers for a stream.
2073
31
int Http2Stream::SubmitTrailers(const Http2Headers& headers) {
2074
31
  CHECK(!this->is_destroyed());
2075
62
  Http2Scope h2scope(this);
2076
62
  Debug(this, "sending %d trailers", headers.length());
2077
  int ret;
2078
  // Sending an empty trailers frame poses problems in Safari, Edge & IE.
2079
  // Instead we can just send an empty data frame with NGHTTP2_FLAG_END_STREAM
2080
  // to indicate that the stream is ready to be closed.
2081
31
  if (headers.length() == 0) {
2082
52
    Http2Stream::Provider::Stream prov(this, 0);
2083
26
    ret = nghttp2_submit_data(
2084
        session_->session(),
2085
        NGHTTP2_FLAG_END_STREAM,
2086
        id_,
2087
26
        *prov);
2088
  } else {
2089
5
    ret = nghttp2_submit_trailer(
2090
        session_->session(),
2091
        id_,
2092
        headers.data(),
2093
        headers.length());
2094
  }
2095
31
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2096
62
  return ret;
2097
}
2098
2099
// Submit a PRIORITY frame to the connected peer.
2100
6
int Http2Stream::SubmitPriority(const Http2Priority& priority,
2101
                                bool silent) {
2102
6
  CHECK(!this->is_destroyed());
2103
12
  Http2Scope h2scope(this);
2104
6
  Debug(this, "sending priority spec");
2105
12
  int ret = silent ?
2106
      nghttp2_session_change_stream_priority(
2107
          session_->session(),
2108
          id_,
2109
          &priority) :
2110
6
      nghttp2_submit_priority(
2111
          session_->session(),
2112
          NGHTTP2_FLAG_NONE,
2113
6
          id_, &priority);
2114
6
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2115
12
  return ret;
2116
}
2117
2118
// Closes the Http2Stream by submitting an RST_STREAM frame to the connected
2119
// peer.
2120
118
void Http2Stream::SubmitRstStream(const uint32_t code) {
2121
118
  CHECK(!this->is_destroyed());
2122
118
  code_ = code;
2123
  // If possible, force a purge of any currently pending data here to make sure
2124
  // it is sent before closing the stream. If it returns non-zero then we need
2125
  // to wait until the current write finishes and try again to avoid nghttp2
2126
  // behaviour where it prioritizes RstStream over everything else.
2127
118
  if (session_->SendPendingData() != 0) {
2128
8
    session_->AddPendingRstStream(id_);
2129
8
    return;
2130
  }
2131
2132
110
  FlushRstStream();
2133
}
2134
2135
118
void Http2Stream::FlushRstStream() {
2136
118
  if (is_destroyed())
2137
5
    return;
2138
226
  Http2Scope h2scope(this);
2139
113
  CHECK_EQ(nghttp2_submit_rst_stream(
2140
      session_->session(),
2141
      NGHTTP2_FLAG_NONE,
2142
      id_,
2143
      code_), 0);
2144
}
2145
2146
2147
// Submit a push promise and create the associated Http2Stream if successful.
2148
9
Http2Stream* Http2Stream::SubmitPushPromise(const Http2Headers& headers,
2149
                                            int32_t* ret,
2150
                                            int options) {
2151
9
  CHECK(!this->is_destroyed());
2152
18
  Http2Scope h2scope(this);
2153
9
  Debug(this, "sending push promise");
2154
9
  *ret = nghttp2_submit_push_promise(
2155
      session_->session(),
2156
      NGHTTP2_FLAG_NONE,
2157
      id_,
2158
      headers.data(),
2159
      headers.length(),
2160
      nullptr);
2161
9
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
2162
9
  Http2Stream* stream = nullptr;
2163
9
  if (*ret > 0) {
2164
9
    stream = Http2Stream::New(
2165
9
        session_.get(), *ret, NGHTTP2_HCAT_HEADERS, options);
2166
  }
2167
2168
18
  return stream;
2169
}
2170
2171
// Switch the StreamBase into flowing mode to begin pushing chunks of data
2172
// out to JS land.
2173
23443
int Http2Stream::ReadStart() {
2174
46886
  Http2Scope h2scope(this);
2175
23443
  CHECK(!this->is_destroyed());
2176
23443
  set_reading();
2177
2178
23443
  Debug(this, "reading starting");
2179
2180
  // Tell nghttp2 about our consumption of the data that was handed
2181
  // off to JS land.
2182
23443
  nghttp2_session_consume_stream(
2183
      session_->session(),
2184
      id_,
2185
23443
      inbound_consumed_data_while_paused_);
2186
23443
  inbound_consumed_data_while_paused_ = 0;
2187
2188
46886
  return 0;
2189
}
2190
2191
// Switch the StreamBase into paused mode.
2192
17759
int Http2Stream::ReadStop() {
2193
17759
  CHECK(!this->is_destroyed());
2194
17759
  if (!is_reading())
2195
2241
    return 0;
2196
15518
  set_paused();
2197
15518
  Debug(this, "reading stopped");
2198
15518
  return 0;
2199
}
2200
2201
// The Http2Stream class is a subclass of StreamBase. The DoWrite method
2202
// receives outbound chunks of data to send as outbound DATA frames. These
2203
// are queued in an internal linked list of uv_buf_t structs that are sent
2204
// when nghttp2 is ready to serialize the data frame.
2205
//
2206
// Queue the given set of uv_but_t handles for writing to an
2207
// nghttp2_stream. The WriteWrap's Done callback will be invoked once the
2208
// chunks of data have been flushed to the underlying nghttp2_session.
2209
// Note that this does *not* mean that the data has been flushed
2210
// to the socket yet.
2211
4025
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2212
                         uv_buf_t* bufs,
2213
                         size_t nbufs,
2214
                         uv_stream_t* send_handle) {
2215
4025
  CHECK_NULL(send_handle);
2216
8050
  Http2Scope h2scope(this);
2217

4025
  if (!is_writable() || is_destroyed()) {
2218
    req_wrap->Done(UV_EOF);
2219
    return 0;
2220
  }
2221
4025
  Debug(this, "queuing %d buffers to send", nbufs);
2222
31806
  for (size_t i = 0; i < nbufs; ++i) {
2223
    // Store the req_wrap on the last write info in the queue, so that it is
2224
    // only marked as finished once all buffers associated with it are finished.
2225
55562
    queue_.emplace(NgHttp2StreamWrite {
2226
59587
      BaseObjectPtr<AsyncWrap>(
2227
31806
          i == nbufs - 1 ? req_wrap->GetAsyncWrap() : nullptr),
2228
27781
      bufs[i]
2229
27781
    });
2230
27781
    IncrementAvailableOutboundLength(bufs[i].len);
2231
  }
2232
4025
  CHECK_NE(nghttp2_session_resume_data(
2233
      session_->session(),
2234
      id_), NGHTTP2_ERR_NOMEM);
2235
4025
  return 0;
2236
}
2237
2238
// Ads a header to the Http2Stream. Note that the header name and value are
2239
// provided using a buffer structure provided by nghttp2 that allows us to
2240
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2241
// is incremented here and are decremented when the header name and values
2242
// are garbage collected later.
2243
71872
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2244
                            nghttp2_rcbuf* value,
2245
                            uint8_t flags) {
2246
71872
  CHECK(!this->is_destroyed());
2247
2248
71872
  if (Http2RcBufferPointer::IsZeroLength(name))
2249
    return true;  // Ignore empty headers.
2250
2251
143744
  Http2Header header(env(), name, value, flags);
2252
71872
  size_t length = header.length() + 32;
2253
  // A header can only be added if we have not exceeded the maximum number
2254
  // of headers and the session has memory available for it.
2255

215616
  if (!session_->has_available_session_memory(length) ||
2256

143743
      current_headers_.size() == max_header_pairs_ ||
2257
71871
      current_headers_length_ + length > max_header_length_) {
2258
3
    return false;
2259
  }
2260
2261
71869
  if (statistics_.first_header == 0)
2262
23469
    statistics_.first_header = uv_hrtime();
2263
2264
71869
  current_headers_.push_back(std::move(header));
2265
2266
71869
  current_headers_length_ += length;
2267
71869
  session_->IncrementCurrentSessionMemory(length);
2268
71869
  return true;
2269
}
2270
2271
// A Provider is the thing that provides outbound DATA frame data.
2272
11729
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2273
11729
  CHECK(!stream->is_destroyed());
2274
11729
  provider_.source.ptr = stream;
2275
11729
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2276
11729
}
2277
2278
11778
Http2Stream::Provider::Provider(int options) {
2279
11778
  provider_.source.ptr = nullptr;
2280
11778
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2281
11778
}
2282
2283
47014
Http2Stream::Provider::~Provider() {
2284
23507
  provider_.source.ptr = nullptr;
2285
23507
}
2286
2287
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2288
// built via the StreamBase API and the Streams js API.
2289
11778
Http2Stream::Provider::Stream::Stream(int options)
2290
11778
    : Http2Stream::Provider(options) {
2291
11778
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2292
11778
}
2293
2294
11729
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2295
11729
    : Http2Stream::Provider(stream, options) {
2296
11729
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2297
11729
}
2298
2299
28062
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2300
                                              int32_t id,
2301
                                              uint8_t* buf,
2302
                                              size_t length,
2303
                                              uint32_t* flags,
2304
                                              nghttp2_data_source* source,
2305
                                              void* user_data) {
2306
28062
  Http2Session* session = static_cast<Http2Session*>(user_data);
2307
  Debug(session, "reading outbound data for stream %d", id);
2308
56124
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
2309
28062
  if (!stream) return 0;
2310
28062
  if (stream->statistics_.first_byte_sent == 0)
2311
12733
    stream->statistics_.first_byte_sent = uv_hrtime();
2312
28062
  CHECK_EQ(id, stream->id());
2313
2314
28062
  size_t amount = 0;          // amount of data being sent in this data frame.
2315
2316
  // Remove all empty chunks from the head of the queue.
2317
  // This is done here so that .write('', cb) is still a meaningful way to
2318
  // find out when the HTTP2 stream wants to consume data, and because the
2319
  // StreamBase API allows empty input chunks.
2320

28072
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2321
    BaseObjectPtr<AsyncWrap> finished =
2322
10
        std::move(stream->queue_.front().req_wrap);
2323
5
    stream->queue_.pop();
2324
5
    if (finished)
2325
3
      WriteWrap::FromObject(finished)->Done(0);
2326
  }
2327
2328
28062
  if (!stream->queue_.empty()) {
2329
    Debug(session, "stream %d has pending outbound data", id);
2330
14011
    amount = std::min(stream->available_outbound_length_, length);
2331
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2332
14011
    if (amount > 0) {
2333
      // Just return the length, let Http2Session::OnSendData take care of
2334
      // actually taking the buffers out of the queue.
2335
14011
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2336
14011
      stream->DecrementAvailableOutboundLength(amount);
2337
    }
2338
  }
2339
2340

28062
  if (amount == 0 && stream->is_writable()) {
2341
2688
    CHECK(stream->queue_.empty());
2342
    Debug(session, "deferring stream %d", id);
2343
2688
    stream->EmitWantsWrite(length);
2344

2688
    if (stream->available_outbound_length_ > 0 || !stream->is_writable()) {
2345
      // EmitWantsWrite() did something interesting synchronously, restart:
2346
      return OnRead(handle, id, buf, length, flags, source, user_data);
2347
    }
2348
2688
    return NGHTTP2_ERR_DEFERRED;
2349
  }
2350
2351

25374
  if (stream->available_outbound_length_ == 0 && !stream->is_writable()) {
2352
    Debug(session, "no more data for stream %d", id);
2353
12724
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2354
12724
    if (stream->has_trailers()) {
2355
37
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2356
37
      stream->OnTrailers();
2357
    }
2358
  }
2359
2360
25374
  stream->statistics_.sent_bytes += amount;
2361
25374
  return amount;
2362
}
2363
2364
27781
void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2365
27781
  available_outbound_length_ += amount;
2366
27781
  session_->IncrementCurrentSessionMemory(amount);
2367
27781
}
2368
2369
14011
void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2370
14011
  available_outbound_length_ -= amount;
2371
14011
  session_->DecrementCurrentSessionMemory(amount);
2372
14011
}
2373
2374
2375
// Implementation of the JavaScript API
2376
2377
// Fetches the string description of a nghttp2 error code and passes that
2378
// back to JS land
2379
64
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2380
64
  Environment* env = Environment::GetCurrent(args);
2381
256
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2382
192
  args.GetReturnValue().Set(
2383
      OneByteString(
2384
          env->isolate(),
2385
64
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val))));
2386
64
}
2387
2388
2389
// Serializes the settings object into a Buffer instance that
2390
// would be suitable, for instance, for creating the Base64
2391
// output for an HTTP2-Settings header field.
2392
17
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2393
17
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2394
51
  args.GetReturnValue().Set(Http2Settings::Pack(state));
2395
17
}
2396
2397
// A TypedArray instance is shared between C++ and JS land to contain the
2398
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2399
// default values.
2400
6
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2401
6
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2402
6
  Http2Settings::RefreshDefaults(state);
2403
6
}
2404
2405
// Sets the next stream ID the Http2Session. If successful, returns true.
2406
1
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2407
1
  Environment* env = Environment::GetCurrent(args);
2408
  Http2Session* session;
2409
1
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2410
4
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2411
1
  if (nghttp2_session_set_next_stream_id(session->session(), id) < 0) {
2412
    Debug(session, "failed to set next stream id to %d", id);
2413
    return args.GetReturnValue().Set(false);
2414
  }
2415
2
  args.GetReturnValue().Set(true);
2416
1
  Debug(session, "set next stream id to %d", id);
2417
}
2418
2419
// Set local window size (local endpoints's window size) to the given
2420
// window_size for the stream denoted by 0.
2421
// This function returns 0 if it succeeds, or one of a negative codes
2422
3
void Http2Session::SetLocalWindowSize(
2423
    const FunctionCallbackInfo<Value>& args) {
2424
3
  Environment* env = Environment::GetCurrent(args);
2425
  Http2Session* session;
2426
3
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2427
2428
12
  int32_t window_size = args[0]->Int32Value(env->context()).ToChecked();
2429
2430
3
  int result = nghttp2_session_set_local_window_size(
2431
3
      session->session(), NGHTTP2_FLAG_NONE, 0, window_size);
2432
2433
6
  args.GetReturnValue().Set(result);
2434
2435
3
  Debug(session, "set local window size to %d", window_size);
2436
}
2437
2438
// A TypedArray instance is shared between C++ and JS land to contain the
2439
// SETTINGS (either remote or local). RefreshSettings updates the current
2440
// values established for each of the settings so those can be read in JS land.
2441
template <get_setting fn>
2442
561
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2443
  Http2Session* session;
2444

561
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2445
561
  Http2Settings::Update(session, fn);
2446
561
  Debug(session, "settings refreshed for session");
2447
}
2448
2449
// A TypedArray instance is shared between C++ and JS land to contain state
2450
// information of the current Http2Session. This updates the values in the
2451
// TypedArray so those can be read in JS land.
2452
12
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2453
  Http2Session* session;
2454
12
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2455
12
  Debug(session, "refreshing state");
2456
2457
12
  AliasedFloat64Array& buffer = session->http2_state()->session_state_buffer;
2458
2459
12
  nghttp2_session* s = session->session();
2460
2461
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2462
12
      nghttp2_session_get_effective_local_window_size(s);
2463
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2464
12
      nghttp2_session_get_effective_recv_data_length(s);
2465
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2466
12
      nghttp2_session_get_next_stream_id(s);
2467
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2468
12
      nghttp2_session_get_local_window_size(s);
2469
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2470
12
      nghttp2_session_get_last_proc_stream_id(s);
2471
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2472
12
      nghttp2_session_get_remote_window_size(s);
2473
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2474
12
      static_cast<double>(nghttp2_session_get_outbound_queue_size(s));
2475
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2476
12
      static_cast<double>(nghttp2_session_get_hd_deflate_dynamic_table_size(s));
2477
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2478
12
      static_cast<double>(nghttp2_session_get_hd_inflate_dynamic_table_size(s));
2479
}
2480
2481
2482
// Constructor for new Http2Session instances.
2483
658
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2484
658
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2485
658
  Environment* env = state->env();
2486
658
  CHECK(args.IsConstructCall());
2487
  SessionType type =
2488
      static_cast<SessionType>(
2489
2632
          args[0]->Int32Value(env->context()).ToChecked());
2490
658
  Http2Session* session = new Http2Session(state, args.This(), type);
2491
658
  session->get_async_id();  // avoid compiler warning
2492
  Debug(session, "session created");
2493
658
}
2494
2495
2496
// Binds the Http2Session with a StreamBase used for i/o
2497
658
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2498
  Http2Session* session;
2499
658
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2500
1316
  CHECK(args[0]->IsObject());
2501
1316
  session->Consume(args[0].As<Object>());
2502
}
2503
2504
// Destroys the Http2Session instance and renders it unusable
2505
639
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2506
  Http2Session* session;
2507
639
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2508
639
  Debug(session, "destroying session");
2509
639
  Environment* env = Environment::GetCurrent(args);
2510
639
  Local<Context> context = env->context();
2511
2512
1917
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2513
1278
  session->Close(code, args[1]->IsTrue());
2514
}
2515
2516
// Submits a new request on the Http2Session and returns either an error code
2517
// or the Http2Stream object.
2518
11778
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2519
  Http2Session* session;
2520
11779
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2521
11778
  Environment* env = session->env();
2522
2523
23556
  Local<Array> headers = args[0].As<Array>();
2524
47112
  int32_t options = args[1]->Int32Value(env->context()).ToChecked();
2525
2526
11778
  Debug(session, "request submitted");
2527
2528
11778
  int32_t ret = 0;
2529
  Http2Stream* stream =
2530
11778
      session->Http2Session::SubmitRequest(
2531
23556
          Http2Priority(env, args[2], args[3], args[4]),
2532
23556
          Http2Headers(env, headers),
2533
          &ret,
2534
11778
          static_cast<int>(options));
2535
2536

11778
  if (ret <= 0 || stream == nullptr) {
2537
2
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2538
3
    return args.GetReturnValue().Set(ret);
2539
  }
2540
2541
23554
  Debug(session, "request submitted, new stream id %d", stream->id());
2542
35331
  args.GetReturnValue().Set(stream->object());
2543
}
2544
2545
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2546
// of shutting down. Note that this function does not actually alter the
2547
// state of the Http2Session, it's simply a notification.
2548
580
void Http2Session::Goaway(uint32_t code,
2549
                          int32_t lastStreamID,
2550
                          const uint8_t* data,
2551
                          size_t len) {
2552
580
  if (is_destroyed())
2553
    return;
2554
2555
1160
  Http2Scope h2scope(this);
2556
  // the last proc stream id is the most recently created Http2Stream.
2557
580
  if (lastStreamID <= 0)
2558
580
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_.get());
2559
580
  Debug(this, "submitting goaway");
2560
580
  nghttp2_submit_goaway(session_.get(), NGHTTP2_FLAG_NONE,
2561
580
                        lastStreamID, code, data, len);
2562
}
2563
2564
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2565
// of shutting down. The opaque data argument is an optional TypedArray that
2566
// can be used to send debugging data to the connected peer.
2567
580
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2568
580
  Environment* env = Environment::GetCurrent(args);
2569
580
  Local<Context> context = env->context();
2570
  Http2Session* session;
2571
580
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2572
2573
1740
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2574
1740
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2575
580
  ArrayBufferViewContents<uint8_t> opaque_data;
2576
2577
1160
  if (args[2]->IsArrayBufferView()) {
2578
2
    opaque_data.Read(args[2].As<ArrayBufferView>());
2579
  }
2580
2581
580
  session->Goaway(code, lastStreamID, opaque_data.data(), opaque_data.length());
2582
}
2583
2584
// Update accounting of data chunks. This is used primarily to manage timeout
2585
// logic when using the FD Provider.
2586
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2587
10
  Environment* env = Environment::GetCurrent(args);
2588
10
  Isolate* isolate = env->isolate();
2589
20
  HandleScope scope(isolate);
2590
  Http2Session* session;
2591
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2592
2593
10
  uint32_t length = session->chunks_sent_since_last_write_;
2594
2595
30
  session->object()->Set(env->context(),
2596
                         env->chunks_sent_since_last_write_string(),
2597
50
                         Integer::NewFromUnsigned(isolate, length)).Check();
2598
2599
20
  args.GetReturnValue().Set(length);
2600
}
2601
2602
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2603
// this *WILL* alter the state of the stream, causing the OnStreamClose
2604
// callback to the triggered.
2605
115
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2606
115
  Environment* env = Environment::GetCurrent(args);
2607
115
  Local<Context> context = env->context();
2608
  Http2Stream* stream;
2609
115
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2610
345
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2611
115
  Debug(stream, "sending rst_stream with code %d", code);
2612
115
  stream->SubmitRstStream(code);
2613
}
2614
2615
// Initiates a response on the Http2Stream using the StreamBase API to provide
2616
// outbound DATA frames.
2617
11703
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2618
11703
  Environment* env = Environment::GetCurrent(args);
2619
  Http2Stream* stream;
2620
11703
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2621
2622
23406
  Local<Array> headers = args[0].As<Array>();
2623
46812
  int32_t options = args[1]->Int32Value(env->context()).ToChecked();
2624
2625
35109
  args.GetReturnValue().Set(
2626
      stream->SubmitResponse(
2627
23406
          Http2Headers(env, headers),
2628
          static_cast<int>(options)));
2629
11703
  Debug(stream, "response submitted");
2630
}
2631
2632
2633
// Submits informational headers on the Http2Stream
2634
5
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2635
5
  Environment* env = Environment::GetCurrent(args);
2636
  Http2Stream* stream;
2637
5
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2638
2639
10
  Local<Array> headers = args[0].As<Array>();
2640
2641
15
  args.GetReturnValue().Set(stream->SubmitInfo(Http2Headers(env, headers)));
2642
}
2643
2644
// Submits trailing headers on the Http2Stream
2645
31
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2646
31
  Environment* env = Environment::GetCurrent(args);
2647
  Http2Stream* stream;
2648
31
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2649
2650
62
  Local<Array> headers = args[0].As<Array>();
2651
2652
93
  args.GetReturnValue().Set(
2653
62
      stream->SubmitTrailers(Http2Headers(env, headers)));
2654
}
2655
2656
// Grab the numeric id of the Http2Stream
2657
11786
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2658
  Http2Stream* stream;
2659
11786
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2660
35358
  args.GetReturnValue().Set(stream->id());
2661
}
2662
2663
// Destroy the Http2Stream, rendering it no longer usable
2664
23529
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2665
  Http2Stream* stream;
2666
23529
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2667
23529
  Debug(stream, "destroying stream");
2668
23529
  stream->Destroy();
2669
}
2670
2671
// Initiate a Push Promise and create the associated Http2Stream
2672
9
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2673
9
  Environment* env = Environment::GetCurrent(args);
2674
  Http2Stream* parent;
2675
9
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2676
2677
18
  Local<Array> headers = args[0].As<Array>();
2678
36
  int32_t options = args[1]->Int32Value(env->context()).ToChecked();
2679
2680
9
  Debug(parent, "creating push promise");
2681
2682
9
  int32_t ret = 0;
2683
  Http2Stream* stream =
2684
9
      parent->SubmitPushPromise(
2685
18
          Http2Headers(env, headers),
2686
          &ret,
2687
9
          static_cast<int>(options));
2688
2689

9
  if (ret <= 0 || stream == nullptr) {
2690
    Debug(parent, "failed to create push stream: %d", ret);
2691
    return args.GetReturnValue().Set(ret);
2692
  }
2693
18
  Debug(parent, "push stream %d created", stream->id());
2694
27
  args.GetReturnValue().Set(stream->object());
2695
}
2696
2697
// Send a PRIORITY frame
2698
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2699
6
  Environment* env = Environment::GetCurrent(args);
2700
  Http2Stream* stream;
2701
6
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2702
2703
18
  CHECK_EQ(stream->SubmitPriority(
2704
      Http2Priority(env, args[0], args[1], args[2]),
2705
      args[3]->IsTrue()), 0);
2706
6
  Debug(stream, "priority submitted");
2707
}
2708
2709
// A TypedArray shared by C++ and JS land is used to communicate state
2710
// information about the Http2Stream. This updates the values in that
2711
// TypedArray so that the state can be read by JS.
2712
11
void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
2713
  Http2Stream* stream;
2714
11
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2715
2716
11
  Debug(stream, "refreshing state");
2717
2718
11
  CHECK_NOT_NULL(stream->session());
2719
  AliasedFloat64Array& buffer =
2720
11
      stream->session()->http2_state()->stream_state_buffer;
2721
2722
11
  nghttp2_stream* str = stream->stream();
2723
11
  nghttp2_session* s = stream->session()->session();
2724
2725
11
  if (str == nullptr) {
2726
1
    buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE;
2727
    buffer[IDX_STREAM_STATE_WEIGHT] =
2728
        buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2729
        buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2730
        buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2731
1
        buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0;
2732
  } else {
2733
    buffer[IDX_STREAM_STATE] =
2734
10
        nghttp2_stream_get_state(str);
2735
    buffer[IDX_STREAM_STATE_WEIGHT] =
2736
10
        nghttp2_stream_get_weight(str);
2737
    buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2738
10
        nghttp2_stream_get_sum_dependency_weight(str);
2739
    buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2740
10
        nghttp2_session_get_stream_local_close(s, stream->id());
2741
    buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2742
10
        nghttp2_session_get_stream_remote_close(s, stream->id());
2743
    buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] =
2744
10
        nghttp2_session_get_stream_local_window_size(s, stream->id());
2745
  }
2746
}
2747
2748
5
void Http2Session::AltSvc(int32_t id,
2749
                          uint8_t* origin,
2750
                          size_t origin_len,
2751
                          uint8_t* value,
2752
                          size_t value_len) {
2753
10
  Http2Scope h2scope(this);
2754
5
  CHECK_EQ(nghttp2_submit_altsvc(session_.get(), NGHTTP2_FLAG_NONE, id,
2755
                                 origin, origin_len, value, value_len), 0);
2756
5
}
2757
2758
5
void Http2Session::Origin(const Origins& origins) {
2759
10
  Http2Scope h2scope(this);
2760
5
  CHECK_EQ(nghttp2_submit_origin(
2761
      session_.get(),
2762
      NGHTTP2_FLAG_NONE,
2763
      *origins,
2764
      origins.length()), 0);
2765
5
}
2766
2767
// Submits an AltSvc frame to be sent to the connected peer.
2768
5
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2769
5
  Environment* env = Environment::GetCurrent(args);
2770
  Http2Session* session;
2771
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2772
2773
20
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2774
2775
  // origin and value are both required to be ASCII, handle them as such.
2776
20
  Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2777
20
  Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2778
2779

10
  if (origin_str.IsEmpty() || value_str.IsEmpty())
2780
    return;
2781
2782
5
  size_t origin_len = origin_str->Length();
2783
5
  size_t value_len = value_str->Length();
2784
2785
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2786
  // Verify that origin len != 0 if stream id == 0, or
2787
  // that origin len == 0 if stream id != 0
2788



5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2789
2790
10
  MaybeStackBuffer<uint8_t> origin(origin_len);
2791
10
  MaybeStackBuffer<uint8_t> value(value_len);
2792
10
  origin_str->WriteOneByte(env->isolate(), *origin);
2793
10
  value_str->WriteOneByte(env->isolate(), *value);
2794
2795
5
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2796
}
2797
2798
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2799
5
  Environment* env = Environment::GetCurrent(args);
2800
5
  Local<Context> context = env->context();
2801
  Http2Session* session;
2802
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2803
2804
10
  Local<String> origin_string = args[0].As<String>();
2805
15
  size_t count = args[1]->Int32Value(context).ToChecked();
2806
2807
5
  session->Origin(Origins(env, origin_string, count));
2808
}
2809
2810
// Submits a PING frame to be sent to the connected peer.
2811
13
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2812
  Http2Session* session;
2813
13
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2814
2815
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2816
  // then the current hrtime will be used as the payload.
2817
13
  ArrayBufferViewContents<uint8_t, 8> payload;
2818
26
  if (args[0]->IsArrayBufferView()) {
2819
12
    payload.Read(args[0].As<ArrayBufferView>());
2820
6
    CHECK_EQ(payload.length(), 8);
2821
  }
2822
2823
26
  CHECK(args[1]->IsFunction());
2824
39
  args.GetReturnValue().Set(
2825
39
      session->AddPing(payload.data(), args[1].As<Function>()));
2826
}
2827
2828
// Submits a SETTINGS frame for the Http2Session
2829
668
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2830
  Http2Session* session;
2831
668
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2832
1336
  CHECK(args[0]->IsFunction());
2833
2672
  args.GetReturnValue().Set(session->AddSettings(args[0].As<Function>()));
2834
}
2835
2836
651
BaseObjectPtr<Http2Ping> Http2Session::PopPing() {
2837
651
  BaseObjectPtr<Http2Ping> ping;
2838
651
  if (!outstanding_pings_.empty()) {
2839
11
    ping = std::move(outstanding_pings_.front());
2840
11
    outstanding_pings_.pop();
2841
11
    DecrementCurrentSessionMemory(sizeof(*ping));
2842
  }
2843
651
  return ping;
2844
}
2845
2846
13
bool Http2Session::AddPing(const uint8_t* payload, Local<Function> callback) {
2847
  Local<Object> obj;
2848
39
  if (!env()->http2ping_constructor_template()
2849
39
          ->NewInstance(env()->context())
2850
13
              .ToLocal(&obj)) {
2851
    return false;
2852
  }
2853
2854
  BaseObjectPtr<Http2Ping> ping =
2855
26
      MakeDetachedBaseObject<Http2Ping>(this, obj, callback);
2856
13
  if (!ping)
2857
    return false;
2858
2859
13
  if (outstanding_pings_.size() == max_outstanding_pings_) {
2860
2
    ping->Done(false);
2861
2
    return false;
2862
  }
2863
2864
11
  IncrementCurrentSessionMemory(sizeof(*ping));
2865
  // The Ping itself is an Async resource. When the acknowledgement is received,
2866
  // the callback will be invoked and a notification sent out to JS land. The
2867
  // notification will include the duration of the ping, allowing the round
2868
  // trip to be measured.
2869
11
  ping->Send(payload);
2870
2871
11
  outstanding_pings_.emplace(std::move(ping));
2872
11
  return true;
2873
}
2874
2875
536
BaseObjectPtr<Http2Settings> Http2Session::PopSettings() {
2876
536
  BaseObjectPtr<Http2Settings> settings;
2877
536
  if (!outstanding_settings_.empty()) {
2878
536
    settings = std::move(outstanding_settings_.front());
2879
536
    outstanding_settings_.pop();
2880
536
    DecrementCurrentSessionMemory(sizeof(*settings));
2881
  }
2882
536
  return settings;
2883
}
2884
2885
668
bool Http2Session::AddSettings(Local<Function> callback) {
2886
  Local<Object> obj;
2887
2004
  if (!env()->http2settings_constructor_template()
2888
2004
          ->NewInstance(env()->context())
2889
668
              .ToLocal(&obj)) {
2890
    return false;
2891
  }
2892
2893
  BaseObjectPtr<Http2Settings> settings =
2894
1336
      MakeDetachedBaseObject<Http2Settings>(this, obj, callback, 0);
2895
668
  if (!settings)
2896
    return false;
2897
2898
668
  if (outstanding_settings_.size() == max_outstanding_settings_) {
2899
2
    settings->Done(false);
2900
2
    return false;
2901
  }
2902
2903
666
  IncrementCurrentSessionMemory(sizeof(*settings));
2904
666
  settings->Send();
2905
666
  outstanding_settings_.emplace(std::move(settings));
2906
666
  return true;
2907
}
2908
2909
13
Http2Ping::Http2Ping(
2910
    Http2Session* session,
2911
    Local<Object> obj,
2912
13
    Local<Function> callback)
2913
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2PING),
2914
      session_(session),
2915
26
      startTime_(uv_hrtime()) {
2916
13
  callback_.Reset(env()->isolate(), callback);
2917
13
}
2918
2919
void Http2Ping::MemoryInfo(MemoryTracker* tracker) const {
2920
  tracker->TrackField("callback", callback_);
2921
}
2922
2923
13
Local<Function> Http2Ping::callback() const {
2924
26
  return callback_.Get(env()->isolate());
2925
}
2926
2927
11
void Http2Ping::Send(const uint8_t* payload) {
2928
11
  CHECK(session_);
2929
  uint8_t data[8];
2930
11
  if (payload == nullptr) {
2931
5
    memcpy(&data, &startTime_, arraysize(data));
2932
5
    payload = data;
2933
  }
2934
22
  Http2Scope h2scope(session_.get());
2935
11
  CHECK_EQ(nghttp2_submit_ping(
2936
      session_->session(),
2937
      NGHTTP2_FLAG_NONE,
2938
      payload), 0);
2939
11
}
2940
2941
13
void Http2Ping::Done(bool ack, const uint8_t* payload) {
2942
13
  uint64_t duration_ns = uv_hrtime() - startTime_;
2943
13
  double duration_ms = duration_ns / 1e6;
2944
13
  if (session_) session_->statistics_.ping_rtt = duration_ns;
2945
2946
13
  Isolate* isolate = env()->isolate();
2947
26
  HandleScope handle_scope(isolate);
2948
13
  Context::Scope context_scope(env()->context());
2949
2950
  Local<Value> buf = Undefined(isolate);
2951
13
  if (payload != nullptr) {
2952
30
    buf = Buffer::Copy(isolate,
2953
                       reinterpret_cast<const char*>(payload),
2954
10
                       8).ToLocalChecked();
2955
  }
2956
2957
  Local<Value> argv[] = {
2958
    ack ? v8::True(isolate) : v8::False(isolate),
2959
    Number::New(isolate, duration_ms),
2960
    buf
2961
39
  };
2962
13
  MakeCallback(callback(), arraysize(argv), argv);
2963
13
}
2964
2965
1
void Http2Ping::DetachFromSession() {
2966
1
  session_.reset();
2967
1
}
2968
2969
void NgHttp2StreamWrite::MemoryInfo(MemoryTracker* tracker) const {
2970
  if (req_wrap)
2971
    tracker->TrackField("req_wrap", req_wrap);
2972
  tracker->TrackField("buf", buf);
2973
}
2974
2975
241
void SetCallbackFunctions(const FunctionCallbackInfo<Value>& args) {
2976
241
  Environment* env = Environment::GetCurrent(args);
2977
241
  CHECK_EQ(args.Length(), 11);
2978
2979
#define SET_FUNCTION(arg, name)                                               \
2980
  CHECK(args[arg]->IsFunction());                                             \
2981
  env->set_http2session_on_ ## name ## _function(args[arg].As<Function>());
2982
2983
964
  SET_FUNCTION(0, error)
2984
964
  SET_FUNCTION(1, priority)
2985
964
  SET_FUNCTION(2, settings)
2986
964
  SET_FUNCTION(3, ping)
2987
964
  SET_FUNCTION(4, headers)
2988
964
  SET_FUNCTION(5, frame_error)
2989
964
  SET_FUNCTION(6, goaway_data)
2990
964
  SET_FUNCTION(7, altsvc)
2991
964
  SET_FUNCTION(8, origin)
2992
964
  SET_FUNCTION(9, stream_trailers)
2993
964
  SET_FUNCTION(10, stream_close)
2994
2995
#undef SET_FUNCTION
2996
241
}
2997
2998
2
void Http2State::MemoryInfo(MemoryTracker* tracker) const {
2999
2
  tracker->TrackField("root_buffer", root_buffer);
3000
2
}
3001
3002
// TODO(addaleax): Remove once we're on C++17.
3003
constexpr FastStringKey Http2State::binding_data_name;
3004
3005
// Set up the process.binding('http2') binding.
3006
246
void Initialize(Local<Object> target,
3007
                Local<Value> unused,
3008
                Local<Context> context,
3009
                void* priv) {
3010
246
  Environment* env = Environment::GetCurrent(context);
3011
246
  Isolate* isolate = env->isolate();
3012
492
  HandleScope handle_scope(isolate);
3013
3014
246
  Http2State* const state = env->AddBindingData<Http2State>(context, target);
3015
246
  if (state == nullptr) return;
3016
3017
#define SET_STATE_TYPEDARRAY(name, field)             \
3018
  target->Set(context,                                \
3019
              FIXED_ONE_BYTE_STRING(isolate, (name)), \
3020
              (field)).FromJust()
3021
3022
  // Initialize the buffer used to store the session state
3023
984
  SET_STATE_TYPEDARRAY(
3024
    "sessionState", state->session_state_buffer.GetJSArray());
3025
  // Initialize the buffer used to store the stream state
3026
984
  SET_STATE_TYPEDARRAY(
3027
    "streamState", state->stream_state_buffer.GetJSArray());
3028
984
  SET_STATE_TYPEDARRAY(
3029
    "settingsBuffer", state->settings_buffer.GetJSArray());
3030
984
  SET_STATE_TYPEDARRAY(
3031
    "optionsBuffer", state->options_buffer.GetJSArray());
3032
984
  SET_STATE_TYPEDARRAY(
3033
    "streamStats", state->stream_stats_buffer.GetJSArray());
3034
984
  SET_STATE_TYPEDARRAY(
3035
    "sessionStats", state->session_stats_buffer.GetJSArray());
3036
#undef SET_STATE_TYPEDARRAY
3037
3038
984
  NODE_DEFINE_CONSTANT(target, kBitfield);
3039
246
  NODE_DEFINE_CONSTANT(target, kSessionPriorityListenerCount);
3040
738
  NODE_DEFINE_CONSTANT(target, kSessionFrameErrorListenerCount);
3041
984
  NODE_DEFINE_CONSTANT(target, kSessionMaxInvalidFrames);
3042
1722
  NODE_DEFINE_CONSTANT(target, kSessionMaxRejectedStreams);
3043
1968
  NODE_DEFINE_CONSTANT(target, kSessionUint8FieldCount);
3044
1722
3045
1476
  NODE_DEFINE_CONSTANT(target, kSessionHasRemoteSettingsListeners);
3046
1476
  NODE_DEFINE_CONSTANT(target, kSessionRemoteSettingsIsUpToDate);
3047
1476
  NODE_DEFINE_CONSTANT(target, kSessionHasPingListeners);
3048
1230
  NODE_DEFINE_CONSTANT(target, kSessionHasAltsvcListeners);
3049
1722
3050
1230
  // Method to fetch the nghttp2 string description of an nghttp2 error code
3051
984
  env->SetMethod(target, "nghttp2ErrorString", HttpErrorString);
3052
738
  env->SetMethod(target, "refreshDefaultSettings", RefreshDefaultSettings);
3053
246
  env->SetMethod(target, "packSettings", PackSettings);
3054
246
  env->SetMethod(target, "setCallbackFunctions", SetCallbackFunctions);
3055
3056
  Local<String> http2SessionClassName =
3057
246
    FIXED_ONE_BYTE_STRING(isolate, "Http2Session");
3058
3059
246
  Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate());
3060
492
  ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping"));
3061
492
  ping->Inherit(AsyncWrap::GetConstructorTemplate(env));
3062
246
  Local<ObjectTemplate> pingt = ping->InstanceTemplate();
3063
246
  pingt->SetInternalFieldCount(Http2Ping::kInternalFieldCount);
3064
246
  env->set_http2ping_constructor_template(pingt);
3065
3066
246
  Local<FunctionTemplate> setting = FunctionTemplate::New(env->isolate());
3067
492
  setting->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Setting"));
3068
492
  setting->Inherit(AsyncWrap::GetConstructorTemplate(env));
3069
246
  Local<ObjectTemplate> settingt = setting->InstanceTemplate();
3070
246
  settingt->SetInternalFieldCount(AsyncWrap::kInternalFieldCount);
3071
246
  env->set_http2settings_constructor_template(settingt);
3072
3073
246
  Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
3074
492
  stream->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"));
3075
246
  env->SetProtoMethod(stream, "id", Http2Stream::GetID);
3076
246
  env->SetProtoMethod(stream, "destroy", Http2Stream::Destroy);
3077
246
  env->SetProtoMethod(stream, "priority", Http2Stream::Priority);
3078
246
  env->SetProtoMethod(stream, "pushPromise", Http2Stream::PushPromise);
3079
246
  env->SetProtoMethod(stream, "info", Http2Stream::Info);
3080
246
  env->SetProtoMethod(stream, "trailers", Http2Stream::Trailers);
3081
246
  env->SetProtoMethod(stream, "respond", Http2Stream::Respond);
3082
246
  env->SetProtoMethod(stream, "rstStream", Http2Stream::RstStream);
3083
246
  env->SetProtoMethod(stream, "refreshState", Http2Stream::RefreshState);
3084
492
  stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
3085
246
  StreamBase::AddMethods(env, stream);
3086
246
  Local<ObjectTemplate> streamt = stream->InstanceTemplate();
3087
246
  streamt->SetInternalFieldCount(StreamBase::kInternalFieldCount);
3088
246
  env->set_http2stream_constructor_template(streamt);
3089
492
  target->Set(context,
3090
              FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"),
3091
1230
              stream->GetFunction(env->context()).ToLocalChecked()).Check();
3092
3093
  Local<FunctionTemplate> session =
3094
246
      env->NewFunctionTemplate(Http2Session::New);
3095
246
  session->SetClassName(http2SessionClassName);
3096
738
  session->InstanceTemplate()->SetInternalFieldCount(
3097
246
      Http2Session::kInternalFieldCount);
3098
492
  session->Inherit(AsyncWrap::GetConstructorTemplate(env));
3099
246
  env->SetProtoMethod(session, "origin", Http2Session::Origin);
3100
246
  env->SetProtoMethod(session, "altsvc", Http2Session::AltSvc);
3101
246
  env->SetProtoMethod(session, "ping", Http2Session::Ping);
3102
246
  env->SetProtoMethod(session, "consume", Http2Session::Consume);
3103
246
  env->SetProtoMethod(session, "receive", Http2Session::Receive);
3104
246
  env->SetProtoMethod(session, "destroy", Http2Session::Destroy);
3105
246
  env->SetProtoMethod(session, "goaway", Http2Session::Goaway);
3106
246
  env->SetProtoMethod(session, "settings", Http2Session::Settings);
3107
246
  env->SetProtoMethod(session, "request", Http2Session::Request);
3108
  env->SetProtoMethod(session, "setNextStreamID",
3109
246
                      Http2Session::SetNextStreamID);
3110
  env->SetProtoMethod(session, "setLocalWindowSize",
3111
246
                      Http2Session::SetLocalWindowSize);
3112
  env->SetProtoMethod(session, "updateChunksSent",
3113
246
                      Http2Session::UpdateChunksSent);
3114
246
  env->SetProtoMethod(session, "refreshState", Http2Session::RefreshState);
3115
  env->SetProtoMethod(
3116
      session, "localSettings",
3117
246
      Http2Session::RefreshSettings<nghttp2_session_get_local_settings>);
3118
  env->SetProtoMethod(
3119
      session, "remoteSettings",
3120
246
      Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>);
3121
492
  target->Set(context,
3122
              http2SessionClassName,
3123
984
              session->GetFunction(env->context()).ToLocalChecked()).Check();
3124
3125
246
  Local<Object> constants = Object::New(isolate);
3126
3127
  // This does alocate one more slot than needed but it's not used.
3128
#define V(name) FIXED_ONE_BYTE_STRING(isolate, #name),
3129
  Local<Value> error_code_names[] = {
3130
    HTTP2_ERROR_CODES(V)
3131
3690
  };
3132
#undef V
3133
3134
  Local<Array> name_for_error_code =
3135
      Array::New(
3136
          isolate,
3137
          error_code_names,
3138
246
          arraysize(error_code_names));
3139
3140
492
  target->Set(context,
3141
              FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"),
3142
738
              name_for_error_code).Check();
3143
3144
#define V(constant) NODE_DEFINE_HIDDEN_CONSTANT(constants, constant);
3145
6888
  HTTP2_HIDDEN_CONSTANTS(V)
3146
492
#undef V
3147
492
3148
246
#define V(constant) NODE_DEFINE_CONSTANT(constants, constant);
3149
50676
  HTTP2_CONSTANTS(V)
3150
246
#undef V
3151
492
3152
246
  // NGHTTP2_DEFAULT_WEIGHT is a macro and not a regular define
3153
738
  // it won't be set properly on the constants object if included
3154
738
  // in the HTTP2_CONSTANTS macro.
3155
738
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_DEFAULT_WEIGHT);
3156
738
3157
738
#define V(NAME, VALUE)                                          \
3158
1476
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE);
3159
116112
  HTTP_KNOWN_HEADERS(V)
3160
1230
#undef V
3161
738
3162
984
#define V(NAME, VALUE)                                          \
3163
1230
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE);
3164
48462
  HTTP_KNOWN_METHODS(V)
3165
1722
#undef V
3166
1476
3167
1476
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
3168
57810
  HTTP_STATUS_CODES(V)
3169
1722
#undef V
3170
2214
3171
2706
  target->Set(context, env->constants_string(), constants).Check();
3172
1722
}
3173
1722
}  // namespace http2
3174
1968
}  // namespace node
3175
1968
3176

20672
NODE_MODULE_CONTEXT_AWARE_INTERNAL(http2, node::http2::Initialize)