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: 1609 1667 96.5 %
Date: 2019-08-17 22:35:23 Branches: 583 799 73.0 %

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
40508
inline Http2Stream* GetStream(Http2Session* session,
40
                              int32_t id,
41
                              nghttp2_data_source* source) {
42
40508
  Http2Stream* stream = static_cast<Http2Stream*>(source->ptr);
43
40508
  if (stream == nullptr)
44
32061
    stream = session->FindStream(id);
45
40508
  CHECK_NOT_NULL(stream);
46
40508
  CHECK_EQ(id, stream->id());
47
40508
  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
10032
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
56
    Callbacks(false),
57
5016
    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
62073
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
71
72
105068
Http2Scope::Http2Scope(Http2Session* session) {
73
105068
  if (session == nullptr)
74
    return;
75
76
105068
  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
73849
    return;
81
  }
82
31219
  session->flags_ |= SESSION_STATE_HAS_SCOPE;
83
31219
  session_ = session;
84
85
  // Always keep the session object alive for at least as long as
86
  // this scope is active.
87
31219
  session_handle_ = session->object();
88
62438
  CHECK(!session_handle_.IsEmpty());
89
}
90
91
105068
Http2Scope::~Http2Scope() {
92
105068
  if (session_ == nullptr)
93
73849
    return;
94
95
31219
  session_->flags_ &= ~SESSION_STATE_HAS_SCOPE;
96
31219
  session_->MaybeScheduleWrite();
97
31219
}
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
582
Http2Options::Http2Options(Environment* env, nghttp2_session_type type) {
104
582
  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
582
  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
582
  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
582
  if (type == NGHTTP2_SESSION_CLIENT) {
121
285
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC);
122
285
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ORIGIN);
123
  }
124
125
582
  AliasedUint32Array& buffer = env->http2_state()->options_buffer;
126
582
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
127
128
582
  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
582
  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
582
  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
582
  nghttp2_option_set_peer_max_concurrent_streams(options_, 100);
148
582
  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
582
  if (IsReverted(SECURITY_REVERT_CVE_2019_9512))
155
    nghttp2_option_set_max_outbound_ack(options_, 10000);
156
157
  // The padding strategy sets the mechanism by which we determine how much
158
  // additional frame padding to apply to DATA and HEADERS frames. Currently
159
  // this is set on a per-session basis, but eventually we may switch to
160
  // a per-stream setting, giving users greater control
161
582
  if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
162
    padding_strategy_type strategy =
163
        static_cast<padding_strategy_type>(
164
4
            buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
165
4
    SetPaddingStrategy(strategy);
166
  }
167
168
  // The max header list pairs option controls the maximum number of
169
  // header pairs the session may accept. This is a hard limit.. that is,
170
  // if the remote peer sends more than this amount, the stream will be
171
  // automatically closed with an RST_STREAM.
172
582
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS)) {
173
3
    SetMaxHeaderPairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
174
  }
175
176
  // The HTTP2 specification places no limits on the number of HTTP2
177
  // PING frames that can be sent. In order to prevent PINGS from being
178
  // abused as an attack vector, however, we place a strict upper limit
179
  // on the number of unacknowledged PINGS that can be sent at any given
180
  // time.
181
582
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS)) {
182
2
    SetMaxOutstandingPings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
183
  }
184
185
  // The HTTP2 specification places no limits on the number of HTTP2
186
  // SETTINGS frames that can be sent. In order to prevent PINGS from being
187
  // abused as an attack vector, however, we place a strict upper limit
188
  // on the number of unacknowledged SETTINGS that can be sent at any given
189
  // time.
190
582
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS)) {
191
2
    SetMaxOutstandingSettings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
192
  }
193
194
  // The HTTP2 specification places no limits on the amount of memory
195
  // that a session can consume. In order to prevent abuse, we place a
196
  // cap on the amount of memory a session can consume at any given time.
197
  // this is a credit based system. Existing streams may cause the limit
198
  // to be temporarily exceeded but once over the limit, new streams cannot
199
  // created.
200
  // Important: The maxSessionMemory option in javascript is expressed in
201
  //            terms of MB increments (i.e. the value 1 == 1 MB)
202
582
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY)) {
203
5
    SetMaxSessionMemory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1e6);
204
  }
