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: 1593 1646 96.8 %
Date: 2019-10-07 22:40:39 Branches: 578 782 73.9 %

Line Branch Exec Source
1
#include "aliased_buffer.h"
2
#include "debug_utils.h"
3
#include "memory_tracker-inl.h"
4
#include "node.h"
5
#include "node_buffer.h"
6
#include "node_http2.h"
7
#include "node_http2_state.h"
8
#include "node_perf.h"
9
#include "node_revert.h"
10
#include "util-inl.h"
11
12
#include <algorithm>
13
14
namespace node {
15
16
using v8::ArrayBuffer;
17
using v8::ArrayBufferView;
18
using v8::Boolean;
19
using v8::Context;
20
using v8::Float64Array;
21
using v8::Function;
22
using v8::Integer;
23
using v8::NewStringType;
24
using v8::Number;
25
using v8::ObjectTemplate;
26
using v8::String;
27
using v8::Uint32;
28
using v8::Uint32Array;
29
using v8::Uint8Array;
30
using v8::Undefined;
31
32
using node::performance::PerformanceEntry;
33
namespace http2 {
34
35
namespace {
36
37
const char zero_bytes_256[256] = {};
38
39
40369
inline Http2Stream* GetStream(Http2Session* session,
40
                              int32_t id,
41
                              nghttp2_data_source* source) {
42
40369
  Http2Stream* stream = static_cast<Http2Stream*>(source->ptr);
43
40369
  if (stream == nullptr)
44
31977
    stream = session->FindStream(id);
45
40369
  CHECK_NOT_NULL(stream);
46
40369
  CHECK_EQ(id, stream->id());
47
40369
  return stream;
48
}
49
50
}  // anonymous namespace
51
52
// These configure the callbacks required by nghttp2 itself. There are
53
// two sets of callback functions, one that is used if a padding callback
54
// is set, and other that does not include the padding callback.
55
9898
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
56
    Callbacks(false),
57
4949
    Callbacks(true)};
58
59
// The Http2Scope object is used to queue a write to the i/o stream. It is
60
// used whenever any action is take on the underlying nghttp2 API that may
61
// push data into nghttp2 outbound data queue.
62
//
63
// For example:
64
//
65
// Http2Scope h2scope(session);
66
// nghttp2_submit_ping(**session, ... );
67
//
68
// When the Http2Scope passes out of scope and is deconstructed, it will
69
// call Http2Session::MaybeScheduleWrite().
70
61466
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
71
72
104158
Http2Scope::Http2Scope(Http2Session* session) {
73
104158
  if (session == nullptr)
74
    return;
75
76
104158
  if (session->flags_ & (SESSION_STATE_HAS_SCOPE |
77
                         SESSION_STATE_WRITE_SCHEDULED)) {
78
    // There is another scope further below on the stack, or it is already
79
    // known that a write is scheduled. In either case, there is nothing to do.
80
73133
    return;
81
  }
82
31025
  session->flags_ |= SESSION_STATE_HAS_SCOPE;
83
31025
  session_ = session;
84
85
  // Always keep the session object alive for at least as long as
86
  // this scope is active.
87
31025
  session_handle_ = session->object();
88
62050
  CHECK(!session_handle_.IsEmpty());
89
}
90
91
104157
Http2Scope::~Http2Scope() {
92
104157
  if (session_ == nullptr)
93
73133
    return;
94
95
31024
  session_->flags_ &= ~SESSION_STATE_HAS_SCOPE;
96
31024
  session_->MaybeScheduleWrite();
97
31024
}
98
99
// The Http2Options object is used during the construction of Http2Session
100
// instances to configure an appropriate nghttp2_options struct. The class
101
// uses a single TypedArray instance that is shared with the JavaScript side
102
// to more efficiently pass values back and forth.
103
584
Http2Options::Http2Options(Environment* env, nghttp2_session_type type) {
104
584
  nghttp2_option_new(&options_);
105
106
  // Make sure closed connections aren't kept around, taking up memory.
107
  // Note that this breaks the priority tree, which we don't use.
108
584
  nghttp2_option_set_no_closed_streams(options_, 1);
109
110
  // We manually handle flow control within a session in order to
111
  // implement backpressure -- that is, we only send WINDOW_UPDATE
112
  // frames to the remote peer as data is actually consumed by user
113
  // code. This ensures that the flow of data over the connection
114
  // does not move too quickly and limits the amount of data we
115
  // are required to buffer.
116
584
  nghttp2_option_set_no_auto_window_update(options_, 1);
117
118
  // Enable built in support for receiving ALTSVC and ORIGIN frames (but
119
  // only on client side sessions
120
584
  if (type == NGHTTP2_SESSION_CLIENT) {
121
286
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC);
122
286
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ORIGIN);
123
  }
124
125
584
  AliasedUint32Array& buffer = env->http2_state()->options_buffer;
126
584
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
127
128
584
  if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) {
129
    nghttp2_option_set_max_deflate_dynamic_table_size(
130
        options_,
131
        buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
132
  }
133
134
584
  if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
135
    nghttp2_option_set_max_reserved_remote_streams(
136
        options_,
137
1
        buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]);
138
  }
139
140
584
  if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) {
141
    nghttp2_option_set_max_send_header_block_length(
142
        options_,
143
1
        buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
144
  }
145
146
  // Recommended default
147
584
  nghttp2_option_set_peer_max_concurrent_streams(options_, 100);
148
584
  if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
149
    nghttp2_option_set_peer_max_concurrent_streams(
150
        options_,
151
        buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
152
  }
153
154
  // The padding strategy sets the mechanism by which we determine how much
155
  // additional frame padding to apply to DATA and HEADERS frames. Currently
156
  // this is set on a per-session basis, but eventually we may switch to
157
  // a per-stream setting, giving users greater control
158
584
  if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
159
    padding_strategy_type strategy =
160
        static_cast<padding_strategy_type>(
161
2
            buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
162
2
    SetPaddingStrategy(strategy);
163
  }
164
165
  // The max header list pairs option controls the maximum number of
166
  // header pairs the session may accept. This is a hard limit.. that is,
167
  // if the remote peer sends more than this amount, the stream will be
168
  // automatically closed with an RST_STREAM.
169
584
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS)) {
170
3
    SetMaxHeaderPairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
171
  }
172
173
  // The HTTP2 specification places no limits on the number of HTTP2
174
  // PING frames that can be sent. In order to prevent PINGS from being
175
  // abused as an attack vector, however, we place a strict upper limit
176
  // on the number of unacknowledged PINGS that can be sent at any given
177
  // time.
178
584
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS)) {
179
2
    SetMaxOutstandingPings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
180
  }
181
182
  // The HTTP2 specification places no limits on the number of HTTP2
183
  // SETTINGS frames that can be sent. In order to prevent PINGS from being
184
  // abused as an attack vector, however, we place a strict upper limit
185
  // on the number of unacknowledged SETTINGS that can be sent at any given
186
  // time.
187
584
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS)) {
188
2
    SetMaxOutstandingSettings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
189
  }
190
191
  // The HTTP2 specification places no limits on the amount of memory
192
  // that a session can consume. In order to prevent abuse, we place a
193
  // cap on the amount of memory a session can consume at any given time.
194
  // this is a credit based system. Existing streams may cause the limit
195
  // to be temporarily exceeded but once over the limit, new streams cannot
196
  // created.
197
  // Important: The maxSessionMemory option in javascript is expressed in
198
  //            terms of MB increments (i.e. the value 1 == 1 MB)
199
584
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY)) {
200
5
    SetMaxSessionMemory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1e6);
201
  }
