GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/node_http2.cc Lines: 1530 1583 96.7 %
Date: 2019-01-07 12:15:22 Branches: 517 717 72.1 %

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_internals.h"
8
#include "node_perf.h"
9
10
#include <algorithm>
11
12
namespace node {
13
14
using v8::ArrayBuffer;
15
using v8::ArrayBufferCreationMode;
16
using v8::Boolean;
17
using v8::Context;
18
using v8::Float64Array;
19
using v8::Function;
20
using v8::Integer;
21
using v8::NewStringType;
22
using v8::Number;
23
using v8::ObjectTemplate;
24
using v8::String;
25
using v8::Uint32;
26
using v8::Uint32Array;
27
using v8::Undefined;
28
29
using node::performance::PerformanceEntry;
30
namespace http2 {
31
32
namespace {
33
34
const char zero_bytes_256[256] = {};
35
36
33298
inline Http2Stream* GetStream(Http2Session* session,
37
                              int32_t id,
38
                              nghttp2_data_source* source) {
39
33298
  Http2Stream* stream = static_cast<Http2Stream*>(source->ptr);
40
33298
  if (stream == nullptr)
41
27959
    stream = session->FindStream(id);
42
33298
  CHECK_NOT_NULL(stream);
43
33298
  CHECK_EQ(id, stream->id());
44
33298
  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
7194
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
53
    Callbacks(false),
54
3597
    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
55382
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
68
69
94652
Http2Scope::Http2Scope(Http2Session* session) {
70
94652
  if (session == nullptr)
71
    return;
72
73
94652
  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
66219
    return;
78
  }
79
28433
  session->flags_ |= SESSION_STATE_HAS_SCOPE;
80
28433
  session_ = session;
81
82
  // Always keep the session object alive for at least as long as
83
  // this scope is active.
84
28433
  session_handle_ = session->object();
85
56866
  CHECK(!session_handle_.IsEmpty());
86
}
87
88
94652
Http2Scope::~Http2Scope() {
89
94652
  if (session_ == nullptr)
90
66219
    return;
91
92
28433
  session_->flags_ &= ~SESSION_STATE_HAS_SCOPE;
93
28433
  session_->MaybeScheduleWrite();
94
28433
}
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
541
Http2Options::Http2Options(Environment* env, nghttp2_session_type type) {
101
541
  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
541
  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
541
  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
541
  if (type == NGHTTP2_SESSION_CLIENT) {
118
265
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC);
119
265
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ORIGIN);
120
  }
121
122
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
123
541
      env->http2_state()->options_buffer;
124
541
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
125
126
541
  if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) {
127
    nghttp2_option_set_max_deflate_dynamic_table_size(
128
        options_,
129
        buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
130
  }
131
132
541
  if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
133
    nghttp2_option_set_max_reserved_remote_streams(
134
        options_,
135
1
        buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]);
136
  }
137
138
541
  if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) {
139
    nghttp2_option_set_max_send_header_block_length(
140
        options_,
141
1
        buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
142
  }
143
144
  // Recommended default
145
541
  nghttp2_option_set_peer_max_concurrent_streams(options_, 100);
146
541
  if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
147
    nghttp2_option_set_peer_max_concurrent_streams(
148
        options_,
149
        buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
150
  }
151
152
  // The padding strategy sets the mechanism by which we determine how much
153
  // additional frame padding to apply to DATA and HEADERS frames. Currently
154
  // this is set on a per-session basis, but eventually we may switch to
155
  // a per-stream setting, giving users greater control
156
541
  if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
157
    padding_strategy_type strategy =
158
        static_cast<padding_strategy_type>(
159
4
            buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
160
4
    SetPaddingStrategy(strategy);
161
  }
162
163
  // The max header list pairs option controls the maximum number of
164
  // header pairs the session may accept. This is a hard limit.. that is,
165
  // if the remote peer sends more than this amount, the stream will be
166
  // automatically closed with an RST_STREAM.
167
541
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS)) {
168
1
    SetMaxHeaderPairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
169
  }
170
171
  // The HTTP2 specification places no limits on the number of HTTP2
172
  // PING frames that can be sent. In order to prevent PINGS from being
173
  // abused as an attack vector, however, we place a strict upper limit