205
582
}
206
207
606
void Http2Session::Http2Settings::Init() {
208
606
  AliasedUint32Array& buffer = env()->http2_state()->settings_buffer;
209
606
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
210
211
606
  size_t n = 0;
212
213
#define GRABSETTING(N, trace)                                                 \
214
  if (flags & (1 << IDX_SETTINGS_##N)) {                                      \
215
    uint32_t val = buffer[IDX_SETTINGS_##N];                                  \
216
    if (session_ != nullptr)                                                  \
217
      Debug(session_, "setting " trace ": %d\n", val);                        \
218
    entries_[n++] =                                                           \
219
        nghttp2_settings_entry {NGHTTP2_SETTINGS_##N, val};                   \
220
  }
221
222

611
  GRABSETTING(HEADER_TABLE_SIZE, "header table size");
223

611
  GRABSETTING(MAX_CONCURRENT_STREAMS, "max concurrent streams");
224

612
  GRABSETTING(MAX_FRAME_SIZE, "max frame size");
225

624
  GRABSETTING(INITIAL_WINDOW_SIZE, "initial window size");
226

613
  GRABSETTING(MAX_HEADER_LIST_SIZE, "max header list size");
227

617
  GRABSETTING(ENABLE_PUSH, "enable push");
228

609
  GRABSETTING(ENABLE_CONNECT_PROTOCOL, "enable connect protocol");
229
230
#undef GRABSETTING
231
232
606
  count_ = n;
233
606
}
234
235
// The Http2Settings class is used to configure a SETTINGS frame that is
236
// to be sent to the connected peer. The settings are set using a TypedArray
237
// that is shared with the JavaScript side.
238
606
Http2Session::Http2Settings::Http2Settings(Environment* env,
239
                                           Http2Session* session,
240
                                           Local<Object> obj,
241
                                           uint64_t start_time)
242
    : AsyncWrap(env, obj, PROVIDER_HTTP2SETTINGS),
243
      session_(session),
244
606
      startTime_(start_time) {
245
606
  RemoveCleanupHook();  // This object is owned by the Http2Session.
246
606
  Init();
247
606
}
248
249
// Generates a Buffer that contains the serialized payload of a SETTINGS
250
// frame. This can be used, for instance, to create the Base64-encoded
251
// content of an Http2-Settings header field.
252
15
Local<Value> Http2Session::Http2Settings::Pack() {
253
15
  const size_t len = count_ * 6;
254
30
  Local<Value> buf = Buffer::New(env(), len).ToLocalChecked();
255
  ssize_t ret =
256
      nghttp2_pack_settings_payload(
257
15
        reinterpret_cast<uint8_t*>(Buffer::Data(buf)), len,
258
30
        &entries_[0], count_);
259
15
  if (ret >= 0)
260
14
    return buf;
261
  else
262
2
    return Undefined(env()->isolate());
263
}
264
265
// Updates the shared TypedArray with the current remote or local settings for
266
// the session.
267
502
void Http2Session::Http2Settings::Update(Environment* env,
268
                                         Http2Session* session,
269
                                         get_setting fn) {
270
502
  AliasedUint32Array& buffer = env->http2_state()->settings_buffer;
271
1004
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
272
1004
      fn(**session, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
273
1004
  buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
274
1004
      fn(**session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
275
1004
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
276
1004
      fn(**session, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
277
1004
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
278
1004
      fn(**session, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
279
1004
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
280
1004
      fn(**session, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
281
1004
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
282
1004
      fn(**session, NGHTTP2_SETTINGS_ENABLE_PUSH);
283
1004
  buffer[IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL] =
284
1004
      fn(**session, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
285
502
}
286
287
// Initializes the shared TypedArray with the default settings values.
288
3
void Http2Session::Http2Settings::RefreshDefaults(Environment* env) {
289
3
  AliasedUint32Array& buffer = env->http2_state()->settings_buffer;
290
291
6
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
292
3
      DEFAULT_SETTINGS_HEADER_TABLE_SIZE;
293
6
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
294
3
      DEFAULT_SETTINGS_ENABLE_PUSH;
295
6
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
296
3
      DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE;
297
6
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
298
3
      DEFAULT_SETTINGS_MAX_FRAME_SIZE;
299
6
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
300
3
      DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
301
6
  buffer[IDX_SETTINGS_COUNT] =
302
    (1 << IDX_SETTINGS_HEADER_TABLE_SIZE) |
303
    (1 << IDX_SETTINGS_ENABLE_PUSH) |
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
589
void Http2Session::Http2Settings::Send() {
311
589
  Http2Scope h2scope(session_);
312
589
  CHECK_EQ(nghttp2_submit_settings(**session_, NGHTTP2_FLAG_NONE,
313
589
                                   &entries_[0], count_), 0);
314
589
}
315
316
484
void Http2Session::Http2Settings::Done(bool ack) {
317
484
  uint64_t end = uv_hrtime();
318
484
  double duration = (end - startTime_) / 1e6;
319
320
  Local<Value> argv[] = {
321
    Boolean::New(env()->isolate(), ack),
322
    Number::New(env()->isolate(), duration)
323
1452
  };
324
484
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
325
484
}
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
11758
Http2Priority::Http2Priority(Environment* env,
331
                             Local<Value> parent,
332
                             Local<Value> weight,
333
                             Local<Value> exclusive) {
334
11758
  Local<Context> context = env->context();
335
23516
  int32_t parent_ = parent->Int32Value(context).ToChecked();
336
23516
  int32_t weight_ = weight->Int32Value(context).ToChecked();
337
23516
  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
11758
  nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0);
342
11758
}
343
344
345
126
const char* Http2Session::TypeName() const {
346
126
  switch (session_type_) {
347
66
    case NGHTTP2_SESSION_SERVER: return "server";
348
60
    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
23474
Headers::Headers(Isolate* isolate,
358
                 Local<Context> context,
359
23474
                 Local<Array> headers) {
360
46948
  Local<Value> header_string = headers->Get(context, 0).ToLocalChecked();
361
46948
  Local<Value> header_count = headers->Get(context, 1).ToLocalChecked();
362
46948
  count_ = header_count.As<Uint32>()->Value();
363
46948
  int header_string_len = header_string.As<String>()->Length();
364
365
23474
  if (count_ == 0) {
366
24
    CHECK_EQ(header_string_len, 0);
367
49
    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
23450
                                 count_ * sizeof(nghttp2_nv) +
375
46900
                                 header_string_len);
376
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
377
  char* start = reinterpret_cast<char*>(
378
23450
      RoundUp(reinterpret_cast<uintptr_t>(*buf_), alignof(nghttp2_nv)));
379
23450
  char* header_contents = start + (count_ * sizeof(nghttp2_nv));
380
23450
  nghttp2_nv* const nva = reinterpret_cast<nghttp2_nv*>(start);
381
382
23450
  CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length());
383
70350
  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
23450
  size_t n = 0;
392
  char* p;
393
95229
  for (p = header_contents; p < header_contents + header_string_len; n++) {
394
71780
    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
71779
    nva[n].flags = NGHTTP2_NV_FLAG_NONE;
406
71779
    nva[n].name = reinterpret_cast<uint8_t*>(p);
407
71779
    nva[n].namelen = strlen(p);
408
71779
    p += nva[n].namelen + 1;
409
71779
    nva[n].value = reinterpret_cast<uint8_t*>(p);
410
71779
    nva[n].valuelen = strlen(p);
411
71779
    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
10032
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
469
10032
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0);
470
471
  nghttp2_session_callbacks_set_on_begin_headers_callback(
472
10032
    callbacks, OnBeginHeadersCallback);
473
  nghttp2_session_callbacks_set_on_header_callback2(
474
10032
    callbacks, OnHeaderCallback);
475
  nghttp2_session_callbacks_set_on_frame_recv_callback(
476
10032
    callbacks, OnFrameReceive);
477
  nghttp2_session_callbacks_set_on_stream_close_callback(
478
10032
    callbacks, OnStreamClose);
479
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
480
10032
    callbacks, OnDataChunkReceived);
481
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
482
10032
    callbacks, OnFrameNotSent);
483
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
484
10032
    callbacks, OnInvalidHeader);
485
  nghttp2_session_callbacks_set_error_callback(
486
10032
    callbacks, OnNghttpError);
487
  nghttp2_session_callbacks_set_send_data_callback(
488
10032
    callbacks, OnSendData);
489
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
490
10032
    callbacks, OnInvalidFrame);
491
  nghttp2_session_callbacks_set_on_frame_send_callback(
492
10032
    callbacks, OnFrameSent);
493
494
10032
  if (kHasGetPaddingCallback) {
495
    nghttp2_session_callbacks_set_select_padding_callback(
496
5016
      callbacks, OnSelectPadding);
497
  }
498
10032
}
499
500
501
10032
Http2Session::Callbacks::~Callbacks() {
502
10032
  nghttp2_session_callbacks_del(callbacks);
503
10032
}
504
505
// Track memory allocated by nghttp2 using a custom allocator.
506
class Http2Session::MemoryAllocatorInfo {
507
 public:
508
582
  explicit MemoryAllocatorInfo(Http2Session* session)
509
582
      : info({ session, H2Malloc, H2Free, H2Calloc, H2Realloc }) {}
510
511
102077
  static void* H2Malloc(size_t size, void* user_data) {
512
102077
    return H2Realloc(nullptr, size, user_data);
513
  }
514
515
1167
  static void* H2Calloc(size_t nmemb, size_t size, void* user_data) {
516
1167
    size_t real_size = MultiplyWithOverflowCheck(nmemb, size);
517
1167
    void* mem = H2Malloc(real_size, user_data);
518
1167
    if (mem != nullptr)
519
1167
      memset(mem, 0, real_size);
520
1167
    return mem;
521
  }
522
523
237488
  static void H2Free(void* ptr, void* user_data) {
524
474976
    if (ptr == nullptr) return;  // free(null); happens quite often.
525
102891
    void* result = H2Realloc(ptr, 0, user_data);
526
102891
    CHECK_NULL(result);
527
  }
528
529
205806
  static void* H2Realloc(void* ptr, size_t size, void* user_data) {
530
205806
    Http2Session* session = static_cast<Http2Session*>(user_data);
531
205806
    size_t previous_size = 0;
532
205806
    char* original_ptr = nullptr;
533
534
    // We prepend each allocated buffer with a size_t containing the full
535
    // size of the allocation.
536
205806
    if (size > 0) size += sizeof(size_t);
537
538
205806
    if (ptr != nullptr) {
539
      // We are free()ing or re-allocating.
540
102915
      original_ptr = static_cast<char*>(ptr) - sizeof(size_t);
541
102915
      previous_size = *reinterpret_cast<size_t*>(original_ptr);
542
      // This means we called StopTracking() on this pointer before.
543
102915
      if (previous_size == 0) {
544
        // Fall back to the standard Realloc() function.
545
1818
        char* ret = UncheckedRealloc(original_ptr, size);
546
1818
        if (ret != nullptr)
547
          ret += sizeof(size_t);
548
1818
        return ret;
549
      }
550
    }
551
203988
    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
203988
    char* mem = UncheckedRealloc(original_ptr, size);
562
563
203988
    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
102915
      const int64_t new_size = size - previous_size;
570
102915
      session->current_nghttp2_memory_ += new_size;
571
      session->env()->isolate()->AdjustAmountOfExternalAllocatedMemory(
572
102915
          new_size);
573
102915
      *reinterpret_cast<size_t*>(mem) = size;
574
102915
      mem += sizeof(size_t);
575
101073
    } else if (size == 0) {
576
101073
      session->current_nghttp2_memory_ -= previous_size;
577
      session->env()->isolate()->AdjustAmountOfExternalAllocatedMemory(
578
101073
          -static_cast<int64_t>(previous_size));
579
    }
580
581
203988
    return mem;
582
  }
583
584
25072
  static void StopTracking(Http2Session* session, void* ptr) {
585
    size_t* original_ptr = reinterpret_cast<size_t*>(
586
25072
        static_cast<char*>(ptr) - sizeof(size_t));
587
25072
    session->current_nghttp2_memory_ -= *original_ptr;
588
    session->env()->isolate()->AdjustAmountOfExternalAllocatedMemory(
589
25072
        -static_cast<int64_t>(*original_ptr));
590
25072
    *original_ptr = 0;
591
25072
  }
592
593
582
  inline nghttp2_mem* operator*() { return &info; }
594
595
  nghttp2_mem info;
596
};
597
598
25072
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
599
25072
  MemoryAllocatorInfo::StopTracking(this, buf);
600
25072
}
601
602
582
Http2Session::Http2Session(Environment* env,
603
                           Local<Object> wrap,
604
                           nghttp2_session_type type)
605
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
606
1164
      session_type_(type) {
607
582
  MakeWeak();
608
582
  statistics_.start_time = uv_hrtime();
609
610
  // Capture the configuration options for this session
611
582
  Http2Options opts(env, type);
612
613
582
  max_session_memory_ = opts.GetMaxSessionMemory();
614
615
582
  uint32_t maxHeaderPairs = opts.GetMaxHeaderPairs();
616
  max_header_pairs_ =
617
      type == NGHTTP2_SESSION_SERVER
618
1473
          ? std::max(maxHeaderPairs, 4U)     // minimum # of request headers
619

1461
          : std::max(maxHeaderPairs, 1U);    // minimum # of response headers
620
621
582
  max_outstanding_pings_ = opts.GetMaxOutstandingPings();
622
582
  max_outstanding_settings_ = opts.GetMaxOutstandingSettings();
623
624
582
  padding_strategy_ = opts.GetPaddingStrategy();
625
626
  bool hasGetPaddingCallback =
627
582
      padding_strategy_ != PADDING_STRATEGY_NONE;
628
629
  nghttp2_session_callbacks* callbacks
630
582
      = callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks;
631
632
  auto fn = type == NGHTTP2_SESSION_SERVER ?
633
      nghttp2_session_server_new3 :
634
582
      nghttp2_session_client_new3;
635
636
582
  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
582
  CHECK_EQ(fn(&session_, callbacks, this, *opts, *allocator_info), 0);
644
645
582
  outgoing_storage_.reserve(1024);
646
582
  outgoing_buffers_.reserve(32);
647
648
  {
649
    // Make the js_fields_ property accessible to JS land.
650
    Local<ArrayBuffer> ab =
651
582
        ArrayBuffer::New(env->isolate(), js_fields_, kSessionUint8FieldCount);
652
    Local<Uint8Array> uint8_arr =
653
582
        Uint8Array::New(ab, 0, kSessionUint8FieldCount);
654
1746
    USE(wrap->Set(env->context(), env->fields_string(), uint8_arr));
655
582
  }
656
582
}
657
658
2328
Http2Session::~Http2Session() {
659
582
  CHECK_EQ(flags_ & SESSION_STATE_HAS_SCOPE, 0);
660
582
  Debug(this, "freeing nghttp2 session");
661
619
  for (const auto& iter : streams_)
662
37
    iter.second->session_ = nullptr;
663
582
  nghttp2_session_del(session_);
664
582
  CHECK_EQ(current_nghttp2_memory_, 0);
665
1164
}
666
667
126
std::string Http2Session::diagnostic_name() const {
668
252
  return std::string("Http2Session ") + TypeName() + " (" +
669
378
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
670
}
671
672
25034
inline bool HasHttp2Observer(Environment* env) {
673
25034
  AliasedUint32Array& observers = env->performance_state()->observers;
674
25034
  return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
675
}
676
677
24475
void Http2Stream::EmitStatistics() {
678
24475
  if (!HasHttp2Observer(env()))
679
48948
    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
    stream_->ReadStop();
750
751
  // If the socket is not closed, then attempt to send a closing GOAWAY
752
  // frame. There is no guarantee that this GOAWAY will be received by
753
  // the peer but the HTTP/2 spec recommends sending it anyway. We'll
754
  // make a best effort.
755
555
  if (!socket_closed) {
756
522
    Debug(this, "terminating session with code %d", code);
757
522
    CHECK_EQ(nghttp2_session_terminate_session(session_, code), 0);
758
522
    SendPendingData();
759
33
  } else if (stream_ != nullptr) {
760
23
    stream_->RemoveStreamListener(this);
761
  }
762
763
555
  flags_ |= SESSION_STATE_CLOSED;
764
765
  // If there are outstanding pings, those will need to be canceled, do
766
  // so on the next iteration of the event loop to avoid calling out into
767
  // javascript since this may be called during garbage collection.
768
556
  while (std::unique_ptr<Http2Ping> ping = PopPing()) {
769
1
    ping->DetachFromSession();
770
    env()->SetImmediate(
771
5
        [ping = std::move(ping)](Environment* env) {
772
1
          ping->Done(false);
773
2
        });
774
1
  }
775
776
555
  statistics_.end_time = uv_hrtime();
777
556
  EmitStatistics();
778
}
779
780
// Locates an existing known stream by ID. nghttp2 has a similar method
781
// but this is faster and does not fail if the stream is not found.
782
213454
inline Http2Stream* Http2Session::FindStream(int32_t id) {
783
213454
  auto s = streams_.find(id);
784
213454
  return s != streams_.end() ? s->second : nullptr;
785
}
786
787
12760
inline bool Http2Session::CanAddStream() {
788
  uint32_t maxConcurrentStreams =
789
      nghttp2_session_get_local_settings(
790
12760
          session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
791
  size_t maxSize =
792
12760
      std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
793
  // We can add a new stream so long as we are less than the current
794
  // maximum on concurrent streams and there's enough available memory
795

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

24481
  if (streams_.empty() || stream == nullptr)
811
24481
    return;  // Nothing to remove, item was never added?
812
24481
  streams_.erase(stream->id());
813
24481
  DecrementCurrentSessionMemory(sizeof(*stream));
814
}
815
816
// Used as one of the Padding Strategy functions. Will attempt to ensure
817
// that the total frame size, including header bytes, are 8-byte aligned.
818
// If maxPayloadLen is smaller than the number of bytes necessary to align,
819
// will return maxPayloadLen instead.
820
4
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
821
                                            size_t maxPayloadLen) {
822
4
  size_t r = (frameLen + 9) % 8;
823
4
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
824
825
4
  size_t pad = frameLen + (8 - r);
826
827
  // If maxPayloadLen happens to be less than the calculated pad length,
828
  // use the max instead, even tho this means the frame will not be
829
  // aligned.
830
4
  pad = std::min(maxPayloadLen, pad);
831
4
  Debug(this, "using frame size padding: %d", pad);
832
4
  return pad;
833
}
834
835
// Used as one of the Padding Strategy functions. Uses the maximum amount
836
// of padding allowed for the current frame.
837
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
838
                                            size_t maxPayloadLen) {
839
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
840
  return maxPayloadLen;
841
}
842
843
// Used as one of the Padding Strategy functions. Uses a callback to JS land
844
// to determine the amount of padding for the current frame. This option is
845
// rather more expensive because of the JS boundary cross. It generally should
846
// not be the preferred option.
847
4
ssize_t Http2Session::OnCallbackPadding(size_t frameLen,
848
                                        size_t maxPayloadLen) {
849
4
  if (frameLen == 0) return 0;
850
3
  Debug(this, "using callback to determine padding");
851
3
  Isolate* isolate = env()->isolate();
852
3
  HandleScope handle_scope(isolate);
853
3
  Local<Context> context = env()->context();
854
  Context::Scope context_scope(context);
855
856
3
  AliasedUint32Array& buffer = env()->http2_state()->padding_buffer;
857
3
  buffer[PADDING_BUF_FRAME_LENGTH] = frameLen;
858
3
  buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen;
859
3
  buffer[PADDING_BUF_RETURN_VALUE] = frameLen;
860
3
  MakeCallback(env()->http2session_on_select_padding_function(), 0, nullptr);
861
3
  uint32_t retval = buffer[PADDING_BUF_RETURN_VALUE];
862
3
  retval = std::min(retval, static_cast<uint32_t>(maxPayloadLen));
863
3
  retval = std::max(retval, static_cast<uint32_t>(frameLen));
864
3
  Debug(this, "using padding size %d", retval);
865
6
  return retval;
866
}
867
868
869
// Write data received from the i/o stream to the underlying nghttp2_session.
870
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
871
// various callback functions. Each of these will typically result in a call
872
// out to JavaScript so this particular function is rather hot and can be
873
// quite expensive. This is a potential performance optimization target later.
874
30109
ssize_t Http2Session::ConsumeHTTP2Data() {
875
30109
  CHECK_NOT_NULL(stream_buf_.base);
876
30109
  CHECK_LT(stream_buf_offset_, stream_buf_.len);
877
30109
  size_t read_len = stream_buf_.len - stream_buf_offset_;
878
879
  // multiple side effects.
880
  Debug(this, "receiving %d bytes [wants data? %d]",
881
        read_len,
882
60218
        nghttp2_session_want_read(session_));
883
30109
  flags_ &= ~SESSION_STATE_NGHTTP2_RECV_PAUSED;
884
  ssize_t ret =
885
    nghttp2_session_mem_recv(session_,
886
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
887
                                 stream_buf_offset_,
888
30109
                             read_len);
889
30109
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
890
891
30109
  if (flags_ & SESSION_STATE_NGHTTP2_RECV_PAUSED) {
892
93
    CHECK_NE(flags_ & SESSION_STATE_READING_STOPPED, 0);
893
894
93
    CHECK_GT(ret, 0);
895
93
    CHECK_LE(static_cast<size_t>(ret), read_len);
896
897
93
    if (static_cast<size_t>(ret) < read_len) {
898
      // Mark the remainder of the data as available for later consumption.
899
33
      stream_buf_offset_ += ret;
900
33
      return ret;
901
    }
902
  }
903
904
  // We are done processing the current input chunk.
905
30076
  DecrementCurrentSessionMemory(stream_buf_.len);
906
30076
  stream_buf_offset_ = 0;
907
30076
  stream_buf_ab_.Reset();
908
30076
  stream_buf_allocation_.clear();
909
30076
  stream_buf_ = uv_buf_init(nullptr, 0);
910
911
30076
  if (ret < 0)
912
5
    return ret;
913
914
  // Send any data that was queued up while processing the received data.
915
30071
  if (!IsDestroyed()) {
916
29608
    SendPendingData();
917
  }
918
30071
  return ret;
919
}
920
921
922
144216
inline int32_t GetFrameID(const nghttp2_frame* frame) {
923
  // If this is a push promise, we want to grab the id of the promised stream
924
144216
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
925
      frame->push_promise.promised_stream_id :
926
144216
      frame->hd.stream_id;
927
}
928
929
930
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
931
// callback to determine if a new stream is being created or if we are simply
932
// adding a new block of headers to an existing stream. The header pairs
933
// themselves are set in the OnHeaderCallback
934
24442
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
935
                                         const nghttp2_frame* frame,
936
                                         void* user_data) {
937
24442
  Http2Session* session = static_cast<Http2Session*>(user_data);
938
24442
  int32_t id = GetFrameID(frame);
939
  Debug(session, "beginning headers for stream %d", id);
940
941
24442
  Http2Stream* stream = session->FindStream(id);
942
  // The common case is that we're creating a new stream. The less likely
943
  // case is that we're receiving a set of trailers
944
24442
  if (LIKELY(stream == nullptr)) {
945

12760
    if (UNLIKELY(!session->CanAddStream() ||
946
                 Http2Stream::New(session, id, frame->headers.cat) ==
947
                     nullptr)) {
948

1
      if (session->rejected_stream_count_++ > 100 &&
949
          !IsReverted(SECURITY_REVERT_CVE_2019_9514)) {
950
        return NGHTTP2_ERR_CALLBACK_FAILURE;
951
      }
952
      // Too many concurrent streams being opened
953
      nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id,
954
1
                                NGHTTP2_ENHANCE_YOUR_CALM);
955
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
956
    }
957
958
12759
    session->rejected_stream_count_ = 0;
959
11682
  } else if (!stream->IsDestroyed()) {
960
11682
    stream->StartHeaders(frame->headers.cat);
961
  }
962
24441
  return 0;
963
}
964
965
// Called by nghttp2 for each header name/value pair in a HEADERS block.
966
// This had to have been preceded by a call to OnBeginHeadersCallback so
967
// the Http2Stream is guaranteed to already exist.
968
71719
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
969
                                   const nghttp2_frame* frame,
970
                                   nghttp2_rcbuf* name,
971
                                   nghttp2_rcbuf* value,
972
                                   uint8_t flags,
973
                                   void* user_data) {
974
71719
  Http2Session* session = static_cast<Http2Session*>(user_data);
975
71719
  int32_t id = GetFrameID(frame);
976
71719
  Http2Stream* stream = session->FindStream(id);
977
  // If stream is null at this point, either something odd has happened
978
  // or the stream was closed locally while header processing was occurring.
979
  // either way, do not proceed and close the stream.
980
71719
  if (UNLIKELY(stream == nullptr))
981
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
982
983
  // If the stream has already been destroyed, ignore.
984

71719
  if (!stream->IsDestroyed() && !stream->AddHeader(name, value, flags)) {
985
    // This will only happen if the connected peer sends us more
986
    // than the allowed number of header items at any given time
987
2
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
988
2
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
989
  }
990
71717
  return 0;
991
}
992
993
994
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
995
// only a handful of frame types that we care about handling here.
996
55599
int Http2Session::OnFrameReceive(nghttp2_session* handle,
997
                                 const nghttp2_frame* frame,
998
                                 void* user_data) {
999
55599
  Http2Session* session = static_cast<Http2Session*>(user_data);
1000
55599
  session->statistics_.frame_count++;
1001
  Debug(session, "complete frame received: type: %d",
1002
55599
        frame->hd.type);
1003


55599
  switch (frame->hd.type) {
1004
    case NGHTTP2_DATA:
1005
24643
      return session->HandleDataFrame(frame);
1006
    case NGHTTP2_PUSH_PROMISE:
1007
      // Intentional fall-through, handled just like headers frames
1008
    case NGHTTP2_HEADERS:
1009
23403
      session->HandleHeadersFrame(frame);
1010
23403
      break;
1011
    case NGHTTP2_SETTINGS:
1012
2013
      session->HandleSettingsFrame(frame);
1013
2013
      break;
1014
    case NGHTTP2_PRIORITY:
1015
16
      session->HandlePriorityFrame(frame);
1016
16
      break;
1017
    case NGHTTP2_GOAWAY:
1018
268
      session->HandleGoawayFrame(frame);
1019
268
      break;
1020
    case NGHTTP2_PING:
1021
1021
      session->HandlePingFrame(frame);
1022
1021
      break;
1023
    case NGHTTP2_ALTSVC:
1024
4
      session->HandleAltSvcFrame(frame);
1025
4
      break;
1026
    case NGHTTP2_ORIGIN:
1027
5
      session->HandleOriginFrame(frame);
1028
5
      break;
1029
    default:
1030
4226
      break;
1031
  }
1032
30956
  return 0;
1033
}
1034
1035
1040
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
1036
                                 const nghttp2_frame* frame,
