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: 22 1533 1.4 %
Date: 2019-02-01 22:03:38 Branches: 7 717 1.0 %

Line Branch Exec Source
1
#include "aliased_buffer.h"
2
#include "debug_utils.h"
3
#include "node.h"
4
#include "node_buffer.h"
5
#include "node_http2.h"
6
#include "node_http2_state.h"
7
#include "node_perf.h"
8
#include "util.h"
9
10
#include <algorithm>
11
12
namespace node {
13
14
using v8::ArrayBuffer;
15
using v8::ArrayBufferCreationMode;
16
using v8::Boolean;
17
using v8::Context;
18
using v8::Float64Array;
19
using v8::Function;
20
using v8::Integer;
21
using v8::NewStringType;
22
using v8::Number;
23
using v8::ObjectTemplate;
24
using v8::String;
25
using v8::Uint32;
26
using v8::Uint32Array;
27
using v8::Undefined;
28
29
using node::performance::PerformanceEntry;
30
namespace http2 {
31
32
namespace {
33
34
const char zero_bytes_256[256] = {};
35
36
inline Http2Stream* GetStream(Http2Session* session,
37
                              int32_t id,
38
                              nghttp2_data_source* source) {
39
  Http2Stream* stream = static_cast<Http2Stream*>(source->ptr);
40
  if (stream == nullptr)
41
    stream = session->FindStream(id);
42
  CHECK_NOT_NULL(stream);
43
  CHECK_EQ(id, stream->id());
44
  return stream;
45
}
46
47
}  // anonymous namespace
48
49
// These configure the callbacks required by nghttp2 itself. There are
50
// two sets of callback functions, one that is used if a padding callback
51
// is set, and other that does not include the padding callback.
52
328
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
53
    Callbacks(false),
54
164
    Callbacks(true)};
55
56
// The Http2Scope object is used to queue a write to the i/o stream. It is
57
// used whenever any action is take on the underlying nghttp2 API that may
58
// push data into nghttp2 outbound data queue.
59
//
60
// For example:
61
//
62
// Http2Scope h2scope(session);
63
// nghttp2_submit_ping(**session, ... );
64
//
65
// When the Http2Scope passes out of scope and is deconstructed, it will
66
// call Http2Session::MaybeScheduleWrite().
67
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
68
69
Http2Scope::Http2Scope(Http2Session* session) {
70
  if (session == nullptr)
71
    return;
72
73
  if (session->flags_ & (SESSION_STATE_HAS_SCOPE |
74
                         SESSION_STATE_WRITE_SCHEDULED)) {
75
    // There is another scope further below on the stack, or it is already
76
    // known that a write is scheduled. In either case, there is nothing to do.
77
    return;
78
  }
79
  session->flags_ |= SESSION_STATE_HAS_SCOPE;
80
  session_ = session;
81
82
  // Always keep the session object alive for at least as long as
83
  // this scope is active.
84
  session_handle_ = session->object();
85
  CHECK(!session_handle_.IsEmpty());
86
}
87
88
Http2Scope::~Http2Scope() {
89
  if (session_ == nullptr)
90
    return;
91
92
  session_->flags_ &= ~SESSION_STATE_HAS_SCOPE;
93
  session_->MaybeScheduleWrite();
94
}
95
96
// The Http2Options object is used during the construction of Http2Session
97
// instances to configure an appropriate nghttp2_options struct. The class
98
// uses a single TypedArray instance that is shared with the JavaScript side
99
// to more efficiently pass values back and forth.
100
Http2Options::Http2Options(Environment* env, nghttp2_session_type type) {
101
  nghttp2_option_new(&options_);
102
103
  // Make sure closed connections aren't kept around, taking up memory.
104
  // Note that this breaks the priority tree, which we don't use.
105
  nghttp2_option_set_no_closed_streams(options_, 1);
106
107
  // We manually handle flow control within a session in order to
108
  // implement backpressure -- that is, we only send WINDOW_UPDATE
109
  // frames to the remote peer as data is actually consumed by user
110
  // code. This ensures that the flow of data over the connection
111
  // does not move too quickly and limits the amount of data we
112
  // are required to buffer.
113
  nghttp2_option_set_no_auto_window_update(options_, 1);
114
115
  // Enable built in support for receiving ALTSVC and ORIGIN frames (but
116
  // only on client side sessions
117
  if (type == NGHTTP2_SESSION_CLIENT) {
118
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC);
119
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ORIGIN);
120
  }
121
122
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
123
      env->http2_state()->options_buffer;
124
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
125
126
  if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) {
127
    nghttp2_option_set_max_deflate_dynamic_table_size(
128
        options_,
129
        buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
130
  }
131
132
  if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
133
    nghttp2_option_set_max_reserved_remote_streams(
134
        options_,
135
        buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]);
136
  }
137
138
  if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) {
139
    nghttp2_option_set_max_send_header_block_length(
140
        options_,
141
        buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
142
  }
143
144
  // Recommended default
145
  nghttp2_option_set_peer_max_concurrent_streams(options_, 100);
146
  if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
147
    nghttp2_option_set_peer_max_concurrent_streams(
148
        options_,
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
  if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
157
    padding_strategy_type strategy =
158
        static_cast<padding_strategy_type>(
159
            buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
160
    SetPaddingStrategy(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
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS)) {
168
    SetMaxHeaderPairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
169
  }
170
171
  // The HTTP2 specification places no limits on the number of HTTP2
172
  // PING frames that can be sent. In order to prevent PINGS from being
173
  // abused as an attack vector, however, we place a strict upper limit
174
  // on the number of unacknowledged PINGS that can be sent at any given
175
  // time.
176
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS)) {
177
    SetMaxOutstandingPings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
178
  }
179
180
  // The HTTP2 specification places no limits on the number of HTTP2
181
  // SETTINGS frames that can be sent. In order to prevent PINGS from being
182
  // abused as an attack vector, however, we place a strict upper limit
183
  // on the number of unacknowledged SETTINGS that can be sent at any given
184
  // time.
185
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS)) {
186
    SetMaxOutstandingSettings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
187
  }
188
189
  // The HTTP2 specification places no limits on the amount of memory
190
  // that a session can consume. In order to prevent abuse, we place a
191
  // cap on the amount of memory a session can consume at any given time.
192
  // this is a credit based system. Existing streams may cause the limit
193
  // to be temporarily exceeded but once over the limit, new streams cannot
194
  // created.
195
  // Important: The maxSessionMemory option in javascript is expressed in
196
  //            terms of MB increments (i.e. the value 1 == 1 MB)
197
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY)) {
198
    SetMaxSessionMemory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1e6);
199
  }
200
}
201
202
void Http2Session::Http2Settings::Init() {
203
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
204
      env()->http2_state()->settings_buffer;
205
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
206
207
  size_t n = 0;
208
209
#define GRABSETTING(N, trace)                                                 \
210
  if (flags & (1 << IDX_SETTINGS_##N)) {                                      \
211
    uint32_t val = buffer[IDX_SETTINGS_##N];                                  \
212
    if (session_ != nullptr)                                                  \
213
      Debug(session_, "setting " trace ": %d\n", val);                        \
214
    entries_[n++] =                                                           \
215
        nghttp2_settings_entry {NGHTTP2_SETTINGS_##N, val};                   \
216
  }
217
218
  GRABSETTING(HEADER_TABLE_SIZE, "header table size");
219
  GRABSETTING(MAX_CONCURRENT_STREAMS, "max concurrent streams");
220
  GRABSETTING(MAX_FRAME_SIZE, "max frame size");
221
  GRABSETTING(INITIAL_WINDOW_SIZE, "initial window size");
222
  GRABSETTING(MAX_HEADER_LIST_SIZE, "max header list size");
223
  GRABSETTING(ENABLE_PUSH, "enable push");
224
  GRABSETTING(ENABLE_CONNECT_PROTOCOL, "enable connect protocol");
225
226
#undef GRABSETTING
227
228
  count_ = n;
229
}
230
231
Http2Session::Http2Settings::Http2Settings(Environment* env,
232
    Http2Session* session, uint64_t start_time)
233
        : AsyncWrap(env,
234
                    env->http2settings_constructor_template()
235
                        ->NewInstance(env->context())
236
                            .ToLocalChecked(),
237
                    PROVIDER_HTTP2SETTINGS),
238
          session_(session),
239
          startTime_(start_time) {
240
  Init();
241
}
242
243
244
Http2Session::Http2Settings::Http2Settings(Environment* env)
245
  : Http2Settings(env, nullptr, 0) {}
246
247
// The Http2Settings class is used to configure a SETTINGS frame that is
248
// to be sent to the connected peer. The settings are set using a TypedArray
249
// that is shared with the JavaScript side.
250
Http2Session::Http2Settings::Http2Settings(Http2Session* session)
251
  : Http2Settings(session->env(), session, uv_hrtime()) {}
252
253
// Generates a Buffer that contains the serialized payload of a SETTINGS
254
// frame. This can be used, for instance, to create the Base64-encoded
255
// content of an Http2-Settings header field.
256
Local<Value> Http2Session::Http2Settings::Pack() {
257
  const size_t len = count_ * 6;
258
  Local<Value> buf = Buffer::New(env(), len).ToLocalChecked();
259
  ssize_t ret =
260
      nghttp2_pack_settings_payload(
261
        reinterpret_cast<uint8_t*>(Buffer::Data(buf)), len,
262
        &entries_[0], count_);
263
  if (ret >= 0)
264
    return buf;
265
  else
266
    return Undefined(env()->isolate());
267
}
268
269
// Updates the shared TypedArray with the current remote or local settings for
270
// the session.
271
void Http2Session::Http2Settings::Update(Environment* env,
272
                                         Http2Session* session,
273
                                         get_setting fn) {
274
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
275
      env->http2_state()->settings_buffer;
276
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
277
      fn(**session, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
278
  buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
279
      fn(**session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
280
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
281
      fn(**session, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
282
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
283
      fn(**session, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
284
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
285
      fn(**session, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
286
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
287
      fn(**session, NGHTTP2_SETTINGS_ENABLE_PUSH);
288
  buffer[IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL] =
289
      fn(**session, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
290
}
291
292
// Initializes the shared TypedArray with the default settings values.
293
void Http2Session::Http2Settings::RefreshDefaults(Environment* env) {
294
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
295
      env->http2_state()->settings_buffer;
296
297
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
298
      DEFAULT_SETTINGS_HEADER_TABLE_SIZE;
299
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
300
      DEFAULT_SETTINGS_ENABLE_PUSH;
301
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
302
      DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE;
303
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
304
      DEFAULT_SETTINGS_MAX_FRAME_SIZE;
305
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
306
      DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
307
  buffer[IDX_SETTINGS_COUNT] =
308
    (1 << IDX_SETTINGS_HEADER_TABLE_SIZE) |
309
    (1 << IDX_SETTINGS_ENABLE_PUSH) |
310
    (1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE) |
311
    (1 << IDX_SETTINGS_MAX_FRAME_SIZE) |
312
    (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE);
313
}
314
315
316
void Http2Session::Http2Settings::Send() {
317
  Http2Scope h2scope(session_);
318
  CHECK_EQ(nghttp2_submit_settings(**session_, NGHTTP2_FLAG_NONE,
319
                                   &entries_[0], count_), 0);
320
}
321
322
void Http2Session::Http2Settings::Done(bool ack) {
323
  uint64_t end = uv_hrtime();
324
  double duration = (end - startTime_) / 1e6;
325
326
  Local<Value> argv[2] = {
327
    Boolean::New(env()->isolate(), ack),
328
    Number::New(env()->isolate(), duration)
329
  };
330
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
331
  delete this;
332
}
333
334
// The Http2Priority class initializes an appropriate nghttp2_priority_spec
335
// struct used when either creating a stream or updating its priority
336
// settings.
337
Http2Priority::Http2Priority(Environment* env,
338
                             Local<Value> parent,
339
                             Local<Value> weight,
340
                             Local<Value> exclusive) {
341
  Local<Context> context = env->context();
342
  int32_t parent_ = parent->Int32Value(context).ToChecked();
343
  int32_t weight_ = weight->Int32Value(context).ToChecked();
344
  bool exclusive_ = exclusive->BooleanValue(env->isolate());
345
  Debug(env, DebugCategory::HTTP2STREAM,
346
        "Http2Priority: parent: %d, weight: %d, exclusive: %d\n",
347
        parent_, weight_, exclusive_);
348
  nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0);
349
}
350
351
352
const char* Http2Session::TypeName() const {
353
  switch (session_type_) {
354
    case NGHTTP2_SESSION_SERVER: return "server";
355
    case NGHTTP2_SESSION_CLIENT: return "client";
356
    default:
357
      // This should never happen
358
      ABORT();
359
  }
360
}
361
362
// The Headers class initializes a proper array of nghttp2_nv structs
363
// containing the header name value pairs.
364
Headers::Headers(Isolate* isolate,
365
                 Local<Context> context,
366
                 Local<Array> headers) {
367
  Local<Value> header_string = headers->Get(context, 0).ToLocalChecked();
368
  Local<Value> header_count = headers->Get(context, 1).ToLocalChecked();
369
  count_ = header_count.As<Uint32>()->Value();
370
  int header_string_len = header_string.As<String>()->Length();
371
372
  if (count_ == 0) {
373
    CHECK_EQ(header_string_len, 0);
374
    return;
375
  }
376
377
  // Allocate a single buffer with count_ nghttp2_nv structs, followed
378
  // by the raw header data as passed from JS. This looks like:
379
  // | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents |
380
  buf_.AllocateSufficientStorage((alignof(nghttp2_nv) - 1) +
381
                                 count_ * sizeof(nghttp2_nv) +
382
                                 header_string_len);
383
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
384
  char* start = reinterpret_cast<char*>(
385
      RoundUp(reinterpret_cast<uintptr_t>(*buf_), alignof(nghttp2_nv)));
386
  char* header_contents = start + (count_ * sizeof(nghttp2_nv));
387
  nghttp2_nv* const nva = reinterpret_cast<nghttp2_nv*>(start);
388
389
  CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length());
390
  CHECK_EQ(header_string.As<String>()->WriteOneByte(
391
               isolate,
392
               reinterpret_cast<uint8_t*>(header_contents),
393
               0,
394
               header_string_len,
395
               String::NO_NULL_TERMINATION),
396
           header_string_len);
397
398
  size_t n = 0;
399
  char* p;
400
  for (p = header_contents; p < header_contents + header_string_len; n++) {
401
    if (n >= count_) {
402
      // This can happen if a passed header contained a null byte. In that
403
      // case, just provide nghttp2 with an invalid header to make it reject
404
      // the headers list.
405
      static uint8_t zero = '\0';
406
      nva[0].name = nva[0].value = &zero;
407
      nva[0].namelen = nva[0].valuelen = 1;
408
      count_ = 1;
409
      return;
410
    }
411
412
    nva[n].flags = NGHTTP2_NV_FLAG_NONE;
413
    nva[n].name = reinterpret_cast<uint8_t*>(p);
414
    nva[n].namelen = strlen(p);
415
    p += nva[n].namelen + 1;
416
    nva[n].value = reinterpret_cast<uint8_t*>(p);
417
    nva[n].valuelen = strlen(p);
418
    p += nva[n].valuelen + 1;
419
  }
420
}
421
422
Origins::Origins(Isolate* isolate,
423
                 Local<Context> context,
424
                 Local<String> origin_string,
425
                 size_t origin_count) : count_(origin_count) {
426
  int origin_string_len = origin_string->Length();
427
  if (count_ == 0) {
428
    CHECK_EQ(origin_string_len, 0);
429
    return;
430
  }
431
432
  // Allocate a single buffer with count_ nghttp2_nv structs, followed
433
  // by the raw header data as passed from JS. This looks like:
434
  // | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents |
435
  buf_.AllocateSufficientStorage((alignof(nghttp2_origin_entry) - 1) +
436
                                 count_ * sizeof(nghttp2_origin_entry) +
437
                                 origin_string_len);
438
439
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
440
  char* start = reinterpret_cast<char*>(
441
      RoundUp(reinterpret_cast<uintptr_t>(*buf_),
442
              alignof(nghttp2_origin_entry)));
443
  char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
444
  nghttp2_origin_entry* const nva =
445
      reinterpret_cast<nghttp2_origin_entry*>(start);
446
447
  CHECK_LE(origin_contents + origin_string_len, *buf_ + buf_.length());
448
  CHECK_EQ(origin_string->WriteOneByte(
449
               isolate,
450
               reinterpret_cast<uint8_t*>(origin_contents),
451
               0,
452
               origin_string_len,
453
               String::NO_NULL_TERMINATION),
454
           origin_string_len);
455
456
  size_t n = 0;
457
  char* p;
458
  for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
459
    if (n >= count_) {
460
      static uint8_t zero = '\0';
461
      nva[0].origin = &zero;
462
      nva[0].origin_len = 1;
463
      count_ = 1;
464
      return;
465
    }
466
467
    nva[n].origin = reinterpret_cast<uint8_t*>(p);
468
    nva[n].origin_len = strlen(p);
469
    p += nva[n].origin_len + 1;
470
  }
471
}
472
473
// Sets the various callback functions that nghttp2 will use to notify us
474
// about significant events while processing http2 stuff.
475
328
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
476
328
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0);
477
478
  nghttp2_session_callbacks_set_on_begin_headers_callback(
479
328
    callbacks, OnBeginHeadersCallback);
480
  nghttp2_session_callbacks_set_on_header_callback2(
481
328
    callbacks, OnHeaderCallback);
482
  nghttp2_session_callbacks_set_on_frame_recv_callback(
483
328
    callbacks, OnFrameReceive);
484
  nghttp2_session_callbacks_set_on_stream_close_callback(
485
328
    callbacks, OnStreamClose);
486
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
487
328
    callbacks, OnDataChunkReceived);
488
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
489
328
    callbacks, OnFrameNotSent);
490
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
491
328
    callbacks, OnInvalidHeader);
492
  nghttp2_session_callbacks_set_error_callback(
493
328
    callbacks, OnNghttpError);
494
  nghttp2_session_callbacks_set_send_data_callback(
495
328
    callbacks, OnSendData);
496
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
497
328
    callbacks, OnInvalidFrame);
498
  nghttp2_session_callbacks_set_on_frame_send_callback(
499
328
    callbacks, OnFrameSent);
500
501
328
  if (kHasGetPaddingCallback) {
502
    nghttp2_session_callbacks_set_select_padding_callback(
503
164
      callbacks, OnSelectPadding);
504
  }
505
328
}
506
507
508
328
Http2Session::Callbacks::~Callbacks() {
509
328
  nghttp2_session_callbacks_del(callbacks);
510
328
}
511
512
// Track memory allocated by nghttp2 using a custom allocator.
513
class Http2Session::MemoryAllocatorInfo {
514
 public:
515
  explicit MemoryAllocatorInfo(Http2Session* session)
516
      : info({ session, H2Malloc, H2Free, H2Calloc, H2Realloc }) {}
517
518
  static void* H2Malloc(size_t size, void* user_data) {
519
    return H2Realloc(nullptr, size, user_data);
520
  }
521
522
  static void* H2Calloc(size_t nmemb, size_t size, void* user_data) {
523
    size_t real_size = MultiplyWithOverflowCheck(nmemb, size);
524
    void* mem = H2Malloc(real_size, user_data);
525
    if (mem != nullptr)
526
      memset(mem, 0, real_size);
527
    return mem;
528
  }
529
530
  static void H2Free(void* ptr, void* user_data) {
531
    if (ptr == nullptr) return;  // free(null); happens quite often.
532
    void* result = H2Realloc(ptr, 0, user_data);
533
    CHECK_EQ(result, nullptr);
534
  }
535
536
  static void* H2Realloc(void* ptr, size_t size, void* user_data) {
537
    Http2Session* session = static_cast<Http2Session*>(user_data);
538
    size_t previous_size = 0;
539
    char* original_ptr = nullptr;
540
541
    // We prepend each allocated buffer with a size_t containing the full
542
    // size of the allocation.
543
    if (size > 0) size += sizeof(size_t);
544
545
    if (ptr != nullptr) {
546
      // We are free()ing or re-allocating.
547
      original_ptr = static_cast<char*>(ptr) - sizeof(size_t);
548
      previous_size = *reinterpret_cast<size_t*>(original_ptr);
549
      // This means we called StopTracking() on this pointer before.
550
      if (previous_size == 0) {
551
        // Fall back to the standard Realloc() function.
552
        char* ret = UncheckedRealloc(original_ptr, size);
553
        if (ret != nullptr)
554
          ret += sizeof(size_t);
555
        return ret;
556
      }
557
    }
558
    CHECK_GE(session->current_nghttp2_memory_, previous_size);
559
560
    // TODO(addaleax): Add the following, and handle NGHTTP2_ERR_NOMEM properly
561
    // everywhere:
562
    //
563
    // if (size > previous_size &&
564
    //     !session->IsAvailableSessionMemory(size - previous_size)) {
565
    //  return nullptr;
566
    //}
567
568
    char* mem = UncheckedRealloc(original_ptr, size);
569
570
    if (mem != nullptr) {
571
      // Adjust the memory info counter.
572
      session->current_nghttp2_memory_ += size - previous_size;
573
      *reinterpret_cast<size_t*>(mem) = size;
574
      mem += sizeof(size_t);
575
    } else if (size == 0) {
576
      session->current_nghttp2_memory_ -= previous_size;
577
    }
578
579
    return mem;
580
  }
581
582
  static void StopTracking(Http2Session* session, void* ptr) {
583
    size_t* original_ptr = reinterpret_cast<size_t*>(
584
        static_cast<char*>(ptr) - sizeof(size_t));
585
    session->current_nghttp2_memory_ -= *original_ptr;
586
    *original_ptr = 0;
587
  }
588
589
  inline nghttp2_mem* operator*() { return &info; }
590
591
  nghttp2_mem info;
592
};
593
594
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
595
  MemoryAllocatorInfo::StopTracking(this, buf);