174
  // on the number of unacknowledged PINGS that can be sent at any given
175
  // time.
176
541
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS)) {
177
2
    SetMaxOutstandingPings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
178
  }
179
180
  // The HTTP2 specification places no limits on the number of HTTP2
181
  // SETTINGS frames that can be sent. In order to prevent PINGS from being
182
  // abused as an attack vector, however, we place a strict upper limit
183
  // on the number of unacknowledged SETTINGS that can be sent at any given
184
  // time.
185
541
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS)) {
186
2
    SetMaxOutstandingSettings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
187
  }
188
189
  // The HTTP2 specification places no limits on the amount of memory
190
  // that a session can consume. In order to prevent abuse, we place a
191
  // cap on the amount of memory a session can consume at any given time.
192
  // this is a credit based system. Existing streams may cause the limit
193
  // to be temporarily exceeded but once over the limit, new streams cannot
194
  // created.
195
  // Important: The maxSessionMemory option in javascript is expressed in
196
  //            terms of MB increments (i.e. the value 1 == 1 MB)
197
541
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY)) {
198
2
    SetMaxSessionMemory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1e6);
199
  }
200
541
}
201
202
564
void Http2Session::Http2Settings::Init() {
203
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
204
564
      env()->http2_state()->settings_buffer;
205
564
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
206
207
564
  size_t n = 0;
208
209
#define GRABSETTING(N, trace)                                                 \
210
  if (flags & (1 << IDX_SETTINGS_##N)) {                                      \
211
    uint32_t val = buffer[IDX_SETTINGS_##N];                                  \
212
    if (session_ != nullptr)                                                  \
213
      Debug(session_, "setting " trace ": %d\n", val);                        \
214
    entries_[n++] =                                                           \
215
        nghttp2_settings_entry {NGHTTP2_SETTINGS_##N, val};                   \
216
  }
217
218

569
  GRABSETTING(HEADER_TABLE_SIZE, "header table size");
219

569
  GRABSETTING(MAX_CONCURRENT_STREAMS, "max concurrent streams");
220

570
  GRABSETTING(MAX_FRAME_SIZE, "max frame size");
221

582
  GRABSETTING(INITIAL_WINDOW_SIZE, "initial window size");
222

571
  GRABSETTING(MAX_HEADER_LIST_SIZE, "max header list size");
223

575
  GRABSETTING(ENABLE_PUSH, "enable push");
224

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

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

21180
  return streams_.size() < maxSize &&
789
21180
         IsAvailableSessionMemory(sizeof(Http2Stream));
790
}
791
792
21180
inline void Http2Session::AddStream(Http2Stream* stream) {
793
21180
  CHECK_GE(++statistics_.stream_count, 0);
794
21180
  streams_[stream->id()] = stream;
795
21180
  size_t size = streams_.size();
796
21180
  if (size > statistics_.max_concurrent_streams)
797
997
    statistics_.max_concurrent_streams = size;
798
21180
  IncrementCurrentSessionMemory(sizeof(*stream));
799
21180
}
800
801
802
21180
inline void Http2Session::RemoveStream(Http2Stream* stream) {
803

21180
  if (streams_.empty() || stream == nullptr)
804
21180
    return;  // Nothing to remove, item was never added?
805
21180
  streams_.erase(stream->id());
806
21180
  DecrementCurrentSessionMemory(sizeof(*stream));
807
}
808
809
// Used as one of the Padding Strategy functions. Will attempt to ensure
810
// that the total frame size, including header bytes, are 8-byte aligned.
811
// If maxPayloadLen is smaller than the number of bytes necessary to align,
812
// will return maxPayloadLen instead.
813
4
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
814
                                            size_t maxPayloadLen) {
815
4
  size_t r = (frameLen + 9) % 8;
816
4
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
817
818
4
  size_t pad = frameLen + (8 - r);
819
820
  // If maxPayloadLen happens to be less than the calculated pad length,
821
  // use the max instead, even tho this means the frame will not be
822
  // aligned.
823
4
  pad = std::min(maxPayloadLen, pad);
824
4
  Debug(this, "using frame size padding: %d", pad);
825
4
  return pad;
826
}
827
828
// Used as one of the Padding Strategy functions. Uses the maximum amount
829
// of padding allowed for the current frame.
830
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
831
                                            size_t maxPayloadLen) {
832
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
833
  return maxPayloadLen;
834
}
835
836
// Used as one of the Padding Strategy functions. Uses a callback to JS land
837
// to determine the amount of padding for the current frame. This option is
838
// rather more expensive because of the JS boundary cross. It generally should
839
// not be the preferred option.
840
4
ssize_t Http2Session::OnCallbackPadding(size_t frameLen,
841
                                        size_t maxPayloadLen) {
842
4
  if (frameLen == 0) return 0;
843
3
  Debug(this, "using callback to determine padding");
844
3
  Isolate* isolate = env()->isolate();
845
3
  HandleScope handle_scope(isolate);
846
3
  Local<Context> context = env()->context();
847
  Context::Scope context_scope(context);
848
849
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
850
3
      env()->http2_state()->padding_buffer;
851
3
  buffer[PADDING_BUF_FRAME_LENGTH] = frameLen;
852
3
  buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen;
853
3
  buffer[PADDING_BUF_RETURN_VALUE] = frameLen;
854
3
  MakeCallback(env()->http2session_on_select_padding_function(), 0, nullptr);
855
3
  uint32_t retval = buffer[PADDING_BUF_RETURN_VALUE];
856
3
  retval = std::min(retval, static_cast<uint32_t>(maxPayloadLen));
857
3
  retval = std::max(retval, static_cast<uint32_t>(frameLen));
858
3
  Debug(this, "using padding size %d", retval);
859
6
  return retval;
860
}
861
862
863
// Write data received from the i/o stream to the underlying nghttp2_session.
864
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
865
// various callback functions. Each of these will typically result in a call
866
// out to JavaScript so this particular function is rather hot and can be
867
// quite expensive. This is a potential performance optimization target later.
868
27618
ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) {
869
27618
  size_t total = 0;
870
  // Note that nghttp2_session_mem_recv is a synchronous operation that
871
  // will trigger a number of other callbacks. Those will, in turn have
872
  // multiple side effects.
873
55232
  for (size_t n = 0; n < nbufs; n++) {
874
    Debug(this, "receiving %d bytes [wants data? %d]",
875
27618
          bufs[n].len,
876
82854
          nghttp2_session_want_read(session_));
877
    ssize_t ret =
878
      nghttp2_session_mem_recv(session_,
879
27618
                               reinterpret_cast<uint8_t*>(bufs[n].base),
880
55236
                               bufs[n].len);
881
27618
    CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
882
883
27618
    if (ret < 0)
884
4
      return ret;
885
886
27614
    total += ret;
887
  }
888
  // Send any data that was queued up while processing the received data.
889
27614
  if (!IsDestroyed()) {
890
27157
    SendPendingData();
891
  }
892
27614
  return total;
893
}
894
895
896
126365
inline int32_t GetFrameID(const nghttp2_frame* frame) {
897
  // If this is a push promise, we want to grab the id of the promised stream
898
126365
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
899
      frame->push_promise.promised_stream_id :
900
126365
      frame->hd.stream_id;
901
}
902
903
904
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
905
// callback to determine if a new stream is being created or if we are simply
906
// adding a new block of headers to an existing stream. The header pairs
907
// themselves are set in the OnHeaderCallback
908
21105
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
909
                                         const nghttp2_frame* frame,