1037
                                 int lib_error_code,
1038
                                 void* user_data) {
1039
1040
  Http2Session* session = static_cast<Http2Session*>(user_data);
1040
1041
  Debug(session, "invalid frame received, code: %d", lib_error_code);
1042

1041
  if (session->invalid_frame_count_++ > 1000 &&
1043
1
      !IsReverted(SECURITY_REVERT_CVE_2019_9514)) {
1044
1
    return 1;
1045
  }
1046
1047
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
1048

2078
  if (nghttp2_is_fatal(lib_error_code) ||
1049
1039
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
1050
1
    Environment* env = session->env();
1051
1
    Isolate* isolate = env->isolate();
1052
1
    HandleScope scope(isolate);
1053
1
    Local<Context> context = env->context();
1054
    Context::Scope context_scope(context);
1055
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
1056
2
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1057
  }
1058
1039
  return 0;
1059
}
1060
1061
// If nghttp2 is unable to send a queued up frame, it will call this callback
1062
// to let us know. If the failure occurred because we are in the process of
1063
// closing down the session or stream, we go ahead and ignore it. We don't
1064
// really care about those and there's nothing we can reasonably do about it
1065
// anyway. Other types of failures are reported up to JavaScript. This should
1066
// be exceedingly rare.
1067
2111
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1068
                                 const nghttp2_frame* frame,