202
584
}
203
204
609
void Http2Session::Http2Settings::Init() {
205
609
  AliasedUint32Array& buffer = env()->http2_state()->settings_buffer;
206
609
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
207
208
609
  size_t n = 0;
209
210
#define GRABSETTING(N, trace)                                                 \
211
  if (flags & (1 << IDX_SETTINGS_##N)) {                                      \
212
    uint32_t val = buffer[IDX_SETTINGS_##N];                                  \
213
    if (session_ != nullptr)                                                  \
214
      Debug(session_, "setting " trace ": %d\n", val);                        \
215
    entries_[n++] =                                                           \
216
        nghttp2_settings_entry {NGHTTP2_SETTINGS_##N, val};                   \
217
  }
218
219

614
  GRABSETTING(HEADER_TABLE_SIZE, "header table size");
220

617
  GRABSETTING(MAX_CONCURRENT_STREAMS, "max concurrent streams");
221

615
  GRABSETTING(MAX_FRAME_SIZE, "max frame size");
222

627
  GRABSETTING(INITIAL_WINDOW_SIZE, "initial window size");
223

616
  GRABSETTING(MAX_HEADER_LIST_SIZE, "max header list size");
224

620
  GRABSETTING(ENABLE_PUSH, "enable push");
225

612
  GRABSETTING(ENABLE_CONNECT_PROTOCOL, "enable connect protocol");
226
227
#undef GRABSETTING
228
229
609
  count_ = n;
230
609
}
231
232
// The Http2Settings class is used to configure a SETTINGS frame that is
233
// to be sent to the connected peer. The settings are set using a TypedArray
234
// that is shared with the JavaScript side.
235
609
Http2Session::Http2Settings::Http2Settings(Environment* env,
236
                                           Http2Session* session,
237
                                           Local<Object> obj,
238
                                           uint64_t start_time)
239
    : AsyncWrap(env, obj, PROVIDER_HTTP2SETTINGS),
240
      session_(session),
241
609
      startTime_(start_time) {
242
609
  RemoveCleanupHook();  // This object is owned by the Http2Session.
243
609
  Init();
244
609
}
245
246
// Generates a Buffer that contains the serialized payload of a SETTINGS
247
// frame. This can be used, for instance, to create the Base64-encoded
248
// content of an Http2-Settings header field.
249
15
Local<Value> Http2Session::Http2Settings::Pack() {
250
15
  const size_t len = count_ * 6;
251
30
  Local<Value> buf = Buffer::New(env(), len).ToLocalChecked();
252
  ssize_t ret =
253
      nghttp2_pack_settings_payload(
254
15
        reinterpret_cast<uint8_t*>(Buffer::Data(buf)), len,
255
30
        &entries_[0], count_);
256
15
  if (ret >= 0)
257
14
    return buf;
258
  else
259
2
    return Undefined(env()->isolate());
260
}
261
262
// Updates the shared TypedArray with the current remote or local settings for
263
// the session.
264
506
void Http2Session::Http2Settings::Update(Environment* env,
265
                                         Http2Session* session,
266
                                         get_setting fn) {
267
506
  AliasedUint32Array& buffer = env->http2_state()->settings_buffer;
268
1012
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
269
1012
      fn(**session, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
270
1012
  buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
271
1012
      fn(**session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
272
1012
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
273
1012
      fn(**session, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
274
1012
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
275
1012
      fn(**session, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
276
1012
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
277
1012
      fn(**session, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
278
1012
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
279
1012
      fn(**session, NGHTTP2_SETTINGS_ENABLE_PUSH);
280
1012
  buffer[IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL] =
281
1012
      fn(**session, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
282
506
}
283
284
// Initializes the shared TypedArray with the default settings values.
285
3
void Http2Session::Http2Settings::RefreshDefaults(Environment* env) {
286
3
  AliasedUint32Array& buffer = env->http2_state()->settings_buffer;
287
288
6
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
289
3
      DEFAULT_SETTINGS_HEADER_TABLE_SIZE;
290
6
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
291
3
      DEFAULT_SETTINGS_ENABLE_PUSH;
292
6
  buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
293
3
      DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS;
294
6
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
295
3
      DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE;
296
6
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
297
3
      DEFAULT_SETTINGS_MAX_FRAME_SIZE;
298
6
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
299
3
      DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
300
6
  buffer[IDX_SETTINGS_COUNT] =
301
    (1 << IDX_SETTINGS_HEADER_TABLE_SIZE) |
302
    (1 << IDX_SETTINGS_ENABLE_PUSH) |
303
    (1 << IDX_SETTINGS_MAX_CONCURRENT_STREAMS) |
304
    (1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE) |
305
    (1 << IDX_SETTINGS_MAX_FRAME_SIZE) |
306
3
    (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE);
307
3
}
308
309
310
592
void Http2Session::Http2Settings::Send() {
311
592
  Http2Scope h2scope(session_);
312
592
  CHECK_EQ(nghttp2_submit_settings(**session_, NGHTTP2_FLAG_NONE,
313
592
                                   &entries_[0], count_), 0);
314
592
}
315
316
487
void Http2Session::Http2Settings::Done(bool ack) {
317
487
  uint64_t end = uv_hrtime();
318
487
  double duration = (end - startTime_) / 1e6;
319
320
  Local<Value> argv[] = {
321
    Boolean::New(env()->isolate(), ack),
322
    Number::New(env()->isolate(), duration)
323
1461
  };
324
487
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
325
487
}
326
327
// The Http2Priority class initializes an appropriate nghttp2_priority_spec
328
// struct used when either creating a stream or updating its priority
329
// settings.
330
11655
Http2Priority::Http2Priority(Environment* env,
331
                             Local<Value> parent,
332
                             Local<Value> weight,
333
                             Local<Value> exclusive) {
334
11655
  Local<Context> context = env->context();
335
23310
  int32_t parent_ = parent->Int32Value(context).ToChecked();
336
23310
  int32_t weight_ = weight->Int32Value(context).ToChecked();
337
23310
  bool exclusive_ = exclusive->BooleanValue(env->isolate());
338
  Debug(env, DebugCategory::HTTP2STREAM,
339
        "Http2Priority: parent: %d, weight: %d, exclusive: %d\n",
340
        parent_, weight_, exclusive_);
341
11655
  nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0);
342
11655
}
343
344
345
124
const char* Http2Session::TypeName() const {
346
124
  switch (session_type_) {
347
65
    case NGHTTP2_SESSION_SERVER: return "server";
348
59
    case NGHTTP2_SESSION_CLIENT: return "client";
349
    default:
350
      // This should never happen
351
      ABORT();
352
  }
353
}
354
355
// The Headers class initializes a proper array of nghttp2_nv structs
356
// containing the header name value pairs.
357
23269
Headers::Headers(Isolate* isolate,
358
                 Local<Context> context,
359
23269
                 Local<Array> headers) {
360
46538
  Local<Value> header_string = headers->Get(context, 0).ToLocalChecked();
361
46538
  Local<Value> header_count = headers->Get(context, 1).ToLocalChecked();
362
46538
  count_ = header_count.As<Uint32>()->Value();
363
46538
  int header_string_len = header_string.As<String>()->Length();
364
365
23269
  if (count_ == 0) {
366
25
    CHECK_EQ(header_string_len, 0);
367
51
    return;
368
  }
369
370
  // Allocate a single buffer with count_ nghttp2_nv structs, followed
371
  // by the raw header data as passed from JS. This looks like:
372
  // | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents |
373
  buf_.AllocateSufficientStorage((alignof(nghttp2_nv) - 1) +
374
23244
                                 count_ * sizeof(nghttp2_nv) +
375
46488
                                 header_string_len);
376
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
377
  char* start = reinterpret_cast<char*>(
378
23244
      RoundUp(reinterpret_cast<uintptr_t>(*buf_), alignof(nghttp2_nv)));
379
23244
  char* header_contents = start + (count_ * sizeof(nghttp2_nv));
380
23244
  nghttp2_nv* const nva = reinterpret_cast<nghttp2_nv*>(start);
381
382
23244
  CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length());
383
69732
  CHECK_EQ(header_string.As<String>()->WriteOneByte(
384
               isolate,
385
               reinterpret_cast<uint8_t*>(header_contents),
386
               0,
387
               header_string_len,
388
               String::NO_NULL_TERMINATION),
389
           header_string_len);
390
391
23244
  size_t n = 0;
392
  char* p;
393
94405
  for (p = header_contents; p < header_contents + header_string_len; n++) {
394
71162
    if (n >= count_) {
395
      // This can happen if a passed header contained a null byte. In that
396
      // case, just provide nghttp2 with an invalid header to make it reject
397
      // the headers list.
398
      static uint8_t zero = '\0';
399
1
      nva[0].name = nva[0].value = &zero;
400
1
      nva[0].namelen = nva[0].valuelen = 1;
401
1
      count_ = 1;
402
1
      return;
403
    }
404
405
71161
    nva[n].flags = NGHTTP2_NV_FLAG_NONE;
406
71161
    nva[n].name = reinterpret_cast<uint8_t*>(p);
407
71161
    nva[n].namelen = strlen(p);
408
71161
    p += nva[n].namelen + 1;
409
71161
    nva[n].value = reinterpret_cast<uint8_t*>(p);
410
71161
    nva[n].valuelen = strlen(p);
411
71161
    p += nva[n].valuelen + 1;
412
  }
413
}
414
415
5
Origins::Origins(Isolate* isolate,
416
                 Local<Context> context,
417
                 Local<String> origin_string,
418
5
                 size_t origin_count) : count_(origin_count) {
419
5
  int origin_string_len = origin_string->Length();
420
5
  if (count_ == 0) {
421
    CHECK_EQ(origin_string_len, 0);
422
    return;
423
  }
424
425
  // Allocate a single buffer with count_ nghttp2_nv structs, followed
426
  // by the raw header data as passed from JS. This looks like:
427
  // | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents |
428
  buf_.AllocateSufficientStorage((alignof(nghttp2_origin_entry) - 1) +
429
5
                                 count_ * sizeof(nghttp2_origin_entry) +
430
10
                                 origin_string_len);
431
432
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
433
  char* start = reinterpret_cast<char*>(
434
5
      RoundUp(reinterpret_cast<uintptr_t>(*buf_),
435
5
              alignof(nghttp2_origin_entry)));
436
5
  char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
437
  nghttp2_origin_entry* const nva =
438
5
      reinterpret_cast<nghttp2_origin_entry*>(start);
439
440
5
  CHECK_LE(origin_contents + origin_string_len, *buf_ + buf_.length());
441
10
  CHECK_EQ(origin_string->WriteOneByte(
442
               isolate,
443
               reinterpret_cast<uint8_t*>(origin_contents),
444
               0,
445
               origin_string_len,
446
               String::NO_NULL_TERMINATION),
447
           origin_string_len);
448
449
5
  size_t n = 0;
450
  char* p;
451
14
  for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
452
9
    if (n >= count_) {
453
      static uint8_t zero = '\0';
454
      nva[0].origin = &zero;
455
      nva[0].origin_len = 1;
456
      count_ = 1;
457
      return;
458
    }
459
460
9
    nva[n].origin = reinterpret_cast<uint8_t*>(p);
461
9
    nva[n].origin_len = strlen(p);
462
9
    p += nva[n].origin_len + 1;
463
  }
464
}
465
466
// Sets the various callback functions that nghttp2 will use to notify us
467
// about significant events while processing http2 stuff.
468
9898
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
469
9898
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0);
470
471
  nghttp2_session_callbacks_set_on_begin_headers_callback(
472
9898
    callbacks, OnBeginHeadersCallback);
473
  nghttp2_session_callbacks_set_on_header_callback2(
474
9898
    callbacks, OnHeaderCallback);
475
  nghttp2_session_callbacks_set_on_frame_recv_callback(
476
9898
    callbacks, OnFrameReceive);
477
  nghttp2_session_callbacks_set_on_stream_close_callback(
478
9898
    callbacks, OnStreamClose);
479
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
480
9898
    callbacks, OnDataChunkReceived);
481
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
482
9898
    callbacks, OnFrameNotSent);
483
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
484
9898
    callbacks, OnInvalidHeader);
485
  nghttp2_session_callbacks_set_error_callback(
486
9898
    callbacks, OnNghttpError);
487
  nghttp2_session_callbacks_set_send_data_callback(
488
9898
    callbacks, OnSendData);
489
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
490
9898
    callbacks, OnInvalidFrame);
491
  nghttp2_session_callbacks_set_on_frame_send_callback(
492
9898
    callbacks, OnFrameSent);
493
494
9898
  if (kHasGetPaddingCallback) {
495
    nghttp2_session_callbacks_set_select_padding_callback(
496
4949
      callbacks, OnSelectPadding);
497
  }
498
9898
}
499
500
501
9898
Http2Session::Callbacks::~Callbacks() {
502
9898
  nghttp2_session_callbacks_del(callbacks);
503
9898
}
504
505
// Track memory allocated by nghttp2 using a custom allocator.
506
class Http2Session::MemoryAllocatorInfo {
507
 public:
508
584
  explicit MemoryAllocatorInfo(Http2Session* session)
509
584
      : info({ session, H2Malloc, H2Free, H2Calloc, H2Realloc }) {}
510
511
101417
  static void* H2Malloc(size_t size, void* user_data) {
512
101417
    return H2Realloc(nullptr, size, user_data);
513
  }
514
515
1170
  static void* H2Calloc(size_t nmemb, size_t size, void* user_data) {
516
1170
    size_t real_size = MultiplyWithOverflowCheck(nmemb, size);
517
1170
    void* mem = H2Malloc(real_size, user_data);
518
1170
    if (mem != nullptr)
519
1170
      memset(mem, 0, real_size);
520
1170
    return mem;
521
  }
522
523
236048
  static void H2Free(void* ptr, void* user_data) {
524
472096
    if (ptr == nullptr) return;  // free(null); happens quite often.
525
102207
    void* result = H2Realloc(ptr, 0, user_data);
526
102207
    CHECK_NULL(result);
527
  }
528
529
204467
  static void* H2Realloc(void* ptr, size_t size, void* user_data) {
530
204467
    Http2Session* session = static_cast<Http2Session*>(user_data);
531
204467
    size_t previous_size = 0;
532
204467
    char* original_ptr = nullptr;
533
534
    // We prepend each allocated buffer with a size_t containing the full
535
    // size of the allocation.
536
204467
    if (size > 0) size += sizeof(size_t);
537
538
204467
    if (ptr != nullptr) {
539
      // We are free()ing or re-allocating.
540
102233
      original_ptr = static_cast<char*>(ptr) - sizeof(size_t);
541
102233
      previous_size = *reinterpret_cast<size_t*>(original_ptr);
542
      // This means we called StopTracking() on this pointer before.
543
102233
      if (previous_size == 0) {
544
        // Fall back to the standard Realloc() function.
545
1715
        char* ret = UncheckedRealloc(original_ptr, size);
546
1715
        if (ret != nullptr)
547
          ret += sizeof(size_t);
548
1715
        return ret;
549
      }
550
    }
551
202752
    CHECK_GE(session->current_nghttp2_memory_, previous_size);
552
553
    // TODO(addaleax): Add the following, and handle NGHTTP2_ERR_NOMEM properly
554
    // everywhere:
555
    //
556
    // if (size > previous_size &&
557
    //     !session->IsAvailableSessionMemory(size - previous_size)) {
558
    //  return nullptr;
559
    //}
560
561
202752
    char* mem = UncheckedRealloc(original_ptr, size);
562
563
202752
    if (mem != nullptr) {
564
      // Adjust the memory info counter.
565
      // TODO(addaleax): Avoid the double bookkeeping we do with
566
      // current_nghttp2_memory_ + AdjustAmountOfExternalAllocatedMemory
567
      // and provide versions of our memory allocation utilities that take an
568
      // Environment*/Isolate* parameter and call the V8 method transparently.
569
102260
      const int64_t new_size = size - previous_size;
570
102260
      session->current_nghttp2_memory_ += new_size;
571
      session->env()->isolate()->AdjustAmountOfExternalAllocatedMemory(
572
102260
          new_size);
573
102260
      *reinterpret_cast<size_t*>(mem) = size;
574
102260
      mem += sizeof(size_t);
575
100492
    } else if (size == 0) {
576
100492
      session->current_nghttp2_memory_ -= previous_size;
577
      session->env()->isolate()->AdjustAmountOfExternalAllocatedMemory(
578
100492
          -static_cast<int64_t>(previous_size));
579
    }
580
581
202752
    return mem;
582
  }
583
584
24763
  static void StopTracking(Http2Session* session, void* ptr) {
585
    size_t* original_ptr = reinterpret_cast<size_t*>(
586
24763
        static_cast<char*>(ptr) - sizeof(size_t));
587
24763
    session->current_nghttp2_memory_ -= *original_ptr;
588
    session->env()->isolate()->AdjustAmountOfExternalAllocatedMemory(
589
24763
        -static_cast<int64_t>(*original_ptr));
590
24763
    *original_ptr = 0;
591
24763
  }
592
593
584
  inline nghttp2_mem* operator*() { return &info; }
594
595
  nghttp2_mem info;
596
};
597
598
24763
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
599
24763
  MemoryAllocatorInfo::StopTracking(this, buf);
600
24763
}
601
602
584
Http2Session::Http2Session(Environment* env,
603
                           Local<Object> wrap,
604
                           nghttp2_session_type type)
605
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
606
1168
      session_type_(type) {
607
584
  MakeWeak();
608
584
  statistics_.start_time = uv_hrtime();
609
610
  // Capture the configuration options for this session
611
584
  Http2Options opts(env, type);
612
613
584
  max_session_memory_ = opts.GetMaxSessionMemory();
614
615
584
  uint32_t maxHeaderPairs = opts.GetMaxHeaderPairs();
616
  max_header_pairs_ =
617
      type == NGHTTP2_SESSION_SERVER
618
1478
          ? std::max(maxHeaderPairs, 4U)     // minimum # of request headers
619

1466
          : std::max(maxHeaderPairs, 1U);    // minimum # of response headers
620
621
584
  max_outstanding_pings_ = opts.GetMaxOutstandingPings();
622
584
  max_outstanding_settings_ = opts.GetMaxOutstandingSettings();
623
624
584
  padding_strategy_ = opts.GetPaddingStrategy();
625
626
  bool hasGetPaddingCallback =
627
584
      padding_strategy_ != PADDING_STRATEGY_NONE;
628
629
  nghttp2_session_callbacks* callbacks
630
584
      = callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks;
631
632
  auto fn = type == NGHTTP2_SESSION_SERVER ?
633
      nghttp2_session_server_new3 :
634
584
      nghttp2_session_client_new3;
635
636
584
  MemoryAllocatorInfo allocator_info(this);
637
638
  // This should fail only if the system is out of memory, which
639
  // is going to cause lots of other problems anyway, or if any
640
  // of the options are out of acceptable range, which we should
641
  // be catching before it gets this far. Either way, crash if this
642
  // fails.
643
584
  CHECK_EQ(fn(&session_, callbacks, this, *opts, *allocator_info), 0);
644
645
584
  outgoing_storage_.reserve(1024);
646
584
  outgoing_buffers_.reserve(32);
647
648
  {
649
    // Make the js_fields_ property accessible to JS land.
650
    Local<ArrayBuffer> ab =
651
584
        ArrayBuffer::New(env->isolate(), js_fields_, kSessionUint8FieldCount);
652
    Local<Uint8Array> uint8_arr =
653
584
        Uint8Array::New(ab, 0, kSessionUint8FieldCount);
654
1752
    USE(wrap->Set(env->context(), env->fields_string(), uint8_arr));
655
584
  }
656
584
}
657
658
2328
Http2Session::~Http2Session() {
659
582
  CHECK_EQ(flags_ & SESSION_STATE_HAS_SCOPE, 0);
660
582
  Debug(this, "freeing nghttp2 session");
661
584
  for (const auto& iter : streams_)
662
2
    iter.second->session_ = nullptr;
663
582
  nghttp2_session_del(session_);
664
582
  CHECK_EQ(current_nghttp2_memory_, 0);
665
1164
}
666
667
124
std::string Http2Session::diagnostic_name() const {
668
248
  return std::string("Http2Session ") + TypeName() + " (" +
669
372
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
670
}
671
672
24861
inline bool HasHttp2Observer(Environment* env) {
673
24861
  AliasedUint32Array& observers = env->performance_state()->observers;
674
24861
  return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
675
}
676
677
24302
void Http2Stream::EmitStatistics() {
678
24302
  if (!HasHttp2Observer(env()))
679
48602
    return;
680
  auto entry =
681
2
      std::make_unique<Http2StreamPerformanceEntry>(env(), id_, statistics_);
682
10
  env()->SetImmediate([entry = move(entry)](Environment* env) {
683
2
    if (!HasHttp2Observer(env))
684
2
      return;
685
2
    HandleScope handle_scope(env->isolate());
686
2
    AliasedFloat64Array& buffer = env->http2_state()->stream_stats_buffer;
687
2
    buffer[IDX_STREAM_STATS_ID] = entry->id();
688
2
    if (entry->first_byte() != 0) {
689
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] =
690
          (entry->first_byte() - entry->startTimeNano()) / 1e6;
691
    } else {
692
2
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0;
693
    }
694
2
    if (entry->first_header() != 0) {
695
4
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] =
696
4
          (entry->first_header() - entry->startTimeNano()) / 1e6;
697
    } else {
698
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0;
699
    }
700
2
    if (entry->first_byte_sent() != 0) {
701
2
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] =
702
2
          (entry->first_byte_sent() - entry->startTimeNano()) / 1e6;
703
    } else {
704
1
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0;
705
    }