910
                                         void* user_data) {
911
21105
  Http2Session* session = static_cast<Http2Session*>(user_data);
912
21105
  int32_t id = GetFrameID(frame);
913
  Debug(session, "beginning headers for stream %d", id);
914
915
21105
  Http2Stream* stream = session->FindStream(id);
916
  // The common case is that we're creating a new stream. The less likely
917
  // case is that we're receiving a set of trailers
918
21105
  if (LIKELY(stream == nullptr)) {
919
10590
    if (UNLIKELY(!session->CanAddStream())) {
920
      // Too many concurrent streams being opened
921
      nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id,
922
1
                                NGHTTP2_ENHANCE_YOUR_CALM);
923
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
924
    }
925
10589
    new Http2Stream(session, id, frame->headers.cat);
926
10515
  } else if (!stream->IsDestroyed()) {
927
10515
    stream->StartHeaders(frame->headers.cat);
928
  }
929
21104
  return 0;
930
}
931
932
// Called by nghttp2 for each header name/value pair in a HEADERS block.
933
// This had to have been preceded by a call to OnBeginHeadersCallback so
934
// the Http2Stream is guaranteed to already exist.
935
63597
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
936
                                   const nghttp2_frame* frame,
937
                                   nghttp2_rcbuf* name,
938
                                   nghttp2_rcbuf* value,