1069
                                 int error_code,
1070
                                 void* user_data) {
1071
2111
  Http2Session* session = static_cast<Http2Session*>(user_data);
1072
2111
  Environment* env = session->env();
1073
  Debug(session, "frame type %d was not sent, code: %d",
1074
2111
        frame->hd.type, error_code);
1075
1076
  // Do not report if the frame was not sent due to the session closing
1077

2115
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
1078
7
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1079
5
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
1080
2
      session->js_fields_[kSessionFrameErrorListenerCount] == 0) {
1081
2110
    return 0;
1082
  }
1083
1084
1
  Isolate* isolate = env->isolate();
1085
1
  HandleScope scope(isolate);
1086
1
  Local<Context> context = env->context();
1087
  Context::Scope context_scope(context);
1088
1089
  Local<Value> argv[3] = {
1090
    Integer::New(isolate, frame->hd.stream_id),
1091
    Integer::New(isolate, frame->hd.type),
1092
    Integer::New(isolate, error_code)
1093
4
  };
1094
  session->MakeCallback(
1095
      env->http2session_on_frame_error_function(),
1096
1
      arraysize(argv), argv);
1097
2
  return 0;
1098
}
1099
1100
55465
int Http2Session::OnFrameSent(nghttp2_session* handle,
1101
                              const nghttp2_frame* frame,
1102
                              void* user_data) {
1103
55465
  Http2Session* session = static_cast<Http2Session*>(user_data);
1104
55465
  session->statistics_.frame_sent += 1;
1105
55465
  return 0;
1106
}
1107
1108
// Called by nghttp2 when a stream closes.
1109
24453
int Http2Session::OnStreamClose(nghttp2_session* handle,
1110
                                int32_t id,
1111
                                uint32_t code,
1112
                                void* user_data) {
1113
24453
  Http2Session* session = static_cast<Http2Session*>(user_data);
1114
24453
  Environment* env = session->env();
1115
24453
  Isolate* isolate = env->isolate();
1116
24453
  HandleScope scope(isolate);
1117
24453
  Local<Context> context = env->context();
1118
  Context::Scope context_scope(context);
1119
  Debug(session, "stream %d closed with code: %d", id, code);
1120
24453
  Http2Stream* stream = session->FindStream(id);
1121
  // Intentionally ignore the callback if the stream does not exist or has
1122
  // already been destroyed
1123

24453
  if (stream == nullptr || stream->IsDestroyed())
1124
48
    return 0;
1125
1126
24405
  stream->Close(code);
1127
1128
  // It is possible for the stream close to occur before the stream is
1129
  // ever passed on to the javascript side. If that happens, the callback
1130
  // will return false.
1131
24405
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1132
  MaybeLocal<Value> answer =
1133
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1134
24405
                          1, &arg);