706
2
    buffer[IDX_STREAM_STATS_SENTBYTES] = entry->sent_bytes();
707
2
    buffer[IDX_STREAM_STATS_RECEIVEDBYTES] = entry->received_bytes();
708
    Local<Object> obj;
709
6
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
710
4
  });
711
}
712
713
555
void Http2Session::EmitStatistics() {
714
555
  if (!HasHttp2Observer(env()))
715
1108
    return;
716
  auto entry = std::make_unique<Http2SessionPerformanceEntry>(
717
2
      env(), statistics_, session_type_);
718
10
  env()->SetImmediate([entry = std::move(entry)](Environment* env) {
719
2
    if (!HasHttp2Observer(env))
720
2
      return;
721
2
    HandleScope handle_scope(env->isolate());
722
2
    AliasedFloat64Array& buffer = env->http2_state()->session_stats_buffer;
723
2
    buffer[IDX_SESSION_STATS_TYPE] = entry->type();
724
2
    buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6;
725
2
    buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count();
726
2
    buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent();
727
2
    buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count();
728
4
    buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] =
729
4
        entry->stream_average_duration();
730
2
    buffer[IDX_SESSION_STATS_DATA_SENT] = entry->data_sent();
731
2
    buffer[IDX_SESSION_STATS_DATA_RECEIVED] = entry->data_received();
732
4
    buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] =
733
4
        entry->max_concurrent_streams();
734
    Local<Object> obj;
735
6
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
736
4
  });
737
}
738
739
// Closes the session and frees the associated resources
740
555
void Http2Session::Close(uint32_t code, bool socket_closed) {
741
555
  Debug(this, "closing session");
742
743
555
  if (flags_ & SESSION_STATE_CLOSING)
744
555
    return;
745
555
  flags_ |= SESSION_STATE_CLOSING;
746
747
  // Stop reading on the i/o stream
748
555
  if (stream_ != nullptr) {
749
545
    flags_ |= SESSION_STATE_READING_STOPPED;
750
545
    stream_->ReadStop();
751
  }
752
753
  // If the socket is not closed, then attempt to send a closing GOAWAY
754
  // frame. There is no guarantee that this GOAWAY will be received by
755
  // the peer but the HTTP/2 spec recommends sending it anyway. We'll
756
  // make a best effort.
757
555
  if (!socket_closed) {
758
521
    Debug(this, "terminating session with code %d", code);
759
521
    CHECK_EQ(nghttp2_session_terminate_session(session_, code), 0);
760
521
    SendPendingData();
761
34
  } else if (stream_ != nullptr) {
762
24
    stream_->RemoveStreamListener(this);
763
  }
764
765
555
  flags_ |= SESSION_STATE_CLOSED;
766
767
  // If there are outstanding pings, those will need to be canceled, do
768
  // so on the next iteration of the event loop to avoid calling out into
769
  // javascript since this may be called during garbage collection.
770
556
  while (std::unique_ptr<Http2Ping> ping = PopPing()) {
771
1
    ping->DetachFromSession();
772
    env()->SetImmediate(
773
5
        [ping = std::move(ping)](Environment* env) {
774
1
          ping->Done(false);
775
2
        });
776
1
  }
777
778
555
  statistics_.end_time = uv_hrtime();
779
556
  EmitStatistics();
780
}
781
782
// Locates an existing known stream by ID. nghttp2 has a similar method
783
// but this is faster and does not fail if the stream is not found.
784
212061
inline Http2Stream* Http2Session::FindStream(int32_t id) {
785
212061
  auto s = streams_.find(id);
786
212061
  return s != streams_.end() ? s->second : nullptr;
787
}
788
789
12657
inline bool Http2Session::CanAddStream() {
790
  uint32_t maxConcurrentStreams =
791
      nghttp2_session_get_local_settings(
792
12657
          session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
793
  size_t maxSize =
794
12657
      std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
795
  // We can add a new stream so long as we are less than the current
796
  // maximum on concurrent streams and there's enough available memory
797

25314
  return streams_.size() < maxSize &&
798
25314
         IsAvailableSessionMemory(sizeof(Http2Stream));
799
}
800
801
24312
inline void Http2Session::AddStream(Http2Stream* stream) {
802
24312
  CHECK_GE(++statistics_.stream_count, 0);
803
24312
  streams_[stream->id()] = stream;
804
24312
  size_t size = streams_.size();
805
24312
  if (size > statistics_.max_concurrent_streams)
806
1718
    statistics_.max_concurrent_streams = size;
807
24312
  IncrementCurrentSessionMemory(sizeof(*stream));
808
24312
}
809
810
811
24308
inline void Http2Session::RemoveStream(Http2Stream* stream) {
812

24308
  if (streams_.empty() || stream == nullptr)
813
24308
    return;  // Nothing to remove, item was never added?
814
24308
  streams_.erase(stream->id());
815
24308
  DecrementCurrentSessionMemory(sizeof(*stream));
816
}
817
818
// Used as one of the Padding Strategy functions. Will attempt to ensure
819
// that the total frame size, including header bytes, are 8-byte aligned.
820
// If maxPayloadLen is smaller than the number of bytes necessary to align,
821
// will return maxPayloadLen instead.
822
4
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
823
                                            size_t maxPayloadLen) {
824
4
  size_t r = (frameLen + 9) % 8;
825
4
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
826
827
4
  size_t pad = frameLen + (8 - r);
828
829
  // If maxPayloadLen happens to be less than the calculated pad length,
830
  // use the max instead, even tho this means the frame will not be
831
  // aligned.
832
4
  pad = std::min(maxPayloadLen, pad);
833
4
  Debug(this, "using frame size padding: %d", pad);
834
4
  return pad;
835
}
836
837
// Used as one of the Padding Strategy functions. Uses the maximum amount
838
// of padding allowed for the current frame.
839
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
840
                                            size_t maxPayloadLen) {
841
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
842
  return maxPayloadLen;
843
}
844
845
// Write data received from the i/o stream to the underlying nghttp2_session.
846
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
847
// various callback functions. Each of these will typically result in a call
848
// out to JavaScript so this particular function is rather hot and can be
849
// quite expensive. This is a potential performance optimization target later.
850
29910
ssize_t Http2Session::ConsumeHTTP2Data() {
851
29910
  CHECK_NOT_NULL(stream_buf_.base);
852
29910
  CHECK_LT(stream_buf_offset_, stream_buf_.len);
853
29910
  size_t read_len = stream_buf_.len - stream_buf_offset_;
854
855
  // multiple side effects.
856
  Debug(this, "receiving %d bytes [wants data? %d]",
857
        read_len,
858
59820
        nghttp2_session_want_read(session_));
859
29910
  flags_ &= ~SESSION_STATE_NGHTTP2_RECV_PAUSED;
860
  ssize_t ret =
861
    nghttp2_session_mem_recv(session_,
862
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
863
                                 stream_buf_offset_,
864
29910
                             read_len);
865
29909
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
866
867
29909
  if (flags_ & SESSION_STATE_NGHTTP2_RECV_PAUSED) {
868
105
    CHECK_NE(flags_ & SESSION_STATE_READING_STOPPED, 0);
869
870
105
    CHECK_GT(ret, 0);
871
105
    CHECK_LE(static_cast<size_t>(ret), read_len);
872
873
105
    if (static_cast<size_t>(ret) < read_len) {
874
      // Mark the remainder of the data as available for later consumption.
875
43
      stream_buf_offset_ += ret;
876
43
      return ret;
877
    }
878
  }
879
880
  // We are done processing the current input chunk.
881
29866
  DecrementCurrentSessionMemory(stream_buf_.len);
882
29866
  stream_buf_offset_ = 0;
883
29866
  stream_buf_ab_.Reset();
884
29866
  stream_buf_allocation_.clear();
885
29866
  stream_buf_ = uv_buf_init(nullptr, 0);
886
887
29866
  if (ret < 0)
888
5
    return ret;
889
890
  // Send any data that was queued up while processing the received data.
891
29861
  if (!IsDestroyed()) {
892
29399
    SendPendingData();
893
  }
894
29861
  return ret;
895
}
896
897
898
143126
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
143126
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
901
      frame->push_promise.promised_stream_id :
902
143126
      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
24236
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
911
                                         const nghttp2_frame* frame,
912
                                         void* user_data) {
913
24236
  Http2Session* session = static_cast<Http2Session*>(user_data);
914
24236
  int32_t id = GetFrameID(frame);
915
  Debug(session, "beginning headers for stream %d", id);
916
917
24236
  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
24236
  if (LIKELY(stream == nullptr)) {
921

12657
    if (UNLIKELY(!session->CanAddStream() ||
922
                 Http2Stream::New(session, id, frame->headers.cat) ==
923
                     nullptr)) {
924
1
      if (session->rejected_stream_count_++ > 100)
925
        return NGHTTP2_ERR_CALLBACK_FAILURE;
926
      // Too many concurrent streams being opened
927
      nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id,
928
1
                                NGHTTP2_ENHANCE_YOUR_CALM);
929
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
930
    }
931
932
12656
    session->rejected_stream_count_ = 0;
933
11579
  } else if (!stream->IsDestroyed()) {
934
11579
    stream->StartHeaders(frame->headers.cat);
935
  }
936
24235
  return 0;
937
}
938
939
// Called by nghttp2 for each header name/value pair in a HEADERS block.
940
// This had to have been preceded by a call to OnBeginHeadersCallback so
941
// the Http2Stream is guaranteed to already exist.
942
71101
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
943
                                   const nghttp2_frame* frame,
944
                                   nghttp2_rcbuf* name,
945
                                   nghttp2_rcbuf* value,
946
                                   uint8_t flags,
947
                                   void* user_data) {
948
71101
  Http2Session* session = static_cast<Http2Session*>(user_data);
949
71101
  int32_t id = GetFrameID(frame);
950
71101
  Http2Stream* stream = session->FindStream(id);
951
  // If stream is null at this point, either something odd has happened
952
  // or the stream was closed locally while header processing was occurring.
953
  // either way, do not proceed and close the stream.
954
71101
  if (UNLIKELY(stream == nullptr))
955
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
956
957
  // If the stream has already been destroyed, ignore.
958

71101
  if (!stream->IsDestroyed() && !stream->AddHeader(name, value, flags)) {
959
    // This will only happen if the connected peer sends us more
960
    // than the allowed number of header items at any given time
961
2
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
962
2
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
963
  }
964
71099
  return 0;
965
}
966
967
968
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
969
// only a handful of frame types that we care about handling here.
970
55347
int Http2Session::OnFrameReceive(nghttp2_session* handle,
971
                                 const nghttp2_frame* frame,
972
                                 void* user_data) {
973
55347
  Http2Session* session = static_cast<Http2Session*>(user_data);
974
55347
  session->statistics_.frame_count++;
975
  Debug(session, "complete frame received: type: %d",
976
55347
        frame->hd.type);
977


55347
  switch (frame->hd.type) {
978
    case NGHTTP2_DATA:
979
24583
      return session->HandleDataFrame(frame);
980
    case NGHTTP2_PUSH_PROMISE:
981
      // Intentional fall-through, handled just like headers frames
982
    case NGHTTP2_HEADERS:
983
23197
      session->HandleHeadersFrame(frame);
984
23197
      break;
985
    case NGHTTP2_SETTINGS:
986
2019
      session->HandleSettingsFrame(frame);
987
2019
      break;
988
    case NGHTTP2_PRIORITY:
989
16
      session->HandlePriorityFrame(frame);
990
16
      break;
991
    case NGHTTP2_GOAWAY:
992
269
      session->HandleGoawayFrame(frame);
993
269
      break;
994
    case NGHTTP2_PING:
995
1020
      session->HandlePingFrame(frame);
996
1020
      break;
997
    case NGHTTP2_ALTSVC:
998
4
      session->HandleAltSvcFrame(frame);
999
4
      break;
1000
    case NGHTTP2_ORIGIN:
1001
5
      session->HandleOriginFrame(frame);
1002
5
      break;
1003
    default:
1004
4234
      break;
1005
  }
1006
30764
  return 0;
1007
}
1008
1009
1040
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
1010
                                 const nghttp2_frame* frame,
1011
                                 int lib_error_code,
1012
                                 void* user_data) {
1013
1040
  Http2Session* session = static_cast<Http2Session*>(user_data);
1014
1015
  Debug(session, "invalid frame received, code: %d", lib_error_code);
1016
1040
  if (session->invalid_frame_count_++ > 1000)
1017
1
    return 1;
1018
1019
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
1020

2078
  if (nghttp2_is_fatal(lib_error_code) ||
1021
1039
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
1022
1
    Environment* env = session->env();
1023
1
    Isolate* isolate = env->isolate();
1024
1
    HandleScope scope(isolate);
1025
1
    Local<Context> context = env->context();
1026
    Context::Scope context_scope(context);
1027
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
1028
2
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1029
  }
1030
1039
  return 0;
1031
}
1032
1033
// If nghttp2 is unable to send a queued up frame, it will call this callback
1034
// to let us know. If the failure occurred because we are in the process of
1035
// closing down the session or stream, we go ahead and ignore it. We don't
1036
// really care about those and there's nothing we can reasonably do about it
1037
// anyway. Other types of failures are reported up to JavaScript. This should
1038
// be exceedingly rare.
1039
2077
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1040
                                 const nghttp2_frame* frame,
1041
                                 int error_code,
1042
                                 void* user_data) {
1043
2077
  Http2Session* session = static_cast<Http2Session*>(user_data);
1044
2077
  Environment* env = session->env();
1045
  Debug(session, "frame type %d was not sent, code: %d",
1046
2077
        frame->hd.type, error_code);
1047
1048
  // Do not report if the frame was not sent due to the session closing
1049

2081
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
1050
7
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1051
5
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
1052
2
      session->js_fields_[kSessionFrameErrorListenerCount] == 0) {
1053
2076
    return 0;
1054
  }
1055
1056
1
  Isolate* isolate = env->isolate();
1057
1
  HandleScope scope(isolate);
1058
1
  Local<Context> context = env->context();
1059
  Context::Scope context_scope(context);
1060
1061
  Local<Value> argv[3] = {
1062
    Integer::New(isolate, frame->hd.stream_id),
1063
    Integer::New(isolate, frame->hd.type),
1064
    Integer::New(isolate, error_code)
1065
4
  };
1066
  session->MakeCallback(
1067
      env->http2session_on_frame_error_function(),
1068
1
      arraysize(argv), argv);
1069
2
  return 0;