939
                                   uint8_t flags,
940
                                   void* user_data) {
941
63597
  Http2Session* session = static_cast<Http2Session*>(user_data);
942
63597
  int32_t id = GetFrameID(frame);
943
63597
  Http2Stream* stream = session->FindStream(id);
944
  // If stream is null at this point, either something odd has happened
945
  // or the stream was closed locally while header processing was occurring.
946
  // either way, do not proceed and close the stream.
947
63597
  if (UNLIKELY(stream == nullptr))
948
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
949
950
  // If the stream has already been destroyed, ignore.
951

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


77079
  switch (frame->hd.type) {
971
    case NGHTTP2_DATA:
972
20575
      session->HandleDataFrame(frame);
973
20575
      break;
974
    case NGHTTP2_PUSH_PROMISE:
975
      // Intentional fall-through, handled just like headers frames
976
    case NGHTTP2_HEADERS:
977
21068
      session->HandleHeadersFrame(frame);
978
21068
      break;
979
    case NGHTTP2_SETTINGS:
980
18234
      session->HandleSettingsFrame(frame);
981
18234
      break;
982
    case NGHTTP2_PRIORITY:
983
16
      session->HandlePriorityFrame(frame);
984
16
      break;
985
    case NGHTTP2_GOAWAY:
986
255
      session->HandleGoawayFrame(frame);
987
255
      break;
988
    case NGHTTP2_PING:
989
13876
      session->HandlePingFrame(frame);
990
13876
      break;
991
    case NGHTTP2_ALTSVC:
992
4
      session->HandleAltSvcFrame(frame);
993
4
      break;
994
    case NGHTTP2_ORIGIN:
995
5
      session->HandleOriginFrame(frame);
996
5
      break;
997
    default:
998
3046
      break;
999
  }
1000
77079
  return 0;
1001
}
1002
1003
38
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
1004
                                 const nghttp2_frame* frame,
1005
                                 int lib_error_code,
1006
                                 void* user_data) {
1007
38
  Http2Session* session = static_cast<Http2Session*>(user_data);
1008
1009
  Debug(session, "invalid frame received, code: %d", lib_error_code);
1010
1011
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
1012

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

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

21157
  if (stream == nullptr || stream->IsDestroyed())
1087
43
    return 0;
1088
1089
21114
  stream->Close(code);
1090
1091
  // It is possible for the stream close to occur before the stream is
1092
  // ever passed on to the javascript side. If that happens, the callback
1093
  // will return false.
1094
21114
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1095
  MaybeLocal<Value> answer =
1096
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1097
21114
                          1, &arg);
1098

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

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

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

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


3321
    if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream)
1843
2
      return true;
1844
  }
1845
21172
  return false;
1846
}
1847
1848
// Every Http2Session session is tightly bound to a single i/o StreamBase
1849
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1850
// tightly coupled with all data transfer between the two happening at the
1851
// C++ layer via the StreamBase API.
1852
541
void Http2Session::Consume(Local<External> external) {
1853
541
  StreamBase* stream = static_cast<StreamBase*>(external->Value());
1854
541
  stream->PushStreamListener(this);
1855
541
  Debug(this, "i/o stream consumed");
1856
541
}
1857
1858
1859
21180
Http2Stream::Http2Stream(
1860
    Http2Session* session,
1861
    int32_t id,
1862
    nghttp2_headers_category category,
1863
    int options) : AsyncWrap(session->env(),
1864
21180
                             session->env()->http2stream_constructor_template()
1865
84720
                                 ->NewInstance(session->env()->context())
1866
                                     .ToLocalChecked(),
1867
                             AsyncWrap::PROVIDER_HTTP2STREAM),
1868
                   StreamBase(session->env()),
1869
                   session_(session),
