GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_http2.cc Lines: 1590 1643 96.8 %
Date: 2019-09-17 22:33:17 Branches: 578 782 73.9 %

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

1803
  if ((flags_ & SESSION_STATE_READING_STOPPED) &&
1555

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

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

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


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


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

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

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

214038
  if (!session_->IsAvailableSessionMemory(length) ||
2277

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

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

28256
  if (amount == 0 && stream->IsWritable()) {
2361
3590
    CHECK(stream->queue_.empty());
2362
    Debug(session, "deferring stream %d", id);
2363
3590
    stream->EmitWantsWrite(length);
2364

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

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

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

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

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


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

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