1135

122025
  if (answer.IsEmpty() ||
1136
122025
      !(answer.ToLocalChecked()->BooleanValue(env->isolate()))) {
1137
    // Skip to destroy
1138
1003
    stream->Destroy();
1139
  }
1140
48858
  return 0;
1141
}
1142
1143
// Called by nghttp2 when an invalid header has been received. For now, we
1144
// ignore these. If this callback was not provided, nghttp2 would handle
1145
// invalid headers strictly and would shut down the stream. We are intentionally
1146
// being more lenient here although we may want to revisit this choice later.
1147
4
int Http2Session::OnInvalidHeader(nghttp2_session* session,
1148
                                  const nghttp2_frame* frame,
1149
                                  nghttp2_rcbuf* name,
1150
                                  nghttp2_rcbuf* value,
1151
                                  uint8_t flags,
1152
                                  void* user_data) {
1153
  // Ignore invalid header fields by default.
1154
4
  return 0;
1155
}
1156
1157
// When nghttp2 receives a DATA frame, it will deliver the data payload to
1158
// us in discrete chunks. We push these into a linked list stored in the
1159
// Http2Sttream which is flushed out to JavaScript as quickly as possible.
1160
// This can be a particularly hot path.
1161
12731
int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
1162
                                      uint8_t flags,
1163
                                      int32_t id,
1164
                                      const uint8_t* data,
1165
                                      size_t len,
1166
                                      void* user_data) {
1167
12731
  Http2Session* session = static_cast<Http2Session*>(user_data);
1168
  Debug(session, "buffering data chunk for stream %d, size: "
1169
        "%d, flags: %d", id, len, flags);
1170
12731
  Environment* env = session->env();
1171
12731
  HandleScope scope(env->isolate());
1172
1173
  // We should never actually get a 0-length chunk so this check is
1174
  // only a precaution at this point.
1175
12731
  if (len == 0)
1176
    return 0;
1177
1178
  // Notify nghttp2 that we've consumed a chunk of data on the connection
1179
  // so that it can send a WINDOW_UPDATE frame. This is a critical part of
1180
  // the flow control process in http2
1181
12731
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1182
12731
  Http2Stream* stream = session->FindStream(id);
1183
  // If the stream has been destroyed, ignore this chunk
1184
12731
  if (stream->IsDestroyed())
1185
    return 0;
1186
1187
12731
  stream->statistics_.received_bytes += len;
1188
1189
  // Repeatedly ask the stream's owner for memory, and copy the read data
1190
  // into those buffers.
1191
  // The typical case is actually the exception here; Http2StreamListeners
1192
  // know about the HTTP2 session associated with this stream, so they know
1193
  // about the larger from-socket read buffer, so they do not require copying.
1194
12731
  do {
1195
12731
    uv_buf_t buf = stream->EmitAlloc(len);
1196
12731
    ssize_t avail = len;
1197
12731
    if (static_cast<ssize_t>(buf.len) < avail)
1198
      avail = buf.len;
1199
1200
    // `buf.base == nullptr` is the default Http2StreamListener's way
1201
    // of saying that it wants a pointer to the raw original.
1202
    // Since it has access to the original socket buffer from which the data
1203
    // was read in the first place, it can use that to minimize ArrayBuffer
1204
    // allocations.
1205
12731
    if (LIKELY(buf.base == nullptr))
1206
12731
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1207
    else
1208
      memcpy(buf.base, data, avail);
1209
12731
    data += avail;
1210
12731
    len -= avail;
1211
12731
    stream->EmitRead(avail, buf);
1212
1213
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1214
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1215
    // more data is being requested.
1216
12731
    if (stream->IsReading())
1217
11623
      nghttp2_session_consume_stream(handle, id, avail);
1218
    else
1219
1108
      stream->inbound_consumed_data_while_paused_ += avail;
1220
1221
    // If we have a gathered a lot of data for output, try sending it now.
1222
12731
    if (session->outgoing_length_ > 4096) session->SendPendingData();
1223
12731
  } while (len != 0);
1224
1225
  // If we are currently waiting for a write operation to finish, we should
1226
  // tell nghttp2 that we want to wait before we process more input data.
1227
12731
  if (session->flags_ & SESSION_STATE_WRITE_IN_PROGRESS) {
1228
93
    session->flags_ |= SESSION_STATE_NGHTTP2_RECV_PAUSED;
1229
93
    return NGHTTP2_ERR_PAUSE;
1230
  }
1231
1232
12638
  return 0;
1233
}
1234
1235
// Called by nghttp2 when it needs to determine how much padding to use in
1236
// a DATA or HEADERS frame.
1237
8
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1238
                                      const nghttp2_frame* frame,
1239
                                      size_t maxPayloadLen,