1870
                   id_(id),
1871
63540
                   current_headers_category_(category) {
1872
21180
  MakeWeak();
1873
21180
  statistics_.start_time = uv_hrtime();
1874
1875
  // Limit the number of header pairs
1876
21180
  max_header_pairs_ = session->GetMaxHeaderPairs();
1877
21180
  if (max_header_pairs_ == 0)
1878
  max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1879
21180
  current_headers_.reserve(max_header_pairs_);
1880
1881
  // Limit the number of header octets
1882
  max_header_length_ =
1883
      std::min(
1884
        nghttp2_session_get_local_settings(
1885
          session->session(),
1886
21180
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1887
42360
      MAX_MAX_HEADER_LIST_SIZE);
1888
1889
21180
  if (options & STREAM_OPTION_GET_TRAILERS)
1890
2
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1891
1892
21180
  PushStreamListener(&stream_listener_);
1893
1894
21180
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1895
414
    Shutdown();
1896
21180
  session->AddStream(this);
1897
21180
}
1898
1899
1900


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

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

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

190791
  if (!session_->IsAvailableSessionMemory(length) ||
2200

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

46378
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2264
4
    WriteWrap* finished = stream->queue_.front().req_wrap;
2265
4
    stream->queue_.pop();
2266
4
    if (finished != nullptr)
2267
2
      finished->Done(0);
2268
  }
2269
2270
23187
  if (!stream->queue_.empty()) {
2271
    Debug(session, "stream %d has pending outbound data", id);
2272
10111
    amount = std::min(stream->available_outbound_length_, length);
2273
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2274
10111
    if (amount > 0) {
2275
      // Just return the length, let Http2Session::OnSendData take care of
2276
      // actually taking the buffers out of the queue.
2277
10111
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2278
10111
      stream->DecrementAvailableOutboundLength(amount);
2279
    }
2280
  }
2281
2282

23187
  if (amount == 0 && stream->IsWritable()) {
2283
2543
    CHECK(stream->queue_.empty());
2284
    Debug(session, "deferring stream %d", id);
2285
2543
    stream->EmitWantsWrite(length);
2286

2543
    if (stream->available_outbound_length_ > 0 || !stream->IsWritable()) {
2287
      // EmitWantsWrite() did something interesting synchronously, restart:
2288
      return OnRead(handle, id, buf, length, flags, source, user_data);
2289
    }
2290
2543
    return NGHTTP2_ERR_DEFERRED;
2291
  }
2292
2293

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

36464
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2371
18232
  Http2Settings::Update(env, session, fn);
2372
18232
  Debug(session, "settings refreshed for session");
2373
}
2374
2375
// A TypedArray instance is shared between C++ and JS land to contain state
2376
// information of the current Http2Session. This updates the values in the
2377
// TypedArray so those can be read in JS land.
2378
3
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2379
3
  Environment* env = Environment::GetCurrent(args);
2380
  Http2Session* session;
2381
6
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2382
3
  Debug(session, "refreshing state");
2383
2384
  AliasedBuffer<double, Float64Array>& buffer =
2385
3
      env->http2_state()->session_state_buffer;
2386
2387
3
  nghttp2_session* s = **session;
2388
2389
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2390
6
      nghttp2_session_get_effective_local_window_size(s);
2391
6
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2392
6
      nghttp2_session_get_effective_recv_data_length(s);
2393
6
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2394
6
      nghttp2_session_get_next_stream_id(s);
2395
6
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2396
6
      nghttp2_session_get_local_window_size(s);
2397
6
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2398
6
      nghttp2_session_get_last_proc_stream_id(s);
2399
6
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2400
6
      nghttp2_session_get_remote_window_size(s);
2401
6
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2402
6
      nghttp2_session_get_outbound_queue_size(s);
2403
6
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2404
6
      nghttp2_session_get_hd_deflate_dynamic_table_size(s);
2405
6
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2406
6
      nghttp2_session_get_hd_inflate_dynamic_table_size(s);
2407
}
2408
2409
2410
// Constructor for new Http2Session instances.
2411
541
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2412
541
  Environment* env = Environment::GetCurrent(args);
2413
541
  CHECK(args.IsConstructCall());
2414
2164
  int val = args[0]->IntegerValue(env->context()).ToChecked();
