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: 1527 1589 96.1 %
Date: 2019-05-05 22:32:45 Branches: 528 737 71.6 %

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

587
  GRABSETTING(HEADER_TABLE_SIZE, "header table size");
217

587
  GRABSETTING(MAX_CONCURRENT_STREAMS, "max concurrent streams");
218

588
  GRABSETTING(MAX_FRAME_SIZE, "max frame size");
219

600
  GRABSETTING(INITIAL_WINDOW_SIZE, "initial window size");
220

589
  GRABSETTING(MAX_HEADER_LIST_SIZE, "max header list size");
221

593
  GRABSETTING(ENABLE_PUSH, "enable push");
222

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

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

21190
  return streams_.size() < maxSize &&
775
21190
         IsAvailableSessionMemory(sizeof(Http2Stream));
776
}
777
778
21190
inline void Http2Session::AddStream(Http2Stream* stream) {
779
21190
  CHECK_GE(++statistics_.stream_count, 0);
780
21190
  streams_[stream->id()] = stream;
781
21190
  size_t size = streams_.size();
782
21190
  if (size > statistics_.max_concurrent_streams)
783
1012
    statistics_.max_concurrent_streams = size;
784
21190
  IncrementCurrentSessionMemory(sizeof(*stream));
785
21190
}
786
787
788
21190
inline void Http2Session::RemoveStream(Http2Stream* stream) {
789

21190
  if (streams_.empty() || stream == nullptr)
790
21190
    return;  // Nothing to remove, item was never added?
791
21190
  streams_.erase(stream->id());
792
21190
  DecrementCurrentSessionMemory(sizeof(*stream));
793
}
794
795
// Used as one of the Padding Strategy functions. Will attempt to ensure
796
// that the total frame size, including header bytes, are 8-byte aligned.
797
// If maxPayloadLen is smaller than the number of bytes necessary to align,
798
// will return maxPayloadLen instead.
799
4
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
800
                                            size_t maxPayloadLen) {
801
4
  size_t r = (frameLen + 9) % 8;
802
4
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
803
804
4
  size_t pad = frameLen + (8 - r);
805
806
  // If maxPayloadLen happens to be less than the calculated pad length,
807
  // use the max instead, even tho this means the frame will not be
808
  // aligned.
809
4
  pad = std::min(maxPayloadLen, pad);
810
4
  Debug(this, "using frame size padding: %d", pad);
811
4
  return pad;
812
}
813
814
// Used as one of the Padding Strategy functions. Uses the maximum amount
815
// of padding allowed for the current frame.
816
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
817
                                            size_t maxPayloadLen) {
818
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
819
  return maxPayloadLen;
820
}
821
822
// Used as one of the Padding Strategy functions. Uses a callback to JS land
823
// to determine the amount of padding for the current frame. This option is
824
// rather more expensive because of the JS boundary cross. It generally should
825
// not be the preferred option.
826
4
ssize_t Http2Session::OnCallbackPadding(size_t frameLen,
827
                                        size_t maxPayloadLen) {
828
4
  if (frameLen == 0) return 0;
829
3
  Debug(this, "using callback to determine padding");
830
3
  Isolate* isolate = env()->isolate();
831
3
  HandleScope handle_scope(isolate);
832
3
  Local<Context> context = env()->context();
833
  Context::Scope context_scope(context);
834
835
3
  AliasedUint32Array& buffer = env()->http2_state()->padding_buffer;
836
3
  buffer[PADDING_BUF_FRAME_LENGTH] = frameLen;
837
3
  buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen;
838
3
  buffer[PADDING_BUF_RETURN_VALUE] = frameLen;
839
3
  MakeCallback(env()->http2session_on_select_padding_function(), 0, nullptr);
840
3
  uint32_t retval = buffer[PADDING_BUF_RETURN_VALUE];
841
3
  retval = std::min(retval, static_cast<uint32_t>(maxPayloadLen));
842
3
  retval = std::max(retval, static_cast<uint32_t>(frameLen));
843
3
  Debug(this, "using padding size %d", retval);
844
6
  return retval;
845
}
846
847
848
// Write data received from the i/o stream to the underlying nghttp2_session.
849
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
850
// various callback functions. Each of these will typically result in a call
851
// out to JavaScript so this particular function is rather hot and can be
852
// quite expensive. This is a potential performance optimization target later.
853
27694
ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) {
854
27694
  size_t total = 0;
855
  // Note that nghttp2_session_mem_recv is a synchronous operation that
856
  // will trigger a number of other callbacks. Those will, in turn have
857
  // multiple side effects.
858
55384
  for (size_t n = 0; n < nbufs; n++) {
859
    Debug(this, "receiving %d bytes [wants data? %d]",
860
27694
          bufs[n].len,
861
83082
          nghttp2_session_want_read(session_));
862
    ssize_t ret =
863
      nghttp2_session_mem_recv(session_,
864
27694
                               reinterpret_cast<uint8_t*>(bufs[n].base),
865
55388
                               bufs[n].len);
866
27694
    CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
867
868
27694
    if (ret < 0)
869
4
      return ret;
870
871
27690
    total += ret;
872
  }
873
  // Send any data that was queued up while processing the received data.
874
27690
  if (!IsDestroyed()) {
875
27227
    SendPendingData();
876
  }
877
27690
  return total;
878
}
879
880
881
126525
inline int32_t GetFrameID(const nghttp2_frame* frame) {
882
  // If this is a push promise, we want to grab the id of the promised stream
883
126525
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
884
      frame->push_promise.promised_stream_id :
885
126525
      frame->hd.stream_id;
886
}
887
888
889
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
890
// callback to determine if a new stream is being created or if we are simply
891
// adding a new block of headers to an existing stream. The header pairs
892
// themselves are set in the OnHeaderCallback
893
21115
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
894
                                         const nghttp2_frame* frame,
895
                                         void* user_data) {
896
21115
  Http2Session* session = static_cast<Http2Session*>(user_data);
897
21115
  int32_t id = GetFrameID(frame);
898
  Debug(session, "beginning headers for stream %d", id);
899
900
21115
  Http2Stream* stream = session->FindStream(id);
901
  // The common case is that we're creating a new stream. The less likely
902
  // case is that we're receiving a set of trailers
903
21115
  if (LIKELY(stream == nullptr)) {
904

10595
    if (UNLIKELY(!session->CanAddStream() ||
905
                 Http2Stream::New(session, id, frame->headers.cat) ==
906
                     nullptr)) {
907
      // Too many concurrent streams being opened
908
      nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id,
909
1
                                NGHTTP2_ENHANCE_YOUR_CALM);
910
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
911
    }
912
10520
  } else if (!stream->IsDestroyed()) {
913
10520
    stream->StartHeaders(frame->headers.cat);
914
  }
915
21114
  return 0;
916
}
917
918
// Called by nghttp2 for each header name/value pair in a HEADERS block.
919
// This had to have been preceded by a call to OnBeginHeadersCallback so
920
// the Http2Stream is guaranteed to already exist.
921
63639
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
922
                                   const nghttp2_frame* frame,
923
                                   nghttp2_rcbuf* name,
924
                                   nghttp2_rcbuf* value,
925
                                   uint8_t flags,
926
                                   void* user_data) {
927
63639
  Http2Session* session = static_cast<Http2Session*>(user_data);
928
63639
  int32_t id = GetFrameID(frame);
929
63639
  Http2Stream* stream = session->FindStream(id);
930
  // If stream is null at this point, either something odd has happened
931
  // or the stream was closed locally while header processing was occurring.
932
  // either way, do not proceed and close the stream.
933
63639
  if (UNLIKELY(stream == nullptr))
934
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
935
936
  // If the stream has already been destroyed, ignore.
937

63639
  if (!stream->IsDestroyed() && !stream->AddHeader(name, value, flags)) {
938
    // This will only happen if the connected peer sends us more
939
    // than the allowed number of header items at any given time
940
2
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
941
2
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
942
  }
943
63637
  return 0;
944
}
945
946
947
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
948
// only a handful of frame types that we care about handling here.
949
77257
int Http2Session::OnFrameReceive(nghttp2_session* handle,
950
                                 const nghttp2_frame* frame,
951
                                 void* user_data) {
952
77257
  Http2Session* session = static_cast<Http2Session*>(user_data);
953
77257
  session->statistics_.frame_count++;
954
  Debug(session, "complete frame received: type: %d",
955
77257
        frame->hd.type);
956


77257
  switch (frame->hd.type) {
957
    case NGHTTP2_DATA:
958
20673
      session->HandleDataFrame(frame);
959
20673
      break;
960
    case NGHTTP2_PUSH_PROMISE:
961
      // Intentional fall-through, handled just like headers frames
962
    case NGHTTP2_HEADERS:
963
21078
      session->HandleHeadersFrame(frame);
964
21078
      break;
965
    case NGHTTP2_SETTINGS:
966
18265
      session->HandleSettingsFrame(frame);
967
18265
      break;
968
    case NGHTTP2_PRIORITY:
969
16
      session->HandlePriorityFrame(frame);
970
16
      break;
971
    case NGHTTP2_GOAWAY:
972
259
      session->HandleGoawayFrame(frame);
973
259
      break;
974
    case NGHTTP2_PING:
975
13876
      session->HandlePingFrame(frame);
976
13876
      break;
977
    case NGHTTP2_ALTSVC:
978
4
      session->HandleAltSvcFrame(frame);
979
4
      break;
980
    case NGHTTP2_ORIGIN:
981
5
      session->HandleOriginFrame(frame);
982
5
      break;
983
    default:
984
3081
      break;
985
  }
986
77257
  return 0;
987
}
988
989
38
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
990
                                 const nghttp2_frame* frame,
991
                                 int lib_error_code,
992
                                 void* user_data) {
993
38
  Http2Session* session = static_cast<Http2Session*>(user_data);
994
995
  Debug(session, "invalid frame received, code: %d", lib_error_code);
996
997
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
998

76
  if (nghttp2_is_fatal(lib_error_code) ||
999
38
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
1000
1
    Environment* env = session->env();
1001
1
    Isolate* isolate = env->isolate();
1002
1
    HandleScope scope(isolate);
1003
1
    Local<Context> context = env->context();
1004
    Context::Scope context_scope(context);
1005
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
1006
2
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1007
  }
1008
38
  return 0;
1009
}
1010
1011
// If nghttp2 is unable to send a queued up frame, it will call this callback
1012
// to let us know. If the failure occurred because we are in the process of
1013
// closing down the session or stream, we go ahead and ignore it. We don't
1014
// really care about those and there's nothing we can reasonably do about it
1015
// anyway. Other types of failures are reported up to JavaScript. This should
1016
// be exceedingly rare.
1017
61
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
1018
                                 const nghttp2_frame* frame,
1019
                                 int error_code,
1020
                                 void* user_data) {
1021
61
  Http2Session* session = static_cast<Http2Session*>(user_data);
1022
61
  Environment* env = session->env();
1023
  Debug(session, "frame type %d was not sent, code: %d",
1024
61
        frame->hd.type, error_code);
1025
1026
  // Do not report if the frame was not sent due to the session closing
1027

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

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

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

8
  switch (session->padding_strategy_) {
1184
    case PADDING_STRATEGY_NONE:
1185
      // Fall-through
1186
      break;
1187
    case PADDING_STRATEGY_MAX:
1188
      padding = session->OnMaxFrameSizePadding(padding, maxPayloadLen);
1189
      break;
1190
    case PADDING_STRATEGY_ALIGNED:
1191
4
      padding = session->OnDWordAlignedPadding(padding, maxPayloadLen);
1192
4
      break;
1193
    case PADDING_STRATEGY_CALLBACK:
1194
4
      padding = session->OnCallbackPadding(padding, maxPayloadLen);
1195
4
      break;
1196
  }
1197
8
  return padding;
1198
}
1199
1200
#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we "     \
1201
                         "expected SETTINGS frame.  Perhaps, peer does not "  \
1202
                         "support HTTP/2 properly."