596
}
597
598
Http2Session::Http2Session(Environment* env,
599
                           Local<Object> wrap,
600
                           nghttp2_session_type type)
601
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
602
      session_type_(type) {
603
  MakeWeak();
604
  statistics_.start_time = uv_hrtime();
605
606
  // Capture the configuration options for this session
607
  Http2Options opts(env, type);
608
609
  max_session_memory_ = opts.GetMaxSessionMemory();
610
611
  uint32_t maxHeaderPairs = opts.GetMaxHeaderPairs();
612
  max_header_pairs_ =
613
      type == NGHTTP2_SESSION_SERVER
614
          ? std::max(maxHeaderPairs, 4U)     // minimum # of request headers
615
          : std::max(maxHeaderPairs, 1U);    // minimum # of response headers
616
617
  max_outstanding_pings_ = opts.GetMaxOutstandingPings();
618
  max_outstanding_settings_ = opts.GetMaxOutstandingSettings();
619
620
  padding_strategy_ = opts.GetPaddingStrategy();
621
622
  bool hasGetPaddingCallback =
623
      padding_strategy_ != PADDING_STRATEGY_NONE;
624
625
  nghttp2_session_callbacks* callbacks
626
      = callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks;
627
628
  auto fn = type == NGHTTP2_SESSION_SERVER ?
629
      nghttp2_session_server_new3 :
630
      nghttp2_session_client_new3;
631
632
  MemoryAllocatorInfo allocator_info(this);
633
634
  // This should fail only if the system is out of memory, which
635
  // is going to cause lots of other problems anyway, or if any
636
  // of the options are out of acceptable range, which we should
637
  // be catching before it gets this far. Either way, crash if this
638
  // fails.
639
  CHECK_EQ(fn(&session_, callbacks, this, *opts, *allocator_info), 0);
640
641
  outgoing_storage_.reserve(4096);
642
  outgoing_buffers_.reserve(32);
643
}
644
645
Http2Session::~Http2Session() {
646
  CHECK_EQ(flags_ & SESSION_STATE_HAS_SCOPE, 0);
647
  Debug(this, "freeing nghttp2 session");
648
  for (const auto& iter : streams_)
649
    iter.second->session_ = nullptr;
650
  nghttp2_session_del(session_);
651
  CHECK_EQ(current_nghttp2_memory_, 0);
652
}
653
654
std::string Http2Session::diagnostic_name() const {
655
  return std::string("Http2Session ") + TypeName() + " (" +
656
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
657
}
658
659
inline bool HasHttp2Observer(Environment* env) {
660
  AliasedBuffer<uint32_t, Uint32Array>& observers =
661
      env->performance_state()->observers;
662
  return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
663
}
664
665
void Http2Stream::EmitStatistics() {
666
  if (!HasHttp2Observer(env()))
667
    return;
668
  Http2StreamPerformanceEntry* entry =
669
    new Http2StreamPerformanceEntry(env(), id_, statistics_);
670
  env()->SetImmediate([](Environment* env, void* data) {
671
    // This takes ownership, the entry is destroyed at the end of this scope.
672
    std::unique_ptr<Http2StreamPerformanceEntry> entry {
673
        static_cast<Http2StreamPerformanceEntry*>(data) };
674
    if (!HasHttp2Observer(env))
675
      return;
676
    HandleScope handle_scope(env->isolate());
677
    AliasedBuffer<double, Float64Array>& buffer =
678
        env->http2_state()->stream_stats_buffer;
679
    buffer[IDX_STREAM_STATS_ID] = entry->id();
680
    if (entry->first_byte() != 0) {
681
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] =
682
          (entry->first_byte() - entry->startTimeNano()) / 1e6;
683
    } else {
684
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0;
685
    }
686
    if (entry->first_header() != 0) {
687
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] =
688
          (entry->first_header() - entry->startTimeNano()) / 1e6;
689
    } else {
690
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0;
691
    }
692
    if (entry->first_byte_sent() != 0) {
693
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] =
694
          (entry->first_byte_sent() - entry->startTimeNano()) / 1e6;
695
    } else {
696
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0;
697
    }
698
    buffer[IDX_STREAM_STATS_SENTBYTES] = entry->sent_bytes();
699
    buffer[IDX_STREAM_STATS_RECEIVEDBYTES] = entry->received_bytes();
700
    Local<Object> obj;
701
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
702
  }, static_cast<void*>(entry));
703
}
704
705
void Http2Session::EmitStatistics() {
706
  if (!HasHttp2Observer(env()))
707
    return;
708
  Http2SessionPerformanceEntry* entry =
709
    new Http2SessionPerformanceEntry(env(), statistics_, session_type_);
710
  env()->SetImmediate([](Environment* env, void* data) {
711
    // This takes ownership, the entr is destroyed at the end of this scope.
712
    std::unique_ptr<Http2SessionPerformanceEntry> entry {
713
        static_cast<Http2SessionPerformanceEntry*>(data) };
714
    if (!HasHttp2Observer(env))
715
      return;
716
    HandleScope handle_scope(env->isolate());
717
    AliasedBuffer<double, Float64Array>& buffer =
718
        env->http2_state()->session_stats_buffer;
719
    buffer[IDX_SESSION_STATS_TYPE] = entry->type();
720
    buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6;
721
    buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count();
722
    buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent();
723
    buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count();
724
    buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] =
725
        entry->stream_average_duration();
726
    buffer[IDX_SESSION_STATS_DATA_SENT] = entry->data_sent();
727
    buffer[IDX_SESSION_STATS_DATA_RECEIVED] = entry->data_received();
728
    buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] =
729
        entry->max_concurrent_streams();
730
    Local<Object> obj;
731
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
732
  }, static_cast<void*>(entry));