1070
}
1071
1072
55266
int Http2Session::OnFrameSent(nghttp2_session* handle,
1073
                              const nghttp2_frame* frame,
1074
                              void* user_data) {
1075
55266
  Http2Session* session = static_cast<Http2Session*>(user_data);
1076
55266
  session->statistics_.frame_sent += 1;
1077
55266
  return 0;
1078
}
1079
1080
// Called by nghttp2 when a stream closes.
1081
24276
int Http2Session::OnStreamClose(nghttp2_session* handle,
1082
                                int32_t id,
1083
                                uint32_t code,
1084
                                void* user_data) {
1085
24276
  Http2Session* session = static_cast<Http2Session*>(user_data);
1086
24276
  Environment* env = session->env();
1087
24276
  Isolate* isolate = env->isolate();
1088
24276
  HandleScope scope(isolate);
1089
24276
  Local<Context> context = env->context();
1090
  Context::Scope context_scope(context);
1091
  Debug(session, "stream %d closed with code: %d", id, code);
1092
24276
  Http2Stream* stream = session->FindStream(id);
1093
  // Intentionally ignore the callback if the stream does not exist or has
1094
  // already been destroyed
1095

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

121105
  if (answer.IsEmpty() ||
1108
121105
      !(answer.ToLocalChecked()->BooleanValue(env->isolate()))) {
1109
    // Skip to destroy
1110
1037
    stream->Destroy();
1111
  }
1112
48497
  return 0;
1113
}
1114
1115
// Called by nghttp2 when an invalid header has been received. For now, we
1116
// ignore these. If this callback was not provided, nghttp2 would handle
1117
// invalid headers strictly and would shut down the stream. We are intentionally
1118
// being more lenient here although we may want to revisit this choice later.
1119
4
int Http2Session::OnInvalidHeader(nghttp2_session* session,
1120
                                  const nghttp2_frame* frame,
1121
                                  nghttp2_rcbuf* name,
1122
                                  nghttp2_rcbuf* value,
1123
                                  uint8_t flags,
1124
                                  void* user_data) {
1125
  // Ignore invalid header fields by default.
1126
4
  return 0;
1127
}
1128
1129
// When nghttp2 receives a DATA frame, it will deliver the data payload to
1130
// us in discrete chunks. We push these into a linked list stored in the
1131
// Http2Sttream which is flushed out to JavaScript as quickly as possible.
1132
// This can be a particularly hot path.
1133
12683
int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
1134
                                      uint8_t flags,
1135
                                      int32_t id,
1136
                                      const uint8_t* data,
1137
                                      size_t len,
1138
                                      void* user_data) {
1139
12683
  Http2Session* session = static_cast<Http2Session*>(user_data);
1140
  Debug(session, "buffering data chunk for stream %d, size: "
1141
        "%d, flags: %d", id, len, flags);
1142
12683
  Environment* env = session->env();
1143
12683
  HandleScope scope(env->isolate());
1144
1145
  // We should never actually get a 0-length chunk so this check is
1146
  // only a precaution at this point.
1147
12683
  if (len == 0)
1148
    return 0;
1149
1150
  // Notify nghttp2 that we've consumed a chunk of data on the connection
1151
  // so that it can send a WINDOW_UPDATE frame. This is a critical part of
1152
  // the flow control process in http2
1153
12683
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1154
12683
  Http2Stream* stream = session->FindStream(id);
1155
  // If the stream has been destroyed, ignore this chunk
1156
12683
  if (stream->IsDestroyed())
1157
1
    return 0;
1158
1159
12682
  stream->statistics_.received_bytes += len;
1160
1161
  // Repeatedly ask the stream's owner for memory, and copy the read data
1162
  // into those buffers.
1163
  // The typical case is actually the exception here; Http2StreamListeners
1164
  // know about the HTTP2 session associated with this stream, so they know
1165
  // about the larger from-socket read buffer, so they do not require copying.
1166
12682
  do {
1167
12682
    uv_buf_t buf = stream->EmitAlloc(len);
1168
12682
    ssize_t avail = len;
1169
12682
    if (static_cast<ssize_t>(buf.len) < avail)
1170
      avail = buf.len;
1171
1172
    // `buf.base == nullptr` is the default Http2StreamListener's way
1173
    // of saying that it wants a pointer to the raw original.
1174
    // Since it has access to the original socket buffer from which the data
1175
    // was read in the first place, it can use that to minimize ArrayBuffer
1176
    // allocations.
1177
12682
    if (LIKELY(buf.base == nullptr))
1178
12682
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1179
    else
1180
      memcpy(buf.base, data, avail);
1181
12682
    data += avail;
1182
12682
    len -= avail;
1183
12682
    stream->EmitRead(avail, buf);
1184
1185
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1186
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1187
    // more data is being requested.
1188
12682
    if (stream->IsReading())
1189
11574
      nghttp2_session_consume_stream(handle, id, avail);
1190
    else
1191
1108
      stream->inbound_consumed_data_while_paused_ += avail;
1192
1193
    // If we have a gathered a lot of data for output, try sending it now.
1194

25363
    if (session->outgoing_length_ > 4096 ||
1195
12681
        stream->available_outbound_length_ > 4096) {
1196
13
      session->SendPendingData();
1197
    }
1198
12682
  } while (len != 0);
1199
1200
  // If we are currently waiting for a write operation to finish, we should
1201
  // tell nghttp2 that we want to wait before we process more input data.
1202
12682
  if (session->flags_ & SESSION_STATE_WRITE_IN_PROGRESS) {
1203
105
    CHECK_NE(session->flags_ & SESSION_STATE_READING_STOPPED, 0);
1204
105
    session->flags_ |= SESSION_STATE_NGHTTP2_RECV_PAUSED;
1205
105
    return NGHTTP2_ERR_PAUSE;
1206
  }
1207
1208
12577
  return 0;
1209
}
1210
1211
// Called by nghttp2 when it needs to determine how much padding to use in
1212
// a DATA or HEADERS frame.
1213
4
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1214
                                      const nghttp2_frame* frame,
1215
                                      size_t maxPayloadLen,
1216
                                      void* user_data) {
1217
4
  Http2Session* session = static_cast<Http2Session*>(user_data);
1218
4
  ssize_t padding = frame->hd.length;
1219
1220

4
  switch (session->padding_strategy_) {
1221
    case PADDING_STRATEGY_NONE:
1222
      // Fall-through
1223
      break;
1224
    case PADDING_STRATEGY_MAX:
1225
      padding = session->OnMaxFrameSizePadding(padding, maxPayloadLen);
1226
      break;
1227
    case PADDING_STRATEGY_ALIGNED:
1228
4
      padding = session->OnDWordAlignedPadding(padding, maxPayloadLen);
1229
4
      break;
1230
  }
1231
4
  return padding;
1232
}
1233
1234
#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we "     \
1235
                         "expected SETTINGS frame.  Perhaps, peer does not "  \
1236
                         "support HTTP/2 properly."
1237
1238
// We use this currently to determine when an attempt is made to use the http2
1239
// protocol with a non-http2 peer.
1240
1037
int Http2Session::OnNghttpError(nghttp2_session* handle,
1241
                                const char* message,
1242
                                size_t len,
1243
                                void* user_data) {
1244
  // Unfortunately, this is currently the only way for us to know if
1245
  // the session errored because the peer is not an http2 peer.
1246
1037
  Http2Session* session = static_cast<Http2Session*>(user_data);
1247
  Debug(session, "Error '%.*s'", len, message);
1248
1037
  if (strncmp(message, BAD_PEER_MESSAGE, len) == 0) {
1249
1
    Environment* env = session->env();
1250
1
    Isolate* isolate = env->isolate();
1251
1
    HandleScope scope(isolate);
1252
1
    Local<Context> context = env->context();
1253
    Context::Scope context_scope(context);
1254
1
    Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1255
2
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1256
  }
1257
1037
  return 0;
1258
}
1259
1260
12682
uv_buf_t Http2StreamListener::OnStreamAlloc(size_t size) {
1261
  // See the comments in Http2Session::OnDataChunkReceived
1262
  // (which is the only possible call site for this method).
1263
12682
  return uv_buf_init(nullptr, size);
1264
}
1265
1266
25193
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1267
25193
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1268
25193
  Http2Session* session = stream->session();
1269
25193
  Environment* env = stream->env();
1270
25193
  HandleScope handle_scope(env->isolate());
1271
37875
  Context::Scope context_scope(env->context());
1272
1273
25193
  if (nread < 0) {
1274
12511
    PassReadErrorToPreviousListener(nread);
1275
37702
    return;
1276
  }
1277
1278
  Local<ArrayBuffer> ab;
1279
25364
  if (session->stream_buf_ab_.IsEmpty()) {
1280
4859
    ab = session->stream_buf_allocation_.ToArrayBuffer();
1281
4859
    session->stream_buf_ab_.Reset(env->isolate(), ab);
1282
  } else {
1283
7823
    ab = PersistentToLocal::Strong(session->stream_buf_ab_);
1284
  }
1285
1286
  // There is a single large array buffer for the entire data read from the
1287
  // network; create a slice of that array buffer and emit it as the
1288
  // received data buffer.
1289
12682
  size_t offset = buf.base - session->stream_buf_.base;
1290
1291
  // Verify that the data offset is inside the current read buffer.
1292
12682
  CHECK_GE(offset, session->stream_buf_offset_);
1293
12682
  CHECK_LE(offset, session->stream_buf_.len);
1294
12682
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1295
1296
25364
  stream->CallJSOnreadMethod(nread, ab, offset);
1297
}
1298
1299
1300
// Called by OnFrameReceived to notify JavaScript land that a complete
1301
// HEADERS frame has been received and processed. This method converts the
1302
// received headers into a JavaScript array and pushes those out to JS.
1303
23197
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1304
23197
  Isolate* isolate = env()->isolate();
1305
23197
  HandleScope scope(isolate);
1306
23197
  Local<Context> context = env()->context();
1307
23197
  Context::Scope context_scope(context);
1308
1309
23197
  int32_t id = GetFrameID(frame);
1310
23197
  Debug(this, "handle headers frame for stream %d", id);
1311
23197
  Http2Stream* stream = FindStream(id);
1312
1313
  // If the stream has already been destroyed, ignore.
1314
23197
  if (stream->IsDestroyed())
1315
23197
    return;
1316
1317
46394
  std::vector<nghttp2_header> headers(stream->move_headers());
1318
23197
  DecrementCurrentSessionMemory(stream->current_headers_length_);
1319
23197
  stream->current_headers_length_ = 0;
1320
1321
  // The headers are passed in above as a queue of nghttp2_header structs.
1322
  // The following converts that into a JS array with the structure:
1323
  // [name1, value1, name2, value2, name3, value3, name3, value4] and so on.
1324
  // That array is passed up to the JS layer and converted into an Object form
1325
  // like {name1: value1, name2: value2, name3: [value3, value4]}. We do it
1326
  // this way for performance reasons (it's faster to generate and pass an
1327
  // array than it is to generate and pass the object).
1328
23197
  size_t headers_size = headers.size();
1329
46394
  std::vector<Local<Value>> headers_v(headers_size * 2);
1330
94187
  for (size_t i = 0; i < headers_size; ++i) {
1331
70990
    const nghttp2_header& item = headers[i];
1332
    // The header name and value are passed as external one-byte strings
1333
70990
    headers_v[i * 2] =
1334
141980
        ExternalHeader::New<true>(this, item.name).ToLocalChecked();
1335
70990
    headers_v[i * 2 + 1] =
1336
141980
        ExternalHeader::New<false>(this, item.value).ToLocalChecked();
1337
  }
1338
1339
  Local<Value> args[5] = {
1340
      stream->object(),
1341
      Integer::New(isolate, id),
1342
23197
      Integer::New(isolate, stream->headers_category()),
1343
      Integer::New(isolate, frame->hd.flags),
1344
162379
      Array::New(isolate, headers_v.data(), headers_size * 2)};
1345
  MakeCallback(env()->http2session_on_headers_function(),
1346
46394
               arraysize(args), args);
1347
}
1348
1349
1350
// Called by OnFrameReceived when a complete PRIORITY frame has been
1351
// received. Notifies JS land about the priority change. Note that priorities
1352
// are considered advisory only, so this has no real effect other than to
1353
// simply let user code know that the priority has changed.
1354
16
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
1355
32
  if (js_fields_[kSessionPriorityListenerCount] == 0) return;
1356
5
  Isolate* isolate = env()->isolate();
1357
5
  HandleScope scope(isolate);
1358
5
  Local<Context> context = env()->context();
1359
  Context::Scope context_scope(context);
1360
1361
5
  nghttp2_priority priority_frame = frame->priority;
1362
5
  int32_t id = GetFrameID(frame);
1363
5
  Debug(this, "handle priority frame for stream %d", id);
1364
  // Priority frame stream ID should never be <= 0. nghttp2 handles this for us
1365
5
  nghttp2_priority_spec spec = priority_frame.pri_spec;
1366
1367
  Local<Value> argv[4] = {
1368
    Integer::New(isolate, id),
1369
    Integer::New(isolate, spec.stream_id),
1370
    Integer::New(isolate, spec.weight),
1371
    Boolean::New(isolate, spec.exclusive)
1372
25
  };
1373
  MakeCallback(env()->http2session_on_priority_function(),
1374
10
               arraysize(argv), argv);
1375
}
1376
1377
1378
// Called by OnFrameReceived when a complete DATA frame has been received.
1379
// If we know that this was the last DATA frame (because the END_STREAM flag
1380
// is set), then we'll terminate the readable side of the StreamBase.
1381
24583
int Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1382
24583
  int32_t id = GetFrameID(frame);
1383
24583
  Debug(this, "handling data frame for stream %d", id);
1384
24583
  Http2Stream* stream = FindStream(id);
1385
1386

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

1797
  if ((flags_ & SESSION_STATE_READING_STOPPED) &&
1558

1193
      !(flags_ & SESSION_STATE_WRITE_IN_PROGRESS) &&
1559
594
      nghttp2_session_want_read(session_)) {
1560
567
    flags_ &= ~SESSION_STATE_READING_STOPPED;
1561
567
    stream_->ReadStart();
1562
  }
1563
1564
  // If there is more incoming data queued up, consume it.
1565
599
  if (stream_buf_offset_ > 0) {
1566
11
    ConsumeHTTP2Data();
1567
  }