1203
1204
// We use this currently to determine when an attempt is made to use the http2
1205
// protocol with a non-http2 peer.
1206
35
int Http2Session::OnNghttpError(nghttp2_session* handle,
1207
                                const char* message,
1208
                                size_t len,
1209
                                void* user_data) {
1210
  // Unfortunately, this is currently the only way for us to know if
1211
  // the session errored because the peer is not an http2 peer.
1212
35
  Http2Session* session = static_cast<Http2Session*>(user_data);
1213
  Debug(session, "Error '%.*s'", len, message);
1214
35
  if (strncmp(message, BAD_PEER_MESSAGE, len) == 0) {
1215
1
    Environment* env = session->env();
1216
1
    Isolate* isolate = env->isolate();
1217
1
    HandleScope scope(isolate);
1218
1
    Local<Context> context = env->context();
1219
    Context::Scope context_scope(context);
1220
1
    Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1221
2
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1222
  }
1223
35
  return 0;
1224
}
1225
1226
10227
uv_buf_t Http2StreamListener::OnStreamAlloc(size_t size) {
1227
  // See the comments in Http2Session::OnDataChunkReceived
1228
  // (which is the only possible call site for this method).
1229
10227
  return uv_buf_init(nullptr, size);
1230
}
1231
1232
20719
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1233
20719
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1234
20719
  Http2Session* session = stream->session();
1235
20719
  Environment* env = stream->env();
1236
20719
  HandleScope handle_scope(env->isolate());
1237
30946
  Context::Scope context_scope(env->context());
1238
1239
20719
  if (nread < 0) {
1240
10492
    PassReadErrorToPreviousListener(nread);
1241
31211
    return;
1242
  }
1243
1244
20454
  CHECK(!session->stream_buf_ab_.IsEmpty());
1245
1246
  // There is a single large array buffer for the entire data read from the
1247
  // network; create a slice of that array buffer and emit it as the
1248
  // received data buffer.
1249
10227
  size_t offset = buf.base - session->stream_buf_.base;
1250
1251
  // Verify that the data offset is inside the current read buffer.
1252
10227
  CHECK_LE(offset, session->stream_buf_.len);
1253
10227
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1254
1255
20454
  stream->CallJSOnreadMethod(nread, session->stream_buf_ab_, offset);
1256
}
1257
1258
1259
// Called by OnFrameReceived to notify JavaScript land that a complete
1260
// HEADERS frame has been received and processed. This method converts the
1261
// received headers into a JavaScript array and pushes those out to JS.
1262
21078
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1263
21078
  Isolate* isolate = env()->isolate();
1264
21078
  HandleScope scope(isolate);
1265
21078
  Local<Context> context = env()->context();
1266
21078
  Context::Scope context_scope(context);
1267
1268
21078
  int32_t id = GetFrameID(frame);
1269
21078
  Debug(this, "handle headers frame for stream %d", id);
1270
21078
  Http2Stream* stream = FindStream(id);
1271
1272
  // If the stream has already been destroyed, ignore.
1273
21078
  if (stream->IsDestroyed())
1274
21078
    return;
1275
1276
42156
  std::vector<nghttp2_header> headers(stream->move_headers());
1277
1278
  // The headers are passed in above as a queue of nghttp2_header structs.
1279
  // The following converts that into a JS array with the structure:
1280
  // [name1, value1, name2, value2, name3, value3, name3, value4] and so on.
1281
  // That array is passed up to the JS layer and converted into an Object form
1282
  // like {name1: value1, name2: value2, name3: [value3, value4]}. We do it
1283
  // this way for performance reasons (it's faster to generate and pass an
1284
  // array than it is to generate and pass the object).
1285
21078
  size_t headers_size = headers.size();
1286
42156
  std::vector<Local<Value>> headers_v(headers_size * 2);
1287
84606
  for (size_t i = 0; i < headers_size; ++i) {
1288
63528
    const nghttp2_header& item = headers[i];
1289
    // The header name and value are passed as external one-byte strings
1290
63528
    headers_v[i * 2] =
1291
127056
        ExternalHeader::New<true>(this, item.name).ToLocalChecked();
1292
63528
    headers_v[i * 2 + 1] =
1293
127056
        ExternalHeader::New<false>(this, item.value).ToLocalChecked();
1294
  }
1295
1296
  Local<Value> args[5] = {
1297
      stream->object(),
1298
      Integer::New(isolate, id),
1299
21078
      Integer::New(isolate, stream->headers_category()),
1300
      Integer::New(isolate, frame->hd.flags),
1301
147546
      Array::New(isolate, headers_v.data(), headers_size * 2)};
1302
  MakeCallback(env()->http2session_on_headers_function(),
1303
42156
               arraysize(args), args);
1304
}
1305
1306
1307
// Called by OnFrameReceived when a complete PRIORITY frame has been
1308
// received. Notifies JS land about the priority change. Note that priorities
1309
// are considered advisory only, so this has no real effect other than to
1310
// simply let user code know that the priority has changed.
1311
16
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
1312
16
  Isolate* isolate = env()->isolate();
1313
16
  HandleScope scope(isolate);
1314
16
  Local<Context> context = env()->context();
1315
  Context::Scope context_scope(context);
1316
1317
16
  nghttp2_priority priority_frame = frame->priority;
1318
16
  int32_t id = GetFrameID(frame);
1319
16
  Debug(this, "handle priority frame for stream %d", id);
1320
  // Priority frame stream ID should never be <= 0. nghttp2 handles this for us
1321
16
  nghttp2_priority_spec spec = priority_frame.pri_spec;
1322
1323
  Local<Value> argv[4] = {
1324
    Integer::New(isolate, id),
1325
    Integer::New(isolate, spec.stream_id),
1326
    Integer::New(isolate, spec.weight),
1327
    Boolean::New(isolate, spec.exclusive)
1328
80
  };
1329
  MakeCallback(env()->http2session_on_priority_function(),
1330
32
               arraysize(argv), argv);
1331
16
}
1332
1333
1334
// Called by OnFrameReceived when a complete DATA frame has been received.
1335
// If we know that this was the last DATA frame (because the END_STREAM flag
1336
// is set), then we'll terminate the readable side of the StreamBase.
1337
20673
void Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1338
20673
  int32_t id = GetFrameID(frame);
1339
20673
  Debug(this, "handling data frame for stream %d", id);
1340
20673
  Http2Stream* stream = FindStream(id);
1341
1342

20673
  if (!stream->IsDestroyed() && frame->hd.flags & NGHTTP2_FLAG_END_STREAM)
1343
10492
    stream->EmitRead(UV_EOF);
1344
20673
}
1345
1346
1347
// Called by OnFrameReceived when a complete GOAWAY frame has been received.
1348
259
void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
1349
259
  Isolate* isolate = env()->isolate();
1350
259
  HandleScope scope(isolate);
1351
259
  Local<Context> context = env()->context();
1352
  Context::Scope context_scope(context);
1353
1354
259
  nghttp2_goaway goaway_frame = frame->goaway;
1355
259
  Debug(this, "handling goaway frame");
1356
1357
  Local<Value> argv[3] = {
1358
    Integer::NewFromUnsigned(isolate, goaway_frame.error_code),
1359
    Integer::New(isolate, goaway_frame.last_stream_id),
1360
    Undefined(isolate)
1361
1036
  };
1362
1363
259
  size_t length = goaway_frame.opaque_data_len;
1364
259
  if (length > 0) {
1365
    argv[2] = Buffer::Copy(isolate,
1366
                           reinterpret_cast<char*>(goaway_frame.opaque_data),
1367
4
                           length).ToLocalChecked();
1368
  }
1369
1370
  MakeCallback(env()->http2session_on_goaway_data_function(),
1371
518
               arraysize(argv), argv);
1372
259
}
1373
1374
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
1375
4
void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
1376
4
  Isolate* isolate = env()->isolate();
1377
4
  HandleScope scope(isolate);
1378
4
  Local<Context> context = env()->context();
1379
  Context::Scope context_scope(context);
1380
1381
4
  int32_t id = GetFrameID(frame);
1382
1383
4
  nghttp2_extension ext = frame->ext;
1384
4
  nghttp2_ext_altsvc* altsvc = static_cast<nghttp2_ext_altsvc*>(ext.payload);
1385
4
  Debug(this, "handling altsvc frame");
1386
1387
  Local<Value> argv[3] = {
1388
    Integer::New(isolate, id),
1389
    String::NewFromOneByte(isolate,
1390
                           altsvc->origin,
1391
                           NewStringType::kNormal,
1392
4
                           altsvc->origin_len).ToLocalChecked(),
1393
    String::NewFromOneByte(isolate,
1394
                           altsvc->field_value,
1395
                           NewStringType::kNormal,
1396
4
                           altsvc->field_value_len).ToLocalChecked(),
1397
24
  };
1398
1399
  MakeCallback(env()->http2session_on_altsvc_function(),
1400
8
               arraysize(argv), argv);
1401
4
}
1402
1403
5
void Http2Session::HandleOriginFrame(const nghttp2_frame* frame) {
1404
5
  Isolate* isolate = env()->isolate();
1405
5
  HandleScope scope(isolate);
1406
5
  Local<Context> context = env()->context();
1407
  Context::Scope context_scope(context);
1408
1409
5
  Debug(this, "handling origin frame");
1410
1411
5
  nghttp2_extension ext = frame->ext;
1412
5
  nghttp2_ext_origin* origin = static_cast<nghttp2_ext_origin*>(ext.payload);
1413
1414
5
  size_t nov = origin->nov;
1415
10
  std::vector<Local<Value>> origin_v(nov);
1416
1417
14
  for (size_t i = 0; i < nov; ++i) {
1418
9
    const nghttp2_origin_entry& entry = origin->ov[i];
1419
9
    origin_v[i] =
1420
        String::NewFromOneByte(
1421
9
            isolate, entry.origin, NewStringType::kNormal, entry.origin_len)
1422
18
            .ToLocalChecked();
1423
  }
1424
5
  Local<Value> holder = Array::New(isolate, origin_v.data(), origin_v.size());
1425
10
  MakeCallback(env()->http2session_on_origin_function(), 1, &holder);
1426
5
}
1427
1428
// Called by OnFrameReceived when a complete PING frame has been received.
1429
13876
void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
1430
13876
  Isolate* isolate = env()->isolate();
1431
13876
  HandleScope scope(isolate);
1432
13876
  Local<Context> context = env()->context();
1433
13865
  Context::Scope context_scope(context);
1434
  Local<Value> arg;
1435
13876
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1436
13876
  if (ack) {
1437
11
    Http2Ping* ping = PopPing();
1438
1439
11
    if (ping == nullptr) {
1440
      // PING Ack is unsolicited. Treat as a connection error. The HTTP/2
1441
      // spec does not require this, but there is no legitimate reason to
1442
      // receive an unsolicited PING ack on a connection. Either the peer
1443
      // is buggy or malicious, and we're not going to tolerate such
1444
      // nonsense.
1445
2
      arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1446
1
      MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1447
1
      return;
1448
    }
1449
1450
10
    ping->Done(true, frame->ping.opaque_data);
1451
10
    return;
1452
  }
1453
1454
  // Notify the session that a ping occurred
1455
  arg = Buffer::Copy(env(),
1456
                      reinterpret_cast<const char*>(frame->ping.opaque_data),
1457
27730
                      8).ToLocalChecked();
1458
27730
  MakeCallback(env()->http2session_on_ping_function(), 1, &arg);
1459
}
1460
1461
// Called by OnFrameReceived when a complete SETTINGS frame has been received.
1462
18265
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
1463
18265
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1464
18265
  if (!ack) {
1465
    // This is not a SETTINGS acknowledgement, notify and return
1466
17795
    MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
1467
17795
    return;
1468
  }
1469
1470
  // If this is an acknowledgement, we should have an Http2Settings
1471
  // object for it.
1472
470
  Http2Settings* settings = PopSettings();
1473
470
  if (settings != nullptr) {
1474
470
    settings->Done(true);
1475
470
    return;
1476
  }
1477
  // SETTINGS Ack is unsolicited. Treat as a connection error. The HTTP/2
1478
  // spec does not require this, but there is no legitimate reason to