1240
                                      void* user_data) {
1241
8
  Http2Session* session = static_cast<Http2Session*>(user_data);
1242
8
  ssize_t padding = frame->hd.length;
1243
1244

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

24643
  if (!stream->IsDestroyed() && frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1414
12511
    stream->EmitRead(UV_EOF);
1415

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

1177
  if ((flags_ & SESSION_STATE_READING_STOPPED) &&
1586
588
      nghttp2_session_want_read(session_)) {
1587
561
    flags_ &= ~SESSION_STATE_READING_STOPPED;
1588
561
    stream_->ReadStart();
1589
  }
1590
1591
  // If there is more incoming data queued up, consume it.
1592
589
  if (stream_buf_offset_ > 0) {
1593
5
    ConsumeHTTP2Data();
1594
  }
1595
1596
589
  if (!(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1597
    // Schedule a new write if nghttp2 wants to send data.
1598
374
    MaybeScheduleWrite();
1599
  }
1600
589
}
1601
1602
// If the underlying nghttp2_session struct has data pending in its outbound
1603
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1604
// on the next iteration of the Node.js event loop (using the SetImmediate
1605
// queue), but only if a write has not already been scheduled.
1606
31593
void Http2Session::MaybeScheduleWrite() {
1607
31593
  CHECK_EQ(flags_ & SESSION_STATE_WRITE_SCHEDULED, 0);
1608
31593
  if (UNLIKELY(session_ == nullptr))
1609
31593
    return;
1610
1611
31593
  if (nghttp2_session_want_write(session_)) {
1612
2405
    HandleScope handle_scope(env()->isolate());
1613
2405
    Debug(this, "scheduling write");
1614
2405
    flags_ |= SESSION_STATE_WRITE_SCHEDULED;
1615
2405
    env()->SetImmediate([this](Environment* env) {
1616

2405
      if (session_ == nullptr || !(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1617
        // This can happen e.g. when a stream was reset before this turn
1618
        // of the event loop, in which case SendPendingData() is called early,
1619
        // or the session was destroyed in the meantime.
1620
2626
        return;
1621
      }
1622
1623
      // Sending data may call arbitrary JS code, so keep track of
1624
      // async context.
1625
2184
      HandleScope handle_scope(env->isolate());
1626
4368
      InternalCallbackScope callback_scope(this);
1627
2184
      SendPendingData();
1628
4589
    }, object());
1629
  }
1630
}
1631
1632
61655
void Http2Session::MaybeStopReading() {
1633
123310
  if (flags_ & SESSION_STATE_READING_STOPPED) return;
1634
60781
  int want_read = nghttp2_session_want_read(session_);
1635
60781
  Debug(this, "wants read? %d", want_read);
1636

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


3315
    if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream)
1937
2
      return true;
1938
  }
1939
24473
  return false;
1940
}
1941
1942
// Every Http2Session session is tightly bound to a single i/o StreamBase
1943
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1944
// tightly coupled with all data transfer between the two happening at the
1945
// C++ layer via the StreamBase API.
1946
582
void Http2Session::Consume(Local<Object> stream_obj) {
1947
582
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1948
582
  stream->PushStreamListener(this);
1949
582
  Debug(this, "i/o stream consumed");
1950
582
}
1951
1952
24518
Http2Stream* Http2Stream::New(Http2Session* session,
1953
                              int32_t id,
1954
                              nghttp2_headers_category category,
1955
                              int options) {
1956
  Local<Object> obj;
1957
49036
  if (!session->env()
1958
24518
           ->http2stream_constructor_template()
1959
98072
           ->NewInstance(session->env()->context())
1960
73554
           .ToLocal(&obj)) {
1961
    return nullptr;
1962
  }
1963
24518
  return new Http2Stream(session, obj, id, category, options);
1964
}
1965
1966
24518
Http2Stream::Http2Stream(Http2Session* session,
1967
                         Local<Object> obj,
1968
                         int32_t id,
1969
                         nghttp2_headers_category category,
1970
                         int options)
1971
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
1972
      StreamBase(session->env()),
1973
      session_(session),
1974
      id_(id),
1975
24518
      current_headers_category_(category) {
1976
24518
  MakeWeak();
1977
24518
  StreamBase::AttachToObject(GetObject());
1978
24518
  statistics_.start_time = uv_hrtime();
1979
1980
  // Limit the number of header pairs
1981
24518
  max_header_pairs_ = session->GetMaxHeaderPairs();
1982
24518
  if (max_header_pairs_ == 0) {
1983
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1984
  }
1985
24518
  current_headers_.reserve(std::min(max_header_pairs_, 12u));
1986
1987
  // Limit the number of header octets
1988
  max_header_length_ =
1989
      std::min(
1990
        nghttp2_session_get_local_settings(
1991
          session->session(),
1992
24518
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1993
49036
      MAX_MAX_HEADER_LIST_SIZE);
1994
1995
24518
  if (options & STREAM_OPTION_GET_TRAILERS)
1996
2
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1997
1998
24518
  PushStreamListener(&stream_listener_);
1999
2000
24518
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
2001
582
    Shutdown();
2002
24518
  session->AddStream(this);
2003
24518
}
2004
2005
2006


73554
Http2Stream::~Http2Stream() {
2007
24627
  for (nghttp2_header& header : current_headers_) {
2008
109
    nghttp2_rcbuf_decref(header.name);
2009
109
    nghttp2_rcbuf_decref(header.value);
2010
  }
2011
2012
24518
  if (session_ == nullptr)
2013
37
    return;
2014
24481
  Debug(this, "tearing down stream");
2015
24481
  session_->DecrementCurrentSessionMemory(current_headers_length_);
2016
24481
  session_->RemoveStream(this);
2017
24481
  session_ = nullptr;
2018
48999
}
2019
2020
17
std::string Http2Stream::diagnostic_name() const {
2021
34
  return "HttpStream " + std::to_string(id()) + " (" +
2022
68
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
2023
51
      session()->diagnostic_name() + "]";
2024
}
2025
2026
// Notify the Http2Stream that a new block of HEADERS is being processed.
2027
11682
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
2028
11682
  Debug(this, "starting headers, category: %d", id_, category);
2029
11682
  CHECK(!this->IsDestroyed());
2030
11682
  session_->DecrementCurrentSessionMemory(current_headers_length_);
2031
11682
  current_headers_length_ = 0;
2032
11682
  current_headers_.clear();
2033
11682
  current_headers_category_ = category;
2034
11682
}
2035
2036
2037
11
nghttp2_stream* Http2Stream::operator*() {
2038
11
  return nghttp2_session_find_stream(**session_, id_);
2039
}
2040
2041
24405
void Http2Stream::Close(int32_t code) {
2042
24405
  CHECK(!this->IsDestroyed());
2043
24405
  flags_ |= NGHTTP2_STREAM_FLAG_CLOSED;
2044
24405
  code_ = code;
2045
24405
  Debug(this, "closed with code %d", code);
2046
24405
}
2047
2048
24004
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
2049
24004
  if (IsDestroyed())
2050
    return UV_EPIPE;
2051
2052
  {
2053
24004
    Http2Scope h2scope(this);
2054
24004
    flags_ |= NGHTTP2_STREAM_FLAG_SHUT;
2055
24004
    CHECK_NE(nghttp2_session_resume_data(**session_, id_),
2056
             NGHTTP2_ERR_NOMEM);
2057
48008
    Debug(this, "writable side shutdown");
2058
  }
2059
24004
  return 1;
2060
}
2061
2062
// Destroy the Http2Stream and render it unusable. Actual resources for the
2063
// Stream will not be freed until the next tick of the Node.js event loop
2064
// using the SetImmediate queue.
2065
24475
void Http2Stream::Destroy() {
2066
  // Do nothing if this stream instance is already destroyed
2067
24475
  if (IsDestroyed())
2068
24475
    return;
2069
24475
  if (session_->HasPendingRstStream(id_))
2070
1
    FlushRstStream();
2071
24475
  flags_ |= NGHTTP2_STREAM_FLAG_DESTROYED;
2072
2073
24475
  Debug(this, "destroying stream");
2074
2075
  // Wait until the start of the next loop to delete because there
2076
  // may still be some pending operations queued for this stream.
2077
24475
  env()->SetImmediate([this](Environment* env) {
2078
    // Free any remaining outgoing data chunks here. This should be done
2079
    // here because it's possible for destroy to have been called while
2080
    // we still have queued outbound writes.
2081
48953
    while (!queue_.empty()) {
2082
3
      nghttp2_stream_write& head = queue_.front();
2083
3
      if (head.req_wrap != nullptr)
2084
3
        head.req_wrap->Done(UV_ECANCELED);
2085
3
      queue_.pop();
2086
    }
2087
2088
    // We can destroy the stream now if there are no writes for it
2089
    // already on the socket. Otherwise, we'll wait for the garbage collector
2090
    // to take care of cleaning up.
2091

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

3705
  if (!IsWritable() || IsDestroyed()) {
2272
    req_wrap->Done(UV_EOF);
2273
    return 0;
2274
  }
2275
3705
  Debug(this, "queuing %d buffers to send", id_, nbufs);
2276
27883
  for (size_t i = 0; i < nbufs; ++i) {
2277
    // Store the req_wrap on the last write info in the queue, so that it is
2278
    // only marked as finished once all buffers associated with it are finished.
2279
    queue_.emplace(nghttp2_stream_write {
2280
24178
      i == nbufs - 1 ? req_wrap : nullptr,
2281
      bufs[i]
2282
24178
    });
2283
24178
    IncrementAvailableOutboundLength(bufs[i].len);
2284
  }
2285
3705
  CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM);
2286
3705
  return 0;
2287
}
2288
2289
// Ads a header to the Http2Stream. Note that the header name and value are
2290
// provided using a buffer structure provided by nghttp2 that allows us to
2291
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2292
// is incremented here and are decremented when the header name and values
2293
// are garbage collected later.
2294
71719
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2295
                            nghttp2_rcbuf* value,
2296
                            uint8_t flags) {
2297
71719
  CHECK(!this->IsDestroyed());
2298
71719
  if (this->statistics_.first_header == 0)
2299
23421
    this->statistics_.first_header = uv_hrtime();
2300
71719
  size_t name_len = nghttp2_rcbuf_get_buf(name).len;
2301

71719
  if (name_len == 0 && !IsReverted(SECURITY_REVERT_CVE_2019_9516)) {
2302
    return true;  // Ignore headers with empty names.
2303
  }
2304
71719
  size_t value_len = nghttp2_rcbuf_get_buf(value).len;
2305
71719
  size_t length = name_len + value_len + 32;
2306
  // A header can only be added if we have not exceeded the maximum number
2307
  // of headers and the session has memory available for it.
2308

215157
  if (!session_->IsAvailableSessionMemory(length) ||
2309

143437
      current_headers_.size() == max_header_pairs_ ||
2310
71718
      current_headers_length_ + length > max_header_length_) {
2311
2
    return false;
2312
  }
2313
71717
  nghttp2_header header;
2314
71717
  header.name = name;
2315
71717
  header.value = value;
2316
71717
  header.flags = flags;
2317
71717
  current_headers_.push_back(header);
2318
71717
  nghttp2_rcbuf_incref(name);
2319
71717
  nghttp2_rcbuf_incref(value);
2320
71717
  current_headers_length_ += length;
2321
71717
  session_->IncrementCurrentSessionMemory(length);
2322
71717
  return true;
2323
}
2324
2325
// A Provider is the thing that provides outbound DATA frame data.
2326
11704
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2327
11704
  CHECK(!stream->IsDestroyed());