1568
1569
599
  if (!(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1570
    // Schedule a new write if nghttp2 wants to send data.
1571
381
    MaybeScheduleWrite();
1572
  }
1573
599
}
1574
1575
// If the underlying nghttp2_session struct has data pending in its outbound
1576
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1577
// on the next iteration of the Node.js event loop (using the SetImmediate
1578
// queue), but only if a write has not already been scheduled.
1579
31405
void Http2Session::MaybeScheduleWrite() {
1580
31405
  CHECK_EQ(flags_ & SESSION_STATE_WRITE_SCHEDULED, 0);
1581
31405
  if (UNLIKELY(session_ == nullptr))
1582
31405
    return;
1583
1584
31405
  if (nghttp2_session_want_write(session_)) {
1585
2425
    HandleScope handle_scope(env()->isolate());
1586
2425
    Debug(this, "scheduling write");
1587
2425
    flags_ |= SESSION_STATE_WRITE_SCHEDULED;
1588
2425
    env()->SetImmediate([this](Environment* env) {
1589

2425
      if (session_ == nullptr || !(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1590
        // This can happen e.g. when a stream was reset before this turn
1591
        // of the event loop, in which case SendPendingData() is called early,
1592
        // or the session was destroyed in the meantime.
1593
2654
        return;
1594
      }
1595
1596
      // Sending data may call arbitrary JS code, so keep track of
1597
      // async context.
1598
2196
      HandleScope handle_scope(env->isolate());
1599
4392
      InternalCallbackScope callback_scope(this);
1600
2196
      SendPendingData();
1601
4621
    }, object());
1602
  }
1603
}
1604
1605
61245
void Http2Session::MaybeStopReading() {
1606
122490
  if (flags_ & SESSION_STATE_READING_STOPPED) return;
1607
59843
  int want_read = nghttp2_session_want_read(session_);
1608
59843
  Debug(this, "wants read? %d", want_read);
1609

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


3338
    if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream)
1910
2
      return true;
1911
  }
1912
24299
  return false;
1913
}
1914
1915
// Every Http2Session session is tightly bound to a single i/o StreamBase
1916
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1917
// tightly coupled with all data transfer between the two happening at the
1918
// C++ layer via the StreamBase API.
1919
584
void Http2Session::Consume(Local<Object> stream_obj) {
1920
584
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1921
584
  stream->PushStreamListener(this);
1922
584
  Debug(this, "i/o stream consumed");
1923
584
}
1924
1925
24312
Http2Stream* Http2Stream::New(Http2Session* session,
1926
                              int32_t id,
1927
                              nghttp2_headers_category category,
1928
                              int options) {
1929
  Local<Object> obj;
1930
48624
  if (!session->env()
1931
24312
           ->http2stream_constructor_template()
1932
97248
           ->NewInstance(session->env()->context())
1933
72936
           .ToLocal(&obj)) {
1934
    return nullptr;
1935
  }
1936
24312
  return new Http2Stream(session, obj, id, category, options);
1937
}
1938
1939
24312
Http2Stream::Http2Stream(Http2Session* session,
1940
                         Local<Object> obj,
1941
                         int32_t id,
1942
                         nghttp2_headers_category category,
1943
                         int options)
1944
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
1945
      StreamBase(session->env()),
1946
      session_(session),
1947
      id_(id),
1948
24312
      current_headers_category_(category) {
1949
24312
  MakeWeak();
1950
24312
  StreamBase::AttachToObject(GetObject());
1951
24312
  statistics_.start_time = uv_hrtime();
1952
1953
  // Limit the number of header pairs
1954
24312
  max_header_pairs_ = session->GetMaxHeaderPairs();
1955
24312
  if (max_header_pairs_ == 0) {
1956
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1957
  }
1958
24312
  current_headers_.reserve(std::min(max_header_pairs_, 12u));
1959
1960
  // Limit the number of header octets
1961
  max_header_length_ =
1962
      std::min(
1963
        nghttp2_session_get_local_settings(
1964
          session->session(),
1965
24312
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1966
48624
      MAX_MAX_HEADER_LIST_SIZE);
1967
1968
24312
  if (options & STREAM_OPTION_GET_TRAILERS)
1969
2
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1970
1971
24312
  PushStreamListener(&stream_listener_);
1972
1973
24312
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1974
479
    Shutdown();
1975
24312
  session->AddStream(this);
1976
24312
}
1977
1978
1979


72930
Http2Stream::~Http2Stream() {
1980
24419
  for (nghttp2_header& header : current_headers_) {
1981
109
    nghttp2_rcbuf_decref(header.name);
1982
109
    nghttp2_rcbuf_decref(header.value);
1983
  }
1984
1985
24310
  if (session_ == nullptr)
1986
2
    return;
1987
24308
  Debug(this, "tearing down stream");
1988
24308
  session_->DecrementCurrentSessionMemory(current_headers_length_);
1989
24308
  session_->RemoveStream(this);
1990
24308
  session_ = nullptr;
1991
48618
}
1992
1993
17
std::string Http2Stream::diagnostic_name() const {
1994
34
  return "HttpStream " + std::to_string(id()) + " (" +
1995
68
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
1996
51
      session()->diagnostic_name() + "]";
1997
}
1998
1999
// Notify the Http2Stream that a new block of HEADERS is being processed.
2000
11579
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
2001
11579
  Debug(this, "starting headers, category: %d", id_, category);
2002
11579
  CHECK(!this->IsDestroyed());
2003
11579
  session_->DecrementCurrentSessionMemory(current_headers_length_);
2004
11579
  current_headers_length_ = 0;
2005
11579
  current_headers_.clear();
2006
11579
  current_headers_category_ = category;
2007
11579
}
2008
2009
2010
11
nghttp2_stream* Http2Stream::operator*() {
2011
11
  return nghttp2_session_find_stream(**session_, id_);
2012
}
2013
2014
24221
void Http2Stream::Close(int32_t code) {
2015
24221
  CHECK(!this->IsDestroyed());
2016
24221
  flags_ |= NGHTTP2_STREAM_FLAG_CLOSED;
2017
24221
  code_ = code;
2018
24221
  Debug(this, "closed with code %d", code);
2019
24221
}
2020
2021
23693
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
2022
23693
  if (IsDestroyed())
2023
    return UV_EPIPE;
2024
2025
  {
2026
23693
    Http2Scope h2scope(this);
2027
23693
    flags_ |= NGHTTP2_STREAM_FLAG_SHUT;
2028
23693
    CHECK_NE(nghttp2_session_resume_data(**session_, id_),
2029
             NGHTTP2_ERR_NOMEM);
2030
47386
    Debug(this, "writable side shutdown");
2031
  }
2032
23693
  return 1;
2033
}
2034
2035
// Destroy the Http2Stream and render it unusable. Actual resources for the
2036
// Stream will not be freed until the next tick of the Node.js event loop
2037
// using the SetImmediate queue.
2038
24302
void Http2Stream::Destroy() {
2039
  // Do nothing if this stream instance is already destroyed
2040
24302
  if (IsDestroyed())
2041
24302
    return;
2042
24302
  if (session_->HasPendingRstStream(id_))
2043
7
    FlushRstStream();
2044
24302
  flags_ |= NGHTTP2_STREAM_FLAG_DESTROYED;
2045
2046
24302
  Debug(this, "destroying stream");
2047
2048
  // Wait until the start of the next loop to delete because there
2049
  // may still be some pending operations queued for this stream.
2050
24301
  env()->SetImmediate([this](Environment* env) {
2051
    // Free any remaining outgoing data chunks here. This should be done
2052
    // here because it's possible for destroy to have been called while
2053
    // we still have queued outbound writes.
2054
48605
    while (!queue_.empty()) {
2055
3
      nghttp2_stream_write& head = queue_.front();
2056
3
      if (head.req_wrap != nullptr)
2057
3
        head.req_wrap->Done(UV_ECANCELED);
2058
3
      queue_.pop();
2059
    }
2060
2061
    // We can destroy the stream now if there are no writes for it
2062
    // already on the socket. Otherwise, we'll wait for the garbage collector
2063
    // to take care of cleaning up.
2064

24301
    if (session() == nullptr || !session()->HasWritesOnSocketForStream(this))
2065
24299
      delete this;
2066
48603
  }, object());
2067
2068
24302
  statistics_.end_time = uv_hrtime();
2069
  session_->statistics_.stream_average_duration =
2070
24302
      ((statistics_.end_time - statistics_.start_time) /
2071
48604
          session_->statistics_.stream_count) / 1e6;
2072
24302
  EmitStatistics();
2073
}
2074
2075
2076
// Initiates a response on the Http2Stream using data provided via the
2077
// StreamBase Streams API.
2078
11577
int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) {
2079
11577
  CHECK(!this->IsDestroyed());
2080
11577
  Http2Scope h2scope(this);
2081
11577
  Debug(this, "submitting response");
2082
11577
  if (options & STREAM_OPTION_GET_TRAILERS)
2083
100
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
2084
2085
11577
  if (!IsWritable())
2086
8
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2087
2088
23154
  Http2Stream::Provider::Stream prov(this, options);
2089
11577
  int ret = nghttp2_submit_response(**session_, id_, nva, len, *prov);
2090
11577
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2091
23154
  return ret;
2092
}
2093
2094
2095
// Submit informational headers for a stream.
2096
5
int Http2Stream::SubmitInfo(nghttp2_nv* nva, size_t len) {
2097
5
  CHECK(!this->IsDestroyed());
2098
5
  Http2Scope h2scope(this);
2099
5
  Debug(this, "sending %d informational headers", len);
2100
  int ret = nghttp2_submit_headers(**session_,
2101
                                   NGHTTP2_FLAG_NONE,
2102
                                   id_, nullptr,
2103
5
                                   nva, len, nullptr);
2104
5
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2105
5
  return ret;
2106
}
2107
2108
32
void Http2Stream::OnTrailers() {
2109
32
  Debug(this, "let javascript know we are ready for trailers");
2110
32
  CHECK(!this->IsDestroyed());
2111
32
  Isolate* isolate = env()->isolate();
2112
32
  HandleScope scope(isolate);
2113
32
  Local<Context> context = env()->context();
2114
  Context::Scope context_scope(context);
2115
32
  flags_ &= ~NGHTTP2_STREAM_FLAG_TRAILERS;
2116
64
  MakeCallback(env()->http2session_on_stream_trailers_function(), 0, nullptr);
2117
32
}
2118
2119
// Submit informational headers for a stream.
2120
30
int Http2Stream::SubmitTrailers(nghttp2_nv* nva, size_t len) {
2121
30
  CHECK(!this->IsDestroyed());
2122
30
  Http2Scope h2scope(this);
2123
30
  Debug(this, "sending %d trailers", len);
2124
  int ret;
2125
  // Sending an empty trailers frame poses problems in Safari, Edge & IE.
2126
  // Instead we can just send an empty data frame with NGHTTP2_FLAG_END_STREAM
2127
  // to indicate that the stream is ready to be closed.
2128
30
  if (len == 0) {
2129
25
    Http2Stream::Provider::Stream prov(this, 0);
2130
25
    ret = nghttp2_submit_data(**session_, NGHTTP2_FLAG_END_STREAM, id_, *prov);
2131
  } else {
2132
5
    ret = nghttp2_submit_trailer(**session_, id_, nva, len);
2133
  }
2134
30
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2135
30
  return ret;
2136
}
2137
2138
// Submit a PRIORITY frame to the connected peer.
2139
6
int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec,
2140
                                bool silent) {
2141
6
  CHECK(!this->IsDestroyed());
2142
6
  Http2Scope h2scope(this);
2143
6
  Debug(this, "sending priority spec");
2144
  int ret = silent ?
2145
      nghttp2_session_change_stream_priority(**session_,
2146
                                             id_, prispec) :
2147
      nghttp2_submit_priority(**session_,
2148
                              NGHTTP2_FLAG_NONE,
2149
6
                              id_, prispec);
2150
6
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2151
6
  return ret;
2152
}
2153
2154
// Closes the Http2Stream by submitting an RST_STREAM frame to the connected
2155
// peer.
2156
229
void Http2Stream::SubmitRstStream(const uint32_t code) {
2157
229
  CHECK(!this->IsDestroyed());
2158
229
  code_ = code;
2159
  // If possible, force a purge of any currently pending data here to make sure
2160
  // it is sent before closing the stream. If it returns non-zero then we need
2161
  // to wait until the current write finishes and try again to avoid nghttp2
2162
  // behaviour where it prioritizes RstStream over everything else.
2163
229
  if (session_->SendPendingData() != 0) {
2164
8
    session_->AddPendingRstStream(id_);
2165
237
    return;
2166
  }
2167
2168
221
  FlushRstStream();
2169
}
2170
2171
236
void Http2Stream::FlushRstStream() {
2172
236
  if (IsDestroyed())
2173
264
    return;
2174
208
  Http2Scope h2scope(this);
2175
208
  CHECK_EQ(nghttp2_submit_rst_stream(**session_, NGHTTP2_FLAG_NONE,
2176
208
                                     id_, code_), 0);
2177
}
2178
2179
2180
// Submit a push promise and create the associated Http2Stream if successful.
2181
8
Http2Stream* Http2Stream::SubmitPushPromise(nghttp2_nv* nva,
2182
                                            size_t len,
2183
                                            int32_t* ret,
2184
                                            int options) {
2185
8
  CHECK(!this->IsDestroyed());
2186
8
  Http2Scope h2scope(this);
2187
8
  Debug(this, "sending push promise");
2188
  *ret = nghttp2_submit_push_promise(**session_, NGHTTP2_FLAG_NONE,
2189
8
                                     id_, nva, len, nullptr);
2190
8
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
2191
8
  Http2Stream* stream = nullptr;
2192
8
  if (*ret > 0)
2193
8
    stream = Http2Stream::New(session_, *ret, NGHTTP2_HCAT_HEADERS, options);
2194
2195
8
  return stream;
2196
}
2197
2198
// Switch the StreamBase into flowing mode to begin pushing chunks of data
2199
// out to JS land.
2200
22280
int Http2Stream::ReadStart() {
2201
22280
  Http2Scope h2scope(this);
2202
22280
  CHECK(!this->IsDestroyed());
2203
22280
  flags_ |= NGHTTP2_STREAM_FLAG_READ_START;
2204
22280
  flags_ &= ~NGHTTP2_STREAM_FLAG_READ_PAUSED;
2205
2206
22280
  Debug(this, "reading starting");
2207
2208
  // Tell nghttp2 about our consumption of the data that was handed
2209
  // off to JS land.
2210
  nghttp2_session_consume_stream(**session_,
2211
                                 id_,
2212
22280
                                 inbound_consumed_data_while_paused_);
2213
22280
  inbound_consumed_data_while_paused_ = 0;
2214
2215
22280
  return 0;
2216
}
2217
2218
// Switch the StreamBase into paused mode.
2219
132
int Http2Stream::ReadStop() {
2220
132
  CHECK(!this->IsDestroyed());
2221
132
  if (!IsReading())
2222
92
    return 0;
2223
40
  flags_ |= NGHTTP2_STREAM_FLAG_READ_PAUSED;
2224
40
  Debug(this, "reading stopped");
2225
40
  return 0;
2226
}
2227
2228
// The Http2Stream class is a subclass of StreamBase. The DoWrite method
2229
// receives outbound chunks of data to send as outbound DATA frames. These
2230
// are queued in an internal linked list of uv_buf_t structs that are sent
2231
// when nghttp2 is ready to serialize the data frame.
2232
//
2233
// Queue the given set of uv_but_t handles for writing to an
2234
// nghttp2_stream. The WriteWrap's Done callback will be invoked once the
2235
// chunks of data have been flushed to the underlying nghttp2_session.
2236
// Note that this does *not* mean that the data has been flushed
2237
// to the socket yet.
2238
3659
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2239
                         uv_buf_t* bufs,