733
}
734
735
// Closes the session and frees the associated resources
736
void Http2Session::Close(uint32_t code, bool socket_closed) {
737
  Debug(this, "closing session");
738
739
  if (flags_ & SESSION_STATE_CLOSING)
740
    return;
741
  flags_ |= SESSION_STATE_CLOSING;
742
743
  // Stop reading on the i/o stream
744
  if (stream_ != nullptr)
745
    stream_->ReadStop();
746
747
  // If the socket is not closed, then attempt to send a closing GOAWAY
748
  // frame. There is no guarantee that this GOAWAY will be received by
749
  // the peer but the HTTP/2 spec recommends sending it anyway. We'll
750
  // make a best effort.
751
  if (!socket_closed) {
752
    Debug(this, "terminating session with code %d", code);
753
    CHECK_EQ(nghttp2_session_terminate_session(session_, code), 0);
754
    SendPendingData();
755
  } else if (stream_ != nullptr) {
756
    stream_->RemoveStreamListener(this);
757
  }
758
759
  flags_ |= SESSION_STATE_CLOSED;
760
761
  // If there are outstanding pings, those will need to be canceled, do
762
  // so on the next iteration of the event loop to avoid calling out into
763
  // javascript since this may be called during garbage collection.
764
  while (!outstanding_pings_.empty()) {
765
    Http2Session::Http2Ping* ping = PopPing();
766
    env()->SetImmediate([](Environment* env, void* data) {
767
      static_cast<Http2Session::Http2Ping*>(data)->Done(false);
768
    }, static_cast<void*>(ping));
769
  }
770
771
  statistics_.end_time = uv_hrtime();
772
  EmitStatistics();
773
}
774
775
// Locates an existing known stream by ID. nghttp2 has a similar method
776
// but this is faster and does not fail if the stream is not found.
777
inline Http2Stream* Http2Session::FindStream(int32_t id) {
778
  auto s = streams_.find(id);
779
  return s != streams_.end() ? s->second : nullptr;
780
}
781
782
inline bool Http2Session::CanAddStream() {
783
  uint32_t maxConcurrentStreams =
784
      nghttp2_session_get_local_settings(
785
          session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
786
  size_t maxSize =
787
      std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
788
  // We can add a new stream so long as we are less than the current
789
  // maximum on concurrent streams and there's enough available memory
790
  return streams_.size() < maxSize &&
791
         IsAvailableSessionMemory(sizeof(Http2Stream));
792
}
793
794
inline void Http2Session::AddStream(Http2Stream* stream) {
795
  CHECK_GE(++statistics_.stream_count, 0);
796
  streams_[stream->id()] = stream;
797
  size_t size = streams_.size();
798
  if (size > statistics_.max_concurrent_streams)
799
    statistics_.max_concurrent_streams = size;
800
  IncrementCurrentSessionMemory(sizeof(*stream));
801
}
802
803
804
inline void Http2Session::RemoveStream(Http2Stream* stream) {
805
  if (streams_.empty() || stream == nullptr)
806
    return;  // Nothing to remove, item was never added?
807
  streams_.erase(stream->id());
808
  DecrementCurrentSessionMemory(sizeof(*stream));
809
}
810
811
// Used as one of the Padding Strategy functions. Will attempt to ensure
812
// that the total frame size, including header bytes, are 8-byte aligned.
813
// If maxPayloadLen is smaller than the number of bytes necessary to align,
814
// will return maxPayloadLen instead.
815
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
816
                                            size_t maxPayloadLen) {
817
  size_t r = (frameLen + 9) % 8;
818
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
819
820
  size_t pad = frameLen + (8 - r);
821
822
  // If maxPayloadLen happens to be less than the calculated pad length,
823
  // use the max instead, even tho this means the frame will not be
824
  // aligned.
825
  pad = std::min(maxPayloadLen, pad);
826
  Debug(this, "using frame size padding: %d", pad);
827
  return pad;
828
}
829
830
// Used as one of the Padding Strategy functions. Uses the maximum amount
831
// of padding allowed for the current frame.
832
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
833
                                            size_t maxPayloadLen) {
834
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
835
  return maxPayloadLen;
836
}
837
838
// Used as one of the Padding Strategy functions. Uses a callback to JS land
839
// to determine the amount of padding for the current frame. This option is
840
// rather more expensive because of the JS boundary cross. It generally should
841
// not be the preferred option.
842
ssize_t Http2Session::OnCallbackPadding(size_t frameLen,
843
                                        size_t maxPayloadLen) {
844
  if (frameLen == 0) return 0;
845
  Debug(this, "using callback to determine padding");
846
  Isolate* isolate = env()->isolate();
847
  HandleScope handle_scope(isolate);
848
  Local<Context> context = env()->context();
849
  Context::Scope context_scope(context);
850
851
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
852
      env()->http2_state()->padding_buffer;
853
  buffer[PADDING_BUF_FRAME_LENGTH] = frameLen;
854
  buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen;
855
  buffer[PADDING_BUF_RETURN_VALUE] = frameLen;
856
  MakeCallback(env()->http2session_on_select_padding_function(), 0, nullptr);
857
  uint32_t retval = buffer[PADDING_BUF_RETURN_VALUE];
858
  retval = std::min(retval, static_cast<uint32_t>(maxPayloadLen));
859
  retval = std::max(retval, static_cast<uint32_t>(frameLen));
860
  Debug(this, "using padding size %d", retval);
861
  return retval;
862
}
863
864
865
// Write data received from the i/o stream to the underlying nghttp2_session.
866
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
867
// various callback functions. Each of these will typically result in a call
868
// out to JavaScript so this particular function is rather hot and can be
869
// quite expensive. This is a potential performance optimization target later.
870
ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) {
871
  size_t total = 0;
872
  // Note that nghttp2_session_mem_recv is a synchronous operation that
873
  // will trigger a number of other callbacks. Those will, in turn have
874
  // multiple side effects.
875
  for (size_t n = 0; n < nbufs; n++) {
876
    Debug(this, "receiving %d bytes [wants data? %d]",
877
          bufs[n].len,
878
          nghttp2_session_want_read(session_));
879
    ssize_t ret =
880
      nghttp2_session_mem_recv(session_,
881
                               reinterpret_cast<uint8_t*>(bufs[n].base),
882
                               bufs[n].len);
883
    CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
884
885
    if (ret < 0)
886
      return ret;
887
888
    total += ret;
889
  }
890
  // Send any data that was queued up while processing the received data.
891
  if (!IsDestroyed()) {
892
    SendPendingData();
893
  }
894
  return total;
895
}
896
897
898
inline int32_t GetFrameID(const nghttp2_frame* frame) {
899
  // If this is a push promise, we want to grab the id of the promised stream
900
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
901
      frame->push_promise.promised_stream_id :
902
      frame->hd.stream_id;
903
}
904
905
906
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
907
// callback to determine if a new stream is being created or if we are simply
908
// adding a new block of headers to an existing stream. The header pairs
909
// themselves are set in the OnHeaderCallback
910
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
911
                                         const nghttp2_frame* frame,
912
                                         void* user_data) {
913
  Http2Session* session = static_cast<Http2Session*>(user_data);
914
  int32_t id = GetFrameID(frame);
915
  Debug(session, "beginning headers for stream %d", id);
916
917
  Http2Stream* stream = session->FindStream(id);
918
  // The common case is that we're creating a new stream. The less likely
919
  // case is that we're receiving a set of trailers
920
  if (LIKELY(stream == nullptr)) {
921
    if (UNLIKELY(!session->CanAddStream())) {
922
      // Too many concurrent streams being opened
923
      nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id,
924
                                NGHTTP2_ENHANCE_YOUR_CALM);
925
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
926
    }
927
    new Http2Stream(session, id, frame->headers.cat);
928
  } else if (!stream->IsDestroyed()) {
929
    stream->StartHeaders(frame->headers.cat);
930
  }
931
  return 0;
932
}
933
934
// Called by nghttp2 for each header name/value pair in a HEADERS block.
935
// This had to have been preceded by a call to OnBeginHeadersCallback so
936
// the Http2Stream is guaranteed to already exist.
937
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
938
                                   const nghttp2_frame* frame,
939
                                   nghttp2_rcbuf* name,
940
                                   nghttp2_rcbuf* value,
941
                                   uint8_t flags,
942
                                   void* user_data) {
943
  Http2Session* session = static_cast<Http2Session*>(user_data);
944
  int32_t id = GetFrameID(frame);
945
  Http2Stream* stream = session->FindStream(id);
946
  // If stream is null at this point, either something odd has happened
947
  // or the stream was closed locally while header processing was occurring.
948
  // either way, do not proceed and close the stream.
949
  if (UNLIKELY(stream == nullptr))
950
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
951
952
  // If the stream has already been destroyed, ignore.
953
  if (!stream->IsDestroyed() && !stream->AddHeader(name, value, flags)) {
954
    // This will only happen if the connected peer sends us more
955
    // than the allowed number of header items at any given time
956
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
957
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
958
  }
959
  return 0;
960
}
961
962
963
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
964
// only a handful of frame types that we care about handling here.
965
int Http2Session::OnFrameReceive(nghttp2_session* handle,
966
                                 const nghttp2_frame* frame,
967
                                 void* user_data) {
968
  Http2Session* session = static_cast<Http2Session*>(user_data);
969
  session->statistics_.frame_count++;
970
  Debug(session, "complete frame received: type: %d",
971
        frame->hd.type);
972
  switch (frame->hd.type) {
973
    case NGHTTP2_DATA:
974
      session->HandleDataFrame(frame);
975
      break;
976
    case NGHTTP2_PUSH_PROMISE:
977
      // Intentional fall-through, handled just like headers frames
978
    case NGHTTP2_HEADERS:
979
      session->HandleHeadersFrame(frame);
980
      break;
981
    case NGHTTP2_SETTINGS:
982
      session->HandleSettingsFrame(frame);
983
      break;
984
    case NGHTTP2_PRIORITY:
985
      session->HandlePriorityFrame(frame);
986
      break;
987
    case NGHTTP2_GOAWAY:
988
      session->HandleGoawayFrame(frame);
989
      break;
990
    case NGHTTP2_PING:
991
      session->HandlePingFrame(frame);
992
      break;
993
    case NGHTTP2_ALTSVC:
994
      session->HandleAltSvcFrame(frame);
995
      break;
996
    case NGHTTP2_ORIGIN:
997
      session->HandleOriginFrame(frame);
998
      break;
999
    default:
1000
      break;
1001
  }
1002
  return 0;
1003
}
1004
1005
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
1006
                                 const nghttp2_frame* frame,
1007
                                 int lib_error_code,
1008
                                 void* user_data) {
1009
  Http2Session* session = static_cast<Http2Session*>(user_data);
1010
1011
  Debug(session, "invalid frame received, code: %d", lib_error_code);
1012
1013
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
1014
  if (nghttp2_is_fatal(lib_error_code) ||
1015
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
1016
    Environment* env = session->env();
1017
    Isolate* isolate = env->isolate();
1018
    HandleScope scope(isolate);
1019
    Local<Context> context = env->context();
1020
    Context::Scope context_scope(context);
1021
    Local<Value> arg = Integer::New(isolate, lib_error_code);
1022
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1023
  }
1024
  return 0;
1025
}
1026
1027
// If nghttp2 is unable to send a queued up frame, it will call this callback
1028
// to let us know. If the failure occurred because we are in the process of
1029
// closing down the session or stream, we go ahead and ignore it. We don't
1030
// really care about those and there's nothing we can reasonably do about it
1031
// anyway. Other types of failures are reported up to JavaScript. This should
1032
// be exceedingly rare.
1033
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1034
                                 const nghttp2_frame* frame,
1035
                                 int error_code,
1036
                                 void* user_data) {
1037
  Http2Session* session = static_cast<Http2Session*>(user_data);
1038
  Environment* env = session->env();
1039
  Debug(session, "frame type %d was not sent, code: %d",
1040
        frame->hd.type, error_code);
1041
1042
  // Do not report if the frame was not sent due to the session closing
1043
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
1044
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1045
      error_code == NGHTTP2_ERR_STREAM_CLOSING) {
1046
    return 0;
1047
  }
1048
1049
  Isolate* isolate = env->isolate();
1050
  HandleScope scope(isolate);
1051
  Local<Context> context = env->context();
1052
  Context::Scope context_scope(context);
1053
1054
  Local<Value> argv[3] = {
1055
    Integer::New(isolate, frame->hd.stream_id),
1056
    Integer::New(isolate, frame->hd.type),
1057
    Integer::New(isolate, error_code)
1058
  };
1059
  session->MakeCallback(
1060
      env->http2session_on_frame_error_function(),
1061
      arraysize(argv), argv);
1062
  return 0;
1063
}
1064
1065
int Http2Session::OnFrameSent(nghttp2_session* handle,
1066
                              const nghttp2_frame* frame,
1067
                              void* user_data) {
1068
  Http2Session* session = static_cast<Http2Session*>(user_data);
1069
  session->statistics_.frame_sent += 1;
1070
  return 0;
1071
}
1072
1073
// Called by nghttp2 when a stream closes.
1074
int Http2Session::OnStreamClose(nghttp2_session* handle,
1075
                                int32_t id,
1076
                                uint32_t code,
1077
                                void* user_data) {
1078
  Http2Session* session = static_cast<Http2Session*>(user_data);
1079
  Environment* env = session->env();
1080
  Isolate* isolate = env->isolate();
1081
  HandleScope scope(isolate);
1082
  Local<Context> context = env->context();
1083
  Context::Scope context_scope(context);
1084
  Debug(session, "stream %d closed with code: %d", id, code);
1085
  Http2Stream* stream = session->FindStream(id);
1086
  // Intentionally ignore the callback if the stream does not exist or has
1087
  // already been destroyed
1088
  if (stream == nullptr || stream->IsDestroyed())
1089
    return 0;
1090
1091
  stream->Close(code);
1092
1093
  // It is possible for the stream close to occur before the stream is
1094
  // ever passed on to the javascript side. If that happens, the callback
1095
  // will return false.
1096
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1097
  MaybeLocal<Value> answer =
1098
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1099
                          1, &arg);
1100
  if (answer.IsEmpty() ||
1101
      !(answer.ToLocalChecked()->BooleanValue(env->isolate()))) {
1102
    // Skip to destroy
1103
    stream->Destroy();
1104
  }
1105
  return 0;
1106
}
1107
1108
// Called by nghttp2 when an invalid header has been received. For now, we
1109
// ignore these. If this callback was not provided, nghttp2 would handle
1110
// invalid headers strictly and would shut down the stream. We are intentionally
1111
// being more lenient here although we may want to revisit this choice later.
1112
int Http2Session::OnInvalidHeader(nghttp2_session* session,
1113
                                  const nghttp2_frame* frame,
1114
                                  nghttp2_rcbuf* name,
1115
                                  nghttp2_rcbuf* value,
1116
                                  uint8_t flags,
1117
                                  void* user_data) {
1118
  // Ignore invalid header fields by default.
1119
  return 0;
1120
}
1121
1122
// When nghttp2 receives a DATA frame, it will deliver the data payload to
1123
// us in discrete chunks. We push these into a linked list stored in the
1124
// Http2Sttream which is flushed out to JavaScript as quickly as possible.
1125
// This can be a particularly hot path.
1126
int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
1127
                                      uint8_t flags,
1128
                                      int32_t id,
1129
                                      const uint8_t* data,
1130
                                      size_t len,
1131
                                      void* user_data) {
1132
  Http2Session* session = static_cast<Http2Session*>(user_data);
1133
  Debug(session, "buffering data chunk for stream %d, size: "
1134
        "%d, flags: %d", id, len, flags);
1135
  Environment* env = session->env();
1136
  HandleScope scope(env->isolate());
1137
1138
  // We should never actually get a 0-length chunk so this check is
1139
  // only a precaution at this point.
1140
  if (len == 0)
1141
    return 0;
1142
1143
  // Notify nghttp2 that we've consumed a chunk of data on the connection
1144
  // so that it can send a WINDOW_UPDATE frame. This is a critical part of
1145
  // the flow control process in http2
1146
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1147
  Http2Stream* stream = session->FindStream(id);
1148
  // If the stream has been destroyed, ignore this chunk
1149
  if (stream->IsDestroyed())
1150
    return 0;
1151
1152
  stream->statistics_.received_bytes += len;
1153
1154
  // Repeatedly ask the stream's owner for memory, and copy the read data
1155
  // into those buffers.
1156
  // The typical case is actually the exception here; Http2StreamListeners
1157
  // know about the HTTP2 session associated with this stream, so they know
1158
  // about the larger from-socket read buffer, so they do not require copying.
1159
  do {
1160
    uv_buf_t buf = stream->EmitAlloc(len);
1161
    ssize_t avail = len;
1162
    if (static_cast<ssize_t>(buf.len) < avail)
1163
      avail = buf.len;
1164
1165
    // `buf.base == nullptr` is the default Http2StreamListener's way
1166
    // of saying that it wants a pointer to the raw original.
1167
    // Since it has access to the original socket buffer from which the data
1168
    // was read in the first place, it can use that to minimize ArrayBuffer
1169
    // allocations.
1170
    if (LIKELY(buf.base == nullptr))
1171
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1172
    else
1173
      memcpy(buf.base, data, avail);
1174
    data += avail;
1175
    len -= avail;
1176
    stream->EmitRead(avail, buf);
1177
1178
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1179
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1180
    // more data is being requested.
1181
    if (stream->IsReading())
1182
      nghttp2_session_consume_stream(handle, id, avail);
1183
    else
1184
      stream->inbound_consumed_data_while_paused_ += avail;
1185
  } while (len != 0);
1186
1187
  return 0;
1188
}
1189
1190
// Called by nghttp2 when it needs to determine how much padding to use in
1191
// a DATA or HEADERS frame.
1192
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1193
                                      const nghttp2_frame* frame,
1194
                                      size_t maxPayloadLen,
1195
                                      void* user_data) {
1196
  Http2Session* session = static_cast<Http2Session*>(user_data);
1197
  ssize_t padding = frame->hd.length;
1198
1199
  switch (session->padding_strategy_) {
1200
    case PADDING_STRATEGY_NONE:
1201
      // Fall-through
1202
      break;
1203
    case PADDING_STRATEGY_MAX:
1204
      padding = session->OnMaxFrameSizePadding(padding, maxPayloadLen);
1205
      break;
1206
    case PADDING_STRATEGY_ALIGNED:
1207
      padding = session->OnDWordAlignedPadding(padding, maxPayloadLen);
1208
      break;
1209
    case PADDING_STRATEGY_CALLBACK:
1210
      padding = session->OnCallbackPadding(padding, maxPayloadLen);
1211
      break;
1212
  }
1213
  return padding;
1214
}
1215
1216
#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we "     \
1217
                         "expected SETTINGS frame.  Perhaps, peer does not "  \
1218
                         "support HTTP/2 properly."