1479
  // receive an unsolicited SETTINGS ack on a connection. Either the peer
1480
  // is buggy or malicious, and we're not going to tolerate such
1481
  // nonsense.
1482
  // Note that nghttp2 currently prevents this from happening for SETTINGS
1483
  // frames, so this block is purely defensive just in case that behavior
1484
  // changes. Specifically, unlike unsolicited PING acks, unsolicited
1485
  // SETTINGS acks should *never* make it this far.
1486
  Isolate* isolate = env()->isolate();
1487
  HandleScope scope(isolate);
1488
  Local<Context> context = env()->context();
1489
  Context::Scope context_scope(context);
1490
  Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1491
  MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1492
}
1493
1494
// Callback used when data has been written to the stream.
1495
633
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
1496
633
  Debug(this, "write finished with status %d", status);
1497
1498
  // Inform all pending writes about their completion.
1499
633
  ClearOutgoing(status);
1500
1501
633
  if (!(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1502
    // Schedule a new write if nghttp2 wants to send data.
1503
409
    MaybeScheduleWrite();
1504
  }
1505
633
}
1506
1507
// If the underlying nghttp2_session struct has data pending in its outbound
1508
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1509
// on the next iteration of the Node.js event loop (using the SetImmediate
1510
// queue), but only if a write has not already been scheduled.
1511
28929
void Http2Session::MaybeScheduleWrite() {
1512
28929
  CHECK_EQ(flags_ & SESSION_STATE_WRITE_SCHEDULED, 0);
1513
28929
  if (UNLIKELY(session_ == nullptr))
1514
28929
    return;
1515
1516
28929
  if (nghttp2_session_want_write(session_)) {
1517
1540
    HandleScope handle_scope(env()->isolate());
1518
1540
    Debug(this, "scheduling write");
1519
1540
    flags_ |= SESSION_STATE_WRITE_SCHEDULED;
1520
4622
    env()->SetImmediate([](Environment* env, void* data) {
1521
1541
      Http2Session* session = static_cast<Http2Session*>(data);
1522

3082
      if (session->session_ == nullptr ||
1523
1541
          !(session->flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1524
        // This can happen e.g. when a stream was reset before this turn
1525
        // of the event loop, in which case SendPendingData() is called early,
1526
        // or the session was destroyed in the meantime.
1527
1831
        return;
1528
      }
1529
1530
      // Sending data may call arbitrary JS code, so keep track of
1531
      // async context.
1532
1251
      HandleScope handle_scope(env->isolate());
1533
2502
      InternalCallbackScope callback_scope(session);
1534
1251
      session->SendPendingData();
1535
5872
    }, static_cast<void*>(this), object());
1536
  }
1537
}
1538
1539
55361
void Http2Session::MaybeStopReading() {
1540
55361
  int want_read = nghttp2_session_want_read(session_);
1541
55361
  Debug(this, "wants read? %d", want_read);
1542
55361
  if (want_read == 0)
1543
963
    stream_->ReadStop();
1544
55361
}
1545
1546
// Unset the sending state, finish up all current writes, and reset
1547
// storage for data and metadata that was associated with these writes.
1548
28424
void Http2Session::ClearOutgoing(int status) {
1549
28424
  CHECK_NE(flags_ & SESSION_STATE_SENDING, 0);
1550
1551
28424
  flags_ &= ~SESSION_STATE_SENDING;
1552
1553
28424
  if (outgoing_buffers_.size() > 0) {
1554
27680
    outgoing_storage_.clear();
1555
1556
27680
    std::vector<nghttp2_stream_write> current_outgoing_buffers_;
1557
27680
    current_outgoing_buffers_.swap(outgoing_buffers_);
1558
113468
    for (const nghttp2_stream_write& wr : current_outgoing_buffers_) {
1559
85788
      WriteWrap* wrap = wr.req_wrap;
1560
85788
      if (wrap != nullptr) {
1561
        // TODO(addaleax): Pass `status` instead of 0, so that we actually error
1562
        // out with the error from the write to the underlying protocol,
1563
        // if one occurred.
1564
2571
        wrap->Done(0);
1565
      }
1566
27680
    }
1567
  }
1568
1569
  // Now that we've finished sending queued data, if there are any pending
1570
  // RstStreams we should try sending again and then flush them one by one.
1571
28424
  if (pending_rst_streams_.size() > 0) {
1572
4
    std::vector<int32_t> current_pending_rst_streams;
1573
4
    pending_rst_streams_.swap(current_pending_rst_streams);
1574
1575
4
    SendPendingData();
1576
1577
8
    for (int32_t stream_id : current_pending_rst_streams) {
1578
4
      Http2Stream* stream = FindStream(stream_id);
1579
4
      if (LIKELY(stream != nullptr))
1580
4
        stream->FlushRstStream();
1581
4
    }
1582
  }
1583
28424
}
1584
1585
// Queue a given block of data for sending. This always creates a copy,
1586
// so it is used for the cases in which nghttp2 requests sending of a
1587
// small chunk of data.
1588
58382
void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
1589
58382
  size_t offset = outgoing_storage_.size();
1590
58382
  outgoing_storage_.resize(offset + src_length);
1591
58382
  memcpy(&outgoing_storage_[offset], src, src_length);
1592
1593
  // Store with a base of `nullptr` initially, since future resizes
1594
  // of the outgoing_buffers_ vector may invalidate the pointer.
1595
  // The correct base pointers will be set later, before writing to the
1596
  // underlying socket.
1597
  outgoing_buffers_.emplace_back(nghttp2_stream_write {
1598
    uv_buf_init(nullptr, src_length)
1599
58382
  });
1600
58382
}
1601
1602
// Prompts nghttp2 to begin serializing it's pending data and pushes each
1603
// chunk out to the i/o socket to be sent. This is a particularly hot method
1604
// that will generally be called at least twice be event loop iteration.
1605
// This is a potential performance optimization target later.
1606
// Returns non-zero value if a write is already in progress.
1607
29107
uint8_t Http2Session::SendPendingData() {
1608
29107
  Debug(this, "sending pending data");
1609
  // Do not attempt to send data on the socket if the destroying flag has
1610
  // been set. That means everything is shutting down and the socket
1611
  // will not be usable.
1612
29107
  if (IsDestroyed())
1613
49
    return 0;
1614
29058
  flags_ &= ~SESSION_STATE_WRITE_SCHEDULED;
1615
1616
  // SendPendingData should not be called recursively.
1617
29058
  if (flags_ & SESSION_STATE_SENDING)
1618
631
    return 1;
1619
  // This is cleared by ClearOutgoing().
1620
28427
  flags_ |= SESSION_STATE_SENDING;
1621
1622
  ssize_t src_length;
1623
  const uint8_t* src;
1624
1625
28427
  CHECK_EQ(outgoing_buffers_.size(), 0);
1626
28427
  CHECK_EQ(outgoing_storage_.size(), 0);
1627
1628
  // Part One: Gather data from nghttp2
1629
1630
105031
  while ((src_length = nghttp2_session_mem_send(session_, &src)) > 0) {
1631
48177
    Debug(this, "nghttp2 has %d bytes to send", src_length);
1632
48177
    CopyDataIntoOutgoing(src, src_length);
1633
  }
1634
1635
28427
  CHECK_NE(src_length, NGHTTP2_ERR_NOMEM);
1636
1637
28427
  if (stream_ == nullptr) {
1638
    // It would seem nice to bail out earlier, but `nghttp2_session_mem_send()`
1639
    // does take care of things like closing the individual streams after
1640
    // a socket has been torn down, so we still need to call it.
1641
12
    ClearOutgoing(UV_ECANCELED);
1642
12
    return 0;
1643
  }
1644
1645
  // Part Two: Pass Data to the underlying stream
1646
1647
28415
  size_t count = outgoing_buffers_.size();
1648
28415
  if (count == 0) {
1649
744
    ClearOutgoing(0);
1650
744
    return 0;
1651
  }
1652
27671
  MaybeStackBuffer<uv_buf_t, 32> bufs;
1653
27671
  bufs.AllocateSufficientStorage(count);
1654
1655
  // Set the buffer base pointers for copied data that ended up in the
1656
  // sessions's own storage since it might have shifted around during gathering.
1657
  // (Those are marked by having .base == nullptr.)
1658
27671
  size_t offset = 0;
1659
27671
  size_t i = 0;
1660
113445
  for (const nghttp2_stream_write& write : outgoing_buffers_) {
1661
85774
    statistics_.data_sent += write.buf.len;
1662
85774
    if (write.buf.base == nullptr) {
1663
58363
      bufs[i++] = uv_buf_init(
1664
58363
          reinterpret_cast<char*>(outgoing_storage_.data() + offset),
1665
116726
          write.buf.len);
1666
58363
      offset += write.buf.len;
1667
    } else {
1668
27411
      bufs[i++] = write.buf;
1669
    }
1670
  }
1671
1672
27671
  chunks_sent_since_last_write_++;
1673
1674
27671
  StreamWriteResult res = underlying_stream()->Write(*bufs, count);
1675
27671
  if (!res.async) {
1676
27035
    ClearOutgoing(res.err);
1677
  }
1678
1679
27671
  MaybeStopReading();
1680
1681
27671
  return 0;
1682
}
1683
1684
1685
// This callback is called from nghttp2 when it wants to send DATA frames for a
1686
// given Http2Stream, when we set the `NGHTTP2_DATA_FLAG_NO_COPY` flag earlier
1687
// in the Http2Stream::Provider::Stream::OnRead callback.
1688
// We take the write information directly out of the stream's data queue.
1689
10203
int Http2Session::OnSendData(
1690
      nghttp2_session* session_,
1691
      nghttp2_frame* frame,
1692
      const uint8_t* framehd,
1693
      size_t length,
1694
      nghttp2_data_source* source,
1695
      void* user_data) {
1696
10203
  Http2Session* session = static_cast<Http2Session*>(user_data);
1697
10203
  Http2Stream* stream = GetStream(session, frame->hd.stream_id, source);
1698
1699
  // Send the frame header + a byte that indicates padding length.
1700
10203
  session->CopyDataIntoOutgoing(framehd, 9);
1701
10203
  if (frame->data.padlen > 0) {
1702
2
    uint8_t padding_byte = frame->data.padlen - 1;
1703
2
    CHECK_EQ(padding_byte, frame->data.padlen - 1);
1704
2
    session->CopyDataIntoOutgoing(&padding_byte, 1);
1705
  }
1706
1707
  Debug(session, "nghttp2 has %d bytes to send directly", length);
1708
40184
  while (length > 0) {
1709
    // nghttp2 thinks that there is data available (length > 0), which means
1710
    // we told it so, which means that we *should* have data available.
1711
27409
    CHECK(!stream->queue_.empty());
1712
1713
27409
    nghttp2_stream_write& write = stream->queue_.front();
1714
27409
    if (write.buf.len <= length) {
1715
      // This write does not suffice by itself, so we can consume it completely.
1716
19778
      length -= write.buf.len;
1717
19778
      session->outgoing_buffers_.emplace_back(std::move(write));
1718
19778
      stream->queue_.pop();
1719
19778
      continue;
1720
    }
1721
1722
    // Slice off `length` bytes of the first write in the queue.
1723
    session->outgoing_buffers_.emplace_back(nghttp2_stream_write {
1724
      uv_buf_init(write.buf.base, length)
1725
7631
    });
1726
7631
    write.buf.base += length;
1727
7631
    write.buf.len -= length;
1728
7631
    break;
1729
  }
1730
1731
10203
  if (frame->data.padlen > 0) {
1732
    // Send padding if that was requested.
1733
    session->outgoing_buffers_.emplace_back(nghttp2_stream_write {
1734
      uv_buf_init(const_cast<char*>(zero_bytes_256), frame->data.padlen - 1)
1735
2
    });
1736
  }
1737
1738
10203
  return 0;
1739
}
1740
1741
// Creates a new Http2Stream and submits a new http2 request.
1742
10589
Http2Stream* Http2Session::SubmitRequest(
1743
    nghttp2_priority_spec* prispec,
1744
    nghttp2_nv* nva,
1745
    size_t len,
1746
    int32_t* ret,
1747
    int options) {
1748
10589
  Debug(this, "submitting request");
1749
10589
  Http2Scope h2scope(this);
1750
10589
  Http2Stream* stream = nullptr;
1751
21178
  Http2Stream::Provider::Stream prov(options);
1752
10589
  *ret = nghttp2_submit_request(session_, prispec, nva, len, *prov, nullptr);
1753
10589
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
1754
10589
  if (LIKELY(*ret > 0))
1755
10588
    stream = Http2Stream::New(this, *ret, NGHTTP2_HCAT_HEADERS, options);
1756
21178
  return stream;
1757
}
1758
1759
27709
uv_buf_t Http2Session::OnStreamAlloc(size_t suggested_size) {
1760
27709
  return env()->AllocateManaged(suggested_size).release();
1761
}
1762
1763
// Callback used to receive inbound data from the i/o stream
1764
27717
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
1765
27717
  HandleScope handle_scope(env()->isolate());