2240
                         size_t nbufs,
2241
                         uv_stream_t* send_handle) {
2242
3659
  CHECK_NULL(send_handle);
2243
3659
  Http2Scope h2scope(this);
2244

3659
  if (!IsWritable() || IsDestroyed()) {
2245
    req_wrap->Done(UV_EOF);
2246
    return 0;
2247
  }
2248
3659
  Debug(this, "queuing %d buffers to send", id_, nbufs);
2249
34373
  for (size_t i = 0; i < nbufs; ++i) {
2250
    // Store the req_wrap on the last write info in the queue, so that it is
2251
    // only marked as finished once all buffers associated with it are finished.
2252
    queue_.emplace(nghttp2_stream_write {
2253
30714
      i == nbufs - 1 ? req_wrap : nullptr,
2254
      bufs[i]
2255
30714
    });
2256
30714
    IncrementAvailableOutboundLength(bufs[i].len);
2257
  }
2258
3659
  CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM);
2259
3659
  return 0;
2260
}
2261
2262
// Ads a header to the Http2Stream. Note that the header name and value are
2263
// provided using a buffer structure provided by nghttp2 that allows us to
2264
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2265
// is incremented here and are decremented when the header name and values
2266
// are garbage collected later.
2267
71101
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2268
                            nghttp2_rcbuf* value,
2269
                            uint8_t flags) {
2270
71101
  CHECK(!this->IsDestroyed());
2271
71101
  if (this->statistics_.first_header == 0)
2272
23215
    this->statistics_.first_header = uv_hrtime();
2273
71101
  size_t name_len = nghttp2_rcbuf_get_buf(name).len;
2274
71101
  if (name_len == 0) return true;  // Ignore headers with empty names.
2275
71101
  size_t value_len = nghttp2_rcbuf_get_buf(value).len;
2276
71101
  size_t length = name_len + value_len + 32;
2277
  // A header can only be added if we have not exceeded the maximum number
2278
  // of headers and the session has memory available for it.
2279

213303
  if (!session_->IsAvailableSessionMemory(length) ||
2280

142201
      current_headers_.size() == max_header_pairs_ ||
2281
71100
      current_headers_length_ + length > max_header_length_) {
2282
2
    return false;
2283
  }
2284
71099
  nghttp2_header header;
2285
71099
  header.name = name;
2286
71099
  header.value = value;
2287
71099
  header.flags = flags;
2288
71099
  current_headers_.push_back(header);
2289
71099
  nghttp2_rcbuf_incref(name);
2290
71099
  nghttp2_rcbuf_incref(value);
2291
71099
  current_headers_length_ += length;
2292
71099
  session_->IncrementCurrentSessionMemory(length);
2293
71099
  return true;
2294
}
2295
2296
// A Provider is the thing that provides outbound DATA frame data.
2297
11602
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2298
11602
  CHECK(!stream->IsDestroyed());
2299
11602
  provider_.source.ptr = stream;
2300
11602
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2301
11602
}
2302
2303
11649
Http2Stream::Provider::Provider(int options) {
2304
11649
  provider_.source.ptr = nullptr;
2305
11649
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2306
11649
}
2307
2308
23251
Http2Stream::Provider::~Provider() {
2309
23251
  provider_.source.ptr = nullptr;
2310
23251
}
2311
2312
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2313
// built via the StreamBase API and the Streams js API.
2314
11649
Http2Stream::Provider::Stream::Stream(int options)
2315
11649
    : Http2Stream::Provider(options) {
2316
11649
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2317
11649
}
2318
2319
11602
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2320
11602
    : Http2Stream::Provider(stream, options) {
2321
11602
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2322
11602
}
2323
2324
28260
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2325
                                              int32_t id,
2326
                                              uint8_t* buf,
2327
                                              size_t length,
2328
                                              uint32_t* flags,
2329
                                              nghttp2_data_source* source,
2330
                                              void* user_data) {
2331
28260
  Http2Session* session = static_cast<Http2Session*>(user_data);
2332
  Debug(session, "reading outbound data for stream %d", id);
2333
28260
  Http2Stream* stream = GetStream(session, id, source);
2334
28260
  if (stream->statistics_.first_byte_sent == 0)
2335
12673
    stream->statistics_.first_byte_sent = uv_hrtime();
2336
28260
  CHECK_EQ(id, stream->id());
2337
2338
28260
  size_t amount = 0;          // amount of data being sent in this data frame.
2339
2340
  // Remove all empty chunks from the head of the queue.
2341
  // This is done here so that .write('', cb) is still a meaningful way to
2342
  // find out when the HTTP2 stream wants to consume data, and because the
2343
  // StreamBase API allows empty input chunks.
2344

56524
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2345
4
    WriteWrap* finished = stream->queue_.front().req_wrap;
2346
4
    stream->queue_.pop();
2347
4
    if (finished != nullptr)
2348
2
      finished->Done(0);
2349
  }
2350
2351
28260
  if (!stream->queue_.empty()) {
2352
    Debug(session, "stream %d has pending outbound data", id);
2353
12109
    amount = std::min(stream->available_outbound_length_, length);
2354
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2355
12109
    if (amount > 0) {
2356
      // Just return the length, let Http2Session::OnSendData take care of
2357
      // actually taking the buffers out of the queue.
2358
12109
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2359
12109
      stream->DecrementAvailableOutboundLength(amount);
2360
    }
2361
  }
2362
2363

28260
  if (amount == 0 && stream->IsWritable()) {
2364
3591
    CHECK(stream->queue_.empty());
2365
    Debug(session, "deferring stream %d", id);
2366
3591
    stream->EmitWantsWrite(length);
2367

3591
    if (stream->available_outbound_length_ > 0 || !stream->IsWritable()) {
2368
      // EmitWantsWrite() did something interesting synchronously, restart:
2369
      return OnRead(handle, id, buf, length, flags, source, user_data);
2370
    }
2371
3591
    return NGHTTP2_ERR_DEFERRED;
2372
  }
2373
2374

24669
  if (stream->queue_.empty() && !stream->IsWritable()) {
2375
    Debug(session, "no more data for stream %d", id);
2376
12560
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2377
12560
    if (stream->HasTrailers()) {
2378
32
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2379
32
      stream->OnTrailers();
2380
    }
2381
  }
2382
2383
24669
  stream->statistics_.sent_bytes += amount;
2384
24669
  return amount;
2385
}
2386
2387
30714
inline void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2388
30714
  available_outbound_length_ += amount;
2389
30714
  session_->IncrementCurrentSessionMemory(amount);
2390
30714
}
2391
2392
12109
inline void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2393
12109
  available_outbound_length_ -= amount;
2394
12109
  session_->DecrementCurrentSessionMemory(amount);
2395
12109
}
2396
2397
2398
// Implementation of the JavaScript API
2399
2400
// Fetches the string description of a nghttp2 error code and passes that
2401
// back to JS land
2402
53
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2403
53
  Environment* env = Environment::GetCurrent(args);
2404
212
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2405
  args.GetReturnValue().Set(
2406
      String::NewFromOneByte(
2407
          env->isolate(),
2408
53
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val)),
2409
159
          NewStringType::kInternalized).ToLocalChecked());
2410
53
}
2411
2412
2413
// Serializes the settings object into a Buffer instance that
2414
// would be suitable, for instance, for creating the Base64
2415
// output for an HTTP2-Settings header field.
2416
15
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2417
15
  Environment* env = Environment::GetCurrent(args);
2418
  // TODO(addaleax): We should not be creating a full AsyncWrap for this.
2419
  Local<Object> obj;
2420
30
  if (!env->http2settings_constructor_template()
2421
45
           ->NewInstance(env->context())
2422
45
           .ToLocal(&obj)) {
2423
15
    return;
2424
  }
2425
15
  Http2Session::Http2Settings settings(env, nullptr, obj);
2426
45
  args.GetReturnValue().Set(settings.Pack());
2427
}
2428
2429
// A TypedArray instance is shared between C++ and JS land to contain the
2430
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2431
// default values.
2432
3
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2433
3
  Environment* env = Environment::GetCurrent(args);
2434
3
  Http2Session::Http2Settings::RefreshDefaults(env);
2435
3
}
2436
2437
// Sets the next stream ID the Http2Session. If successful, returns true.
2438
1
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2439
1
  Environment* env = Environment::GetCurrent(args);
2440
  Http2Session* session;
2441
1
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2442
4
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2443
1
  if (nghttp2_session_set_next_stream_id(**session, id) < 0) {
2444
    Debug(session, "failed to set next stream id to %d", id);
2445
    return args.GetReturnValue().Set(false);
2446
  }
2447
2
  args.GetReturnValue().Set(true);
2448
1
  Debug(session, "set next stream id to %d", id);
2449
}
2450
2451
// A TypedArray instance is shared between C++ and JS land to contain the
2452
// SETTINGS (either remote or local). RefreshSettings updates the current
2453
// values established for each of the settings so those can be read in JS land.
2454
template <get_setting fn>
2455
506
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2456
506
  Environment* env = Environment::GetCurrent(args);
2457
  Http2Session* session;
2458

1012
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2459
506
  Http2Settings::Update(env, session, fn);
2460
506
  Debug(session, "settings refreshed for session");
2461
}
2462
2463
// A TypedArray instance is shared between C++ and JS land to contain state
2464
// information of the current Http2Session. This updates the values in the
2465
// TypedArray so those can be read in JS land.
2466
3
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2467
3
  Environment* env = Environment::GetCurrent(args);
2468
  Http2Session* session;
2469
6
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2470
3
  Debug(session, "refreshing state");
2471
2472
3
  AliasedFloat64Array& buffer = env->http2_state()->session_state_buffer;
2473
2474
3
  nghttp2_session* s = **session;
2475
2476
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2477
6
      nghttp2_session_get_effective_local_window_size(s);
2478
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2479
6
      nghttp2_session_get_effective_recv_data_length(s);
2480
6
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2481
6
      nghttp2_session_get_next_stream_id(s);
2482
6
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2483
6
      nghttp2_session_get_local_window_size(s);
2484
6
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2485
6
      nghttp2_session_get_last_proc_stream_id(s);
2486
6
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2487
6
      nghttp2_session_get_remote_window_size(s);
2488
6
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2489
6
      nghttp2_session_get_outbound_queue_size(s);
2490
6
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2491
6
      nghttp2_session_get_hd_deflate_dynamic_table_size(s);
2492
6
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2493
6
      nghttp2_session_get_hd_inflate_dynamic_table_size(s);
2494
}
2495
2496
2497
// Constructor for new Http2Session instances.
2498
584
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2499
584
  Environment* env = Environment::GetCurrent(args);
2500
584
  CHECK(args.IsConstructCall());
2501
2336
  int val = args[0]->IntegerValue(env->context()).ToChecked();
2502
584
  nghttp2_session_type type = static_cast<nghttp2_session_type>(val);
2503
584
  Http2Session* session = new Http2Session(env, args.This(), type);
2504
584
  session->get_async_id();  // avoid compiler warning
2505
  Debug(session, "session created");
2506
584
}
2507
2508
2509
// Binds the Http2Session with a StreamBase used for i/o
2510
584
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2511
  Http2Session* session;
2512
1168
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2513
1168
  CHECK(args[0]->IsObject());
2514
1168
  session->Consume(args[0].As<Object>());
2515
}
2516
2517
// Destroys the Http2Session instance and renders it unusable
2518
555
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2519
  Http2Session* session;
2520
1110
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2521
555
  Debug(session, "destroying session");
2522
555
  Environment* env = Environment::GetCurrent(args);
2523
555
  Local<Context> context = env->context();
2524
2525
1665
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2526
1665
  bool socketDestroyed = args[1]->BooleanValue(env->isolate());
2527
2528
555
  session->Close(code, socketDestroyed);
2529
}
2530
2531
// Submits a new request on the Http2Session and returns either an error code
2532
// or the Http2Stream object.
2533
11649
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2534
  Http2Session* session;
2535
11650
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2536
11649
  Environment* env = session->env();
2537
11649
  Local<Context> context = env->context();
2538
11649
  Isolate* isolate = env->isolate();
2539
2540
23298
  Local<Array> headers = args[0].As<Array>();
2541
34947
  int options = args[1]->IntegerValue(context).ToChecked();
2542
11649
  Http2Priority priority(env, args[2], args[3], args[4]);
2543
2544
11649
  Headers list(isolate, context, headers);
2545
2546
11649
  Debug(session, "request submitted");
2547
2548
11649
  int32_t ret = 0;
2549
  Http2Stream* stream =
2550
      session->Http2Session::SubmitRequest(*priority, *list, list.length(),
2551
11649
                                           &ret, options);
2552
2553

11649
  if (ret <= 0 || stream == nullptr) {
2554
2
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2555
3
    return args.GetReturnValue().Set(ret);
2556
  }
2557
2558
23296
  Debug(session, "request submitted, new stream id %d", stream->id());
2559
34944
  args.GetReturnValue().Set(stream->object());
2560
}
2561
2562
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2563
// of shutting down. Note that this function does not actually alter the
2564
// state of the Http2Session, it's simply a notification.
2565
503
void Http2Session::Goaway(uint32_t code,
2566
                          int32_t lastStreamID,
2567
                          const uint8_t* data,
2568
                          size_t len) {
2569
503
  if (IsDestroyed())
2570
503
    return;
2571
2572
503
  Http2Scope h2scope(this);
2573
  // the last proc stream id is the most recently created Http2Stream.
2574
503
  if (lastStreamID <= 0)
2575
503
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_);
2576
503
  Debug(this, "submitting goaway");
2577
  nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE,
2578
503
                        lastStreamID, code, data, len);
2579
}
2580
2581
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2582
// of shutting down. The opaque data argument is an optional TypedArray that
2583
// can be used to send debugging data to the connected peer.
2584
503
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2585
503
  Environment* env = Environment::GetCurrent(args);
2586
503
  Local<Context> context = env->context();
2587
  Http2Session* session;
2588
1006
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2589
2590
1509
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2591
1509
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2592
503
  ArrayBufferViewContents<uint8_t> opaque_data;