1219
1220
// We use this currently to determine when an attempt is made to use the http2
1221
// protocol with a non-http2 peer.
1222
int Http2Session::OnNghttpError(nghttp2_session* handle,
1223
                                const char* message,
1224
                                size_t len,
1225
                                void* user_data) {
1226
  // Unfortunately, this is currently the only way for us to know if
1227
  // the session errored because the peer is not an http2 peer.
1228
  Http2Session* session = static_cast<Http2Session*>(user_data);
1229
  Debug(session, "Error '%.*s'", len, message);
1230
  if (strncmp(message, BAD_PEER_MESSAGE, len) == 0) {
1231
    Environment* env = session->env();
1232
    Isolate* isolate = env->isolate();
1233
    HandleScope scope(isolate);
1234
    Local<Context> context = env->context();
1235
    Context::Scope context_scope(context);
1236
    Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1237
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1238
  }
1239
  return 0;
1240
}
1241
1242
uv_buf_t Http2StreamListener::OnStreamAlloc(size_t size) {
1243
  // See the comments in Http2Session::OnDataChunkReceived
1244
  // (which is the only possible call site for this method).
1245
  return uv_buf_init(nullptr, size);
1246
}
1247
1248
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1249
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1250
  Http2Session* session = stream->session();
1251
  Environment* env = stream->env();
1252
  HandleScope handle_scope(env->isolate());
1253
  Context::Scope context_scope(env->context());
1254
1255
  if (nread < 0) {
1256
    PassReadErrorToPreviousListener(nread);
1257
    return;
1258
  }
1259
1260
  CHECK(!session->stream_buf_ab_.IsEmpty());
1261
1262
  // There is a single large array buffer for the entire data read from the
1263
  // network; create a slice of that array buffer and emit it as the
1264
  // received data buffer.
1265
  size_t offset = buf.base - session->stream_buf_.base;
1266
1267
  // Verify that the data offset is inside the current read buffer.
1268
  CHECK_LE(offset, session->stream_buf_.len);
1269
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1270
1271
  stream->CallJSOnreadMethod(nread, session->stream_buf_ab_, offset);
1272
}
1273
1274
1275
// Called by OnFrameReceived to notify JavaScript land that a complete
1276
// HEADERS frame has been received and processed. This method converts the
1277
// received headers into a JavaScript array and pushes those out to JS.
1278
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1279
  Isolate* isolate = env()->isolate();
1280
  HandleScope scope(isolate);
1281
  Local<Context> context = env()->context();
1282
  Context::Scope context_scope(context);
1283
1284
  int32_t id = GetFrameID(frame);
1285
  Debug(this, "handle headers frame for stream %d", id);
1286
  Http2Stream* stream = FindStream(id);
1287
1288
  // If the stream has already been destroyed, ignore.
1289
  if (stream->IsDestroyed())
1290
    return;
1291
1292
  std::vector<nghttp2_header> headers(stream->move_headers());
1293
1294
  Local<String> name_str;
1295
  Local<String> value_str;
1296
1297
  // The headers are passed in above as a queue of nghttp2_header structs.
1298
  // The following converts that into a JS array with the structure:
1299
  // [name1, value1, name2, value2, name3, value3, name3, value4] and so on.
1300
  // That array is passed up to the JS layer and converted into an Object form
1301
  // like {name1: value1, name2: value2, name3: [value3, value4]}. We do it
1302
  // this way for performance reasons (it's faster to generate and pass an
1303
  // array than it is to generate and pass the object).
1304
  size_t headers_size = headers.size();
1305
  std::vector<Local<Value>> headers_v(headers_size * 2);
1306
  for (size_t i = 0; i < headers_size; ++i) {
1307
    const nghttp2_header& item = headers[i];
1308
    // The header name and value are passed as external one-byte strings
1309
    headers_v[i * 2] =
1310
        ExternalHeader::New<true>(this, item.name).ToLocalChecked();
1311
    headers_v[i * 2 + 1] =
1312
        ExternalHeader::New<false>(this, item.value).ToLocalChecked();
1313
  }
1314
1315
  Local<Value> args[5] = {
1316
      stream->object(),
1317
      Integer::New(isolate, id),
1318
      Integer::New(isolate, stream->headers_category()),
1319
      Integer::New(isolate, frame->hd.flags),
1320
      Array::New(isolate, headers_v.data(), headers_size * 2)};
1321
  MakeCallback(env()->http2session_on_headers_function(),
1322
               arraysize(args), args);
1323
}
1324
1325
1326
// Called by OnFrameReceived when a complete PRIORITY frame has been
1327
// received. Notifies JS land about the priority change. Note that priorities
1328
// are considered advisory only, so this has no real effect other than to
1329
// simply let user code know that the priority has changed.
1330
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
1331
  Isolate* isolate = env()->isolate();
1332
  HandleScope scope(isolate);
1333
  Local<Context> context = env()->context();
1334
  Context::Scope context_scope(context);
1335
1336
  nghttp2_priority priority_frame = frame->priority;
1337
  int32_t id = GetFrameID(frame);
1338
  Debug(this, "handle priority frame for stream %d", id);
1339
  // Priority frame stream ID should never be <= 0. nghttp2 handles this for us
1340
  nghttp2_priority_spec spec = priority_frame.pri_spec;
1341
1342
  Local<Value> argv[4] = {
1343
    Integer::New(isolate, id),
1344
    Integer::New(isolate, spec.stream_id),
1345
    Integer::New(isolate, spec.weight),
1346
    Boolean::New(isolate, spec.exclusive)
1347
  };
1348
  MakeCallback(env()->http2session_on_priority_function(),
1349
               arraysize(argv), argv);
1350
}
1351
1352
1353
// Called by OnFrameReceived when a complete DATA frame has been received.
1354
// If we know that this was the last DATA frame (because the END_STREAM flag
1355
// is set), then we'll terminate the readable side of the StreamBase.
1356
void Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1357
  int32_t id = GetFrameID(frame);
1358
  Debug(this, "handling data frame for stream %d", id);
1359
  Http2Stream* stream = FindStream(id);
1360
1361
  if (!stream->IsDestroyed() && frame->hd.flags & NGHTTP2_FLAG_END_STREAM)
1362
    stream->EmitRead(UV_EOF);
1363
}
1364
1365
1366
// Called by OnFrameReceived when a complete GOAWAY frame has been received.
1367
void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
1368
  Isolate* isolate = env()->isolate();
1369
  HandleScope scope(isolate);
1370
  Local<Context> context = env()->context();
1371
  Context::Scope context_scope(context);
1372
1373
  nghttp2_goaway goaway_frame = frame->goaway;
1374
  Debug(this, "handling goaway frame");
1375
1376
  Local<Value> argv[3] = {
1377
    Integer::NewFromUnsigned(isolate, goaway_frame.error_code),
1378
    Integer::New(isolate, goaway_frame.last_stream_id),
1379
    Undefined(isolate)
1380
  };
1381
1382
  size_t length = goaway_frame.opaque_data_len;
1383
  if (length > 0) {
1384
    argv[2] = Buffer::Copy(isolate,
1385
                           reinterpret_cast<char*>(goaway_frame.opaque_data),
1386
                           length).ToLocalChecked();
1387
  }
1388
1389
  MakeCallback(env()->http2session_on_goaway_data_function(),
1390
               arraysize(argv), argv);
1391
}
1392
1393
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
1394
void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
1395
  Isolate* isolate = env()->isolate();
1396
  HandleScope scope(isolate);
1397
  Local<Context> context = env()->context();
1398
  Context::Scope context_scope(context);
1399
1400
  int32_t id = GetFrameID(frame);
1401
1402
  nghttp2_extension ext = frame->ext;
1403
  nghttp2_ext_altsvc* altsvc = static_cast<nghttp2_ext_altsvc*>(ext.payload);
1404
  Debug(this, "handling altsvc frame");
1405
1406
  Local<Value> argv[3] = {
1407
    Integer::New(isolate, id),
1408
    String::NewFromOneByte(isolate,
1409
                           altsvc->origin,
1410
                           NewStringType::kNormal,
1411
                           altsvc->origin_len).ToLocalChecked(),
1412
    String::NewFromOneByte(isolate,
1413
                           altsvc->field_value,
1414
                           NewStringType::kNormal,
1415
                           altsvc->field_value_len).ToLocalChecked(),
1416
  };
1417
1418
  MakeCallback(env()->http2session_on_altsvc_function(),
1419
               arraysize(argv), argv);
1420
}
1421
1422
void Http2Session::HandleOriginFrame(const nghttp2_frame* frame) {
1423
  Isolate* isolate = env()->isolate();
1424
  HandleScope scope(isolate);
1425
  Local<Context> context = env()->context();
1426
  Context::Scope context_scope(context);
1427
1428
  Debug(this, "handling origin frame");
1429
1430
  nghttp2_extension ext = frame->ext;
1431
  nghttp2_ext_origin* origin = static_cast<nghttp2_ext_origin*>(ext.payload);
1432
1433
  size_t nov = origin->nov;
1434
  std::vector<Local<Value>> origin_v(nov);
1435
1436
  for (size_t i = 0; i < nov; ++i) {
1437
    const nghttp2_origin_entry& entry = origin->ov[i];
1438
    origin_v[i] =
1439
        String::NewFromOneByte(
1440
            isolate, entry.origin, NewStringType::kNormal, entry.origin_len)
1441
            .ToLocalChecked();
1442
  }
1443
  Local<Value> holder = Array::New(isolate, origin_v.data(), origin_v.size());
1444
  MakeCallback(env()->http2session_on_origin_function(), 1, &holder);
1445
}
1446
1447
// Called by OnFrameReceived when a complete PING frame has been received.
1448
void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
1449
  Isolate* isolate = env()->isolate();
1450
  HandleScope scope(isolate);
1451
  Local<Context> context = env()->context();
1452
  Context::Scope context_scope(context);
1453
  Local<Value> arg;
1454
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1455
  if (ack) {
1456
    Http2Ping* ping = PopPing();
1457
1458
    if (ping == nullptr) {
1459
      // PING Ack is unsolicited. Treat as a connection error. The HTTP/2
1460
      // spec does not require this, but there is no legitimate reason to
1461
      // receive an unsolicited PING ack on a connection. Either the peer
1462
      // is buggy or malicious, and we're not going to tolerate such
1463
      // nonsense.
1464
      arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1465
      MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1466
      return;
1467
    }
1468
1469
    ping->Done(true, frame->ping.opaque_data);
1470
    return;
1471
  }
1472
1473
  // Notify the session that a ping occurred
1474
  arg = Buffer::Copy(env(),
1475
                      reinterpret_cast<const char*>(frame->ping.opaque_data),
1476
                      8).ToLocalChecked();
1477
  MakeCallback(env()->http2session_on_ping_function(), 1, &arg);
1478
}
1479
1480
// Called by OnFrameReceived when a complete SETTINGS frame has been received.
1481
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
1482
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1483
  if (!ack) {
1484
    // This is not a SETTINGS acknowledgement, notify and return
1485
    MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
1486
    return;
1487
  }
1488
1489
  // If this is an acknowledgement, we should have an Http2Settings
1490
  // object for it.
1491
  Http2Settings* settings = PopSettings();
1492
  if (settings != nullptr) {
1493
    settings->Done(true);
1494
    return;
1495
  }
1496
  // SETTINGS Ack is unsolicited. Treat as a connection error. The HTTP/2
1497
  // spec does not require this, but there is no legitimate reason to
1498
  // receive an unsolicited SETTINGS ack on a connection. Either the peer
1499
  // is buggy or malicious, and we're not going to tolerate such
1500
  // nonsense.
1501
  // Note that nghttp2 currently prevents this from happening for SETTINGS
1502
  // frames, so this block is purely defensive just in case that behavior
1503
  // changes. Specifically, unlike unsolicited PING acks, unsolicited
1504
  // SETTINGS acks should *never* make it this far.
1505
  Isolate* isolate = env()->isolate();
1506
  HandleScope scope(isolate);
1507
  Local<Context> context = env()->context();
1508
  Context::Scope context_scope(context);
1509
  Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1510
  MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1511
}
1512
1513
// Callback used when data has been written to the stream.
1514
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
1515
  Debug(this, "write finished with status %d", status);
1516
1517
  // Inform all pending writes about their completion.
1518
  ClearOutgoing(status);
