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: 1526 1588 96.1 %
Date: 2019-03-02 22:23:06 Branches: 528 737 71.6 %

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

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

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

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

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

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

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

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

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

21252
  return streams_.size() < maxSize &&
782
21252
         IsAvailableSessionMemory(sizeof(Http2Stream));
783
}
784
785
21252
inline void Http2Session::AddStream(Http2Stream* stream) {
786
21252
  CHECK_GE(++statistics_.stream_count, 0);
787
21252
  streams_[stream->id()] = stream;
788
21252
  size_t size = streams_.size();
789
21252
  if (size > statistics_.max_concurrent_streams)
790
1010
    statistics_.max_concurrent_streams = size;
791
21252
  IncrementCurrentSessionMemory(sizeof(*stream));
792
21252
}
793
794
795
21252
inline void Http2Session::RemoveStream(Http2Stream* stream) {
796

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

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

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


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

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

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

21227
  if (stream == nullptr || stream->IsDestroyed())
1081
48
    return 0;
1082
1083
21179
  stream->Close(code);
1084
1085
  // It is possible for the stream close to occur before the stream is
1086
  // ever passed on to the javascript side. If that happens, the callback
1087
  // will return false.
1088
21179
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1089
  MaybeLocal<Value> answer =
1090
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1091
21179
                          1, &arg);
1092

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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

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


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

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