1766
55407
  Context::Scope context_scope(env()->context());
1767
55407
  Http2Scope h2scope(this);
1768
27717
  CHECK_NOT_NULL(stream_);
1769
27717
  Debug(this, "receiving %d bytes", nread);
1770
55434
  CHECK(stream_buf_ab_.IsEmpty());
1771
55407
  AllocatedBuffer buf(env(), buf_);
1772
1773
  // Only pass data on if nread > 0
1774
27717
  if (nread <= 0) {
1775
23
    if (nread < 0) {
1776
23
      PassReadErrorToPreviousListener(nread);
1777
    }
1778
23
    return;
1779
  }
1780
1781
  // Shrink to the actual amount of used data.
1782
27694
  buf.Resize(nread);
1783
1784
27694
  IncrementCurrentSessionMemory(buf.size());
1785
27694
  OnScopeLeave on_scope_leave([&]() {
1786
    // Once finished handling this write, reset the stream buffer.
1787
    // The memory has either been free()d or was handed over to V8.
1788
27694
    DecrementCurrentSessionMemory(buf.size());
1789
55388
    stream_buf_ab_ = Local<ArrayBuffer>();
1790
27694
    stream_buf_ = uv_buf_init(nullptr, 0);
1791
83078
  });
1792
1793
  // Make sure that there was no read previously active.
1794
27694
  CHECK_NULL(stream_buf_.base);
1795
27694
  CHECK_EQ(stream_buf_.len, 0);
1796
1797
  // Remember the current buffer, so that OnDataChunkReceived knows the
1798
  // offset of a DATA frame's data into the socket read buffer.
1799
27694
  stream_buf_ = uv_buf_init(buf.data(), nread);
1800
1801
27694
  Isolate* isolate = env()->isolate();
1802
1803
  // Create an array buffer for the read data. DATA frames will be emitted
1804
  // as slices of this array buffer to avoid having to copy memory.
1805
27694
  stream_buf_ab_ = buf.ToArrayBuffer();
1806
1807
27694
  statistics_.data_received += nread;
1808
27694
  ssize_t ret = Write(&stream_buf_, 1);
1809
1810
27694
  if (UNLIKELY(ret < 0)) {
1811
4
    Debug(this, "fatal error receiving data: %d", ret);
1812
4
    Local<Value> arg = Integer::New(isolate, ret);
1813
4
    MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1814
4
    return;
1815
  }
1816
1817
55380
  MaybeStopReading();
1818
}
1819
1820
21182
bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
1821
24496
  for (const nghttp2_stream_write& wr : outgoing_buffers_) {
1822


3316
    if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream)
1823
2
      return true;
1824
  }
1825
21180
  return false;
1826
}
1827
1828
// Every Http2Session session is tightly bound to a single i/o StreamBase
1829
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1830
// tightly coupled with all data transfer between the two happening at the
1831
// C++ layer via the StreamBase API.
1832
559
void Http2Session::Consume(Local<Object> stream_obj) {
1833
559
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1834
559
  stream->PushStreamListener(this);
1835
559
  Debug(this, "i/o stream consumed");
1836
559
}
1837
1838
21190
Http2Stream* Http2Stream::New(Http2Session* session,
1839
                              int32_t id,
1840
                              nghttp2_headers_category category,
1841
                              int options) {
1842
  Local<Object> obj;
1843
42380
  if (!session->env()
1844
21190
           ->http2stream_constructor_template()
1845
84760
           ->NewInstance(session->env()->context())
1846
63570
           .ToLocal(&obj)) {
1847
    return nullptr;
1848
  }
1849
21190
  return new Http2Stream(session, obj, id, category, options);
1850
}
1851
1852
21190
Http2Stream::Http2Stream(Http2Session* session,
1853
                         Local<Object> obj,
1854
                         int32_t id,
1855
                         nghttp2_headers_category category,
1856
                         int options)
1857
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
1858
      StreamBase(session->env()),
1859
      session_(session),
1860
      id_(id),
1861
21190
      current_headers_category_(category) {
1862
21190
  MakeWeak();
1863
21190
  StreamBase::AttachToObject(GetObject());
1864
21190
  statistics_.start_time = uv_hrtime();
1865
1866
  // Limit the number of header pairs
1867
21190
  max_header_pairs_ = session->GetMaxHeaderPairs();
1868
21190
  if (max_header_pairs_ == 0) {
1869
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1870
  }
1871
21190
  current_headers_.reserve(max_header_pairs_);
1872
1873
  // Limit the number of header octets
1874
  max_header_length_ =
1875
      std::min(
1876
        nghttp2_session_get_local_settings(
1877
          session->session(),
1878
21190
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1879
42380
      MAX_MAX_HEADER_LIST_SIZE);
1880
1881
21190
  if (options & STREAM_OPTION_GET_TRAILERS)
1882
2
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1883
1884
21190
  PushStreamListener(&stream_listener_);
1885
1886
21190
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1887
419
    Shutdown();
1888
21190
  session->AddStream(this);
1889
21190
}
1890
1891
1892


63570
Http2Stream::~Http2Stream() {
1893
21299
  for (nghttp2_header& header : current_headers_) {
1894
109
    nghttp2_rcbuf_decref(header.name);
1895
109
    nghttp2_rcbuf_decref(header.value);
1896
  }
1897
1898
21190
  if (session_ == nullptr)
1899
    return;
1900
21190
  Debug(this, "tearing down stream");
1901
21190
  session_->RemoveStream(this);
1902
21190
  session_ = nullptr;
1903
42380
}
1904
1905
17
std::string Http2Stream::diagnostic_name() const {
1906
34
  return "HttpStream " + std::to_string(id()) + " (" +
1907
68
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
1908
51
      session()->diagnostic_name() + "]";
1909
}
1910
1911
// Notify the Http2Stream that a new block of HEADERS is being processed.
1912
10520
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
1913
10520
  Debug(this, "starting headers, category: %d", id_, category);
1914
10520
  CHECK(!this->IsDestroyed());
1915
10520
  current_headers_length_ = 0;
1916
10520
  current_headers_.clear();
1917
10520
  current_headers_category_ = category;
1918
10520
}
1919
1920
1921
11
nghttp2_stream* Http2Stream::operator*() {
1922
11
  return nghttp2_session_find_stream(**session_, id_);
1923
}
1924
1925
21117
void Http2Stream::Close(int32_t code) {
1926
21117
  CHECK(!this->IsDestroyed());
1927
21117
  flags_ |= NGHTTP2_STREAM_FLAG_CLOSED;
1928
21117
  code_ = code;
1929
21117
  Debug(this, "closed with code %d", code);
1930
21117
}
1931
1932
21519
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
1933
21519
  if (IsDestroyed())
1934
    return UV_EPIPE;
1935
1936
  {
1937
21519
    Http2Scope h2scope(this);
1938
21519
    flags_ |= NGHTTP2_STREAM_FLAG_SHUT;
1939
21519
    CHECK_NE(nghttp2_session_resume_data(**session_, id_),
1940
             NGHTTP2_ERR_NOMEM);
1941
43038
    Debug(this, "writable side shutdown");
1942
  }
1943
21519
  return 1;