1519
1520
  if (!(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1521
    // Schedule a new write if nghttp2 wants to send data.
1522
    MaybeScheduleWrite();
1523
  }
1524
}
1525
1526
// If the underlying nghttp2_session struct has data pending in its outbound
1527
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1528
// on the next iteration of the Node.js event loop (using the SetImmediate
1529
// queue), but only if a write has not already been scheduled.
1530
void Http2Session::MaybeScheduleWrite() {
1531
  CHECK_EQ(flags_ & SESSION_STATE_WRITE_SCHEDULED, 0);
1532
  if (UNLIKELY(session_ == nullptr))
1533
    return;
1534
1535
  if (nghttp2_session_want_write(session_)) {
1536
    HandleScope handle_scope(env()->isolate());
1537
    Debug(this, "scheduling write");
1538
    flags_ |= SESSION_STATE_WRITE_SCHEDULED;
1539
    env()->SetImmediate([](Environment* env, void* data) {
1540
      Http2Session* session = static_cast<Http2Session*>(data);
1541
      if (session->session_ == nullptr ||
1542
          !(session->flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1543
        // This can happen e.g. when a stream was reset before this turn
1544
        // of the event loop, in which case SendPendingData() is called early,
1545
        // or the session was destroyed in the meantime.
1546
        return;
1547
      }
1548
1549
      // Sending data may call arbitrary JS code, so keep track of
1550
      // async context.
1551
      HandleScope handle_scope(env->isolate());
1552
      InternalCallbackScope callback_scope(session);
1553
      session->SendPendingData();
1554
    }, static_cast<void*>(this), object());
1555
  }
1556
}
1557
1558
void Http2Session::MaybeStopReading() {
1559
  int want_read = nghttp2_session_want_read(session_);
1560
  Debug(this, "wants read? %d", want_read);
1561
  if (want_read == 0)
1562
    stream_->ReadStop();
1563
}
1564
1565
// Unset the sending state, finish up all current writes, and reset
1566
// storage for data and metadata that was associated with these writes.
1567
void Http2Session::ClearOutgoing(int status) {
1568
  CHECK_NE(flags_ & SESSION_STATE_SENDING, 0);
1569
1570
  flags_ &= ~SESSION_STATE_SENDING;
1571
1572
  if (outgoing_buffers_.size() > 0) {
1573
    outgoing_storage_.clear();
1574
1575
    std::vector<nghttp2_stream_write> current_outgoing_buffers_;
1576
    current_outgoing_buffers_.swap(outgoing_buffers_);
1577
    for (const nghttp2_stream_write& wr : current_outgoing_buffers_) {
1578
      WriteWrap* wrap = wr.req_wrap;
1579
      if (wrap != nullptr) {
1580
        // TODO(addaleax): Pass `status` instead of 0, so that we actually error
1581
        // out with the error from the write to the underlying protocol,
1582
        // if one occurred.
1583
        wrap->Done(0);
1584
      }
1585
    }
1586
  }
1587
1588
  // Now that we've finished sending queued data, if there are any pending
1589
  // RstStreams we should try sending again and then flush them one by one.
1590
  if (pending_rst_streams_.size() > 0) {
1591
    std::vector<int32_t> current_pending_rst_streams;
1592
    pending_rst_streams_.swap(current_pending_rst_streams);
1593
1594
    SendPendingData();
1595
1596
    for (int32_t stream_id : current_pending_rst_streams) {
1597
      Http2Stream* stream = FindStream(stream_id);
1598
      if (LIKELY(stream != nullptr))
1599
        stream->FlushRstStream();
1600
    }
1601
  }
1602
}
1603
1604
// Queue a given block of data for sending. This always creates a copy,
1605
// so it is used for the cases in which nghttp2 requests sending of a
1606
// small chunk of data.
1607
void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
1608
  size_t offset = outgoing_storage_.size();
1609
  outgoing_storage_.resize(offset + src_length);
1610
  memcpy(&outgoing_storage_[offset], src, src_length);
1611
1612
  // Store with a base of `nullptr` initially, since future resizes
1613
  // of the outgoing_buffers_ vector may invalidate the pointer.
1614
  // The correct base pointers will be set later, before writing to the
1615
  // underlying socket.
1616
  outgoing_buffers_.emplace_back(nghttp2_stream_write {
1617
    uv_buf_init(nullptr, src_length)
1618
  });
1619
}
1620
1621
// Prompts nghttp2 to begin serializing it's pending data and pushes each
1622
// chunk out to the i/o socket to be sent. This is a particularly hot method
1623
// that will generally be called at least twice be event loop iteration.
1624
// This is a potential performance optimization target later.
1625
// Returns non-zero value if a write is already in progress.
1626
uint8_t Http2Session::SendPendingData() {
1627
  Debug(this, "sending pending data");
1628
  // Do not attempt to send data on the socket if the destroying flag has
1629
  // been set. That means everything is shutting down and the socket
1630
  // will not be usable.
1631
  if (IsDestroyed())
1632
    return 0;
1633
  flags_ &= ~SESSION_STATE_WRITE_SCHEDULED;
1634
1635
  // SendPendingData should not be called recursively.
1636
  if (flags_ & SESSION_STATE_SENDING)
1637
    return 1;
1638
  // This is cleared by ClearOutgoing().
1639
  flags_ |= SESSION_STATE_SENDING;
1640
1641
  ssize_t src_length;
1642
  const uint8_t* src;
1643
1644
  CHECK_EQ(outgoing_buffers_.size(), 0);
1645
  CHECK_EQ(outgoing_storage_.size(), 0);
1646
1647
  // Part One: Gather data from nghttp2
1648
1649
  while ((src_length = nghttp2_session_mem_send(session_, &src)) > 0) {
1650
    Debug(this, "nghttp2 has %d bytes to send", src_length);
1651
    CopyDataIntoOutgoing(src, src_length);
1652
  }
1653
1654
  CHECK_NE(src_length, NGHTTP2_ERR_NOMEM);
1655
1656
  if (stream_ == nullptr) {
1657
    // It would seem nice to bail out earlier, but `nghttp2_session_mem_send()`
1658
    // does take care of things like closing the individual streams after
1659
    // a socket has been torn down, so we still need to call it.
1660
    ClearOutgoing(UV_ECANCELED);
1661
    return 0;
1662
  }
1663
1664
  // Part Two: Pass Data to the underlying stream
1665
1666
  size_t count = outgoing_buffers_.size();
1667
  if (count == 0) {
1668
    ClearOutgoing(0);
1669
    return 0;
1670
  }
1671
  MaybeStackBuffer<uv_buf_t, 32> bufs;
1672
  bufs.AllocateSufficientStorage(count);
1673
1674
  // Set the buffer base pointers for copied data that ended up in the
1675
  // sessions's own storage since it might have shifted around during gathering.
1676
  // (Those are marked by having .base == nullptr.)
1677
  size_t offset = 0;
1678
  size_t i = 0;
1679
  for (const nghttp2_stream_write& write : outgoing_buffers_) {
1680
    statistics_.data_sent += write.buf.len;
1681
    if (write.buf.base == nullptr) {
1682
      bufs[i++] = uv_buf_init(
1683
          reinterpret_cast<char*>(outgoing_storage_.data() + offset),
1684
          write.buf.len);
1685
      offset += write.buf.len;
1686
    } else {
1687
      bufs[i++] = write.buf;
1688
    }
1689
  }
1690
1691
  chunks_sent_since_last_write_++;
1692
1693
  StreamWriteResult res = underlying_stream()->Write(*bufs, count);
1694
  if (!res.async) {
1695
    ClearOutgoing(res.err);
1696
  }
1697
1698
  MaybeStopReading();
1699
1700
  return 0;
1701
}
1702
1703
1704
// This callback is called from nghttp2 when it wants to send DATA frames for a
1705
// given Http2Stream, when we set the `NGHTTP2_DATA_FLAG_NO_COPY` flag earlier
1706
// in the Http2Stream::Provider::Stream::OnRead callback.
1707
// We take the write information directly out of the stream's data queue.
1708
int Http2Session::OnSendData(
1709
      nghttp2_session* session_,
1710
      nghttp2_frame* frame,
1711
      const uint8_t* framehd,
1712
      size_t length,
1713
      nghttp2_data_source* source,
1714
      void* user_data) {
1715
  Http2Session* session = static_cast<Http2Session*>(user_data);
1716
  Http2Stream* stream = GetStream(session, frame->hd.stream_id, source);
1717
1718
  // Send the frame header + a byte that indicates padding length.
1719
  session->CopyDataIntoOutgoing(framehd, 9);
1720
  if (frame->data.padlen > 0) {
1721
    uint8_t padding_byte = frame->data.padlen - 1;
1722
    CHECK_EQ(padding_byte, frame->data.padlen - 1);
1723
    session->CopyDataIntoOutgoing(&padding_byte, 1);
1724
  }
1725
1726
  Debug(session, "nghttp2 has %d bytes to send directly", length);
1727
  while (length > 0) {
1728
    // nghttp2 thinks that there is data available (length > 0), which means
1729
    // we told it so, which means that we *should* have data available.
1730
    CHECK(!stream->queue_.empty());
1731
1732
    nghttp2_stream_write& write = stream->queue_.front();
1733
    if (write.buf.len <= length) {
1734
      // This write does not suffice by itself, so we can consume it completely.
1735
      length -= write.buf.len;
1736
      session->outgoing_buffers_.emplace_back(std::move(write));
1737
      stream->queue_.pop();
1738
      continue;
1739
    }
1740
1741
    // Slice off `length` bytes of the first write in the queue.
1742
    session->outgoing_buffers_.emplace_back(nghttp2_stream_write {
1743
      uv_buf_init(write.buf.base, length)
1744
    });
1745
    write.buf.base += length;
1746
    write.buf.len -= length;
1747
    break;
1748
  }
1749
1750
  if (frame->data.padlen > 0) {
1751
    // Send padding if that was requested.
1752
    session->outgoing_buffers_.emplace_back(nghttp2_stream_write {
1753
      uv_buf_init(const_cast<char*>(zero_bytes_256), frame->data.padlen - 1)
1754
    });
1755
  }
1756
1757
  return 0;
1758
}
1759
1760
// Creates a new Http2Stream and submits a new http2 request.
1761
Http2Stream* Http2Session::SubmitRequest(
1762
    nghttp2_priority_spec* prispec,
1763
    nghttp2_nv* nva,
1764
    size_t len,
1765
    int32_t* ret,
1766
    int options) {
1767
  Debug(this, "submitting request");
1768
  Http2Scope h2scope(this);
1769
  Http2Stream* stream = nullptr;
1770
  Http2Stream::Provider::Stream prov(options);
1771
  *ret = nghttp2_submit_request(session_, prispec, nva, len, *prov, nullptr);
1772
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
1773
  if (LIKELY(*ret > 0))
1774
    stream = new Http2Stream(this, *ret, NGHTTP2_HCAT_HEADERS, options);
1775
  return stream;
1776
}
1777
1778
// Callback used to receive inbound data from the i/o stream
1779
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1780
  HandleScope handle_scope(env()->isolate());
1781
  Context::Scope context_scope(env()->context());
1782
  Http2Scope h2scope(this);
1783
  CHECK_NOT_NULL(stream_);
1784
  Debug(this, "receiving %d bytes", nread);
1785
  IncrementCurrentSessionMemory(buf.len);
1786
  CHECK(stream_buf_ab_.IsEmpty());
1787
1788
  OnScopeLeave on_scope_leave([&]() {
1789
    // Once finished handling this write, reset the stream buffer.
1790
    // The memory has either been free()d or was handed over to V8.
1791
    DecrementCurrentSessionMemory(buf.len);
1792
    stream_buf_ab_ = Local<ArrayBuffer>();
1793
    stream_buf_ = uv_buf_init(nullptr, 0);
1794
  });
1795
1796
  // Only pass data on if nread > 0
1797
  if (nread <= 0) {
1798
    free(buf.base);
1799
    if (nread < 0) {
1800
      PassReadErrorToPreviousListener(nread);
1801
    }
1802
    return;
1803
  }
1804
1805
  // Make sure that there was no read previously active.
1806
  CHECK_NULL(stream_buf_.base);
1807
  CHECK_EQ(stream_buf_.len, 0);
1808
1809
  // Remember the current buffer, so that OnDataChunkReceived knows the
1810
  // offset of a DATA frame's data into the socket read buffer.
1811
  stream_buf_ = uv_buf_init(buf.base, nread);
1812
1813
  // Verify that currently: There is memory allocated into which
1814
  // the data has been read, and that memory buffer is at least as large
1815
  // as the amount of data we have read, but we have not yet made an
1816
  // ArrayBuffer out of it.
1817
  CHECK_LE(static_cast<size_t>(nread), stream_buf_.len);
1818
1819
  Isolate* isolate = env()->isolate();
1820
1821
  // Create an array buffer for the read data. DATA frames will be emitted
1822
  // as slices of this array buffer to avoid having to copy memory.
1823
  stream_buf_ab_ =
1824
      ArrayBuffer::New(isolate,
1825
                        buf.base,
1826
                        nread,
1827
                        ArrayBufferCreationMode::kInternalized);
1828
1829
  statistics_.data_received += nread;
1830
  ssize_t ret = Write(&stream_buf_, 1);
1831
1832
  if (UNLIKELY(ret < 0)) {
1833
    Debug(this, "fatal error receiving data: %d", ret);
1834
    Local<Value> arg = Integer::New(isolate, ret);
1835
    MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1836
    return;
1837
  }
1838
1839
  MaybeStopReading();
1840
}
1841
1842
bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
1843
  for (const nghttp2_stream_write& wr : outgoing_buffers_) {
1844
    if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream)
1845
      return true;
1846
  }
1847
  return false;
1848
}
1849
1850
// Every Http2Session session is tightly bound to a single i/o StreamBase
1851
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1852
// tightly coupled with all data transfer between the two happening at the
1853
// C++ layer via the StreamBase API.
1854
void Http2Session::Consume(Local<External> external) {
1855
  StreamBase* stream = static_cast<StreamBase*>(external->Value());
1856
  stream->PushStreamListener(this);
1857
  Debug(this, "i/o stream consumed");
1858
}
1859
1860
1861
Http2Stream::Http2Stream(
1862
    Http2Session* session,
1863
    int32_t id,
1864
    nghttp2_headers_category category,
1865
    int options) : AsyncWrap(session->env(),
1866
                             session->env()->http2stream_constructor_template()
1867
                                 ->NewInstance(session->env()->context())
1868
                                     .ToLocalChecked(),
1869
                             AsyncWrap::PROVIDER_HTTP2STREAM),
1870
                   StreamBase(session->env()),
1871
                   session_(session),
1872
                   id_(id),
1873
                   current_headers_category_(category) {
1874
  MakeWeak();
1875
  statistics_.start_time = uv_hrtime();
1876
1877
  // Limit the number of header pairs
1878
  max_header_pairs_ = session->GetMaxHeaderPairs();
1879
  if (max_header_pairs_ == 0)
1880
  max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1881
  current_headers_.reserve(max_header_pairs_);
1882
1883
  // Limit the number of header octets
1884
  max_header_length_ =
1885
      std::min(
1886
        nghttp2_session_get_local_settings(
1887
          session->session(),
1888
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1889
      MAX_MAX_HEADER_LIST_SIZE);
1890
1891
  if (options & STREAM_OPTION_GET_TRAILERS)
1892
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1893
1894
  PushStreamListener(&stream_listener_);
1895
1896
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1897
    Shutdown();
1898
  session->AddStream(this);
1899
}
1900
1901
1902
Http2Stream::~Http2Stream() {
1903
  for (nghttp2_header& header : current_headers_) {
1904
    nghttp2_rcbuf_decref(header.name);
1905
    nghttp2_rcbuf_decref(header.value);
1906
  }
1907
1908
  if (session_ == nullptr)
1909
    return;
1910
  Debug(this, "tearing down stream");
1911
  session_->RemoveStream(this);
1912
  session_ = nullptr;
1913
}
1914
1915
std::string Http2Stream::diagnostic_name() const {
1916
  return "HttpStream " + std::to_string(id()) + " (" +
1917
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
1918
      session()->diagnostic_name() + "]";
1919
}
1920
1921
// Notify the Http2Stream that a new block of HEADERS is being processed.
1922
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
1923
  Debug(this, "starting headers, category: %d", id_, category);
1924
  CHECK(!this->IsDestroyed());
1925
  current_headers_length_ = 0;
1926
  current_headers_.clear();
1927
  current_headers_category_ = category;
1928
}
1929
1930
1931
nghttp2_stream* Http2Stream::operator*() {
1932
  return nghttp2_session_find_stream(**session_, id_);
1933
}
1934
1935
void Http2Stream::Close(int32_t code) {
1936
  CHECK(!this->IsDestroyed());
1937
  flags_ |= NGHTTP2_STREAM_FLAG_CLOSED;
1938
  code_ = code;
1939
  Debug(this, "closed with code %d", code);
1940
}
1941
1942
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
1943
  if (IsDestroyed())
1944
    return UV_EPIPE;
1945
1946
  {
1947
    Http2Scope h2scope(this);
1948
    flags_ |= NGHTTP2_STREAM_FLAG_SHUT;
1949
    CHECK_NE(nghttp2_session_resume_data(**session_, id_),
1950
             NGHTTP2_ERR_NOMEM);
1951
    Debug(this, "writable side shutdown");
1952
  }
1953
  return 1;