2328
11704
  provider_.source.ptr = stream;
2329
11704
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2330
11704
}
2331
2332
11752
Http2Stream::Provider::Provider(int options) {
2333
11752
  provider_.source.ptr = nullptr;
2334
11752
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2335
11752
}
2336
2337
23456
Http2Stream::Provider::~Provider() {
2338
23456
  provider_.source.ptr = nullptr;
2339
23456
}
2340
2341
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2342
// built via the StreamBase API and the Streams js API.
2343
11752
Http2Stream::Provider::Stream::Stream(int options)
2344
11752
    : Http2Stream::Provider(options) {
2345
11752
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2346
11752
}
2347
2348
11704
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2349
11704
    : Http2Stream::Provider(stream, options) {
2350
11704
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2351
11704
}
2352
2353
28354
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2354
                                              int32_t id,
2355
                                              uint8_t* buf,
2356
                                              size_t length,
2357
                                              uint32_t* flags,
2358
                                              nghttp2_data_source* source,
2359
                                              void* user_data) {
2360
28354
  Http2Session* session = static_cast<Http2Session*>(user_data);
2361
  Debug(session, "reading outbound data for stream %d", id);
2362
28354
  Http2Stream* stream = GetStream(session, id, source);
2363
28354
  if (stream->statistics_.first_byte_sent == 0)
2364
12663
    stream->statistics_.first_byte_sent = uv_hrtime();
2365
28354
  CHECK_EQ(id, stream->id());
2366
2367
28354
  size_t amount = 0;          // amount of data being sent in this data frame.
2368
2369
  // Remove all empty chunks from the head of the queue.
2370
  // This is done here so that .write('', cb) is still a meaningful way to
2371
  // find out when the HTTP2 stream wants to consume data, and because the
2372
  // StreamBase API allows empty input chunks.
2373

56712
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2374
4
    WriteWrap* finished = stream->queue_.front().req_wrap;
2375
4
    stream->queue_.pop();
2376
4
    if (finished != nullptr)
2377
2
      finished->Done(0);
2378
  }
2379
2380
28354
  if (!stream->queue_.empty()) {
2381
    Debug(session, "stream %d has pending outbound data", id);
2382
12154
    amount = std::min(stream->available_outbound_length_, length);
2383
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2384
12154
    if (amount > 0) {
2385
      // Just return the length, let Http2Session::OnSendData take care of
2386
      // actually taking the buffers out of the queue.
2387
12154
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2388
12154
      stream->DecrementAvailableOutboundLength(amount);
2389
    }
2390
  }
2391
2392

28354
  if (amount == 0 && stream->IsWritable()) {
2393
3641
    CHECK(stream->queue_.empty());
2394
    Debug(session, "deferring stream %d", id);
2395
3641
    stream->EmitWantsWrite(length);
2396

3641
    if (stream->available_outbound_length_ > 0 || !stream->IsWritable()) {
2397
      // EmitWantsWrite() did something interesting synchronously, restart:
2398
      return OnRead(handle, id, buf, length, flags, source, user_data);
2399
    }
2400
3641
    return NGHTTP2_ERR_DEFERRED;
2401
  }
2402
2403

24713
  if (stream->queue_.empty() && !stream->IsWritable()) {
2404
    Debug(session, "no more data for stream %d", id);
2405
12559
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2406
12559
    if (stream->HasTrailers()) {
2407
31
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2408
31
      stream->OnTrailers();
2409
    }
2410
  }
2411
2412
24713
  stream->statistics_.sent_bytes += amount;
2413
24713
  return amount;
2414
}
2415
2416
24178
inline void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2417
24178
  available_outbound_length_ += amount;
2418
24178
  session_->IncrementCurrentSessionMemory(amount);
2419
24178
}
2420
2421
12154
inline void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2422
12154
  available_outbound_length_ -= amount;
2423
12154
  session_->DecrementCurrentSessionMemory(amount);
2424
12154
}
2425
2426
2427
// Implementation of the JavaScript API
2428
2429
// Fetches the string description of a nghttp2 error code and passes that
2430
// back to JS land
2431
53
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2432
53
  Environment* env = Environment::GetCurrent(args);
2433
212
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2434
  args.GetReturnValue().Set(
2435
      String::NewFromOneByte(
2436
          env->isolate(),
2437
53
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val)),
2438
159
          NewStringType::kInternalized).ToLocalChecked());
2439
53
}
2440
2441
2442
// Serializes the settings object into a Buffer instance that
2443
// would be suitable, for instance, for creating the Base64
2444
// output for an HTTP2-Settings header field.
2445
15
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2446
15
  Environment* env = Environment::GetCurrent(args);
2447
  // TODO(addaleax): We should not be creating a full AsyncWrap for this.
2448
  Local<Object> obj;
2449
30
  if (!env->http2settings_constructor_template()
2450
45
           ->NewInstance(env->context())
2451
45
           .ToLocal(&obj)) {
2452
15
    return;
2453
  }
2454
15
  Http2Session::Http2Settings settings(env, nullptr, obj);
2455
45
  args.GetReturnValue().Set(settings.Pack());
2456
}
2457
2458
// A TypedArray instance is shared between C++ and JS land to contain the
2459
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2460
// default values.
2461
3
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2462
3
  Environment* env = Environment::GetCurrent(args);
2463
3
  Http2Session::Http2Settings::RefreshDefaults(env);
2464
3
}
2465
2466
// Sets the next stream ID the Http2Session. If successful, returns true.
2467
1
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2468
1
  Environment* env = Environment::GetCurrent(args);
2469
  Http2Session* session;
2470
1
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2471
4
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2472
1
  if (nghttp2_session_set_next_stream_id(**session, id) < 0) {
2473
    Debug(session, "failed to set next stream id to %d", id);
2474
    return args.GetReturnValue().Set(false);
2475
  }
2476
2
  args.GetReturnValue().Set(true);
2477
1
  Debug(session, "set next stream id to %d", id);
2478
}
2479
2480
// A TypedArray instance is shared between C++ and JS land to contain the
2481
// SETTINGS (either remote or local). RefreshSettings updates the current
2482
// values established for each of the settings so those can be read in JS land.
2483
template <get_setting fn>
2484
502
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2485
502
  Environment* env = Environment::GetCurrent(args);
2486
  Http2Session* session;
2487

1004
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2488
502
  Http2Settings::Update(env, session, fn);
2489
502
  Debug(session, "settings refreshed for session");
2490
}
2491
2492
// A TypedArray instance is shared between C++ and JS land to contain state
2493
// information of the current Http2Session. This updates the values in the
2494
// TypedArray so those can be read in JS land.
2495
3
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2496
3
  Environment* env = Environment::GetCurrent(args);
2497
  Http2Session* session;
2498
6
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2499
3
  Debug(session, "refreshing state");
2500
2501
3
  AliasedFloat64Array& buffer = env->http2_state()->session_state_buffer;
2502
2503
3
  nghttp2_session* s = **session;
2504
2505
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2506
6
      nghttp2_session_get_effective_local_window_size(s);
2507
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2508
6
      nghttp2_session_get_effective_recv_data_length(s);
2509
6
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2510
6
      nghttp2_session_get_next_stream_id(s);
2511
6
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2512
6
      nghttp2_session_get_local_window_size(s);
2513
6
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2514
6
      nghttp2_session_get_last_proc_stream_id(s);
2515
6
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2516
6
      nghttp2_session_get_remote_window_size(s);