2415
541
  nghttp2_session_type type = static_cast<nghttp2_session_type>(val);
2416
541
  Http2Session* session = new Http2Session(env, args.This(), type);
2417
541
  session->get_async_id();  // avoid compiler warning
2418
  Debug(session, "session created");
2419
541
}
2420
2421
2422
// Binds the Http2Session with a StreamBase used for i/o
2423
541
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2424
  Http2Session* session;
2425
1082
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2426
1082
  CHECK(args[0]->IsExternal());
2427
1082
  session->Consume(args[0].As<External>());
2428
}
2429
2430
// Destroys the Http2Session instance and renders it unusable
2431
519
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2432
  Http2Session* session;
2433
1038
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2434
519
  Debug(session, "destroying session");
2435
519
  Environment* env = Environment::GetCurrent(args);
2436
519
  Local<Context> context = env->context();
2437
2438
1557
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2439
1557
  bool socketDestroyed = args[1]->BooleanValue(env->isolate());
2440
2441
519
  session->Close(code, socketDestroyed);
2442
}
2443
2444
// Submits a new request on the Http2Session and returns either an error code
2445
// or the Http2Stream object.
2446
10584
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2447
  Http2Session* session;
2448
10585
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2449
10584
  Environment* env = session->env();
2450
10584
  Local<Context> context = env->context();
2451
10584
  Isolate* isolate = env->isolate();
2452
2453
21168
  Local<Array> headers = args[0].As<Array>();
2454
31752
  int options = args[1]->IntegerValue(context).ToChecked();
2455
10584
  Http2Priority priority(env, args[2], args[3], args[4]);
2456
2457
10584
  Headers list(isolate, context, headers);
2458
2459
10584
  Debug(session, "request submitted");
2460
2461
10584
  int32_t ret = 0;
2462
  Http2Stream* stream =
2463
      session->Http2Session::SubmitRequest(*priority, *list, list.length(),
2464
10584
                                           &ret, options);
2465
2466
10584
  if (ret <= 0) {
2467
2
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2468
3
    return args.GetReturnValue().Set(ret);
2469
  }
2470
2471
21166
  Debug(session, "request submitted, new stream id %d", stream->id());
2472
31749
  args.GetReturnValue().Set(stream->object());
2473
}
2474
2475
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2476
// of shutting down. Note that this function does not actually alter the
2477
// state of the Http2Session, it's simply a notification.
2478
479
void Http2Session::Goaway(uint32_t code,
2479
                          int32_t lastStreamID,
2480
                          uint8_t* data,
2481
                          size_t len) {
2482
479
  if (IsDestroyed())
2483
479
    return;
2484
2485
479
  Http2Scope h2scope(this);
2486
  // the last proc stream id is the most recently created Http2Stream.
2487
479
  if (lastStreamID <= 0)
2488
479
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_);
2489
479
  Debug(this, "submitting goaway");
2490
  nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE,
2491
479
                        lastStreamID, code, data, len);
2492
}
2493
2494
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2495
// of shutting down. The opaque data argument is an optional TypedArray that
2496
// can be used to send debugging data to the connected peer.
2497
479
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2498
479
  Environment* env = Environment::GetCurrent(args);
2499
479
  Local<Context> context = env->context();
2500
  Http2Session* session;
2501
958
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2502
2503
1437
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2504
1437
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2505
479
  Local<Value> opaqueData = args[2];
2506
479
  uint8_t* data = nullptr;
2507
479
  size_t length = 0;
2508
2509
479
  if (Buffer::HasInstance(opaqueData)) {
2510
1
    data = reinterpret_cast<uint8_t*>(Buffer::Data(opaqueData));
2511
1
    length = Buffer::Length(opaqueData);
2512
  }
2513
2514
479
  session->Goaway(code, lastStreamID, data, length);
2515
}
2516
2517
// Update accounting of data chunks. This is used primarily to manage timeout
2518
// logic when using the FD Provider.
2519
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2520
10
  Environment* env = Environment::GetCurrent(args);
2521
10
  Isolate* isolate = env->isolate();
2522
10
  HandleScope scope(isolate);
2523
  Http2Session* session;