1954
}
1955
1956
// Destroy the Http2Stream and render it unusable. Actual resources for the
1957
// Stream will not be freed until the next tick of the Node.js event loop
1958
// using the SetImmediate queue.
1959
void Http2Stream::Destroy() {
1960
  // Do nothing if this stream instance is already destroyed
1961
  if (IsDestroyed())
1962
    return;
1963
  if (session_->HasPendingRstStream(id_))
1964
    FlushRstStream();
1965
  flags_ |= NGHTTP2_STREAM_FLAG_DESTROYED;
1966
1967
  Debug(this, "destroying stream");
1968
1969
  // Wait until the start of the next loop to delete because there
1970
  // may still be some pending operations queued for this stream.
1971
  env()->SetImmediate([](Environment* env, void* data) {
1972
    Http2Stream* stream = static_cast<Http2Stream*>(data);
1973
    // Free any remaining outgoing data chunks here. This should be done
1974
    // here because it's possible for destroy to have been called while
1975
    // we still have queued outbound writes.
1976
    while (!stream->queue_.empty()) {
1977
      nghttp2_stream_write& head = stream->queue_.front();
1978
      if (head.req_wrap != nullptr)
1979
        head.req_wrap->Done(UV_ECANCELED);
1980
      stream->queue_.pop();
1981
    }
1982
1983
    // We can destroy the stream now if there are no writes for it
1984
    // already on the socket. Otherwise, we'll wait for the garbage collector
1985
    // to take care of cleaning up.
1986
    if (stream->session() == nullptr ||
1987
        !stream->session()->HasWritesOnSocketForStream(stream))
1988
      delete stream;
1989
  }, this, this->object());
1990
1991
  statistics_.end_time = uv_hrtime();
1992
  session_->statistics_.stream_average_duration =
1993
      ((statistics_.end_time - statistics_.start_time) /
1994
          session_->statistics_.stream_count) / 1e6;
1995
  EmitStatistics();
1996
}
1997
1998
1999
// Initiates a response on the Http2Stream using data provided via the
2000
// StreamBase Streams API.
2001
int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) {
2002
  CHECK(!this->IsDestroyed());
2003
  Http2Scope h2scope(this);
2004
  Debug(this, "submitting response");
2005
  if (options & STREAM_OPTION_GET_TRAILERS)
2006
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
2007
2008
  if (!IsWritable())
2009
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2010
2011
  Http2Stream::Provider::Stream prov(this, options);
2012
  int ret = nghttp2_submit_response(**session_, id_, nva, len, *prov);
2013
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2014
  return ret;
2015
}
2016
2017
2018
// Submit informational headers for a stream.
2019
int Http2Stream::SubmitInfo(nghttp2_nv* nva, size_t len) {
2020
  CHECK(!this->IsDestroyed());
2021
  Http2Scope h2scope(this);
2022
  Debug(this, "sending %d informational headers", len);
2023
  int ret = nghttp2_submit_headers(**session_,
2024
                                   NGHTTP2_FLAG_NONE,
2025
                                   id_, nullptr,
2026
                                   nva, len, nullptr);
2027
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2028
  return ret;
2029
}
2030
2031
void Http2Stream::OnTrailers() {
2032
  Debug(this, "let javascript know we are ready for trailers");
2033
  CHECK(!this->IsDestroyed());
2034
  Isolate* isolate = env()->isolate();
2035
  HandleScope scope(isolate);
2036
  Local<Context> context = env()->context();
2037
  Context::Scope context_scope(context);
2038
  flags_ &= ~NGHTTP2_STREAM_FLAG_TRAILERS;
2039
  MakeCallback(env()->http2session_on_stream_trailers_function(), 0, nullptr);
2040
}
2041
2042
// Submit informational headers for a stream.
2043
int Http2Stream::SubmitTrailers(nghttp2_nv* nva, size_t len) {
2044
  CHECK(!this->IsDestroyed());
2045
  Http2Scope h2scope(this);
2046
  Debug(this, "sending %d trailers", len);
2047
  int ret;
2048
  // Sending an empty trailers frame poses problems in Safari, Edge & IE.
2049
  // Instead we can just send an empty data frame with NGHTTP2_FLAG_END_STREAM
2050
  // to indicate that the stream is ready to be closed.
2051
  if (len == 0) {
2052
    Http2Stream::Provider::Stream prov(this, 0);
2053
    ret = nghttp2_submit_data(**session_, NGHTTP2_FLAG_END_STREAM, id_, *prov);
2054
  } else {
2055
    ret = nghttp2_submit_trailer(**session_, id_, nva, len);
2056
  }
2057
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2058
  return ret;
2059
}
2060
2061
// Submit a PRIORITY frame to the connected peer.
2062
int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec,
2063
                                bool silent) {
2064
  CHECK(!this->IsDestroyed());
2065
  Http2Scope h2scope(this);
2066
  Debug(this, "sending priority spec");
2067
  int ret = silent ?
2068
      nghttp2_session_change_stream_priority(**session_,
2069
                                             id_, prispec) :
2070
      nghttp2_submit_priority(**session_,
2071
                              NGHTTP2_FLAG_NONE,
2072
                              id_, prispec);
2073
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2074
  return ret;
2075
}
2076
2077
// Closes the Http2Stream by submitting an RST_STREAM frame to the connected
2078
// peer.
2079
void Http2Stream::SubmitRstStream(const uint32_t code) {
2080
  CHECK(!this->IsDestroyed());
2081
  code_ = code;
2082
  // If possible, force a purge of any currently pending data here to make sure
2083
  // it is sent before closing the stream. If it returns non-zero then we need
2084
  // to wait until the current write finishes and try again to avoid nghttp2
2085
  // behaviour where it prioritizes RstStream over everything else.
2086
  if (session_->SendPendingData() != 0) {
2087
    session_->AddPendingRstStream(id_);
2088
    return;
2089
  }
2090
2091
  FlushRstStream();
2092
}
2093
2094
void Http2Stream::FlushRstStream() {
2095
  if (IsDestroyed())
2096
    return;
2097
  Http2Scope h2scope(this);
2098
  CHECK_EQ(nghttp2_submit_rst_stream(**session_, NGHTTP2_FLAG_NONE,
2099
                                     id_, code_), 0);
2100
}
2101
2102
2103
// Submit a push promise and create the associated Http2Stream if successful.
2104
Http2Stream* Http2Stream::SubmitPushPromise(nghttp2_nv* nva,
2105
                                            size_t len,
2106
                                            int32_t* ret,
2107
                                            int options) {
2108
  CHECK(!this->IsDestroyed());
2109
  Http2Scope h2scope(this);
2110
  Debug(this, "sending push promise");
2111
  *ret = nghttp2_submit_push_promise(**session_, NGHTTP2_FLAG_NONE,
2112
                                     id_, nva, len, nullptr);
2113
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
2114
  Http2Stream* stream = nullptr;
2115
  if (*ret > 0)
2116
    stream = new Http2Stream(session_, *ret, NGHTTP2_HCAT_HEADERS, options);
2117
2118
  return stream;
2119
}
2120
2121
// Switch the StreamBase into flowing mode to begin pushing chunks of data
2122
// out to JS land.
2123
int Http2Stream::ReadStart() {
2124
  Http2Scope h2scope(this);
2125
  CHECK(!this->IsDestroyed());
2126
  flags_ |= NGHTTP2_STREAM_FLAG_READ_START;
2127
  flags_ &= ~NGHTTP2_STREAM_FLAG_READ_PAUSED;
2128
2129
  Debug(this, "reading starting");
2130
2131
  // Tell nghttp2 about our consumption of the data that was handed
2132
  // off to JS land.
2133
  nghttp2_session_consume_stream(**session_,
2134
                                 id_,
2135
                                 inbound_consumed_data_while_paused_);
2136
  inbound_consumed_data_while_paused_ = 0;
2137
2138
  return 0;
2139
}
2140
2141
// Switch the StreamBase into paused mode.
2142
int Http2Stream::ReadStop() {
2143
  CHECK(!this->IsDestroyed());
2144
  if (!IsReading())
2145
    return 0;
2146
  flags_ |= NGHTTP2_STREAM_FLAG_READ_PAUSED;
2147
  Debug(this, "reading stopped");
2148
  return 0;
2149
}
2150
2151
// The Http2Stream class is a subclass of StreamBase. The DoWrite method
2152
// receives outbound chunks of data to send as outbound DATA frames. These
2153
// are queued in an internal linked list of uv_buf_t structs that are sent
2154
// when nghttp2 is ready to serialize the data frame.
2155
//
2156
// Queue the given set of uv_but_t handles for writing to an
2157
// nghttp2_stream. The WriteWrap's Done callback will be invoked once the
2158
// chunks of data have been flushed to the underlying nghttp2_session.
2159
// Note that this does *not* mean that the data has been flushed
2160
// to the socket yet.
2161
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2162
                         uv_buf_t* bufs,
2163
                         size_t nbufs,
2164
                         uv_stream_t* send_handle) {
2165
  CHECK_NULL(send_handle);
2166
  Http2Scope h2scope(this);
2167
  if (!IsWritable() || IsDestroyed()) {
2168
    req_wrap->Done(UV_EOF);
2169
    return 0;
2170
  }
2171
  Debug(this, "queuing %d buffers to send", id_, nbufs);
2172
  for (size_t i = 0; i < nbufs; ++i) {
2173
    // Store the req_wrap on the last write info in the queue, so that it is
2174
    // only marked as finished once all buffers associated with it are finished.
2175
    queue_.emplace(nghttp2_stream_write {
2176
      i == nbufs - 1 ? req_wrap : nullptr,
2177
      bufs[i]
2178
    });
2179
    IncrementAvailableOutboundLength(bufs[i].len);
2180
  }
2181
  CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM);
2182
  return 0;
2183
}
2184
2185
// Ads a header to the Http2Stream. Note that the header name and value are
2186
// provided using a buffer structure provided by nghttp2 that allows us to
2187
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2188
// is incremented here and are decremented when the header name and values
2189
// are garbage collected later.
2190
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2191
                            nghttp2_rcbuf* value,
2192
                            uint8_t flags) {
2193
  CHECK(!this->IsDestroyed());
2194
  if (this->statistics_.first_header == 0)
2195
    this->statistics_.first_header = uv_hrtime();
2196
  size_t length = nghttp2_rcbuf_get_buf(name).len +
2197
                  nghttp2_rcbuf_get_buf(value).len + 32;
2198
  // A header can only be added if we have not exceeded the maximum number
2199
  // of headers and the session has memory available for it.
2200
  if (!session_->IsAvailableSessionMemory(length) ||
2201
      current_headers_.size() == max_header_pairs_ ||
2202
      current_headers_length_ + length > max_header_length_) {
2203
    return false;
2204
  }
2205
  nghttp2_header header;
2206
  header.name = name;
2207
  header.value = value;
2208
  header.flags = flags;
2209
  current_headers_.push_back(header);
2210
  nghttp2_rcbuf_incref(name);
2211
  nghttp2_rcbuf_incref(value);
2212
  current_headers_length_ += length;
2213
  return true;
2214
}
2215
2216
// A Provider is the thing that provides outbound DATA frame data.
2217
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2218
  CHECK(!stream->IsDestroyed());
2219
  provider_.source.ptr = stream;
2220
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2221
}
2222
2223
Http2Stream::Provider::Provider(int options) {
2224
  provider_.source.ptr = nullptr;
2225
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2226
}
2227
2228
Http2Stream::Provider::~Provider() {
2229
  provider_.source.ptr = nullptr;
2230
}
2231
2232
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2233
// built via the StreamBase API and the Streams js API.
2234
Http2Stream::Provider::Stream::Stream(int options)
2235
    : Http2Stream::Provider(options) {
2236
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2237
}
2238
2239
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2240
    : Http2Stream::Provider(stream, options) {
2241
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2242
}
2243
2244
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2245
                                              int32_t id,
2246
                                              uint8_t* buf,
2247
                                              size_t length,
2248
                                              uint32_t* flags,
2249
                                              nghttp2_data_source* source,
2250
                                              void* user_data) {
2251
  Http2Session* session = static_cast<Http2Session*>(user_data);
2252
  Debug(session, "reading outbound data for stream %d", id);
2253
  Http2Stream* stream = GetStream(session, id, source);
2254
  if (stream->statistics_.first_byte_sent == 0)
2255
    stream->statistics_.first_byte_sent = uv_hrtime();
2256
  CHECK_EQ(id, stream->id());
2257
2258
  size_t amount = 0;          // amount of data being sent in this data frame.
2259
2260
  // Remove all empty chunks from the head of the queue.
2261
  // This is done here so that .write('', cb) is still a meaningful way to
2262
  // find out when the HTTP2 stream wants to consume data, and because the
2263
  // StreamBase API allows empty input chunks.
2264
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2265
    WriteWrap* finished = stream->queue_.front().req_wrap;
2266
    stream->queue_.pop();
2267
    if (finished != nullptr)
2268
      finished->Done(0);
2269
  }
2270
2271
  if (!stream->queue_.empty()) {
2272
    Debug(session, "stream %d has pending outbound data", id);
2273
    amount = std::min(stream->available_outbound_length_, length);
2274
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2275
    if (amount > 0) {
2276
      // Just return the length, let Http2Session::OnSendData take care of
2277
      // actually taking the buffers out of the queue.
2278
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2279
      stream->DecrementAvailableOutboundLength(amount);
2280
    }
2281
  }
2282
2283
  if (amount == 0 && stream->IsWritable()) {
2284
    CHECK(stream->queue_.empty());
2285
    Debug(session, "deferring stream %d", id);
2286
    stream->EmitWantsWrite(length);
2287
    if (stream->available_outbound_length_ > 0 || !stream->IsWritable()) {
2288
      // EmitWantsWrite() did something interesting synchronously, restart:
2289
      return OnRead(handle, id, buf, length, flags, source, user_data);
2290
    }
2291
    return NGHTTP2_ERR_DEFERRED;
2292
  }
2293
2294
  if (stream->queue_.empty() && !stream->IsWritable()) {
2295
    Debug(session, "no more data for stream %d", id);
2296
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2297
    if (stream->HasTrailers()) {
2298
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2299
      stream->OnTrailers();
2300
    }
2301
  }
2302
2303
  stream->statistics_.sent_bytes += amount;
2304
  return amount;
2305
}
2306
2307
inline void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2308
  available_outbound_length_ += amount;
2309
  session_->IncrementCurrentSessionMemory(amount);
2310
}
2311
2312
inline void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2313
  available_outbound_length_ -= amount;
2314
  session_->DecrementCurrentSessionMemory(amount);
2315
}
2316
2317
2318
// Implementation of the JavaScript API
2319
2320
// Fetches the string description of a nghttp2 error code and passes that
2321
// back to JS land
2322
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2323
  Environment* env = Environment::GetCurrent(args);
2324
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2325
  args.GetReturnValue().Set(
2326
      String::NewFromOneByte(
2327
          env->isolate(),
2328
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val)),
2329
          NewStringType::kInternalized).ToLocalChecked());
2330
}
2331
2332
2333
// Serializes the settings object into a Buffer instance that
2334
// would be suitable, for instance, for creating the Base64
2335
// output for an HTTP2-Settings header field.
2336
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2337
  Environment* env = Environment::GetCurrent(args);
2338
  Http2Session::Http2Settings settings(env);
2339
  args.GetReturnValue().Set(settings.Pack());
2340
}
2341
2342
// A TypedArray instance is shared between C++ and JS land to contain the
2343
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2344
// default values.
2345
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2346
  Environment* env = Environment::GetCurrent(args);
2347
  Http2Session::Http2Settings::RefreshDefaults(env);
2348
}
2349
2350
// Sets the next stream ID the Http2Session. If successful, returns true.
2351
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2352
  Environment* env = Environment::GetCurrent(args);
2353
  Http2Session* session;
2354
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2355
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2356
  if (nghttp2_session_set_next_stream_id(**session, id) < 0) {
2357
    Debug(session, "failed to set next stream id to %d", id);
2358
    return args.GetReturnValue().Set(false);
2359
  }
2360
  args.GetReturnValue().Set(true);
2361
  Debug(session, "set next stream id to %d", id);
2362
}
2363
2364
// A TypedArray instance is shared between C++ and JS land to contain the
2365
// SETTINGS (either remote or local). RefreshSettings updates the current
2366
// values established for each of the settings so those can be read in JS land.
2367
template <get_setting fn>
2368
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2369
  Environment* env = Environment::GetCurrent(args);
2370
  Http2Session* session;
2371
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2372
  Http2Settings::Update(env, session, fn);
2373
  Debug(session, "settings refreshed for session");
2374
}
2375
2376
// A TypedArray instance is shared between C++ and JS land to contain state
2377
// information of the current Http2Session. This updates the values in the
2378
// TypedArray so those can be read in JS land.
2379
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2380
  Environment* env = Environment::GetCurrent(args);
2381
  Http2Session* session;
2382
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2383
  Debug(session, "refreshing state");
2384
2385
  AliasedBuffer<double, Float64Array>& buffer =