1944
}
1945
1946
// Destroy the Http2Stream and render it unusable. Actual resources for the
1947
// Stream will not be freed until the next tick of the Node.js event loop
1948
// using the SetImmediate queue.
1949
21182
void Http2Stream::Destroy() {
1950
  // Do nothing if this stream instance is already destroyed
1951
21182
  if (IsDestroyed())
1952
21182
    return;
1953
21182
  if (session_->HasPendingRstStream(id_))
1954
3
    FlushRstStream();
1955
21182
  flags_ |= NGHTTP2_STREAM_FLAG_DESTROYED;
1956
1957
21182
  Debug(this, "destroying stream");
1958
1959
  // Wait until the start of the next loop to delete because there
1960
  // may still be some pending operations queued for this stream.
1961
63546
  env()->SetImmediate([](Environment* env, void* data) {
1962
21182
    Http2Stream* stream = static_cast<Http2Stream*>(data);
1963
    // Free any remaining outgoing data chunks here. This should be done
1964
    // here because it's possible for destroy to have been called while
1965
    // we still have queued outbound writes.
1966
42368
    while (!stream->queue_.empty()) {
1967
4
      nghttp2_stream_write& head = stream->queue_.front();
1968
4
      if (head.req_wrap != nullptr)
1969
4
        head.req_wrap->Done(UV_ECANCELED);
1970
4
      stream->queue_.pop();
1971
    }
1972
1973
    // We can destroy the stream now if there are no writes for it
1974
    // already on the socket. Otherwise, we'll wait for the garbage collector
1975
    // to take care of cleaning up.
1976

42364
    if (stream->session() == nullptr ||
1977
21182
        !stream->session()->HasWritesOnSocketForStream(stream))
1978
21180
      delete stream;
1979
84728
  }, this, this->object());
1980
1981
21182
  statistics_.end_time = uv_hrtime();
1982
  session_->statistics_.stream_average_duration =
1983
21182
      ((statistics_.end_time - statistics_.start_time) /
1984
42364
          session_->statistics_.stream_count) / 1e6;
1985
21182
  EmitStatistics();
1986
}
1987
1988
1989
// Initiates a response on the Http2Stream using data provided via the
1990
// StreamBase Streams API.
1991
10519
int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) {
1992
10519
  CHECK(!this->IsDestroyed());
1993
10519
  Http2Scope h2scope(this);
1994
10519
  Debug(this, "submitting response");
1995
10519
  if (options & STREAM_OPTION_GET_TRAILERS)
1996
162
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1997
1998
10519
  if (!IsWritable())
1999
8
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2000
2001
21038
  Http2Stream::Provider::Stream prov(this, options);
2002
10519
  int ret = nghttp2_submit_response(**session_, id_, nva, len, *prov);
2003
10519
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2004
21038
  return ret;
2005
}
2006
2007
2008
// Submit informational headers for a stream.
2009
5
int Http2Stream::SubmitInfo(nghttp2_nv* nva, size_t len) {
2010
5
  CHECK(!this->IsDestroyed());
2011
5
  Http2Scope h2scope(this);
2012
5
  Debug(this, "sending %d informational headers", len);
2013
  int ret = nghttp2_submit_headers(**session_,
2014
                                   NGHTTP2_FLAG_NONE,
2015
                                   id_, nullptr,
2016
5
                                   nva, len, nullptr);
2017
5
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2018
5
  return ret;
2019
}
2020
2021
31
void Http2Stream::OnTrailers() {
2022
31
  Debug(this, "let javascript know we are ready for trailers");
2023
31
  CHECK(!this->IsDestroyed());
2024
31
  Isolate* isolate = env()->isolate();
2025
31
  HandleScope scope(isolate);
2026
31
  Local<Context> context = env()->context();
2027
  Context::Scope context_scope(context);
2028
31
  flags_ &= ~NGHTTP2_STREAM_FLAG_TRAILERS;
2029
62
  MakeCallback(env()->http2session_on_stream_trailers_function(), 0, nullptr);
2030
31
}
2031
2032
// Submit informational headers for a stream.
2033
29
int Http2Stream::SubmitTrailers(nghttp2_nv* nva, size_t len) {
2034
29
  CHECK(!this->IsDestroyed());
2035
29
  Http2Scope h2scope(this);
2036
29
  Debug(this, "sending %d trailers", len);
2037
  int ret;
2038
  // Sending an empty trailers frame poses problems in Safari, Edge & IE.
2039
  // Instead we can just send an empty data frame with NGHTTP2_FLAG_END_STREAM
2040
  // to indicate that the stream is ready to be closed.
2041
29
  if (len == 0) {
2042
24
    Http2Stream::Provider::Stream prov(this, 0);
2043
24
    ret = nghttp2_submit_data(**session_, NGHTTP2_FLAG_END_STREAM, id_, *prov);
2044
  } else {
2045
5
    ret = nghttp2_submit_trailer(**session_, id_, nva, len);
2046
  }
2047
29
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2048
29
  return ret;
2049
}
2050
2051
// Submit a PRIORITY frame to the connected peer.
2052
6
int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec,
2053
                                bool silent) {
2054
6
  CHECK(!this->IsDestroyed());
2055
6
  Http2Scope h2scope(this);
2056
6
  Debug(this, "sending priority spec");
2057
  int ret = silent ?
2058
      nghttp2_session_change_stream_priority(**session_,
2059
                                             id_, prispec) :
2060
      nghttp2_submit_priority(**session_,
2061
                              NGHTTP2_FLAG_NONE,
2062
6
                              id_, prispec);
2063
6
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2064
6
  return ret;
2065
}
2066
2067
// Closes the Http2Stream by submitting an RST_STREAM frame to the connected
2068
// peer.
2069
121
void Http2Stream::SubmitRstStream(const uint32_t code) {
2070
121
  CHECK(!this->IsDestroyed());
2071
121
  code_ = code;
2072
  // If possible, force a purge of any currently pending data here to make sure
2073
  // it is sent before closing the stream. If it returns non-zero then we need
2074
  // to wait until the current write finishes and try again to avoid nghttp2
2075
  // behaviour where it prioritizes RstStream over everything else.
2076
121
  if (session_->SendPendingData() != 0) {
2077
4
    session_->AddPendingRstStream(id_);
2078
125
    return;
2079
  }
2080
2081
117
  FlushRstStream();
2082
}
2083
2084
124
void Http2Stream::FlushRstStream() {
2085
124
  if (IsDestroyed())
2086
150
    return;
2087
98
  Http2Scope h2scope(this);
2088
98
  CHECK_EQ(nghttp2_submit_rst_stream(**session_, NGHTTP2_FLAG_NONE,
2089
98
                                     id_, code_), 0);
2090
}
2091
2092
2093
// Submit a push promise and create the associated Http2Stream if successful.
2094
8
Http2Stream* Http2Stream::SubmitPushPromise(nghttp2_nv* nva,
2095
                                            size_t len,
2096
                                            int32_t* ret,
2097
                                            int options) {
2098
8
  CHECK(!this->IsDestroyed());
2099
8
  Http2Scope h2scope(this);
2100
8
  Debug(this, "sending push promise");
2101
  *ret = nghttp2_submit_push_promise(**session_, NGHTTP2_FLAG_NONE,
2102
8
                                     id_, nva, len, nullptr);
2103
8
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
2104
8
  Http2Stream* stream = nullptr;
2105
8
  if (*ret > 0)
2106
8
    stream = Http2Stream::New(session_, *ret, NGHTTP2_HCAT_HEADERS, options);
2107
2108
8
  return stream;
2109
}
2110
2111
// Switch the StreamBase into flowing mode to begin pushing chunks of data
2112
// out to JS land.
2113
20808
int Http2Stream::ReadStart() {
2114
20808
  Http2Scope h2scope(this);
2115
20808
  CHECK(!this->IsDestroyed());
2116
20808
  flags_ |= NGHTTP2_STREAM_FLAG_READ_START;
2117
20808
  flags_ &= ~NGHTTP2_STREAM_FLAG_READ_PAUSED;
2118
2119
20808
  Debug(this, "reading starting");
2120
2121
  // Tell nghttp2 about our consumption of the data that was handed
2122
  // off to JS land.
2123
  nghttp2_session_consume_stream(**session_,
2124
                                 id_,
2125
20808
                                 inbound_consumed_data_while_paused_);
2126
20808
  inbound_consumed_data_while_paused_ = 0;
2127
2128
20808
  return 0;
2129
}
2130
2131
// Switch the StreamBase into paused mode.
2132
111
int Http2Stream::ReadStop() {
2133
111
  CHECK(!this->IsDestroyed());
2134
111
  if (!IsReading())
2135
71
    return 0;
2136
40
  flags_ |= NGHTTP2_STREAM_FLAG_READ_PAUSED;
2137
40
  Debug(this, "reading stopped");
2138
40
  return 0;
2139
}
2140
2141
// The Http2Stream class is a subclass of StreamBase. The DoWrite method
2142
// receives outbound chunks of data to send as outbound DATA frames. These
2143
// are queued in an internal linked list of uv_buf_t structs that are sent
2144
// when nghttp2 is ready to serialize the data frame.
2145
//
2146
// Queue the given set of uv_but_t handles for writing to an
2147
// nghttp2_stream. The WriteWrap's Done callback will be invoked once the
2148
// chunks of data have been flushed to the underlying nghttp2_session.
2149
// Note that this does *not* mean that the data has been flushed
2150
// to the socket yet.
2151
2581
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2152
                         uv_buf_t* bufs,
2153
                         size_t nbufs,
2154
                         uv_stream_t* send_handle) {
2155
2581
  CHECK_NULL(send_handle);
2156
2581
  Http2Scope h2scope(this);
2157

2581
  if (!IsWritable() || IsDestroyed()) {
2158
    req_wrap->Done(UV_EOF);
2159
    return 0;
2160
  }
2161
2581
  Debug(this, "queuing %d buffers to send", id_, nbufs);
2162
22370
  for (size_t i = 0; i < nbufs; ++i) {
2163
    // Store the req_wrap on the last write info in the queue, so that it is
2164
    // only marked as finished once all buffers associated with it are finished.
2165
    queue_.emplace(nghttp2_stream_write {
2166
19789
      i == nbufs - 1 ? req_wrap : nullptr,
2167
      bufs[i]
2168
19789
    });
2169
19789
    IncrementAvailableOutboundLength(bufs[i].len);
2170
  }
2171
2581
  CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM);
2172
2581
  return 0;
2173
}
2174
2175
// Ads a header to the Http2Stream. Note that the header name and value are
2176
// provided using a buffer structure provided by nghttp2 that allows us to
2177
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2178
// is incremented here and are decremented when the header name and values
2179
// are garbage collected later.
2180
63639
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2181
                            nghttp2_rcbuf* value,
2182
                            uint8_t flags) {
2183
63639
  CHECK(!this->IsDestroyed());
2184
63639
  if (this->statistics_.first_header == 0)
2185
21096
    this->statistics_.first_header = uv_hrtime();
2186
63639
  size_t length = nghttp2_rcbuf_get_buf(name).len +
2187
63639
                  nghttp2_rcbuf_get_buf(value).len + 32;
2188
  // A header can only be added if we have not exceeded the maximum number
2189
  // of headers and the session has memory available for it.
2190

190917
  if (!session_->IsAvailableSessionMemory(length) ||
2191

127277
      current_headers_.size() == max_header_pairs_ ||
2192
63638
      current_headers_length_ + length > max_header_length_) {
2193
2
    return false;
2194
  }
2195
63637
  nghttp2_header header;
2196
63637
  header.name = name;
2197
63637
  header.value = value;
2198
63637
  header.flags = flags;
2199
63637
  current_headers_.push_back(header);
2200
63637
  nghttp2_rcbuf_incref(name);
2201
63637
  nghttp2_rcbuf_incref(value);
2202
63637
  current_headers_length_ += length;
2203
63637
  return true;
2204
}
2205
2206
// A Provider is the thing that provides outbound DATA frame data.
2207
10543
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2208
10543
  CHECK(!stream->IsDestroyed());
2209
10543
  provider_.source.ptr = stream;
2210
10543
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2211
10543
}
2212
2213
10589
Http2Stream::Provider::Provider(int options) {
2214
10589
  provider_.source.ptr = nullptr;
2215
10589
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2216
10589
}
2217
2218
21132
Http2Stream::Provider::~Provider() {
2219
21132
  provider_.source.ptr = nullptr;
2220
21132
}
2221
2222
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2223
// built via the StreamBase API and the Streams js API.
2224
10589
Http2Stream::Provider::Stream::Stream(int options)
2225
10589
    : Http2Stream::Provider(options) {
2226
10589
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2227
10589
}
2228
2229
10543
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2230
10543
    : Http2Stream::Provider(stream, options) {
2231
10543
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2232
10543
}
2233
2234
23351
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2235
                                              int32_t id,
2236
                                              uint8_t* buf,
2237
                                              size_t length,
2238
                                              uint32_t* flags,
2239
                                              nghttp2_data_source* source,
2240
                                              void* user_data) {
2241
23351
  Http2Session* session = static_cast<Http2Session*>(user_data);
2242
  Debug(session, "reading outbound data for stream %d", id);
2243
23351
  Http2Stream* stream = GetStream(session, id, source);
2244
23351
  if (stream->statistics_.first_byte_sent == 0)
2245
10551
    stream->statistics_.first_byte_sent = uv_hrtime();
2246
23351
  CHECK_EQ(id, stream->id());
2247
2248
23351
  size_t amount = 0;          // amount of data being sent in this data frame.
2249
2250
  // Remove all empty chunks from the head of the queue.
2251
  // This is done here so that .write('', cb) is still a meaningful way to
2252
  // find out when the HTTP2 stream wants to consume data, and because the
2253
  // StreamBase API allows empty input chunks.
2254

46706
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2255
4
    WriteWrap* finished = stream->queue_.front().req_wrap;
2256
4
    stream->queue_.pop();
2257
4
    if (finished != nullptr)
2258
2
      finished->Done(0);
2259
  }
2260
2261
23351
  if (!stream->queue_.empty()) {
2262
    Debug(session, "stream %d has pending outbound data", id);
2263
10203
    amount = std::min(stream->available_outbound_length_, length);
2264
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2265
10203
    if (amount > 0) {
2266
      // Just return the length, let Http2Session::OnSendData take care of
2267
      // actually taking the buffers out of the queue.
2268
10203
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2269
10203
      stream->DecrementAvailableOutboundLength(amount);
2270
    }
2271
  }
2272
2273

23351
  if (amount == 0 && stream->IsWritable()) {
2274
2608
    CHECK(stream->queue_.empty());
2275
    Debug(session, "deferring stream %d", id);
2276
2608
    stream->EmitWantsWrite(length);
2277

2608
    if (stream->available_outbound_length_ > 0 || !stream->IsWritable()) {
2278
      // EmitWantsWrite() did something interesting synchronously, restart:
2279
      return OnRead(handle, id, buf, length, flags, source, user_data);
2280
    }
2281
2608
    return NGHTTP2_ERR_DEFERRED;
2282
  }
2283
2284

20743
  if (stream->queue_.empty() && !stream->IsWritable()) {
2285
    Debug(session, "no more data for stream %d", id);
2286
10540
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2287
10540
    if (stream->HasTrailers()) {
2288
31
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2289
31
      stream->OnTrailers();
2290
    }
2291
  }
2292
2293
20743
  stream->statistics_.sent_bytes += amount;
2294
20743
  return amount;
2295
}
2296
2297
19789
inline void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2298
19789
  available_outbound_length_ += amount;
2299
19789
  session_->IncrementCurrentSessionMemory(amount);
2300
19789
}
2301
2302
10203
inline void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2303
10203
  available_outbound_length_ -= amount;
2304
10203
  session_->DecrementCurrentSessionMemory(amount);
2305
10203
}
2306
2307
2308
// Implementation of the JavaScript API
2309
2310
// Fetches the string description of a nghttp2 error code and passes that
2311
// back to JS land
2312
52
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2313
52
  Environment* env = Environment::GetCurrent(args);