2524
20
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2525
2526
10
  uint32_t length = session->chunks_sent_since_last_write_;
2527
2528
10
  session->object()->Set(env->context(),
2529
                         env->chunks_sent_since_last_write_string(),
2530
60
                         Integer::NewFromUnsigned(isolate, length)).FromJust();
2531
2532
20
  args.GetReturnValue().Set(length);
2533
}
2534
2535
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2536
// this *WILL* alter the state of the stream, causing the OnStreamClose
2537
// callback to the triggered.
2538
113
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2539
113
  Environment* env = Environment::GetCurrent(args);
2540
113
  Local<Context> context = env->context();
2541
  Http2Stream* stream;
2542
226
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2543
339
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2544
113
  Debug(stream, "sending rst_stream with code %d", code);
2545
113
  stream->SubmitRstStream(code);
2546
}
2547
2548
// Initiates a response on the Http2Stream using the StreamBase API to provide
2549
// outbound DATA frames.
2550
10514
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2551
10514
  Environment* env = Environment::GetCurrent(args);
2552
10514
  Local<Context> context = env->context();
2553
10514
  Isolate* isolate = env->isolate();
2554
  Http2Stream* stream;
2555
21028
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2556
2557
21028
  Local<Array> headers = args[0].As<Array>();
2558
31542
  int options = args[1]->IntegerValue(context).ToChecked();
2559
2560
10514
  Headers list(isolate, context, headers);
2561
2562
  args.GetReturnValue().Set(
2563
31542
      stream->SubmitResponse(*list, list.length(), options));
2564
21028
  Debug(stream, "response submitted");
2565
}
2566
2567
2568
// Submits informational headers on the Http2Stream
2569
5
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2570
5
  Environment* env = Environment::GetCurrent(args);
2571
5
  Local<Context> context = env->context();
2572
5
  Isolate* isolate = env->isolate();
2573
  Http2Stream* stream;
2574
10
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2575
2576
10
  Local<Array> headers = args[0].As<Array>();
2577
2578
5
  Headers list(isolate, context, headers);
2579
15
  args.GetReturnValue().Set(stream->SubmitInfo(*list, list.length()));
2580
10
  Debug(stream, "%d informational headers sent", list.length());
2581
}
2582
2583
// Submits trailing headers on the Http2Stream
2584
28
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2585
28
  Environment* env = Environment::GetCurrent(args);
2586
28
  Local<Context> context = env->context();
2587
28
  Isolate* isolate = env->isolate();
2588
  Http2Stream* stream;
2589
56
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2590
2591
56
  Local<Array> headers = args[0].As<Array>();
2592
2593
28
  Headers list(isolate, context, headers);
2594
84
  args.GetReturnValue().Set(stream->SubmitTrailers(*list, list.length()));
2595
56
  Debug(stream, "%d trailing headers sent", list.length());
2596
}
2597
2598
// Grab the numeric id of the Http2Stream
2599
10591
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2600
  Http2Stream* stream;
2601
21182
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2602
31773
  args.GetReturnValue().Set(stream->id());
2603
}
2604
2605
// Destroy the Http2Stream, rendering it no longer usable
2606
21138
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2607
  Http2Stream* stream;
2608
42276
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2609
21138
  Debug(stream, "destroying stream");
2610
21138
  stream->Destroy();
2611
}
2612
2613
// Prompt the Http2Stream to begin sending data to the JS land.
2614
void Http2Stream::FlushData(const FunctionCallbackInfo<Value>& args) {
2615
  Http2Stream* stream;
2616
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2617
  stream->ReadStart();
2618
  Debug(stream, "data flushed to js");
2619
}
2620
2621
// Initiate a Push Promise and create the associated Http2Stream
2622
8
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2623
8
  Environment* env = Environment::GetCurrent(args);
2624
8
  Local<Context> context = env->context();
2625
8
  Isolate* isolate = env->isolate();
2626
  Http2Stream* parent;
2627
8
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2628
2629
16
  Local<Array> headers = args[0].As<Array>();
2630
24
  int options = args[1]->IntegerValue(context).ToChecked();
2631
2632
8
  Headers list(isolate, context, headers);
2633
2634
8
  Debug(parent, "creating push promise");
2635
2636
8
  int32_t ret = 0;