2386
      env->http2_state()->session_state_buffer;
2387
2388
  nghttp2_session* s = **session;
2389
2390
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2391
      nghttp2_session_get_effective_local_window_size(s);
2392
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2393
      nghttp2_session_get_effective_recv_data_length(s);
2394
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2395
      nghttp2_session_get_next_stream_id(s);
2396
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2397
      nghttp2_session_get_local_window_size(s);
2398
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2399
      nghttp2_session_get_last_proc_stream_id(s);
2400
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2401
      nghttp2_session_get_remote_window_size(s);
2402
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2403
      nghttp2_session_get_outbound_queue_size(s);
2404
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2405
      nghttp2_session_get_hd_deflate_dynamic_table_size(s);
2406
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2407
      nghttp2_session_get_hd_inflate_dynamic_table_size(s);
2408
}
2409
2410
2411
// Constructor for new Http2Session instances.
2412
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2413
  Environment* env = Environment::GetCurrent(args);
2414
  CHECK(args.IsConstructCall());
2415
  int val = args[0]->IntegerValue(env->context()).ToChecked();
2416
  nghttp2_session_type type = static_cast<nghttp2_session_type>(val);
2417
  Http2Session* session = new Http2Session(env, args.This(), type);
2418
  session->get_async_id();  // avoid compiler warning
2419
  Debug(session, "session created");
2420
}
2421
2422
2423
// Binds the Http2Session with a StreamBase used for i/o
2424
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2425
  Http2Session* session;
2426
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2427
  CHECK(args[0]->IsExternal());
2428
  session->Consume(args[0].As<External>());
2429
}
2430
2431
// Destroys the Http2Session instance and renders it unusable
2432
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2433
  Http2Session* session;
2434
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2435
  Debug(session, "destroying session");
2436
  Environment* env = Environment::GetCurrent(args);
2437
  Local<Context> context = env->context();
2438
2439
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2440
  bool socketDestroyed = args[1]->BooleanValue(env->isolate());
2441
2442
  session->Close(code, socketDestroyed);
2443
}
2444
2445
// Submits a new request on the Http2Session and returns either an error code
2446
// or the Http2Stream object.
2447
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2448
  Http2Session* session;
2449
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2450
  Environment* env = session->env();
2451
  Local<Context> context = env->context();
2452
  Isolate* isolate = env->isolate();
2453
2454
  Local<Array> headers = args[0].As<Array>();
2455
  int options = args[1]->IntegerValue(context).ToChecked();
2456
  Http2Priority priority(env, args[2], args[3], args[4]);
2457
2458
  Headers list(isolate, context, headers);
2459
2460
  Debug(session, "request submitted");
2461
2462
  int32_t ret = 0;
2463
  Http2Stream* stream =
2464
      session->Http2Session::SubmitRequest(*priority, *list, list.length(),
2465
                                           &ret, options);
2466
2467
  if (ret <= 0) {
2468
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2469
    return args.GetReturnValue().Set(ret);
2470
  }
2471
2472
  Debug(session, "request submitted, new stream id %d", stream->id());
2473
  args.GetReturnValue().Set(stream->object());
2474
}
2475
2476
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2477
// of shutting down. Note that this function does not actually alter the
2478
// state of the Http2Session, it's simply a notification.
2479
void Http2Session::Goaway(uint32_t code,
2480
                          int32_t lastStreamID,
2481
                          uint8_t* data,
2482
                          size_t len) {
2483
  if (IsDestroyed())
2484
    return;
2485
2486
  Http2Scope h2scope(this);
2487
  // the last proc stream id is the most recently created Http2Stream.
2488
  if (lastStreamID <= 0)
2489
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_);
2490
  Debug(this, "submitting goaway");
2491
  nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE,
2492
                        lastStreamID, code, data, len);
2493
}
2494
2495
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2496
// of shutting down. The opaque data argument is an optional TypedArray that
2497
// can be used to send debugging data to the connected peer.
2498
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2499
  Environment* env = Environment::GetCurrent(args);
2500
  Local<Context> context = env->context();
2501
  Http2Session* session;
2502
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2503
2504
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2505
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2506
  Local<Value> opaqueData = args[2];
2507
  uint8_t* data = nullptr;
2508
  size_t length = 0;
2509
2510
  if (Buffer::HasInstance(opaqueData)) {
2511
    data = reinterpret_cast<uint8_t*>(Buffer::Data(opaqueData));
2512
    length = Buffer::Length(opaqueData);
2513
  }
2514
2515
  session->Goaway(code, lastStreamID, data, length);
2516
}
2517
2518
// Update accounting of data chunks. This is used primarily to manage timeout
2519
// logic when using the FD Provider.
2520
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2521
  Environment* env = Environment::GetCurrent(args);
2522
  Isolate* isolate = env->isolate();
2523
  HandleScope scope(isolate);
2524
  Http2Session* session;
2525
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2526
2527
  uint32_t length = session->chunks_sent_since_last_write_;
2528
2529
  session->object()->Set(env->context(),
2530
                         env->chunks_sent_since_last_write_string(),
2531
                         Integer::NewFromUnsigned(isolate, length)).FromJust();
2532
2533
  args.GetReturnValue().Set(length);
2534
}
2535
2536
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2537
// this *WILL* alter the state of the stream, causing the OnStreamClose
2538
// callback to the triggered.
2539
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2540
  Environment* env = Environment::GetCurrent(args);
2541
  Local<Context> context = env->context();
2542
  Http2Stream* stream;
2543
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2544
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2545
  Debug(stream, "sending rst_stream with code %d", code);
2546
  stream->SubmitRstStream(code);
2547
}
2548
2549
// Initiates a response on the Http2Stream using the StreamBase API to provide
2550
// outbound DATA frames.
2551
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2552
  Environment* env = Environment::GetCurrent(args);
2553
  Local<Context> context = env->context();
2554
  Isolate* isolate = env->isolate();
2555
  Http2Stream* stream;
2556
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2557
2558
  Local<Array> headers = args[0].As<Array>();
2559
  int options = args[1]->IntegerValue(context).ToChecked();
2560
2561
  Headers list(isolate, context, headers);
2562
2563
  args.GetReturnValue().Set(
2564
      stream->SubmitResponse(*list, list.length(), options));
2565
  Debug(stream, "response submitted");
2566
}
2567
2568
2569
// Submits informational headers on the Http2Stream
2570
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2571
  Environment* env = Environment::GetCurrent(args);
2572
  Local<Context> context = env->context();
2573
  Isolate* isolate = env->isolate();
2574
  Http2Stream* stream;
2575
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2576
2577
  Local<Array> headers = args[0].As<Array>();
2578
2579
  Headers list(isolate, context, headers);
2580
  args.GetReturnValue().Set(stream->SubmitInfo(*list, list.length()));
2581
  Debug(stream, "%d informational headers sent", list.length());
2582
}
2583
2584
// Submits trailing headers on the Http2Stream
2585
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2586
  Environment* env = Environment::GetCurrent(args);
2587
  Local<Context> context = env->context();
2588
  Isolate* isolate = env->isolate();
2589
  Http2Stream* stream;
2590
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2591
2592
  Local<Array> headers = args[0].As<Array>();
2593
2594
  Headers list(isolate, context, headers);
2595
  args.GetReturnValue().Set(stream->SubmitTrailers(*list, list.length()));
2596
  Debug(stream, "%d trailing headers sent", list.length());
2597
}
2598
2599
// Grab the numeric id of the Http2Stream
2600
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2601
  Http2Stream* stream;
2602
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2603
  args.GetReturnValue().Set(stream->id());
2604
}
2605
2606
// Destroy the Http2Stream, rendering it no longer usable
2607
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2608
  Http2Stream* stream;
2609
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2610
  Debug(stream, "destroying stream");
2611
  stream->Destroy();
2612
}
2613
2614
// Prompt the Http2Stream to begin sending data to the JS land.
2615
void Http2Stream::FlushData(const FunctionCallbackInfo<Value>& args) {
2616
  Http2Stream* stream;
2617
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2618
  stream->ReadStart();
2619
  Debug(stream, "data flushed to js");
2620
}
2621
2622
// Initiate a Push Promise and create the associated Http2Stream
2623
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2624
  Environment* env = Environment::GetCurrent(args);
2625
  Local<Context> context = env->context();
2626
  Isolate* isolate = env->isolate();
2627
  Http2Stream* parent;
2628
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2629
2630
  Local<Array> headers = args[0].As<Array>();
2631
  int options = args[1]->IntegerValue(context).ToChecked();
2632
2633
  Headers list(isolate, context, headers);
2634
2635
  Debug(parent, "creating push promise");
2636
2637
  int32_t ret = 0;
2638
  Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(),
2639
                                                  &ret, options);
2640
  if (ret <= 0) {
2641
    Debug(parent, "failed to create push stream: %d", ret);
2642
    return args.GetReturnValue().Set(ret);
2643
  }
2644
  Debug(parent, "push stream %d created", stream->id());
2645
  args.GetReturnValue().Set(stream->object());
2646
}
2647
2648
// Send a PRIORITY frame
2649
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2650
  Environment* env = Environment::GetCurrent(args);
2651
  Http2Stream* stream;
2652
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2653
2654
  Http2Priority priority(env, args[0], args[1], args[2]);
2655
  bool silent = args[3]->BooleanValue(env->isolate());
2656
2657
  CHECK_EQ(stream->SubmitPriority(*priority, silent), 0);
2658
  Debug(stream, "priority submitted");
2659
}
2660
2661
// A TypedArray shared by C++ and JS land is used to communicate state
2662
// information about the Http2Stream. This updates the values in that
2663
// TypedArray so that the state can be read by JS.
2664
void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
2665
  Environment* env = Environment::GetCurrent(args);
2666
  Http2Stream* stream;
2667
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2668
2669
  Debug(stream, "refreshing state");
2670
2671
  AliasedBuffer<double, Float64Array>& buffer =
2672
      env->http2_state()->stream_state_buffer;
2673
2674
  nghttp2_stream* str = **stream;
2675
  nghttp2_session* s = **(stream->session());
2676
2677
  if (str == nullptr) {
2678
    buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE;
2679
    buffer[IDX_STREAM_STATE_WEIGHT] =
2680
        buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2681
        buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2682
        buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2683
        buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0;
2684
  } else {
2685
    buffer[IDX_STREAM_STATE] =
2686
        nghttp2_stream_get_state(str);
2687
    buffer[IDX_STREAM_STATE_WEIGHT] =
2688
        nghttp2_stream_get_weight(str);
2689
    buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2690
        nghttp2_stream_get_sum_dependency_weight(str);
2691
    buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2692
        nghttp2_session_get_stream_local_close(s, stream->id());
2693
    buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2694
        nghttp2_session_get_stream_remote_close(s, stream->id());
2695
    buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] =
2696
        nghttp2_session_get_stream_local_window_size(s, stream->id());
2697
  }
2698
}
2699
2700
void Http2Session::AltSvc(int32_t id,
2701
                          uint8_t* origin,
2702
                          size_t origin_len,
2703
                          uint8_t* value,
2704
                          size_t value_len) {
2705
  Http2Scope h2scope(this);
2706
  CHECK_EQ(nghttp2_submit_altsvc(session_, NGHTTP2_FLAG_NONE, id,
2707
                                 origin, origin_len, value, value_len), 0);
2708
}
2709
2710
void Http2Session::Origin(nghttp2_origin_entry* ov, size_t count) {
2711
  Http2Scope h2scope(this);
2712
  CHECK_EQ(nghttp2_submit_origin(session_, NGHTTP2_FLAG_NONE, ov, count), 0);
2713
}
2714
2715
// Submits an AltSvc frame to be sent to the connected peer.
2716
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2717
  Environment* env = Environment::GetCurrent(args);
2718
  Http2Session* session;
2719
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2720
2721
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2722
2723
  // origin and value are both required to be ASCII, handle them as such.
2724
  Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2725
  Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2726
2727
  size_t origin_len = origin_str->Length();
2728
  size_t value_len = value_str->Length();
2729
2730
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2731
  // Verify that origin len != 0 if stream id == 0, or
2732
  // that origin len == 0 if stream id != 0
2733
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2734
2735
  MaybeStackBuffer<uint8_t> origin(origin_len);
2736
  MaybeStackBuffer<uint8_t> value(value_len);
2737
  origin_str->WriteOneByte(env->isolate(), *origin);
2738
  value_str->WriteOneByte(env->isolate(), *value);
2739
2740
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2741
}
2742
2743
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2744
  Environment* env = Environment::GetCurrent(args);
2745
  Local<Context> context = env->context();
2746
  Http2Session* session;
2747
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2748
2749
  Local<String> origin_string = args[0].As<String>();
2750
  int count = args[1]->IntegerValue(context).ToChecked();
2751
2752
2753
  Origins origins(env->isolate(),
2754
                  env->context(),
2755
                  origin_string,
2756
                  count);
2757
2758
  session->Origin(*origins, origins.length());
2759
}
2760
2761
// Submits a PING frame to be sent to the connected peer.
2762
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2763
  Environment* env = Environment::GetCurrent(args);
2764
  Http2Session* session;
2765
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2766
2767
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2768
  // then the current hrtime will be used as the payload.
2769
  uint8_t* payload = nullptr;
2770
  if (Buffer::HasInstance(args[0])) {
2771
    payload = reinterpret_cast<uint8_t*>(Buffer::Data(args[0]));
2772
    CHECK_EQ(Buffer::Length(args[0]), 8);
2773
  }
2774
2775
  Http2Session::Http2Ping* ping = new Http2Ping(session);
2776
  Local<Object> obj = ping->object();
2777
  obj->Set(env->context(), env->ondone_string(), args[1]).FromJust();
2778
2779
  // To prevent abuse, we strictly limit the number of unacknowledged PING
2780
  // frames that may be sent at any given time. This is configurable in the
2781
  // Options when creating a Http2Session.
2782
  if (!session->AddPing(ping)) {
2783
    ping->Done(false);
2784
    return args.GetReturnValue().Set(false);
2785
  }
2786
2787
  // The Ping itself is an Async resource. When the acknowledgement is received,
2788
  // the callback will be invoked and a notification sent out to JS land. The
2789
  // notification will include the duration of the ping, allowing the round
2790
  // trip to be measured.
2791
  ping->Send(payload);
2792
  args.GetReturnValue().Set(true);
2793
}
2794
2795
// Submits a SETTINGS frame for the Http2Session
2796
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2797
  Environment* env = Environment::GetCurrent(args);
2798
  Http2Session* session;
2799
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2800
2801
  Http2Session::Http2Settings* settings = new Http2Settings(session);
2802
  Local<Object> obj = settings->object();
2803
  obj->Set(env->context(), env->ondone_string(), args[0]).FromJust();
2804
2805
  if (!session->AddSettings(settings)) {
2806
    settings->Done(false);
2807
    return args.GetReturnValue().Set(false);
2808
  }
2809
2810
  settings->Send();
2811
  args.GetReturnValue().Set(true);