2314
208
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2315
  args.GetReturnValue().Set(
2316
      String::NewFromOneByte(
2317
          env->isolate(),
2318
52
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val)),
2319
156
          NewStringType::kInternalized).ToLocalChecked());
2320
52
}
2321
2322
2323
// Serializes the settings object into a Buffer instance that
2324
// would be suitable, for instance, for creating the Base64
2325
// output for an HTTP2-Settings header field.
2326
15
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2327
15
  Environment* env = Environment::GetCurrent(args);
2328
  // TODO(addaleax): We should not be creating a full AsyncWrap for this.
2329
  Local<Object> obj;
2330
30
  if (!env->http2settings_constructor_template()
2331
45
           ->NewInstance(env->context())
2332
45
           .ToLocal(&obj)) {
2333
15
    return;
2334
  }
2335
15
  Http2Session::Http2Settings settings(env, nullptr, obj);
2336
45
  args.GetReturnValue().Set(settings.Pack());
2337
}
2338
2339
// A TypedArray instance is shared between C++ and JS land to contain the
2340
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2341
// default values.
2342
3
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2343
3
  Environment* env = Environment::GetCurrent(args);
2344
3
  Http2Session::Http2Settings::RefreshDefaults(env);
2345
3
}
2346
2347
// Sets the next stream ID the Http2Session. If successful, returns true.
2348
1
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2349
1
  Environment* env = Environment::GetCurrent(args);
2350
  Http2Session* session;
2351
1
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2352
4
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2353
1
  if (nghttp2_session_set_next_stream_id(**session, id) < 0) {
2354
    Debug(session, "failed to set next stream id to %d", id);
2355
    return args.GetReturnValue().Set(false);
2356
  }
2357
2
  args.GetReturnValue().Set(true);
2358
1
  Debug(session, "set next stream id to %d", id);
2359
}
2360
2361
// A TypedArray instance is shared between C++ and JS land to contain the
2362
// SETTINGS (either remote or local). RefreshSettings updates the current
2363
// values established for each of the settings so those can be read in JS land.
2364
template <get_setting fn>
2365
18263
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2366
18263
  Environment* env = Environment::GetCurrent(args);
2367
  Http2Session* session;
2368

36526
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2369
18263
  Http2Settings::Update(env, session, fn);
2370
18263
  Debug(session, "settings refreshed for session");
2371
}
2372
2373
// A TypedArray instance is shared between C++ and JS land to contain state
2374
// information of the current Http2Session. This updates the values in the
2375
// TypedArray so those can be read in JS land.
2376
3
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2377
3
  Environment* env = Environment::GetCurrent(args);
2378
  Http2Session* session;
2379
6
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2380
3
  Debug(session, "refreshing state");
2381
2382
3
  AliasedFloat64Array& buffer = env->http2_state()->session_state_buffer;
2383
2384
3
  nghttp2_session* s = **session;
2385
2386
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2387
6
      nghttp2_session_get_effective_local_window_size(s);
2388
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2389
6
      nghttp2_session_get_effective_recv_data_length(s);
2390
6
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2391
6
      nghttp2_session_get_next_stream_id(s);
2392
6
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2393
6
      nghttp2_session_get_local_window_size(s);
2394
6
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2395
6
      nghttp2_session_get_last_proc_stream_id(s);
2396
6
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2397
6
      nghttp2_session_get_remote_window_size(s);
2398
6
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2399
6
      nghttp2_session_get_outbound_queue_size(s);
2400
6
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2401
6
      nghttp2_session_get_hd_deflate_dynamic_table_size(s);
2402
6
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2403
6
      nghttp2_session_get_hd_inflate_dynamic_table_size(s);
2404
}
2405
2406
2407
// Constructor for new Http2Session instances.
2408
559
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2409
559
  Environment* env = Environment::GetCurrent(args);
2410
559
  CHECK(args.IsConstructCall());
2411
2236
  int val = args[0]->IntegerValue(env->context()).ToChecked();
2412
559
  nghttp2_session_type type = static_cast<nghttp2_session_type>(val);
2413
559
  Http2Session* session = new Http2Session(env, args.This(), type);
2414
559
  session->get_async_id();  // avoid compiler warning
2415
  Debug(session, "session created");
2416
559
}
2417
2418
2419
// Binds the Http2Session with a StreamBase used for i/o
2420
559
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2421
  Http2Session* session;
2422
1118
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2423
1118
  CHECK(args[0]->IsObject());
2424
1118
  session->Consume(args[0].As<Object>());
2425
}
2426
2427
// Destroys the Http2Session instance and renders it unusable
2428
533
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2429
  Http2Session* session;
2430
1066
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2431
533
  Debug(session, "destroying session");
2432
533
  Environment* env = Environment::GetCurrent(args);
2433
533
  Local<Context> context = env->context();
2434
2435
1599
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2436
1599
  bool socketDestroyed = args[1]->BooleanValue(env->isolate());
2437
2438
533
  session->Close(code, socketDestroyed);
2439
}
2440
2441
// Submits a new request on the Http2Session and returns either an error code
2442
// or the Http2Stream object.
2443
10589
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2444
  Http2Session* session;
2445
10590
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2446
10589
  Environment* env = session->env();
2447
10589
  Local<Context> context = env->context();
2448
10589
  Isolate* isolate = env->isolate();
2449
2450
21178
  Local<Array> headers = args[0].As<Array>();
2451
31767
  int options = args[1]->IntegerValue(context).ToChecked();
2452
10589
  Http2Priority priority(env, args[2], args[3], args[4]);
2453
2454
10589
  Headers list(isolate, context, headers);
2455
2456
10589
  Debug(session, "request submitted");
2457
2458
10589
  int32_t ret = 0;
2459
  Http2Stream* stream =
2460
      session->Http2Session::SubmitRequest(*priority, *list, list.length(),
2461
10589
                                           &ret, options);
2462
2463

10589
  if (ret <= 0 || stream == nullptr) {
2464
2
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2465
3
    return args.GetReturnValue().Set(ret);
2466
  }
2467
2468
21176
  Debug(session, "request submitted, new stream id %d", stream->id());
2469
31764
  args.GetReturnValue().Set(stream->object());
2470
}
2471
2472
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2473
// of shutting down. Note that this function does not actually alter the
2474
// state of the Http2Session, it's simply a notification.
2475
487
void Http2Session::Goaway(uint32_t code,
2476
                          int32_t lastStreamID,
2477
                          const uint8_t* data,
2478
                          size_t len) {
2479
487
  if (IsDestroyed())
2480
487
    return;
2481
2482
487
  Http2Scope h2scope(this);
2483
  // the last proc stream id is the most recently created Http2Stream.
2484
487
  if (lastStreamID <= 0)
2485
487
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_);
2486
487
  Debug(this, "submitting goaway");
2487
  nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE,
2488
487
                        lastStreamID, code, data, len);
2489
}
2490
2491
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2492
// of shutting down. The opaque data argument is an optional TypedArray that
2493
// can be used to send debugging data to the connected peer.
2494
487
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2495
487
  Environment* env = Environment::GetCurrent(args);
2496
487
  Local<Context> context = env->context();
2497
  Http2Session* session;
2498
974
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2499
2500
1461
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2501
1461
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2502
487
  ArrayBufferViewContents<uint8_t> opaque_data;
2503
2504
974
  if (args[2]->IsArrayBufferView()) {
2505
2
    opaque_data.Read(args[2].As<ArrayBufferView>());
2506
  }
2507
2508
487
  session->Goaway(code, lastStreamID, opaque_data.data(), opaque_data.length());
2509
}
2510
2511
// Update accounting of data chunks. This is used primarily to manage timeout
2512
// logic when using the FD Provider.
2513
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2514
10
  Environment* env = Environment::GetCurrent(args);
2515
10
  Isolate* isolate = env->isolate();
2516
10
  HandleScope scope(isolate);
2517
  Http2Session* session;
2518
20
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2519
2520
10
  uint32_t length = session->chunks_sent_since_last_write_;
2521
2522
10
  session->object()->Set(env->context(),
2523
                         env->chunks_sent_since_last_write_string(),
2524
60
                         Integer::NewFromUnsigned(isolate, length)).Check();
2525
2526
20
  args.GetReturnValue().Set(length);
2527
}
2528
2529
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2530
// this *WILL* alter the state of the stream, causing the OnStreamClose
2531
// callback to the triggered.
2532
119
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2533
119
  Environment* env = Environment::GetCurrent(args);
2534
119
  Local<Context> context = env->context();
2535
  Http2Stream* stream;
2536
238
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2537
357
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2538
119
  Debug(stream, "sending rst_stream with code %d", code);
2539
119
  stream->SubmitRstStream(code);
2540
}
2541
2542
// Initiates a response on the Http2Stream using the StreamBase API to provide
2543
// outbound DATA frames.
2544
10519
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2545
10519
  Environment* env = Environment::GetCurrent(args);
2546
10519
  Local<Context> context = env->context();
2547
10519
  Isolate* isolate = env->isolate();
2548
  Http2Stream* stream;
2549
21038
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2550
2551
21038
  Local<Array> headers = args[0].As<Array>();
2552
31557
  int options = args[1]->IntegerValue(context).ToChecked();
2553
2554
10519
  Headers list(isolate, context, headers);
2555
2556
  args.GetReturnValue().Set(
2557
31557
      stream->SubmitResponse(*list, list.length(), options));
2558
21038
  Debug(stream, "response submitted");
2559
}
2560
2561
2562
// Submits informational headers on the Http2Stream
2563
5
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2564
5
  Environment* env = Environment::GetCurrent(args);
2565
5
  Local<Context> context = env->context();
2566
5
  Isolate* isolate = env->isolate();
2567
  Http2Stream* stream;
2568
10
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2569
2570
10
  Local<Array> headers = args[0].As<Array>();
2571
2572
5
  Headers list(isolate, context, headers);
2573
15
  args.GetReturnValue().Set(stream->SubmitInfo(*list, list.length()));
2574
10
  Debug(stream, "%d informational headers sent", list.length());
2575
}
2576
2577
// Submits trailing headers on the Http2Stream
2578
29
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2579
29
  Environment* env = Environment::GetCurrent(args);
2580
29
  Local<Context> context = env->context();
2581
29
  Isolate* isolate = env->isolate();
2582
  Http2Stream* stream;
2583
58
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2584
2585
58
  Local<Array> headers = args[0].As<Array>();
2586
2587
29
  Headers list(isolate, context, headers);
2588
87
  args.GetReturnValue().Set(stream->SubmitTrailers(*list, list.length()));
2589
58
  Debug(stream, "%d trailing headers sent", list.length());
2590
}
2591
2592
// Grab the numeric id of the Http2Stream
2593
10596
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2594
  Http2Stream* stream;
2595
21192
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2596
31788
  args.GetReturnValue().Set(stream->id());
2597
}
2598
2599
// Destroy the Http2Stream, rendering it no longer usable
2600
21146
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2601
  Http2Stream* stream;
2602
42292
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2603
21146
  Debug(stream, "destroying stream");
2604
21146
  stream->Destroy();
2605
}
2606
2607
// Prompt the Http2Stream to begin sending data to the JS land.
2608
void Http2Stream::FlushData(const FunctionCallbackInfo<Value>& args) {
2609
  Http2Stream* stream;
2610
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2611
  stream->ReadStart();
2612
  Debug(stream, "data flushed to js");
2613
}
2614
2615
// Initiate a Push Promise and create the associated Http2Stream
2616
8
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2617
8
  Environment* env = Environment::GetCurrent(args);
2618
8
  Local<Context> context = env->context();
2619
8
  Isolate* isolate = env->isolate();
2620
  Http2Stream* parent;
2621
8
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2622
2623
16
  Local<Array> headers = args[0].As<Array>();
2624
24
  int options = args[1]->IntegerValue(context).ToChecked();
2625
2626
8
  Headers list(isolate, context, headers);
2627
2628
8
  Debug(parent, "creating push promise");
2629
2630
8
  int32_t ret = 0;
2631
  Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(),