2637
  Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(),
2638
8
                                                  &ret, options);
2639
8
  if (ret <= 0) {
2640
    Debug(parent, "failed to create push stream: %d", ret);
2641
    return args.GetReturnValue().Set(ret);
2642
  }
2643
16
  Debug(parent, "push stream %d created", stream->id());
2644
24
  args.GetReturnValue().Set(stream->object());
2645
}
2646
2647
// Send a PRIORITY frame
2648
6
void Http2Stream::Priority(const FunctionCallbackInfo<Value>& args) {
2649
6
  Environment* env = Environment::GetCurrent(args);
2650
  Http2Stream* stream;
2651
12
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2652
2653
6
  Http2Priority priority(env, args[0], args[1], args[2]);
2654
18
  bool silent = args[3]->BooleanValue(env->isolate());
2655
2656
6
  CHECK_EQ(stream->SubmitPriority(*priority, silent), 0);
2657
6
  Debug(stream, "priority submitted");
2658
}
2659
2660
// A TypedArray shared by C++ and JS land is used to communicate state
2661
// information about the Http2Stream. This updates the values in that
2662
// TypedArray so that the state can be read by JS.
2663
11
void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
2664
11
  Environment* env = Environment::GetCurrent(args);
2665
  Http2Stream* stream;
2666
22
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2667
2668
11
  Debug(stream, "refreshing state");
2669
2670
  AliasedBuffer<double, Float64Array>& buffer =
2671
11
      env->http2_state()->stream_state_buffer;
2672
2673
11
  nghttp2_stream* str = **stream;
2674
11
  nghttp2_session* s = **(stream->session());
2675
2676
11
  if (str == nullptr) {
2677
1
    buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE;
2678
2
    buffer[IDX_STREAM_STATE_WEIGHT] =
2679
2
        buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2680
2
        buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2681
2
        buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2682
3
        buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] = 0;
2683
  } else {
2684
20
    buffer[IDX_STREAM_STATE] =
2685
20
        nghttp2_stream_get_state(str);
2686
20
    buffer[IDX_STREAM_STATE_WEIGHT] =
2687
20
        nghttp2_stream_get_weight(str);
2688
20
    buffer[IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT] =
2689
20
        nghttp2_stream_get_sum_dependency_weight(str);
2690
20
    buffer[IDX_STREAM_STATE_LOCAL_CLOSE] =
2691
20
        nghttp2_session_get_stream_local_close(s, stream->id());
2692
20
    buffer[IDX_STREAM_STATE_REMOTE_CLOSE] =
2693
20
        nghttp2_session_get_stream_remote_close(s, stream->id());
2694
20
    buffer[IDX_STREAM_STATE_LOCAL_WINDOW_SIZE] =
2695
20
        nghttp2_session_get_stream_local_window_size(s, stream->id());
2696
  }
2697
}
2698
2699
5
void Http2Session::AltSvc(int32_t id,
2700
                          uint8_t* origin,
2701
                          size_t origin_len,
2702
                          uint8_t* value,
2703
                          size_t value_len) {
2704
5
  Http2Scope h2scope(this);
2705
5
  CHECK_EQ(nghttp2_submit_altsvc(session_, NGHTTP2_FLAG_NONE, id,
2706
5
                                 origin, origin_len, value, value_len), 0);
2707
5
}
2708
2709
5
void Http2Session::Origin(nghttp2_origin_entry* ov, size_t count) {
2710
5
  Http2Scope h2scope(this);
2711
5
  CHECK_EQ(nghttp2_submit_origin(session_, NGHTTP2_FLAG_NONE, ov, count), 0);
2712
5
}
2713
2714
// Submits an AltSvc frame to be sent to the connected peer.
2715
5
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2716
5
  Environment* env = Environment::GetCurrent(args);
2717
  Http2Session* session;
2718
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2719
2720
20
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2721
2722
  // origin and value are both required to be ASCII, handle them as such.
2723
20
  Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2724
20
  Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2725
2726
5
  size_t origin_len = origin_str->Length();
2727
5
  size_t value_len = value_str->Length();
2728
2729
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2730
  // Verify that origin len != 0 if stream id == 0, or
2731
  // that origin len == 0 if stream id != 0
2732


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

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