2517
6
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2518
6
      nghttp2_session_get_outbound_queue_size(s);
2519
6
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2520
6
      nghttp2_session_get_hd_deflate_dynamic_table_size(s);
2521
6
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2522
6
      nghttp2_session_get_hd_inflate_dynamic_table_size(s);
2523
}
2524
2525
2526
// Constructor for new Http2Session instances.
2527
582
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2528
582
  Environment* env = Environment::GetCurrent(args);
2529
582
  CHECK(args.IsConstructCall());
2530
2328
  int val = args[0]->IntegerValue(env->context()).ToChecked();
2531
582
  nghttp2_session_type type = static_cast<nghttp2_session_type>(val);
2532
582
  Http2Session* session = new Http2Session(env, args.This(), type);
2533
582
  session->get_async_id();  // avoid compiler warning
2534
  Debug(session, "session created");
2535
582
}
2536
2537
2538
// Binds the Http2Session with a StreamBase used for i/o
2539
582
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2540
  Http2Session* session;
2541
1164
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2542
1164
  CHECK(args[0]->IsObject());
2543
1164
  session->Consume(args[0].As<Object>());
2544
}
2545
2546
// Destroys the Http2Session instance and renders it unusable
2547
555
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2548
  Http2Session* session;
2549
1110
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2550
555
  Debug(session, "destroying session");
2551
555
  Environment* env = Environment::GetCurrent(args);
2552
555
  Local<Context> context = env->context();
2553
2554
1665
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2555
1665
  bool socketDestroyed = args[1]->BooleanValue(env->isolate());
2556
2557
555
  session->Close(code, socketDestroyed);
2558
}
2559
2560
// Submits a new request on the Http2Session and returns either an error code
2561
// or the Http2Stream object.
2562
11752
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2563
  Http2Session* session;
2564
11753
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2565
11752
  Environment* env = session->env();
2566
11752
  Local<Context> context = env->context();
2567
11752
  Isolate* isolate = env->isolate();
2568
2569
23504
  Local<Array> headers = args[0].As<Array>();
2570
35256
  int options = args[1]->IntegerValue(context).ToChecked();
2571
11752
  Http2Priority priority(env, args[2], args[3], args[4]);
2572
2573
11752
  Headers list(isolate, context, headers);
2574
2575
11752
  Debug(session, "request submitted");
2576
2577
11752
  int32_t ret = 0;
2578
  Http2Stream* stream =
2579
      session->Http2Session::SubmitRequest(*priority, *list, list.length(),
2580
11752
                                           &ret, options);
2581
2582

11752
  if (ret <= 0 || stream == nullptr) {
2583
2
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2584
3
    return args.GetReturnValue().Set(ret);
2585
  }
2586
2587
23502
  Debug(session, "request submitted, new stream id %d", stream->id());
2588
35253
  args.GetReturnValue().Set(stream->object());
2589
}
2590
2591
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2592
// of shutting down. Note that this function does not actually alter the
2593
// state of the Http2Session, it's simply a notification.
2594
502
void Http2Session::Goaway(uint32_t code,
2595
                          int32_t lastStreamID,
2596
                          const uint8_t* data,
2597
                          size_t len) {
2598
502
  if (IsDestroyed())
2599
502
    return;
2600
2601
502
  Http2Scope h2scope(this);
2602
  // the last proc stream id is the most recently created Http2Stream.
2603
502
  if (lastStreamID <= 0)
2604
502
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_);
2605
502
  Debug(this, "submitting goaway");
2606
  nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE,
2607
502
                        lastStreamID, code, data, len);
2608
}
2609
2610
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2611
// of shutting down. The opaque data argument is an optional TypedArray that
2612
// can be used to send debugging data to the connected peer.
2613
502
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2614
502
  Environment* env = Environment::GetCurrent(args);
2615
502
  Local<Context> context = env->context();
2616
  Http2Session* session;
2617
1004
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2618
2619
1506
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2620
1506
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2621
502
  ArrayBufferViewContents<uint8_t> opaque_data;
2622
2623
1004
  if (args[2]->IsArrayBufferView()) {
2624
2
    opaque_data.Read(args[2].As<ArrayBufferView>());
2625
  }
2626
2627
502
  session->Goaway(code, lastStreamID, opaque_data.data(), opaque_data.length());
2628
}
2629
2630
// Update accounting of data chunks. This is used primarily to manage timeout
2631
// logic when using the FD Provider.
2632
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2633
10
  Environment* env = Environment::GetCurrent(args);
2634
10
  Isolate* isolate = env->isolate();
2635
10
  HandleScope scope(isolate);
2636
  Http2Session* session;
2637
20
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2638
2639
10
  uint32_t length = session->chunks_sent_since_last_write_;
2640
2641
10
  session->object()->Set(env->context(),
2642
                         env->chunks_sent_since_last_write_string(),
2643
60
                         Integer::NewFromUnsigned(isolate, length)).Check();
2644
2645
20
  args.GetReturnValue().Set(length);
2646
}
2647
2648
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2649
// this *WILL* alter the state of the stream, causing the OnStreamClose
2650
// callback to the triggered.
2651
212
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2652
212
  Environment* env = Environment::GetCurrent(args);
2653
212
  Local<Context> context = env->context();
2654
  Http2Stream* stream;
2655
424
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2656
636
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2657
212
  Debug(stream, "sending rst_stream with code %d", code);
2658
212
  stream->SubmitRstStream(code);
2659
}
2660
2661
// Initiates a response on the Http2Stream using the StreamBase API to provide
2662
// outbound DATA frames.
2663
11680
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2664
11680
  Environment* env = Environment::GetCurrent(args);
2665
11680
  Local<Context> context = env->context();
2666
11680
  Isolate* isolate = env->isolate();
2667
  Http2Stream* stream;
2668
23360
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2669
2670
23360
  Local<Array> headers = args[0].As<Array>();
2671
35040
  int options = args[1]->IntegerValue(context).ToChecked();
2672
2673
11680
  Headers list(isolate, context, headers);
2674
2675
  args.GetReturnValue().Set(
2676
35040
      stream->SubmitResponse(*list, list.length(), options));
2677
23360
  Debug(stream, "response submitted");
2678
}
2679
2680
2681
// Submits informational headers on the Http2Stream
2682
5
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2683
5
  Environment* env = Environment::GetCurrent(args);
2684
5
  Local<Context> context = env->context();
2685
5
  Isolate* isolate = env->isolate();
2686
  Http2Stream* stream;
2687
10
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2688
2689
10
  Local<Array> headers = args[0].As<Array>();
2690
2691
5
  Headers list(isolate, context, headers);
2692
15
  args.GetReturnValue().Set(stream->SubmitInfo(*list, list.length()));
2693
10
  Debug(stream, "%d informational headers sent", list.length());
2694
}
2695
2696
// Submits trailing headers on the Http2Stream
2697
29
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2698
29
  Environment* env = Environment::GetCurrent(args);
2699
29
  Local<Context> context = env->context();
2700
29
  Isolate* isolate = env->isolate();
2701
  Http2Stream* stream;
2702
58
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2703
2704
58
  Local<Array> headers = args[0].As<Array>();
2705
2706
29
  Headers list(isolate, context, headers);
2707
87
  args.GetReturnValue().Set(stream->SubmitTrailers(*list, list.length()));
2708
58
  Debug(stream, "%d trailing headers sent", list.length());
2709
}
2710
2711
// Grab the numeric id of the Http2Stream
2712
11759
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2713
  Http2Stream* stream;
2714
23518
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2715
35277
  args.GetReturnValue().Set(stream->id());
2716
}
2717
2718
// Destroy the Http2Stream, rendering it no longer usable
2719
23472
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2720
  Http2Stream* stream;
2721
46944
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2722
23472
  Debug(stream, "destroying stream");
2723
23472
  stream->Destroy();
2724
}
2725
2726
// Initiate a Push Promise and create the associated Http2Stream
2727
8
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2728
8
  Environment* env = Environment::GetCurrent(args);
2729
8
  Local<Context> context = env->context();
2730
8
  Isolate* isolate = env->isolate();
2731
  Http2Stream* parent;
2732
8
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2733
2734
16
  Local<Array> headers = args[0].As<Array>();
2735
24
  int options = args[1]->IntegerValue(context).ToChecked();
2736
2737
8
  Headers list(isolate, context, headers);
2738
2739
8
  Debug(parent, "creating push promise");
2740
2741
8
  int32_t ret = 0;
2742
  Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(),
2743
8
                                                  &ret, options);
2744

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


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

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