2632
8
                                                  &ret, options);
2633

8
  if (ret <= 0 || stream == nullptr) {
2634
    Debug(parent, "failed to create push stream: %d", ret);
2635
    return args.GetReturnValue().Set(ret);
2636
  }
2637
16
  Debug(parent, "push stream %d created", stream->id());
2638
24
  args.GetReturnValue().Set(stream->object());
2639
}
2640
2641
// Send a PRIORITY frame
2642
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2643
6
  Environment* env = Environment::GetCurrent(args);
2644
  Http2Stream* stream;
2645
12
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2646
2647
6
  Http2Priority priority(env, args[0], args[1], args[2]);
2648
18
  bool silent = args[3]->BooleanValue(env->isolate());
2649
2650
6
  CHECK_EQ(stream->SubmitPriority(*priority, silent), 0);
2651
6
  Debug(stream, "priority submitted");
2652
}
2653
2654
// A TypedArray shared by C++ and JS land is used to communicate state
2655
// information about the Http2Stream. This updates the values in that
2656
// TypedArray so that the state can be read by JS.
2657
11
void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
2658
11
  Environment* env = Environment::GetCurrent(args);
2659
  Http2Stream* stream;
2660
22
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2661
2662
11
  Debug(stream, "refreshing state");
2663
2664
11
  AliasedFloat64Array& buffer = env->http2_state()->stream_state_buffer;
2665
2666
11
  nghttp2_stream* str = **stream;
2667
11
  nghttp2_session* s = **(stream->session());
2668
2669
11
  if (str == nullptr) {
2670
1
    buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE;
2671
2
    buffer[IDX_STREAM_STATE_WEIGHT] =
2672
2
        buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2673
2
        buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2674
2
        buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2675
3
        buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0;
2676
  } else {
2677
20
    buffer[IDX_STREAM_STATE] =
2678
20
        nghttp2_stream_get_state(str);
2679
20
    buffer[IDX_STREAM_STATE_WEIGHT] =
2680
20
        nghttp2_stream_get_weight(str);
2681
20
    buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2682
20
        nghttp2_stream_get_sum_dependency_weight(str);
2683
20
    buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2684
20
        nghttp2_session_get_stream_local_close(s, stream->id());
2685
20
    buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2686
20
        nghttp2_session_get_stream_remote_close(s, stream->id());
2687
20
    buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] =
2688
20
        nghttp2_session_get_stream_local_window_size(s, stream->id());
2689
  }
2690
}
2691
2692
5
void Http2Session::AltSvc(int32_t id,
2693
                          uint8_t* origin,
2694
                          size_t origin_len,
2695
                          uint8_t* value,
2696
                          size_t value_len) {
2697
5
  Http2Scope h2scope(this);
2698
5
  CHECK_EQ(nghttp2_submit_altsvc(session_, NGHTTP2_FLAG_NONE, id,
2699
5
                                 origin, origin_len, value, value_len), 0);
2700
5
}
2701
2702
5
void Http2Session::Origin(nghttp2_origin_entry* ov, size_t count) {
2703
5
  Http2Scope h2scope(this);
2704
5
  CHECK_EQ(nghttp2_submit_origin(session_, NGHTTP2_FLAG_NONE, ov, count), 0);
2705
5
}
2706
2707
// Submits an AltSvc frame to be sent to the connected peer.
2708
5
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2709
5
  Environment* env = Environment::GetCurrent(args);
2710
  Http2Session* session;
2711
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2712
2713
20
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2714
2715
  // origin and value are both required to be ASCII, handle them as such.
2716
20
  Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2717
20
  Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2718
2719
5
  size_t origin_len = origin_str->Length();
2720
5
  size_t value_len = value_str->Length();
2721
2722
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2723
  // Verify that origin len != 0 if stream id == 0, or
2724
  // that origin len == 0 if stream id != 0
2725


5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2726
2727
5
  MaybeStackBuffer<uint8_t> origin(origin_len);
2728
10
  MaybeStackBuffer<uint8_t> value(value_len);
2729
10
  origin_str->WriteOneByte(env->isolate(), *origin);
2730
10
  value_str->WriteOneByte(env->isolate(), *value);
2731
2732
10
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2733
}
2734
2735
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2736
5
  Environment* env = Environment::GetCurrent(args);
2737
5
  Local<Context> context = env->context();
2738
  Http2Session* session;
2739
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2740
2741
10
  Local<String> origin_string = args[0].As<String>();
2742
15
  int count = args[1]->IntegerValue(context).ToChecked();
2743
2744
2745
  Origins origins(env->isolate(),
2746
                  env->context(),
2747
                  origin_string,
2748
5
                  count);
2749
2750
5
  session->Origin(*origins, origins.length());
2751
}
2752
2753
// Submits a PING frame to be sent to the connected peer.
2754
12
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2755
12
  Environment* env = Environment::GetCurrent(args);
2756
  Http2Session* session;
2757
14
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2758
2759
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2760
  // then the current hrtime will be used as the payload.
2761
12
  ArrayBufferViewContents<uint8_t, 8> payload;
2762
24
  if (args[0]->IsArrayBufferView()) {
2763
12
    payload.Read(args[0].As<ArrayBufferView>());
2764
6
    CHECK_EQ(payload.length(), 8);
2765
  }
2766
2767
  Local<Object> obj;
2768
24
  if (!env->http2ping_constructor_template()
2769
36
           ->NewInstance(env->context())
2770
36
           .ToLocal(&obj)) {
2771
    return;
2772
  }
2773
48
  if (obj->Set(env->context(), env->ondone_string(), args[1]).IsNothing())
2774
    return;
2775
12
  Http2Session::Http2Ping* ping = new Http2Ping(session, obj);
2776
2777
  // To prevent abuse, we strictly limit the number of unacknowledged PING
2778
  // frames that may be sent at any given time. This is configurable in the
2779
  // Options when creating a Http2Session.
2780
12
  if (!session->AddPing(ping)) {
2781
2
    ping->Done(false);
2782
4
    return args.GetReturnValue().Set(false);
2783
  }
2784
2785
  // The Ping itself is an Async resource. When the acknowledgement is received,
2786
  // the callback will be invoked and a notification sent out to JS land. The
2787
  // notification will include the duration of the ping, allowing the round
2788
  // trip to be measured.
2789
10
  ping->Send(payload.data());
2790
20
  args.GetReturnValue().Set(true);
2791
}
2792
2793
// Submits a SETTINGS frame for the Http2Session
2794
567
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2795
567
  Environment* env = Environment::GetCurrent(args);
2796
  Http2Session* session;
2797
569
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2798
2799
  Local<Object> obj;
2800
1134
  if (!env->http2settings_constructor_template()
2801
1701
           ->NewInstance(env->context())
2802
1701
           .ToLocal(&obj)) {
2803
    return;
2804
  }
2805
2268
  if (obj->Set(env->context(), env->ondone_string(), args[0]).IsNothing())
2806
    return;
2807
2808
  Http2Session::Http2Settings* settings =
2809
567
      new Http2Settings(session->env(), session, obj, 0);
2810
567
  if (!session->AddSettings(settings)) {
2811
2
    settings->Done(false);
2812
4
    return args.GetReturnValue().Set(false);
2813
  }
2814
2815
565
  settings->Send();
2816
1130
  args.GetReturnValue().Set(true);
2817
}
2818
2819
2820
11
Http2Session::Http2Ping* Http2Session::PopPing() {
2821
11
  Http2Ping* ping = nullptr;
2822
11
  if (!outstanding_pings_.empty()) {
2823
10
    ping = outstanding_pings_.front();
2824
10
    outstanding_pings_.pop();
2825
10
    DecrementCurrentSessionMemory(sizeof(*ping));
2826
  }
2827
11
  return ping;
2828
}
2829
2830
12
bool Http2Session::AddPing(Http2Session::Http2Ping* ping) {
2831
12
  if (outstanding_pings_.size() == max_outstanding_pings_)
2832
2
    return false;
2833
10
  outstanding_pings_.push(ping);
2834
10
  IncrementCurrentSessionMemory(sizeof(*ping));
2835
10
  return true;
2836
}
2837
2838
470
Http2Session::Http2Settings* Http2Session::PopSettings() {
2839
470
  Http2Settings* settings = nullptr;
2840
470
  if (!outstanding_settings_.empty()) {
2841
470
    settings = outstanding_settings_.front();
2842
470
    outstanding_settings_.pop();
2843
470
    DecrementCurrentSessionMemory(sizeof(*settings));
2844
  }
2845
470
  return settings;
2846
}
2847
2848
567
bool Http2Session::AddSettings(Http2Session::Http2Settings* settings) {
2849
567
  if (outstanding_settings_.size() == max_outstanding_settings_)
2850
2
    return false;
2851
565
  outstanding_settings_.push(settings);
2852
565
  IncrementCurrentSessionMemory(sizeof(*settings));
2853
565
  return true;
2854
}
2855
2856
12
Http2Session::Http2Ping::Http2Ping(Http2Session* session, Local<Object> obj)
2857
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2PING),
2858
      session_(session),
2859
12
      startTime_(uv_hrtime()) {}
2860
2861
10
void Http2Session::Http2Ping::Send(const uint8_t* payload) {
2862
  uint8_t data[8];
2863
10
  if (payload == nullptr) {
2864
4
    memcpy(&data, &startTime_, arraysize(data));
2865
4
    payload = data;
2866
  }
2867
10
  Http2Scope h2scope(session_);
2868
10
  CHECK_EQ(nghttp2_submit_ping(**session_, NGHTTP2_FLAG_NONE, payload), 0);
2869
10
}
2870
2871
12
void Http2Session::Http2Ping::Done(bool ack, const uint8_t* payload) {
2872
12
  session_->statistics_.ping_rtt = uv_hrtime() - startTime_;
2873
12
  double duration = session_->statistics_.ping_rtt / 1e6;
2874
2875
12
  Local<Value> buf = Undefined(env()->isolate());
2876
12
  if (payload != nullptr) {
2877
    buf = Buffer::Copy(env()->isolate(),
2878
                       reinterpret_cast<const char*>(payload),
2879
20
                       8).ToLocalChecked();
2880
  }
2881
2882
  Local<Value> argv[3] = {
2883
    Boolean::New(env()->isolate(), ack),
2884
    Number::New(env()->isolate(), duration),
2885
    buf
2886
36
  };
2887
12
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
2888
12
  delete this;
2889
12
}
2890
2891
2892
void nghttp2_stream_write::MemoryInfo(MemoryTracker* tracker) const {
2893
  if (req_wrap != nullptr)
2894
    tracker->TrackField("req_wrap", req_wrap->GetAsyncWrap());
2895
  tracker->TrackField("buf", buf);
2896
}
2897
2898
2899
void nghttp2_header::MemoryInfo(MemoryTracker* tracker) const {
2900
  tracker->TrackFieldWithSize("name", nghttp2_rcbuf_get_buf(name).len);
2901
  tracker->TrackFieldWithSize("value", nghttp2_rcbuf_get_buf(value).len);
2902
}
2903
2904
217
void SetCallbackFunctions(const FunctionCallbackInfo<Value>& args) {
2905
217
  Environment* env = Environment::GetCurrent(args);
2906
217
  CHECK_EQ(args.Length(), 12);
2907
2908
#define SET_FUNCTION(arg, name)                                               \
2909
  CHECK(args[arg]->IsFunction());                                             \
2910
  env->set_http2session_on_ ## name ## _function(args[arg].As<Function>());
2911
2912
868
  SET_FUNCTION(0, error)
2913
868
  SET_FUNCTION(1, priority)
2914
868
  SET_FUNCTION(2, settings)
2915
868
  SET_FUNCTION(3, ping)
2916
868
  SET_FUNCTION(4, headers)
2917
868
  SET_FUNCTION(5, frame_error)
2918
868
  SET_FUNCTION(6, goaway_data)
2919
868
  SET_FUNCTION(7, altsvc)
2920
868
  SET_FUNCTION(8, origin)
2921
868
  SET_FUNCTION(9, select_padding)
2922
868
  SET_FUNCTION(10, stream_trailers)
2923
868
  SET_FUNCTION(11, stream_close)
2924
2925
#undef SET_FUNCTION
2926
217
}
2927
2928
// Set up the process.binding('http2') binding.
2929
223
void Initialize(Local<Object> target,
2930
                Local<Value> unused,
2931
                Local<Context> context,
2932
                void* priv) {
2933
223
  Environment* env = Environment::GetCurrent(context);
2934
223
  Isolate* isolate = env->isolate();
2935
223
  HandleScope scope(isolate);
2936
2937
446
  std::unique_ptr<Http2State> state(new Http2State(isolate));
2938
2939
#define SET_STATE_TYPEDARRAY(name, field)             \
2940
  target->Set(context,                                \
2941
              FIXED_ONE_BYTE_STRING(isolate, (name)), \
2942
              (field)).FromJust()
2943
2944
  // Initialize the buffer used for padding callbacks
2945
892
  SET_STATE_TYPEDARRAY(
2946
    "paddingBuffer", state->padding_buffer.GetJSArray());
2947
  // Initialize the buffer used to store the session state
2948
892
  SET_STATE_TYPEDARRAY(
2949
    "sessionState", state->session_state_buffer.GetJSArray());
2950
  // Initialize the buffer used to store the stream state
2951
892
  SET_STATE_TYPEDARRAY(
2952
    "streamState", state->stream_state_buffer.GetJSArray());
2953
892
  SET_STATE_TYPEDARRAY(
2954
    "settingsBuffer", state->settings_buffer.GetJSArray());
2955
892
  SET_STATE_TYPEDARRAY(
2956
    "optionsBuffer", state->options_buffer.GetJSArray());
2957
892
  SET_STATE_TYPEDARRAY(
2958
    "streamStats", state->stream_stats_buffer.GetJSArray());
2959
892
  SET_STATE_TYPEDARRAY(
2960
    "sessionStats", state->session_stats_buffer.GetJSArray());
2961
#undef SET_STATE_TYPEDARRAY
2962
2963
223
  env->set_http2_state(std::move(state));
2964
2965
892
  NODE_DEFINE_CONSTANT(target, PADDING_BUF_FRAME_LENGTH);
2966
892
  NODE_DEFINE_CONSTANT(target, PADDING_BUF_MAX_PAYLOAD_LENGTH);
2967
892
  NODE_DEFINE_CONSTANT(target, PADDING_BUF_RETURN_VALUE);
2968
2969
  // Method to fetch the nghttp2 string description of an nghttp2 error code
2970
223
  env->SetMethod(target, "nghttp2ErrorString", HttpErrorString);
2971
2972
  Local<String> http2SessionClassName =
2973
223
    FIXED_ONE_BYTE_STRING(isolate, "Http2Session");
2974
2975
223
  Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate());