2593
2594
1006
  if (args[2]->IsArrayBufferView()) {
2595
2
    opaque_data.Read(args[2].As<ArrayBufferView>());
2596
  }
2597
2598
503
  session->Goaway(code, lastStreamID, opaque_data.data(), opaque_data.length());
2599
}
2600
2601
// Update accounting of data chunks. This is used primarily to manage timeout
2602
// logic when using the FD Provider.
2603
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2604
10
  Environment* env = Environment::GetCurrent(args);
2605
10
  Isolate* isolate = env->isolate();
2606
10
  HandleScope scope(isolate);
2607
  Http2Session* session;
2608
20
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2609
2610
10
  uint32_t length = session->chunks_sent_since_last_write_;
2611
2612
10
  session->object()->Set(env->context(),
2613
                         env->chunks_sent_since_last_write_string(),
2614
60
                         Integer::NewFromUnsigned(isolate, length)).Check();
2615
2616
20
  args.GetReturnValue().Set(length);
2617
}
2618
2619
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2620
// this *WILL* alter the state of the stream, causing the OnStreamClose
2621
// callback to the triggered.
2622
227
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2623
227
  Environment* env = Environment::GetCurrent(args);
2624
227
  Local<Context> context = env->context();
2625
  Http2Stream* stream;
2626
454
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2627
681
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2628
227
  Debug(stream, "sending rst_stream with code %d", code);
2629
227
  stream->SubmitRstStream(code);
2630
}
2631
2632
// Initiates a response on the Http2Stream using the StreamBase API to provide
2633
// outbound DATA frames.
2634
11577
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2635
11577
  Environment* env = Environment::GetCurrent(args);
2636
11577
  Local<Context> context = env->context();
2637
11577
  Isolate* isolate = env->isolate();
2638
  Http2Stream* stream;
2639
23154
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2640
2641
23154
  Local<Array> headers = args[0].As<Array>();
2642
34731
  int options = args[1]->IntegerValue(context).ToChecked();
2643
2644
11577
  Headers list(isolate, context, headers);
2645
2646
  args.GetReturnValue().Set(
2647
34731
      stream->SubmitResponse(*list, list.length(), options));
2648
23154
  Debug(stream, "response submitted");
2649
}
2650
2651
2652
// Submits informational headers on the Http2Stream
2653
5
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2654
5
  Environment* env = Environment::GetCurrent(args);
2655
5
  Local<Context> context = env->context();
2656
5
  Isolate* isolate = env->isolate();
2657
  Http2Stream* stream;
2658
10
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2659
2660
10
  Local<Array> headers = args[0].As<Array>();
2661
2662
5
  Headers list(isolate, context, headers);
2663
15
  args.GetReturnValue().Set(stream->SubmitInfo(*list, list.length()));
2664
10
  Debug(stream, "%d informational headers sent", list.length());
2665
}
2666
2667
// Submits trailing headers on the Http2Stream
2668
30
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2669
30
  Environment* env = Environment::GetCurrent(args);
2670
30
  Local<Context> context = env->context();
2671
30
  Isolate* isolate = env->isolate();
2672
  Http2Stream* stream;
2673
60
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2674
2675
60
  Local<Array> headers = args[0].As<Array>();
2676
2677
30
  Headers list(isolate, context, headers);
2678
90
  args.GetReturnValue().Set(stream->SubmitTrailers(*list, list.length()));
2679
60
  Debug(stream, "%d trailing headers sent", list.length());
2680
}
2681
2682
// Grab the numeric id of the Http2Stream
2683
11656
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2684
  Http2Stream* stream;
2685
23312
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2686
34968
  args.GetReturnValue().Set(stream->id());
2687
}
2688
2689
// Destroy the Http2Stream, rendering it no longer usable
2690
23265
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2691
  Http2Stream* stream;
2692
46530
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2693
23265
  Debug(stream, "destroying stream");
2694
23265
  stream->Destroy();
2695
}
2696
2697
// Initiate a Push Promise and create the associated Http2Stream
2698
8
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2699
8
  Environment* env = Environment::GetCurrent(args);
2700
8
  Local<Context> context = env->context();
2701
8
  Isolate* isolate = env->isolate();
2702
  Http2Stream* parent;
2703
8
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2704
2705
16
  Local<Array> headers = args[0].As<Array>();
2706
24
  int options = args[1]->IntegerValue(context).ToChecked();
2707
2708
8
  Headers list(isolate, context, headers);
2709
2710
8
  Debug(parent, "creating push promise");
2711
2712
8
  int32_t ret = 0;
2713
  Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(),
2714
8
                                                  &ret, options);
2715

8
  if (ret <= 0 || stream == nullptr) {
2716
    Debug(parent, "failed to create push stream: %d", ret);
2717
    return args.GetReturnValue().Set(ret);
2718
  }
2719
16
  Debug(parent, "push stream %d created", stream->id());
2720
24
  args.GetReturnValue().Set(stream->object());
2721
}
2722
2723
// Send a PRIORITY frame
2724
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2725
6
  Environment* env = Environment::GetCurrent(args);
2726
  Http2Stream* stream;
2727
12
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2728
2729
6
  Http2Priority priority(env, args[0], args[1], args[2]);
2730
18
  bool silent = args[3]->BooleanValue(env->isolate());
2731
2732
6
  CHECK_EQ(stream->SubmitPriority(*priority, silent), 0);
2733
6
  Debug(stream, "priority submitted");
2734
}
2735
2736
// A TypedArray shared by C++ and JS land is used to communicate state
2737
// information about the Http2Stream. This updates the values in that
2738
// TypedArray so that the state can be read by JS.
2739
11
void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
2740
11
  Environment* env = Environment::GetCurrent(args);
2741
  Http2Stream* stream;
2742
22
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2743
2744
11
  Debug(stream, "refreshing state");
2745
2746
11
  AliasedFloat64Array& buffer = env->http2_state()->stream_state_buffer;
2747
2748
11
  nghttp2_stream* str = **stream;
2749
11
  nghttp2_session* s = **(stream->session());
2750
2751
11
  if (str == nullptr) {
2752
1
    buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE;
2753
2
    buffer[IDX_STREAM_STATE_WEIGHT] =
2754
2
        buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2755
2
        buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2756
2
        buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2757
3
        buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0;
2758
  } else {
2759
20
    buffer[IDX_STREAM_STATE] =
2760
20
        nghttp2_stream_get_state(str);
2761
20
    buffer[IDX_STREAM_STATE_WEIGHT] =
2762
20
        nghttp2_stream_get_weight(str);
2763
20
    buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2764
20
        nghttp2_stream_get_sum_dependency_weight(str);
2765
20
    buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2766
20
        nghttp2_session_get_stream_local_close(s, stream->id());
2767
20
    buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2768
20
        nghttp2_session_get_stream_remote_close(s, stream->id());
2769
20
    buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] =
2770
20
        nghttp2_session_get_stream_local_window_size(s, stream->id());
2771
  }
2772
}
2773
2774
5
void Http2Session::AltSvc(int32_t id,
2775
                          uint8_t* origin,
2776
                          size_t origin_len,
2777
                          uint8_t* value,
2778
                          size_t value_len) {
2779
5
  Http2Scope h2scope(this);
2780
5
  CHECK_EQ(nghttp2_submit_altsvc(session_, NGHTTP2_FLAG_NONE, id,
2781
5
                                 origin, origin_len, value, value_len), 0);
2782
5
}
2783
2784
5
void Http2Session::Origin(nghttp2_origin_entry* ov, size_t count) {
2785
5
  Http2Scope h2scope(this);
2786
5
  CHECK_EQ(nghttp2_submit_origin(session_, NGHTTP2_FLAG_NONE, ov, count), 0);
2787
5
}
2788
2789
// Submits an AltSvc frame to be sent to the connected peer.
2790
5
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2791
5
  Environment* env = Environment::GetCurrent(args);
2792
  Http2Session* session;
2793
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2794
2795
20
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2796
2797
  // origin and value are both required to be ASCII, handle them as such.
2798
20
  Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2799
20
  Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2800
2801
5
  size_t origin_len = origin_str->Length();
2802
5
  size_t value_len = value_str->Length();
2803
2804
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2805
  // Verify that origin len != 0 if stream id == 0, or
2806
  // that origin len == 0 if stream id != 0
2807


5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2808
2809
5
  MaybeStackBuffer<uint8_t> origin(origin_len);
2810
10
  MaybeStackBuffer<uint8_t> value(value_len);
2811
10
  origin_str->WriteOneByte(env->isolate(), *origin);
2812
10
  value_str->WriteOneByte(env->isolate(), *value);
2813
2814
10
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2815
}
2816
2817
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2818
5
  Environment* env = Environment::GetCurrent(args);
2819
5
  Local<Context> context = env->context();
2820
  Http2Session* session;
2821
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2822
2823
10
  Local<String> origin_string = args[0].As<String>();
2824
15
  int count = args[1]->IntegerValue(context).ToChecked();
2825
2826
2827
  Origins origins(env->isolate(),
2828
                  env->context(),
2829
                  origin_string,
2830
5
                  count);
2831
2832
5
  session->Origin(*origins, origins.length());
2833
}
2834
2835
// Submits a PING frame to be sent to the connected peer.
2836
13
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2837
13
  Environment* env = Environment::GetCurrent(args);
2838
  Http2Session* session;
2839
15
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2840
2841
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2842
  // then the current hrtime will be used as the payload.
2843
13
  ArrayBufferViewContents<uint8_t, 8> payload;
2844
26
  if (args[0]->IsArrayBufferView()) {
2845
12
    payload.Read(args[0].As<ArrayBufferView>());
2846
6
    CHECK_EQ(payload.length(), 8);
2847
  }
2848
2849
  Local<Object> obj;
2850
26
  if (!env->http2ping_constructor_template()
2851
39
           ->NewInstance(env->context())
2852
39
           .ToLocal(&obj)) {
2853
    return;
2854
  }
2855
52
  if (obj->Set(env->context(), env->ondone_string(), args[1]).IsNothing())
2856
    return;
2857
2858
13
  Http2Ping* ping = session->AddPing(std::make_unique<Http2Ping>(session, obj));
2859
  // To prevent abuse, we strictly limit the number of unacknowledged PING
2860
  // frames that may be sent at any given time. This is configurable in the
2861
  // Options when creating a Http2Session.
2862
17
  if (ping == nullptr) return args.GetReturnValue().Set(false);
2863
2864
  // The Ping itself is an Async resource. When the acknowledgement is received,
2865
  // the callback will be invoked and a notification sent out to JS land. The
2866
  // notification will include the duration of the ping, allowing the round
2867
  // trip to be measured.
2868
11
  ping->Send(payload.data());
2869
22
  args.GetReturnValue().Set(true);
2870
}
2871
2872
// Submits a SETTINGS frame for the Http2Session
2873
594
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2874
594
  Environment* env = Environment::GetCurrent(args);
2875
  Http2Session* session;
2876
596
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2877
2878
  Local<Object> obj;
2879
1188
  if (!env->http2settings_constructor_template()
2880
1782
           ->NewInstance(env->context())
2881
1782
           .ToLocal(&obj)) {
2882
    return;
2883
  }
2884
2376
  if (obj->Set(env->context(), env->ondone_string(), args[0]).IsNothing())
2885
    return;
2886
2887
  Http2Session::Http2Settings* settings = session->AddSettings(
2888
594
      std::make_unique<Http2Settings>(session->env(), session, obj, 0));
2889
598
  if (settings == nullptr) return args.GetReturnValue().Set(false);
2890
2891
592
  settings->Send();
2892
1184
  args.GetReturnValue().Set(true);
2893
}
2894
2895
567
std::unique_ptr<Http2Session::Http2Ping> Http2Session::PopPing() {
2896
567
  std::unique_ptr<Http2Ping> ping;
2897
567
  if (!outstanding_pings_.empty()) {
2898
11
    ping = std::move(outstanding_pings_.front());
2899
11
    outstanding_pings_.pop();
2900
11
    DecrementCurrentSessionMemory(sizeof(*ping));
2901
  }
2902
567
  return ping;
2903
}
2904
2905
13
Http2Session::Http2Ping* Http2Session::AddPing(
2906
    std::unique_ptr<Http2Session::Http2Ping> ping) {
2907
13
  if (outstanding_pings_.size() == max_outstanding_pings_) {
2908
2
    ping->Done(false);
2909
2
    return nullptr;
2910
  }
2911
11
  Http2Ping* ptr = ping.get();
2912
11
  outstanding_pings_.emplace(std::move(ping));
2913
11
  IncrementCurrentSessionMemory(sizeof(*ping));
2914
11
  return ptr;
2915
}
2916
2917
485
std::unique_ptr<Http2Session::Http2Settings> Http2Session::PopSettings() {
2918
485
  std::unique_ptr<Http2Settings> settings;
2919
485
  if (!outstanding_settings_.empty()) {
2920
485
    settings = std::move(outstanding_settings_.front());
2921
485
    outstanding_settings_.pop();
2922
485
    DecrementCurrentSessionMemory(sizeof(*settings));
2923
  }
2924
485
  return settings;
2925
}
2926
2927
594
Http2Session::Http2Settings* Http2Session::AddSettings(
2928
    std::unique_ptr<Http2Session::Http2Settings> settings) {
2929
594
  if (outstanding_settings_.size() == max_outstanding_settings_) {
2930
2
    settings->Done(false);
2931
2
    return nullptr;
2932
  }
2933
592
  Http2Settings* ptr = settings.get();
2934
592
  outstanding_settings_.emplace(std::move(settings));
2935
592
  IncrementCurrentSessionMemory(sizeof(*settings));
2936
592
  return ptr;
2937
}
2938
2939
13
Http2Session::Http2Ping::Http2Ping(Http2Session* session, Local<Object> obj)
2940
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2PING),
2941
      session_(session),