2812
}
2813
2814
2815
Http2Session::Http2Ping* Http2Session::PopPing() {
2816
  Http2Ping* ping = nullptr;
2817
  if (!outstanding_pings_.empty()) {
2818
    ping = outstanding_pings_.front();
2819
    outstanding_pings_.pop();
2820
    DecrementCurrentSessionMemory(sizeof(*ping));
2821
  }
2822
  return ping;
2823
}
2824
2825
bool Http2Session::AddPing(Http2Session::Http2Ping* ping) {
2826
  if (outstanding_pings_.size() == max_outstanding_pings_)
2827
    return false;
2828
  outstanding_pings_.push(ping);
2829
  IncrementCurrentSessionMemory(sizeof(*ping));
2830
  return true;
2831
}
2832
2833
Http2Session::Http2Settings* Http2Session::PopSettings() {
2834
  Http2Settings* settings = nullptr;
2835
  if (!outstanding_settings_.empty()) {
2836
    settings = outstanding_settings_.front();
2837
    outstanding_settings_.pop();
2838
    DecrementCurrentSessionMemory(sizeof(*settings));
2839
  }
2840
  return settings;
2841
}
2842
2843
bool Http2Session::AddSettings(Http2Session::Http2Settings* settings) {
2844
  if (outstanding_settings_.size() == max_outstanding_settings_)
2845
    return false;
2846
  outstanding_settings_.push(settings);
2847
  IncrementCurrentSessionMemory(sizeof(*settings));
2848
  return true;
2849
}
2850
2851
Http2Session::Http2Ping::Http2Ping(
2852
    Http2Session* session)
2853
        : AsyncWrap(session->env(),
2854
                    session->env()->http2ping_constructor_template()
2855
                        ->NewInstance(session->env()->context())
2856
                            .ToLocalChecked(),
2857
                    AsyncWrap::PROVIDER_HTTP2PING),
2858
          session_(session),
2859
          startTime_(uv_hrtime()) { }
2860
2861
void Http2Session::Http2Ping::Send(uint8_t* payload) {
2862
  uint8_t data[8];
2863
  if (payload == nullptr) {
2864
    memcpy(&data, &startTime_, arraysize(data));
2865
    payload = data;
2866
  }
2867
  Http2Scope h2scope(session_);
2868
  CHECK_EQ(nghttp2_submit_ping(**session_, NGHTTP2_FLAG_NONE, payload), 0);
2869
}
2870
2871
void Http2Session::Http2Ping::Done(bool ack, const uint8_t* payload) {
2872
  session_->statistics_.ping_rtt = uv_hrtime() - startTime_;
2873
  double duration = session_->statistics_.ping_rtt / 1e6;
2874
2875
  Local<Value> buf = Undefined(env()->isolate());
2876
  if (payload != nullptr) {
2877
    buf = Buffer::Copy(env()->isolate(),
2878
                       reinterpret_cast<const char*>(payload),
2879
                       8).ToLocalChecked();
2880
  }
2881
2882
  Local<Value> argv[3] = {
2883
    Boolean::New(env()->isolate(), ack),
2884
    Number::New(env()->isolate(), duration),
2885
    buf
2886
  };
2887
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
2888
  delete this;
2889
}
2890
2891
2892
void nghttp2_stream_write::MemoryInfo(MemoryTracker* tracker) const {
2893
  if (req_wrap != nullptr)
2894
    tracker->TrackField("req_wrap", req_wrap->GetAsyncWrap());
2895
  tracker->TrackField("buf", buf);
2896
}
2897
2898
2899
void nghttp2_header::MemoryInfo(MemoryTracker* tracker) const {
2900
  tracker->TrackFieldWithSize("name", nghttp2_rcbuf_get_buf(name).len);
2901
  tracker->TrackFieldWithSize("value", nghttp2_rcbuf_get_buf(value).len);
2902
}
2903
2904
void SetCallbackFunctions(const FunctionCallbackInfo<Value>& args) {
2905
  Environment* env = Environment::GetCurrent(args);
2906
  CHECK_EQ(args.Length(), 12);
2907
2908
#define SET_FUNCTION(arg, name)                                               \
2909
  CHECK(args[arg]->IsFunction());                                             \
2910
  env->set_http2session_on_ ## name ## _function(args[arg].As<Function>());
2911
2912
  SET_FUNCTION(0, error)
2913
  SET_FUNCTION(1, priority)
2914
  SET_FUNCTION(2, settings)
2915
  SET_FUNCTION(3, ping)
2916
  SET_FUNCTION(4, headers)
2917
  SET_FUNCTION(5, frame_error)
2918
  SET_FUNCTION(6, goaway_data)
2919
  SET_FUNCTION(7, altsvc)
2920
  SET_FUNCTION(8, origin)
2921
  SET_FUNCTION(9, select_padding)
2922
  SET_FUNCTION(10, stream_trailers)
2923
  SET_FUNCTION(11, stream_close)
2924
2925
#undef SET_FUNCTION
2926
}
2927
2928
// Set up the process.binding('http2') binding.
2929
void Initialize(Local<Object> target,
2930
                Local<Value> unused,
2931
                Local<Context> context,
2932
                void* priv) {
2933
  Environment* env = Environment::GetCurrent(context);
2934
  Isolate* isolate = env->isolate();
2935
  HandleScope scope(isolate);
2936
2937
  std::unique_ptr<Http2State> state(new Http2State(isolate));
2938
2939
#define SET_STATE_TYPEDARRAY(name, field)             \
2940
  target->Set(context,                                \
2941
              FIXED_ONE_BYTE_STRING(isolate, (name)), \
2942
              (field)).FromJust()
2943
2944
  // Initialize the buffer used for padding callbacks
2945
  SET_STATE_TYPEDARRAY(
2946
    "paddingBuffer", state->padding_buffer.GetJSArray());
2947
  // Initialize the buffer used to store the session state
2948
  SET_STATE_TYPEDARRAY(
2949
    "sessionState", state->session_state_buffer.GetJSArray());
2950
  // Initialize the buffer used to store the stream state
2951
  SET_STATE_TYPEDARRAY(
2952
    "streamState", state->stream_state_buffer.GetJSArray());
2953
  SET_STATE_TYPEDARRAY(
2954
    "settingsBuffer", state->settings_buffer.GetJSArray());
2955
  SET_STATE_TYPEDARRAY(
2956
    "optionsBuffer", state->options_buffer.GetJSArray());
2957
  SET_STATE_TYPEDARRAY(
2958
    "streamStats", state->stream_stats_buffer.GetJSArray());
2959
  SET_STATE_TYPEDARRAY(
2960
    "sessionStats", state->session_stats_buffer.GetJSArray());
2961
#undef SET_STATE_TYPEDARRAY
2962
2963
  env->set_http2_state(std::move(state));
2964
2965
  NODE_DEFINE_CONSTANT(target, PADDING_BUF_FRAME_LENGTH);
2966
  NODE_DEFINE_CONSTANT(target, PADDING_BUF_MAX_PAYLOAD_LENGTH);
2967
  NODE_DEFINE_CONSTANT(target, PADDING_BUF_RETURN_VALUE);
2968
2969
  // Method to fetch the nghttp2 string description of an nghttp2 error code
2970
  env->SetMethod(target, "nghttp2ErrorString", HttpErrorString);
2971
2972
  Local<String> http2SessionClassName =
2973
    FIXED_ONE_BYTE_STRING(isolate, "Http2Session");
2974
2975
  Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate());
2976
  ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping"));
2977
  ping->Inherit(AsyncWrap::GetConstructorTemplate(env));
2978
  Local<ObjectTemplate> pingt = ping->InstanceTemplate();
2979
  pingt->SetInternalFieldCount(1);
2980
  env->set_http2ping_constructor_template(pingt);
2981
2982
  Local<FunctionTemplate> setting = FunctionTemplate::New(env->isolate());
2983
  setting->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Setting"));
2984
  setting->Inherit(AsyncWrap::GetConstructorTemplate(env));
2985
  Local<ObjectTemplate> settingt = setting->InstanceTemplate();
2986
  settingt->SetInternalFieldCount(1);
2987
  env->set_http2settings_constructor_template(settingt);
2988
2989
  Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
2990
  stream->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"));
2991
  env->SetProtoMethod(stream, "id", Http2Stream::GetID);
2992
  env->SetProtoMethod(stream, "destroy", Http2Stream::Destroy);
2993
  env->SetProtoMethod(stream, "flushData", Http2Stream::FlushData);
2994
  env->SetProtoMethod(stream, "priority", Http2Stream::Priority);
2995
  env->SetProtoMethod(stream, "pushPromise", Http2Stream::PushPromise);
2996
  env->SetProtoMethod(stream, "info", Http2Stream::Info);
2997
  env->SetProtoMethod(stream, "trailers", Http2Stream::Trailers);
2998
  env->SetProtoMethod(stream, "respond", Http2Stream::Respond);
2999
  env->SetProtoMethod(stream, "rstStream", Http2Stream::RstStream);
3000
  env->SetProtoMethod(stream, "refreshState", Http2Stream::RefreshState);
3001
  stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
3002
  StreamBase::AddMethods<Http2Stream>(env, stream);
3003
  Local<ObjectTemplate> streamt = stream->InstanceTemplate();
3004
  streamt->SetInternalFieldCount(1);
3005
  env->set_http2stream_constructor_template(streamt);
3006
  target->Set(context,
3007
              FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"),
3008
              stream->GetFunction(env->context()).ToLocalChecked()).FromJust();
3009
3010
  Local<FunctionTemplate> session =
3011
      env->NewFunctionTemplate(Http2Session::New);
3012
  session->SetClassName(http2SessionClassName);
3013
  session->InstanceTemplate()->SetInternalFieldCount(1);
3014
  session->Inherit(AsyncWrap::GetConstructorTemplate(env));
3015
  env->SetProtoMethod(session, "origin", Http2Session::Origin);
3016
  env->SetProtoMethod(session, "altsvc", Http2Session::AltSvc);
3017
  env->SetProtoMethod(session, "ping", Http2Session::Ping);
3018
  env->SetProtoMethod(session, "consume", Http2Session::Consume);
3019
  env->SetProtoMethod(session, "destroy", Http2Session::Destroy);
3020
  env->SetProtoMethod(session, "goaway", Http2Session::Goaway);
3021
  env->SetProtoMethod(session, "settings", Http2Session::Settings);
3022
  env->SetProtoMethod(session, "request", Http2Session::Request);
3023
  env->SetProtoMethod(session, "setNextStreamID",
3024
                      Http2Session::SetNextStreamID);
3025
  env->SetProtoMethod(session, "updateChunksSent",
3026
                      Http2Session::UpdateChunksSent);
3027
  env->SetProtoMethod(session, "refreshState", Http2Session::RefreshState);
3028
  env->SetProtoMethod(
3029
      session, "localSettings",
3030
      Http2Session::RefreshSettings<nghttp2_session_get_local_settings>);
3031
  env->SetProtoMethod(
3032
      session, "remoteSettings",
3033
      Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>);
3034
  target->Set(context,
3035
              http2SessionClassName,
3036
              session->GetFunction(env->context()).ToLocalChecked()).FromJust();
3037
3038
  Local<Object> constants = Object::New(isolate);
3039
  Local<Array> name_for_error_code = Array::New(isolate);
3040
3041
#define NODE_NGHTTP2_ERROR_CODES(V)                       \
3042
  V(NGHTTP2_SESSION_SERVER);                              \
3043
  V(NGHTTP2_SESSION_CLIENT);                              \
3044
  V(NGHTTP2_STREAM_STATE_IDLE);                           \
3045
  V(NGHTTP2_STREAM_STATE_OPEN);                           \
3046
  V(NGHTTP2_STREAM_STATE_RESERVED_LOCAL);                 \
3047
  V(NGHTTP2_STREAM_STATE_RESERVED_REMOTE);                \
3048
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL);              \
3049
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE);             \
3050
  V(NGHTTP2_STREAM_STATE_CLOSED);                         \
3051
  V(NGHTTP2_NO_ERROR);                                    \
3052
  V(NGHTTP2_PROTOCOL_ERROR);                              \
3053
  V(NGHTTP2_INTERNAL_ERROR);                              \
3054
  V(NGHTTP2_FLOW_CONTROL_ERROR);                          \
3055
  V(NGHTTP2_SETTINGS_TIMEOUT);                            \
3056
  V(NGHTTP2_STREAM_CLOSED);                               \
3057
  V(NGHTTP2_FRAME_SIZE_ERROR);                            \
3058
  V(NGHTTP2_REFUSED_STREAM);                              \
3059
  V(NGHTTP2_CANCEL);                                      \
3060
  V(NGHTTP2_COMPRESSION_ERROR);                           \
3061
  V(NGHTTP2_CONNECT_ERROR);                               \
3062
  V(NGHTTP2_ENHANCE_YOUR_CALM);                           \
3063
  V(NGHTTP2_INADEQUATE_SECURITY);                         \
3064
  V(NGHTTP2_HTTP_1_1_REQUIRED);                           \
3065
3066
#define V(name)                                                         \
3067
  NODE_DEFINE_CONSTANT(constants, name);                                \
3068
  name_for_error_code->Set(env->context(),                              \
3069
                           static_cast<int>(name),                      \
3070
                           FIXED_ONE_BYTE_STRING(isolate,               \
3071
                                                 #name)).FromJust();
3072
  NODE_NGHTTP2_ERROR_CODES(V)
3073
#undef V
3074
3075
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_REQUEST);
3076
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_RESPONSE);
3077
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_PUSH_RESPONSE);
3078
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_HEADERS);
3079
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_NV_FLAG_NONE);
3080
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_NV_FLAG_NO_INDEX);
3081
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_DEFERRED);
3082
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE);
3083
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_INVALID_ARGUMENT);
3084
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_STREAM_CLOSED);
3085
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_ERR_FRAME_SIZE_ERROR);
3086
3087
  NODE_DEFINE_HIDDEN_CONSTANT(constants, STREAM_OPTION_EMPTY_PAYLOAD);
3088
  NODE_DEFINE_HIDDEN_CONSTANT(constants, STREAM_OPTION_GET_TRAILERS);
3089
3090
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_NONE);
3091
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_END_STREAM);
3092
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_END_HEADERS);
3093
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_ACK);
3094
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_PADDED);
3095
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_PRIORITY);
3096
3097
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_HEADER_TABLE_SIZE);
3098
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_ENABLE_PUSH);
3099
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE);
3100
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_MAX_FRAME_SIZE);
3101
  NODE_DEFINE_CONSTANT(constants, MAX_MAX_FRAME_SIZE);
3102
  NODE_DEFINE_CONSTANT(constants, MIN_MAX_FRAME_SIZE);
3103
  NODE_DEFINE_CONSTANT(constants, MAX_INITIAL_WINDOW_SIZE);
3104
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_DEFAULT_WEIGHT);
3105
3106
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
3107
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_ENABLE_PUSH);
3108
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
3109
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
3110
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
3111
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
3112
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
3113
3114
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_NONE);
3115
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_ALIGNED);
3116
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_MAX);
3117
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_CALLBACK);
3118
3119
#define STRING_CONSTANT(NAME, VALUE)                                          \
3120
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE);
3121
HTTP_KNOWN_HEADERS(STRING_CONSTANT)
3122
#undef STRING_CONSTANT
3123
3124
#define STRING_CONSTANT(NAME, VALUE)                                          \
3125
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE);
3126
HTTP_KNOWN_METHODS(STRING_CONSTANT)
3127
#undef STRING_CONSTANT
3128
3129
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
3130
HTTP_STATUS_CODES(V)
3131
#undef V
3132
3133
  env->SetMethod(target, "refreshDefaultSettings", RefreshDefaultSettings);
3134
  env->SetMethod(target, "packSettings", PackSettings);
3135
  env->SetMethod(target, "setCallbackFunctions", SetCallbackFunctions);
3136
3137
  target->Set(context,
3138
              env->constants_string(),
3139
              constants).FromJust();
3140
  target->Set(context,
3141
              FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"),
3142
              name_for_error_code).FromJust();
3143
}
3144
}  // namespace http2
3145
}  // namespace node
3146
3147

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