2976
446
  ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping"));
2977
446
  ping->Inherit(AsyncWrap::GetConstructorTemplate(env));
2978
223
  Local<ObjectTemplate> pingt = ping->InstanceTemplate();
2979
223
  pingt->SetInternalFieldCount(1);
2980
223
  env->set_http2ping_constructor_template(pingt);
2981
2982
223
  Local<FunctionTemplate> setting = FunctionTemplate::New(env->isolate());
2983
446
  setting->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Setting"));
2984
446
  setting->Inherit(AsyncWrap::GetConstructorTemplate(env));
2985
223
  Local<ObjectTemplate> settingt = setting->InstanceTemplate();
2986
223
  settingt->SetInternalFieldCount(1);
2987
223
  env->set_http2settings_constructor_template(settingt);
2988
2989
223
  Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
2990
446
  stream->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"));
2991
223
  env->SetProtoMethod(stream, "id", Http2Stream::GetID);
2992
223
  env->SetProtoMethod(stream, "destroy", Http2Stream::Destroy);
2993
223
  env->SetProtoMethod(stream, "flushData", Http2Stream::FlushData);
2994
223
  env->SetProtoMethod(stream, "priority", Http2Stream::Priority);
2995
223
  env->SetProtoMethod(stream, "pushPromise", Http2Stream::PushPromise);
2996
223
  env->SetProtoMethod(stream, "info", Http2Stream::Info);
2997
223
  env->SetProtoMethod(stream, "trailers", Http2Stream::Trailers);
2998
223
  env->SetProtoMethod(stream, "respond", Http2Stream::Respond);
2999
223
  env->SetProtoMethod(stream, "rstStream", Http2Stream::RstStream);
3000
223
  env->SetProtoMethod(stream, "refreshState", Http2Stream::RefreshState);
3001
446
  stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
3002
223
  StreamBase::AddMethods(env, stream);
3003
223
  Local<ObjectTemplate> streamt = stream->InstanceTemplate();
3004
223
  streamt->SetInternalFieldCount(StreamBase::kStreamBaseFieldCount);
3005
223
  env->set_http2stream_constructor_template(streamt);
3006
  target->Set(context,
3007
              FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"),
3008
1115
              stream->GetFunction(env->context()).ToLocalChecked()).Check();
3009
3010
  Local<FunctionTemplate> session =
3011
223
      env->NewFunctionTemplate(Http2Session::New);
3012
223
  session->SetClassName(http2SessionClassName);
3013
446
  session->InstanceTemplate()->SetInternalFieldCount(1);
3014
446
  session->Inherit(AsyncWrap::GetConstructorTemplate(env));
3015
223
  env->SetProtoMethod(session, "origin", Http2Session::Origin);
3016
223
  env->SetProtoMethod(session, "altsvc", Http2Session::AltSvc);
3017
223
  env->SetProtoMethod(session, "ping", Http2Session::Ping);
3018
223
  env->SetProtoMethod(session, "consume", Http2Session::Consume);
3019
223
  env->SetProtoMethod(session, "destroy", Http2Session::Destroy);
3020
223
  env->SetProtoMethod(session, "goaway", Http2Session::Goaway);
3021
223
  env->SetProtoMethod(session, "settings", Http2Session::Settings);
3022
223
  env->SetProtoMethod(session, "request", Http2Session::Request);
3023
  env->SetProtoMethod(session, "setNextStreamID",
3024
223
                      Http2Session::SetNextStreamID);
3025
  env->SetProtoMethod(session, "updateChunksSent",
3026
223
                      Http2Session::UpdateChunksSent);
3027
223
  env->SetProtoMethod(session, "refreshState", Http2Session::RefreshState);
3028
  env->SetProtoMethod(
3029
      session, "localSettings",
3030
223
      Http2Session::RefreshSettings<nghttp2_session_get_local_settings>);
3031
  env->SetProtoMethod(
3032
      session, "remoteSettings",
3033
223
      Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>);
3034
  target->Set(context,
3035
              http2SessionClassName,
3036
892
              session->GetFunction(env->context()).ToLocalChecked()).Check();
3037
3038
223
  Local<Object> constants = Object::New(isolate);
3039
223
  Local<Array> name_for_error_code = Array::New(isolate);
3040
3041
#define NODE_NGHTTP2_ERROR_CODES(V)                       \
3042
  V(NGHTTP2_SESSION_SERVER);                              \
3043
  V(NGHTTP2_SESSION_CLIENT);                              \
3044
  V(NGHTTP2_STREAM_STATE_IDLE);                           \
3045
  V(NGHTTP2_STREAM_STATE_OPEN);                           \
3046
  V(NGHTTP2_STREAM_STATE_RESERVED_LOCAL);                 \
3047
  V(NGHTTP2_STREAM_STATE_RESERVED_REMOTE);                \
3048
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL);              \
3049
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE);             \
3050
  V(NGHTTP2_STREAM_STATE_CLOSED);                         \
3051
  V(NGHTTP2_NO_ERROR);                                    \
3052
  V(NGHTTP2_PROTOCOL_ERROR);                              \
3053
  V(NGHTTP2_INTERNAL_ERROR);                              \
3054
  V(NGHTTP2_FLOW_CONTROL_ERROR);                          \
3055
  V(NGHTTP2_SETTINGS_TIMEOUT);                            \
3056
  V(NGHTTP2_STREAM_CLOSED);                               \
3057
  V(NGHTTP2_FRAME_SIZE_ERROR);                            \
3058
  V(NGHTTP2_REFUSED_STREAM);                              \
3059
  V(NGHTTP2_CANCEL);                                      \
3060
  V(NGHTTP2_COMPRESSION_ERROR);                           \
3061
  V(NGHTTP2_CONNECT_ERROR);                               \
3062
  V(NGHTTP2_ENHANCE_YOUR_CALM);                           \
3063
  V(NGHTTP2_INADEQUATE_SECURITY);                         \
3064
  V(NGHTTP2_HTTP_1_1_REQUIRED);                           \
3065
3066
#define V(name)                                                         \
3067
  NODE_DEFINE_CONSTANT(constants, name);                                \
3068
  name_for_error_code->Set(env->context(),                              \
3069
                           static_cast<int>(name),                      \
3070
                           FIXED_ONE_BYTE_STRING(isolate,               \
3071
                                                 #name)).Check();
3072
35903
  NODE_NGHTTP2_ERROR_CODES(V)
3073
#undef V
3074
3075
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_REQUEST);
3076
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_RESPONSE);
3077
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_PUSH_RESPONSE);
3078
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_HCAT_HEADERS);
3079
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_NV_FLAG_NONE);
3080
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_NV_FLAG_NO_INDEX);
3081
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_DEFERRED);
3082
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE);
3083
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_INVALID_ARGUMENT);
3084
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, NGHTTP2_ERR_STREAM_CLOSED);
3085
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_ERR_FRAME_SIZE_ERROR);
3086
3087
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, STREAM_OPTION_EMPTY_PAYLOAD);
3088
892
  NODE_DEFINE_HIDDEN_CONSTANT(constants, STREAM_OPTION_GET_TRAILERS);
3089
3090
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_NONE);
3091
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_END_STREAM);
3092
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_END_HEADERS);
3093
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_ACK);
3094
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_PADDED);
3095
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_FLAG_PRIORITY);
3096
3097
892
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_HEADER_TABLE_SIZE);
3098
892
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_ENABLE_PUSH);
3099
892
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE);
3100
892
  NODE_DEFINE_CONSTANT(constants, DEFAULT_SETTINGS_MAX_FRAME_SIZE);
3101
892
  NODE_DEFINE_CONSTANT(constants, MAX_MAX_FRAME_SIZE);
3102
892
  NODE_DEFINE_CONSTANT(constants, MIN_MAX_FRAME_SIZE);
3103
892
  NODE_DEFINE_CONSTANT(constants, MAX_INITIAL_WINDOW_SIZE);
3104
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_DEFAULT_WEIGHT);
3105
3106
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
3107
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_ENABLE_PUSH);
3108
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
3109
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
3110
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
3111
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
3112
892
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
3113
3114
892
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_NONE);
3115
892
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_ALIGNED);
3116
892
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_MAX);
3117
892
  NODE_DEFINE_CONSTANT(constants, PADDING_STRATEGY_CALLBACK);
3118
3119
#define STRING_CONSTANT(NAME, VALUE)                                          \
3120
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE);
3121
101688
HTTP_KNOWN_HEADERS(STRING_CONSTANT)
3122
#undef STRING_CONSTANT
3123
3124
#define STRING_CONSTANT(NAME, VALUE)                                          \
3125
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE);
3126
52182
HTTP_KNOWN_METHODS(STRING_CONSTANT)
3127
#undef STRING_CONSTANT
3128
3129
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
3130
56196
HTTP_STATUS_CODES(V)
3131
#undef V
3132
3133
223
  env->SetMethod(target, "refreshDefaultSettings", RefreshDefaultSettings);
3134
223
  env->SetMethod(target, "packSettings", PackSettings);
3135
223
  env->SetMethod(target, "setCallbackFunctions", SetCallbackFunctions);
3136
3137
  target->Set(context,
3138
              env->constants_string(),
3139
669
              constants).Check();
3140
  target->Set(context,
3141
              FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"),
3142
892
              name_for_error_code).Check();
3143
223
}
3144
}  // namespace http2
3145
}  // namespace node
3146
3147

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