2942
13
      startTime_(uv_hrtime()) {
2943
13
  RemoveCleanupHook();  // This object is owned by the Http2Session.
2944
13
}
2945
2946
11
void Http2Session::Http2Ping::Send(const uint8_t* payload) {
2947
11
  CHECK_NOT_NULL(session_);
2948
  uint8_t data[8];
2949
11
  if (payload == nullptr) {
2950
5
    memcpy(&data, &startTime_, arraysize(data));
2951
5
    payload = data;
2952
  }
2953
11
  Http2Scope h2scope(session_);
2954
11
  CHECK_EQ(nghttp2_submit_ping(**session_, NGHTTP2_FLAG_NONE, payload), 0);
2955
11
}
2956
2957
13
void Http2Session::Http2Ping::Done(bool ack, const uint8_t* payload) {
2958
13
  uint64_t duration_ns = uv_hrtime() - startTime_;
2959
13
  double duration_ms = duration_ns / 1e6;
2960
13
  if (session_ != nullptr) session_->statistics_.ping_rtt = duration_ns;
2961
2962
13
  HandleScope handle_scope(env()->isolate());
2963
13
  Context::Scope context_scope(env()->context());
2964
2965
13
  Local<Value> buf = Undefined(env()->isolate());
2966
13
  if (payload != nullptr) {
2967
    buf = Buffer::Copy(env()->isolate(),
2968
                       reinterpret_cast<const char*>(payload),
2969
20
                       8).ToLocalChecked();
2970
  }
2971
2972
  Local<Value> argv[] = {
2973
    Boolean::New(env()->isolate(), ack),
2974
    Number::New(env()->isolate(), duration_ms),
2975
    buf
2976
39
  };
2977
26
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
2978
13
}
2979
2980
1
void Http2Session::Http2Ping::DetachFromSession() {
2981
1
  session_ = nullptr;
2982
1
}
2983
2984
void nghttp2_stream_write::MemoryInfo(MemoryTracker* tracker) const {
2985
  if (req_wrap != nullptr)
2986
    tracker->TrackField("req_wrap", req_wrap->GetAsyncWrap());
2987
  tracker->TrackField("buf", buf);
2988
}
2989
2990
2991
void nghttp2_header::MemoryInfo(MemoryTracker* tracker) const {
2992
  tracker->TrackFieldWithSize("name", nghttp2_rcbuf_get_buf(name).len);
2993
  tracker->TrackFieldWithSize("value", nghttp2_rcbuf_get_buf(value).len);
2994
}
2995
2996
227
void SetCallbackFunctions(const FunctionCallbackInfo<Value>& args) {
2997
227
  Environment* env = Environment::GetCurrent(args);
2998
227
  CHECK_EQ(args.Length(), 11);
2999
3000
#define SET_FUNCTION(arg, name)                                               \
3001
  CHECK(args[arg]->IsFunction());                                             \
3002
  env->set_http2session_on_ ## name ## _function(args[arg].As<Function>());
3003
3004
908
  SET_FUNCTION(0, error)
3005
908
  SET_FUNCTION(1, priority)
3006
908
  SET_FUNCTION(2, settings)
3007
908
  SET_FUNCTION(3, ping)
3008
908
  SET_FUNCTION(4, headers)
3009
908
  SET_FUNCTION(5, frame_error)
3010
908
  SET_FUNCTION(6, goaway_data)
3011
908
  SET_FUNCTION(7, altsvc)
3012
908
  SET_FUNCTION(8, origin)
3013
908
  SET_FUNCTION(9, stream_trailers)
3014
908
  SET_FUNCTION(10, stream_close)
3015
3016
#undef SET_FUNCTION
3017
227
}
3018
3019
// Set up the process.binding('http2') binding.
3020
233
void Initialize(Local<Object> target,
3021
                Local<Value> unused,
3022
                Local<Context> context,
3023
                void* priv) {
3024
233
  Environment* env = Environment::GetCurrent(context);
3025
233
  Isolate* isolate = env->isolate();
3026
233
  HandleScope scope(isolate);
3027
3028
466
  std::unique_ptr<Http2State> state(new Http2State(isolate));
3029
3030
#define SET_STATE_TYPEDARRAY(name, field)             \
3031
  target->Set(context,                                \
3032
              FIXED_ONE_BYTE_STRING(isolate, (name)), \
3033
              (field)).FromJust()
3034
3035
  // Initialize the buffer used to store the session state
3036
932
  SET_STATE_TYPEDARRAY(
3037
    "sessionState", state->session_state_buffer.GetJSArray());
3038
  // Initialize the buffer used to store the stream state
3039
932
  SET_STATE_TYPEDARRAY(
3040
    "streamState", state->stream_state_buffer.GetJSArray());
3041
932
  SET_STATE_TYPEDARRAY(
3042
    "settingsBuffer", state->settings_buffer.GetJSArray());
3043
932
  SET_STATE_TYPEDARRAY(
3044
    "optionsBuffer", state->options_buffer.GetJSArray());
3045
932
  SET_STATE_TYPEDARRAY(
3046
    "streamStats", state->stream_stats_buffer.GetJSArray());
3047
932
  SET_STATE_TYPEDARRAY(
3048
    "sessionStats", state->session_stats_buffer.GetJSArray());
3049
#undef SET_STATE_TYPEDARRAY
3050
3051
233
  env->set_http2_state(std::move(state));
3052
3053
932
  NODE_DEFINE_CONSTANT(target, kBitfield);
3054
932
  NODE_DEFINE_CONSTANT(target, kSessionPriorityListenerCount);
3055
932
  NODE_DEFINE_CONSTANT(target, kSessionFrameErrorListenerCount);
3056
932
  NODE_DEFINE_CONSTANT(target, kSessionUint8FieldCount);
3057
3058
932
  NODE_DEFINE_CONSTANT(target, kSessionHasRemoteSettingsListeners);
3059
932
  NODE_DEFINE_CONSTANT(target, kSessionRemoteSettingsIsUpToDate);
3060
932
  NODE_DEFINE_CONSTANT(target, kSessionHasPingListeners);
3061
932
  NODE_DEFINE_CONSTANT(target, kSessionHasAltsvcListeners);
3062
3063
  // Method to fetch the nghttp2 string description of an nghttp2 error code
3064
233
  env->SetMethod(target, "nghttp2ErrorString", HttpErrorString);
3065
3066
  Local<String> http2SessionClassName =
3067
233
    FIXED_ONE_BYTE_STRING(isolate, "Http2Session");
3068
3069
233
  Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate());
3070
466
  ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping"));
3071
466
  ping->Inherit(AsyncWrap::GetConstructorTemplate(env));
3072
233
  Local<ObjectTemplate> pingt = ping->InstanceTemplate();
3073
233
  pingt->SetInternalFieldCount(1);
3074
233
  env->set_http2ping_constructor_template(pingt);
3075
3076
233
  Local<FunctionTemplate> setting = FunctionTemplate::New(env->isolate());
3077
466
  setting->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Setting"));
3078
466
  setting->Inherit(AsyncWrap::GetConstructorTemplate(env));
3079
233
  Local<ObjectTemplate> settingt = setting->InstanceTemplate();
3080
233
  settingt->SetInternalFieldCount(1);
3081
233
  env->set_http2settings_constructor_template(settingt);
3082
3083
233
  Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
3084
466
  stream->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"));
3085
233
  env->SetProtoMethod(stream, "id", Http2Stream::GetID);
3086
233
  env->SetProtoMethod(stream, "destroy", Http2Stream::Destroy);
3087
233
  env->SetProtoMethod(stream, "priority", Http2Stream::Priority);
3088
233
  env->SetProtoMethod(stream, "pushPromise", Http2Stream::PushPromise);
3089
233
  env->SetProtoMethod(stream, "info", Http2Stream::Info);
3090
233
  env->SetProtoMethod(stream, "trailers", Http2Stream::Trailers);
3091
233
  env->SetProtoMethod(stream, "respond", Http2Stream::Respond);
3092
233
  env->SetProtoMethod(stream, "rstStream", Http2Stream::RstStream);
3093
233
  env->SetProtoMethod(stream, "refreshState", Http2Stream::RefreshState);
3094
466
  stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
3095
233
  StreamBase::AddMethods(env, stream);
3096
233
  Local<ObjectTemplate> streamt = stream->InstanceTemplate();
3097
233
  streamt->SetInternalFieldCount(StreamBase::kStreamBaseFieldCount);
3098
233
  env->set_http2stream_constructor_template(streamt);
3099
  target->Set(context,
3100
              FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"),
3101
1165
              stream->GetFunction(env->context()).ToLocalChecked()).Check();
3102
3103
  Local<FunctionTemplate> session =
3104
233
      env->NewFunctionTemplate(Http2Session::New);
3105
233
  session->SetClassName(http2SessionClassName);
3106
466
  session->InstanceTemplate()->SetInternalFieldCount(1);
3107
466
  session->Inherit(AsyncWrap::GetConstructorTemplate(env));
3108
233
  env->SetProtoMethod(session, "origin", Http2Session::Origin);
3109
233
  env->SetProtoMethod(session, "altsvc", Http2Session::AltSvc);
3110
233
  env->SetProtoMethod(session, "ping", Http2Session::Ping);
3111
233
  env->SetProtoMethod(session, "consume", Http2Session::Consume);
3112
233
  env->SetProtoMethod(session, "destroy", Http2Session::Destroy);
3113
233
  env->SetProtoMethod(session, "goaway", Http2Session::Goaway);
3114
233
  env->SetProtoMethod(session, "settings", Http2Session::Settings);
3115
233
  env->SetProtoMethod(session, "request", Http2Session::Request);
3116
  env->SetProtoMethod(session, "setNextStreamID",
3117
233
                      Http2Session::SetNextStreamID);
3118
  env->SetProtoMethod(session, "updateChunksSent",
3119
233
                      Http2Session::UpdateChunksSent);
3120
233
  env->SetProtoMethod(session, "refreshState", Http2Session::RefreshState);
3121
  env->SetProtoMethod(
3122
      session, "localSettings",
3123
233
      Http2Session::RefreshSettings<nghttp2_session_get_local_settings>);
3124
  env->SetProtoMethod(
3125
      session, "remoteSettings",
3126
233
      Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>);
3127
  target->Set(context,
3128
              http2SessionClassName,
3129
932
              session->GetFunction(env->context()).ToLocalChecked()).Check();
3130
3131
233
  Local<Object> constants = Object::New(isolate);
3132
233
  Local<Array> name_for_error_code = Array::New(isolate);
3133
3134
#define NODE_NGHTTP2_ERROR_CODES(V)                       \
3135
  V(NGHTTP2_SESSION_SERVER);                              \
3136
  V(NGHTTP2_SESSION_CLIENT);                              \
3137
  V(NGHTTP2_STREAM_STATE_IDLE);                           \
3138
  V(NGHTTP2_STREAM_STATE_OPEN);                           \
3139
  V(NGHTTP2_STREAM_STATE_RESERVED_LOCAL);                 \
3140
  V(NGHTTP2_STREAM_STATE_RESERVED_REMOTE);                \
3141
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL);              \
3142
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE);             \
3143
  V(NGHTTP2_STREAM_STATE_CLOSED);                         \
3144
  V(NGHTTP2_NO_ERROR);                                    \
3145
  V(NGHTTP2_PROTOCOL_ERROR);                              \
3146
  V(NGHTTP2_INTERNAL_ERROR);                              \
3147
  V(NGHTTP2_FLOW_CONTROL_ERROR);                          \
3148
  V(NGHTTP2_SETTINGS_TIMEOUT);                            \
3149
  V(NGHTTP2_STREAM_CLOSED);                               \
3150
  V(NGHTTP2_FRAME_SIZE_ERROR);                            \
3151
  V(NGHTTP2_REFUSED_STREAM);                              \
3152
  V(NGHTTP2_CANCEL);                                      \
3153
  V(NGHTTP2_COMPRESSION_ERROR);                           \
3154
  V(NGHTTP2_CONNECT_ERROR);                               \
3155
  V(NGHTTP2_ENHANCE_YOUR_CALM);                           \
3156
  V(NGHTTP2_INADEQUATE_SECURITY);                         \
3157
  V(NGHTTP2_HTTP_1_1_REQUIRED);                           \
3158
3159
#define V(name)                                                         \
3160
  NODE_DEFINE_CONSTANT(constants, name);                                \
3161
  name_for_error_code->Set(env->context(),                              \
3162
                           static_cast<int>(name),                      \
3163
                           FIXED_ONE_BYTE_STRING(isolate,               \
3164
                                                 #name)).Check();
3165
37513
  NODE_NGHTTP2_ERROR_CODES(V)
3166
#undef V
3167
3168
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_REQUEST);
3169
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_RESPONSE);
3170
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_PUSH_RESPONSE);
3171
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_HEADERS);
3172
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_NV_FLAG_NONE);
3173
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_NV_FLAG_NO_INDEX);
3174
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_DEFERRED);
3175
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE);
3176
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_INVALID_ARGUMENT);
3177
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_STREAM_CLOSED);
3178
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_ERR_FRAME_SIZE_ERROR);
3179
3180
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, STREAM_OPTION_EMPTY_PAYLOAD);
3181
932
  NODE_DEFINE_HIDDEN_CONSTANT(constants, STREAM_OPTION_GET_TRAILERS);
3182
3183
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_NONE);
3184
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_END_STREAM);
3185
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_END_HEADERS);
3186
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_ACK);
3187
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_PADDED);
3188
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_PRIORITY);
3189
3190
932
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_HEADER_TABLE_SIZE);
3191
932
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_ENABLE_PUSH);
3192
932
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS);
3193
932
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE);
3194
932
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_MAX_FRAME_SIZE);
3195
932
  NODE_DEFINE_CONSTANT(constants, MAX_MAX_FRAME_SIZE);
3196
932
  NODE_DEFINE_CONSTANT(constants, MIN_MAX_FRAME_SIZE);
3197
932
  NODE_DEFINE_CONSTANT(constants, MAX_INITIAL_WINDOW_SIZE);
3198
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_DEFAULT_WEIGHT);
3199
3200
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
3201
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_ENABLE_PUSH);
3202
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
3203
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
3204
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
3205
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
3206
932
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
3207
3208
932
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_NONE);
3209
932
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_ALIGNED);
3210
932
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_MAX);
3211
932
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_CALLBACK);
3212
3213
#define STRING_CONSTANT(NAME, VALUE)                                          \
3214
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE);
3215
106248
HTTP_KNOWN_HEADERS(STRING_CONSTANT)
3216
#undef STRING_CONSTANT
3217
3218
#define STRING_CONSTANT(NAME, VALUE)                                          \
3219
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE);
3220
54522
HTTP_KNOWN_METHODS(STRING_CONSTANT)
3221
#undef STRING_CONSTANT
3222
3223
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
3224
58716
HTTP_STATUS_CODES(V)
3225
#undef V
3226
3227
233
  env->SetMethod(target, "refreshDefaultSettings", RefreshDefaultSettings);
3228
233
  env->SetMethod(target, "packSettings", PackSettings);
3229
233
  env->SetMethod(target, "setCallbackFunctions", SetCallbackFunctions);
3230
3231
  target->Set(context,
3232
              env->constants_string(),
3233
699
              constants).Check();
3234
  target->Set(context,
3235
              FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"),
3236
932
              name_for_error_code).Check();
3237
233
}
3238
}  // namespace http2
3239
}  // namespace node
3240
3241

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