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: 1532 1590 96.4 %
Date: 2019-02-23 22:23:05 Branches: 527 735 71.7 %

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::ArrayBufferCreationMode;
16
using v8::Boolean;
17
using v8::Context;
18
using v8::Float64Array;
19
using v8::Function;
20
using v8::Integer;
21
using v8::NewStringType;
22
using v8::Number;
23
using v8::ObjectTemplate;
24
using v8::String;
25
using v8::Uint32;
26
using v8::Uint32Array;
27
using v8::Undefined;
28
29
using node::performance::PerformanceEntry;
30
namespace http2 {
31
32
namespace {
33
34
const char zero_bytes_256[256] = {};
35
36
33646
inline Http2Stream* GetStream(Http2Session* session,
37
                              int32_t id,
38
                              nghttp2_data_source* source) {
39
33646
  Http2Stream* stream = static_cast<Http2Stream*>(source->ptr);
40
33646
  if (stream == nullptr)
41
28070
    stream = session->FindStream(id);
42
33646
  CHECK_NOT_NULL(stream);
43
33646
  CHECK_EQ(id, stream->id());
44
33646
  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
8576
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
53
    Callbacks(false),
54
4288
    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
55779
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
68
69
95241
Http2Scope::Http2Scope(Http2Session* session) {
70
95241
  if (session == nullptr)
71
    return;
72
73
95241
  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
66640
    return;
78
  }
79
28601
  session->flags_ |= SESSION_STATE_HAS_SCOPE;
80
28601
  session_ = session;
81
82
  // Always keep the session object alive for at least as long as
83
  // this scope is active.
84
28601
  session_handle_ = session->object();
85
57202
  CHECK(!session_handle_.IsEmpty());
86
}
87
88
95241
Http2Scope::~Http2Scope() {
89
95241
  if (session_ == nullptr)
90
66640
    return;
91
92
28601
  session_->flags_ &= ~SESSION_STATE_HAS_SCOPE;
93
28601
  session_->MaybeScheduleWrite();
94
28601
}
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
555
Http2Options::Http2Options(Environment* env, nghttp2_session_type type) {
101
555
  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
555
  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
555
  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
555
  if (type == NGHTTP2_SESSION_CLIENT) {
118
273
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC);
119
273
    nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ORIGIN);
120
  }
121
122
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
123
555
      env->http2_state()->options_buffer;
124
555
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
125
126
555
  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
555
  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
555
  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
555
  nghttp2_option_set_peer_max_concurrent_streams(options_, 100);
146
555
  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
555
  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
555
  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
555
  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
555
  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
555
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY)) {
198
2
    SetMaxSessionMemory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1e6);
199
  }
200
555
}
201
202
578
void Http2Session::Http2Settings::Init() {
203
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
204
578
      env()->http2_state()->settings_buffer;
205
578
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
206
207
578
  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

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

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

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

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

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

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

581
  GRABSETTING(ENABLE_CONNECT_PROTOCOL, "enable connect protocol");
225
226
#undef GRABSETTING
227
228
578
  count_ = n;
229
578
}
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
578
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
578
      startTime_(start_time) {
241
578
  Init();
242
578
}
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
18255
void Http2Session::Http2Settings::Update(Environment* env,
263
                                         Http2Session* session,
264
                                         get_setting fn) {
265
  AliasedBuffer<uint32_t, Uint32Array>& buffer =
266
18255
      env->http2_state()->settings_buffer;
267
36510
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
268
36510
      fn(**session, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
269
36510
  buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
270
36510
      fn(**session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
271
36510
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
272
36510
      fn(**session, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
273
36510
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
274
36510
      fn(**session, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
275
36510
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
276
36510
      fn(**session, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
277
36510
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
278
36510
      fn(**session, NGHTTP2_SETTINGS_ENABLE_PUSH);
279
36510
  buffer[IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL] =
280
36510
      fn(**session, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
281
18255
}
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
561
void Http2Session::Http2Settings::Send() {
308
561
  Http2Scope h2scope(session_);
309
561
  CHECK_EQ(nghttp2_submit_settings(**session_, NGHTTP2_FLAG_NONE,
310
561
                                   &entries_[0], count_), 0);
311
561
}
312
313
468
void Http2Session::Http2Settings::Done(bool ack) {
314
468
  uint64_t end = uv_hrtime();
315
468
  double duration = (end - startTime_) / 1e6;
316
317
  Local<Value> argv[2] = {
318
    Boolean::New(env()->isolate(), ack),
319
    Number::New(env()->isolate(), duration)
320
1404
  };
321
468
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
322
468
  delete this;
323
468
}
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
10624
Http2Priority::Http2Priority(Environment* env,
329
                             Local<Value> parent,
330
                             Local<Value> weight,
331
                             Local<Value> exclusive) {
332
10624
  Local<Context> context = env->context();
333
21248
  int32_t parent_ = parent->Int32Value(context).ToChecked();
334
21248
  int32_t weight_ = weight->Int32Value(context).ToChecked();
335
21248
  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
10624
  nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0);
340
10624
}
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
21208
Headers::Headers(Isolate* isolate,
356
                 Local<Context> context,
357
21208
                 Local<Array> headers) {
358
42416
  Local<Value> header_string = headers->Get(context, 0).ToLocalChecked();
359
42416
  Local<Value> header_count = headers->Get(context, 1).ToLocalChecked();
360
42416
  count_ = header_count.As<Uint32>()->Value();
361
42416
  int header_string_len = header_string.As<String>()->Length();
362
363
21208
  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
21184
                                 count_ * sizeof(nghttp2_nv) +
373
42368
                                 header_string_len);
374
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
375
  char* start = reinterpret_cast<char*>(
376
21184
      RoundUp(reinterpret_cast<uintptr_t>(*buf_), alignof(nghttp2_nv)));
377
21184
  char* header_contents = start + (count_ * sizeof(nghttp2_nv));
378
21184
  nghttp2_nv* const nva = reinterpret_cast<nghttp2_nv*>(start);
379
380
21184
  CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length());
381
63552
  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
21184
  size_t n = 0;
390
  char* p;
391
85061
  for (p = header_contents; p < header_contents + header_string_len; n++) {
392
63878
    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
63877
    nva[n].flags = NGHTTP2_NV_FLAG_NONE;
404
63877
    nva[n].name = reinterpret_cast<uint8_t*>(p);
405
63877
    nva[n].namelen = strlen(p);
406
63877
    p += nva[n].namelen + 1;
407
63877
    nva[n].value = reinterpret_cast<uint8_t*>(p);
408
63877
    nva[n].valuelen = strlen(p);
409
63877
    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
8576
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
467
8576
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0);
468
469
  nghttp2_session_callbacks_set_on_begin_headers_callback(
470
8576
    callbacks, OnBeginHeadersCallback);
471
  nghttp2_session_callbacks_set_on_header_callback2(
472
8576
    callbacks, OnHeaderCallback);
473
  nghttp2_session_callbacks_set_on_frame_recv_callback(
474
8576
    callbacks, OnFrameReceive);
475
  nghttp2_session_callbacks_set_on_stream_close_callback(
476
8576
    callbacks, OnStreamClose);
477
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
478
8576
    callbacks, OnDataChunkReceived);
479
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
480
8576
    callbacks, OnFrameNotSent);
481
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
482
8576
    callbacks, OnInvalidHeader);
483
  nghttp2_session_callbacks_set_error_callback(
484
8576
    callbacks, OnNghttpError);
485
  nghttp2_session_callbacks_set_send_data_callback(
486
8576
    callbacks, OnSendData);
487
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
488
8576
    callbacks, OnInvalidFrame);
489
  nghttp2_session_callbacks_set_on_frame_send_callback(
490
8576
    callbacks, OnFrameSent);
491
492
8576
  if (kHasGetPaddingCallback) {
493
    nghttp2_session_callbacks_set_select_padding_callback(
494
4288
      callbacks, OnSelectPadding);
495
  }
496
8576
}
497
498
499
8576
Http2Session::Callbacks::~Callbacks() {
500
8576
  nghttp2_session_callbacks_del(callbacks);
501
8576
}
502
503
// Track memory allocated by nghttp2 using a custom allocator.
504
class Http2Session::MemoryAllocatorInfo {
505
 public:
506
555
  explicit MemoryAllocatorInfo(Http2Session* session)
507
555
      : info({ session, H2Malloc, H2Free, H2Calloc, H2Realloc }) {}
508
509
116821
  static void* H2Malloc(size_t size, void* user_data) {
510
116821
    return H2Realloc(nullptr, size, user_data);
511
  }
512
513
1110
  static void* H2Calloc(size_t nmemb, size_t size, void* user_data) {
514
1110
    size_t real_size = MultiplyWithOverflowCheck(nmemb, size);
515
1110
    void* mem = H2Malloc(real_size, user_data);
516
1110
    if (mem != nullptr)
517
1110
      memset(mem, 0, real_size);
518
1110
    return mem;
519
  }
520
521
309968
  static void H2Free(void* ptr, void* user_data) {
522
619936
    if (ptr == nullptr) return;  // free(null); happens quite often.
523
117602
    void* result = H2Realloc(ptr, 0, user_data);
524
117602
    CHECK_NULL(result);
525
  }
526
527
235221
  static void* H2Realloc(void* ptr, size_t size, void* user_data) {
528
235221
    Http2Session* session = static_cast<Http2Session*>(user_data);
529
235221
    size_t previous_size = 0;
530
235221
    char* original_ptr = nullptr;
531
532
    // We prepend each allocated buffer with a size_t containing the full
533
    // size of the allocation.
534
235221
    if (size > 0) size += sizeof(size_t);
535
536
235221
    if (ptr != nullptr) {
537
      // We are free()ing or re-allocating.
538
117619
      original_ptr = static_cast<char*>(ptr) - sizeof(size_t);
539
117619
      previous_size = *reinterpret_cast<size_t*>(original_ptr);
540
      // This means we called StopTracking() on this pointer before.
541
117619
      if (previous_size == 0) {
542
        // Fall back to the standard Realloc() function.
543
783
        char* ret = UncheckedRealloc(original_ptr, size);
544
783
        if (ret != nullptr)
545
          ret += sizeof(size_t);
546
783
        return ret;
547
      }
548
    }
549
234438
    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
234438
    char* mem = UncheckedRealloc(original_ptr, size);
560
561
234438
    if (mem != nullptr) {
562
      // Adjust the memory info counter.
563
117619
      session->current_nghttp2_memory_ += size - previous_size;
564
117619
      *reinterpret_cast<size_t*>(mem) = size;
565
117619
      mem += sizeof(size_t);
566
116819
    } else if (size == 0) {
567
116819
      session->current_nghttp2_memory_ -= previous_size;
568
    }
569
570
234438
    return mem;
571
  }
572
573
21682
  static void StopTracking(Http2Session* session, void* ptr) {
574
    size_t* original_ptr = reinterpret_cast<size_t*>(
575
21682
        static_cast<char*>(ptr) - sizeof(size_t));
576
21682
    session->current_nghttp2_memory_ -= *original_ptr;
577
21682
    *original_ptr = 0;
578
21682
  }
579
580
555
  inline nghttp2_mem* operator*() { return &info; }
581
582
  nghttp2_mem info;
583
};
584
585
21682
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
586
21682
  MemoryAllocatorInfo::StopTracking(this, buf);
587
21682
}
588
589
555
Http2Session::Http2Session(Environment* env,
590
                           Local<Object> wrap,
591
                           nghttp2_session_type type)
592
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
593
1110
      session_type_(type) {
594
555
  MakeWeak();
595
555
  statistics_.start_time = uv_hrtime();
596
597
  // Capture the configuration options for this session
598
555
  Http2Options opts(env, type);
599
600
555
  max_session_memory_ = opts.GetMaxSessionMemory();
601
602
555
  uint32_t maxHeaderPairs = opts.GetMaxHeaderPairs();
603
  max_header_pairs_ =
604
      type == NGHTTP2_SESSION_SERVER
605
1401
          ? std::max(maxHeaderPairs, 4U)     // minimum # of request headers
606

1392
          : std::max(maxHeaderPairs, 1U);    // minimum # of response headers
607
608
555
  max_outstanding_pings_ = opts.GetMaxOutstandingPings();
609
555
  max_outstanding_settings_ = opts.GetMaxOutstandingSettings();
610
611
555
  padding_strategy_ = opts.GetPaddingStrategy();
612
613
  bool hasGetPaddingCallback =
614
555
      padding_strategy_ != PADDING_STRATEGY_NONE;
615
616
  nghttp2_session_callbacks* callbacks
617
555
      = callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks;
618
619
  auto fn = type == NGHTTP2_SESSION_SERVER ?
620
      nghttp2_session_server_new3 :
621
555
      nghttp2_session_client_new3;
622
623
555
  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
555
  CHECK_EQ(fn(&session_, callbacks, this, *opts, *allocator_info), 0);
631
632
555
  outgoing_storage_.reserve(4096);
633
555
  outgoing_buffers_.reserve(32);
634
555
}
635
636
1665
Http2Session::~Http2Session() {
637
555
  CHECK_EQ(flags_ & SESSION_STATE_HAS_SCOPE, 0);
638
555
  Debug(this, "freeing nghttp2 session");
639
555
  for (const auto& iter : streams_)
640
    iter.second->session_ = nullptr;
641
555
  nghttp2_session_del(session_);
642
555
  CHECK_EQ(current_nghttp2_memory_, 0);
643
1110
}
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
21777
inline bool HasHttp2Observer(Environment* env) {
651
  AliasedBuffer<uint32_t, Uint32Array>& observers =
652
21777
      env->performance_state()->observers;
653
21777
  return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
654
}
655
656
21242
void Http2Stream::EmitStatistics() {
657
21242
  if (!HasHttp2Observer(env()))
658
42482
    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
186382
inline Http2Stream* Http2Session::FindStream(int32_t id) {
769
186382
  auto s = streams_.find(id);
770
186382
  return s != streams_.end() ? s->second : nullptr;
771
}
772
773
10624
inline bool Http2Session::CanAddStream() {
774
  uint32_t maxConcurrentStreams =
775
      nghttp2_session_get_local_settings(
776
10624
          session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
777
  size_t maxSize =
778
10624
      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

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

21248
  if (streams_.empty() || stream == nullptr)
797
21248
    return;  // Nothing to remove, item was never added?
798
21248
  streams_.erase(stream->id());
799
21248
  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
27756
ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) {
862
27756
  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
55508
  for (size_t n = 0; n < nbufs; n++) {
867
    Debug(this, "receiving %d bytes [wants data? %d]",
868
27756
          bufs[n].len,
869
83268
          nghttp2_session_want_read(session_));
870
    ssize_t ret =
871
      nghttp2_session_mem_recv(session_,
872
27756
                               reinterpret_cast<uint8_t*>(bufs[n].base),
873
55512
                               bufs[n].len);
874
27756
    CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
875
876
27756
    if (ret < 0)
877
4
      return ret;
878
879
27752
    total += ret;
880
  }
881
  // Send any data that was queued up while processing the received data.
882
27752
  if (!IsDestroyed()) {
883
27283
    SendPendingData();
884
  }
885
27752
  return total;
886
}
887
888
889
126845
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
126845
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
892
      frame->push_promise.promised_stream_id :
893
126845
      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
21173
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
902
                                         const nghttp2_frame* frame,
903
                                         void* user_data) {
904
21173
  Http2Session* session = static_cast<Http2Session*>(user_data);
905
21173
  int32_t id = GetFrameID(frame);
906
  Debug(session, "beginning headers for stream %d", id);
907
908
21173
  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
21173
  if (LIKELY(stream == nullptr)) {
912

10624
    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
10549
  } else if (!stream->IsDestroyed()) {
921
10549
    stream->StartHeaders(frame->headers.cat);
922
  }
923
21172
  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
63812
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
63812
  Http2Session* session = static_cast<Http2Session*>(user_data);
936
63812
  int32_t id = GetFrameID(frame);
937
63812
  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
63812
  if (UNLIKELY(stream == nullptr))
942
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
943
944
  // If the stream has already been destroyed, ignore.
945

63812
  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
63810
  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
77337
int Http2Session::OnFrameReceive(nghttp2_session* handle,
958
                                 const nghttp2_frame* frame,
959
                                 void* user_data) {
960
77337
  Http2Session* session = static_cast<Http2Session*>(user_data);
961
77337
  session->statistics_.frame_count++;
962
  Debug(session, "complete frame received: type: %d",
963
77337
        frame->hd.type);
964


77337
  switch (frame->hd.type) {
965
    case NGHTTP2_DATA:
966
20704
      session->HandleDataFrame(frame);
967
20704
      break;
968
    case NGHTTP2_PUSH_PROMISE:
969
      // Intentional fall-through, handled just like headers frames
970
    case NGHTTP2_HEADERS:
971
21136
      session->HandleHeadersFrame(frame);
972
21136
      break;
973
    case NGHTTP2_SETTINGS:
974
18257
      session->HandleSettingsFrame(frame);
975
18257
      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
3081
      break;
993
  }
994
77337
  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
58192
int Http2Session::OnFrameSent(nghttp2_session* handle,
1058
                              const nghttp2_frame* frame,
1059
                              void* user_data) {
1060
58192
  Http2Session* session = static_cast<Http2Session*>(user_data);
1061
58192
  session->statistics_.frame_sent += 1;
1062
58192
  return 0;
1063
}
1064
1065
// Called by nghttp2 when a stream closes.
1066
21225
int Http2Session::OnStreamClose(nghttp2_session* handle,
1067
                                int32_t id,
1068
                                uint32_t code,
1069
                                void* user_data) {
1070
21225
  Http2Session* session = static_cast<Http2Session*>(user_data);
1071
21225
  Environment* env = session->env();
1072
21225
  Isolate* isolate = env->isolate();
1073
21225
  HandleScope scope(isolate);
1074
21225
  Local<Context> context = env->context();
1075
  Context::Scope context_scope(context);
1076
  Debug(session, "stream %d closed with code: %d", id, code);
1077
21225
  Http2Stream* stream = session->FindStream(id);
1078
  // Intentionally ignore the callback if the stream does not exist or has
1079
  // already been destroyed
1080

21225
  if (stream == nullptr || stream->IsDestroyed())
1081
48
    return 0;
1082
1083
21177
  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
21177
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1089
  MaybeLocal<Value> answer =
1090
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1091
21177
                          1, &arg);
1092

105885
  if (answer.IsEmpty() ||
1093
105885
      !(answer.ToLocalChecked()->BooleanValue(env->isolate()))) {
1094
    // Skip to destroy
1095
36
    stream->Destroy();
1096
  }
1097
42402
  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
10258
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
10258
  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
10258
  Environment* env = session->env();
1128
10258
  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
10258
  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
10258
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1139
10258
  Http2Stream* stream = session->FindStream(id);
1140
  // If the stream has been destroyed, ignore this chunk
1141
10258
  if (stream->IsDestroyed())
1142
    return 0;
1143
1144
10258
  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
10258
  do {
1152
10258
    uv_buf_t buf = stream->EmitAlloc(len);
1153
10258
    ssize_t avail = len;
1154
10258
    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
10258
    if (LIKELY(buf.base == nullptr))
1163
10258
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1164
    else
1165
      memcpy(buf.base, data, avail);
1166
10258
    data += avail;
1167
10258
    len -= avail;
1168
10258
    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
10258
    if (stream->IsReading())
1174
10171
      nghttp2_session_consume_stream(handle, id, avail);
1175
    else
1176
87
      stream->inbound_consumed_data_while_paused_ += avail;
1177
10258
  } while (len != 0);
1178
1179
10258
  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
10258
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
10258
  return uv_buf_init(nullptr, size);
1238
}
1239
1240
20750
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1241
20750
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1242
20750
  Http2Session* session = stream->session();
1243
20750
  Environment* env = stream->env();
1244
20750
  HandleScope handle_scope(env->isolate());
1245
31008
  Context::Scope context_scope(env->context());
1246
1247
20750
  if (nread < 0) {
1248
10492
    PassReadErrorToPreviousListener(nread);
1249
31242
    return;
1250
  }
1251
1252
20516
  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
10258
  size_t offset = buf.base - session->stream_buf_.base;
1258
1259
  // Verify that the data offset is inside the current read buffer.
1260
10258
  CHECK_LE(offset, session->stream_buf_.len);
1261
10258
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1262
1263
20516
  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
21136
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1271
21136
  Isolate* isolate = env()->isolate();
1272
21136
  HandleScope scope(isolate);
1273
21136
  Local<Context> context = env()->context();
1274
21136
  Context::Scope context_scope(context);
1275
1276
21136
  int32_t id = GetFrameID(frame);
1277
21136
  Debug(this, "handle headers frame for stream %d", id);
1278
21136
  Http2Stream* stream = FindStream(id);
1279
1280
  // If the stream has already been destroyed, ignore.
1281
21136
  if (stream->IsDestroyed())
1282
21136
    return;
1283
1284
42272
  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
21136
  size_t headers_size = headers.size();
1297
42272
  std::vector<Local<Value>> headers_v(headers_size * 2);
1298
84837
  for (size_t i = 0; i < headers_size; ++i) {
1299
63701
    const nghttp2_header& item = headers[i];
1300
    // The header name and value are passed as external one-byte strings
1301
63701
    headers_v[i * 2] =
1302
127402
        ExternalHeader::New<true>(this, item.name).ToLocalChecked();
1303
63701
    headers_v[i * 2 + 1] =
1304
127402
        ExternalHeader::New<false>(this, item.value).ToLocalChecked();
1305
  }
1306
1307
  Local<Value> args[5] = {
1308
      stream->object(),
1309
      Integer::New(isolate, id),
1310
21136
      Integer::New(isolate, stream->headers_category()),
1311
      Integer::New(isolate, frame->hd.flags),
1312
147952
      Array::New(isolate, headers_v.data(), headers_size * 2)};
1313
  MakeCallback(env()->http2session_on_headers_function(),
1314
42272
               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
20704
void Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1349
20704
  int32_t id = GetFrameID(frame);
1350
20704
  Debug(this, "handling data frame for stream %d", id);
1351
20704
  Http2Stream* stream = FindStream(id);
1352
1353

20704
  if (!stream->IsDestroyed() && frame->hd.flags & NGHTTP2_FLAG_END_STREAM)
1354
10492
    stream->EmitRead(UV_EOF);
1355
20704
}
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
18257
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
1474
18257
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1475
18257
  if (!ack) {
1476
    // This is not a SETTINGS acknowledgement, notify and return
1477
17791
    MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
1478
17791
    return;
1479
  }
1480
1481
  // If this is an acknowledgement, we should have an Http2Settings
1482
  // object for it.
1483
466
  Http2Settings* settings = PopSettings();
1484
466
  if (settings != nullptr) {
1485
466
    settings->Done(true);
1486
466
    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
638
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
1507
638
  Debug(this, "write finished with status %d", status);
1508
1509
  // Inform all pending writes about their completion.
1510
638
  ClearOutgoing(status);
1511
1512
638
  if (!(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1513
    // Schedule a new write if nghttp2 wants to send data.
1514
375
    MaybeScheduleWrite();
1515
  }
1516
638
}
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
28976
void Http2Session::MaybeScheduleWrite() {
1523
28976
  CHECK_EQ(flags_ & SESSION_STATE_WRITE_SCHEDULED, 0);
1524
28976
  if (UNLIKELY(session_ == nullptr))
1525
28976
    return;
1526
1527
28976
  if (nghttp2_session_want_write(session_)) {
1528
1466
    HandleScope handle_scope(env()->isolate());
1529
1466
    Debug(this, "scheduling write");
1530
1466
    flags_ |= SESSION_STATE_WRITE_SCHEDULED;
1531
4398
    env()->SetImmediate([](Environment* env, void* data) {
1532
1466
      Http2Session* session = static_cast<Http2Session*>(data);
1533

2932
      if (session->session_ == nullptr ||
1534
1466
          !(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
1733
        return;
1539
      }
1540
1541
      // Sending data may call arbitrary JS code, so keep track of
1542
      // async context.
1543
1199
      HandleScope handle_scope(env->isolate());
1544
2398
      InternalCallbackScope callback_scope(session);
1545
1199
      session->SendPendingData();
1546
5597
    }, static_cast<void*>(this), object());
1547
  }
1548
}
1549
1550
55490
void Http2Session::MaybeStopReading() {
1551
55490
  int want_read = nghttp2_session_want_read(session_);
1552
55490
  Debug(this, "wants read? %d", want_read);
1553
55490
  if (want_read == 0)
1554
973
    stream_->ReadStop();
1555
55490
}
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
27748
    outgoing_storage_.clear();
1566
1567
27748
    std::vector<nghttp2_stream_write> current_outgoing_buffers_;
1568
27748
    current_outgoing_buffers_.swap(outgoing_buffers_);
1569
113638
    for (const nghttp2_stream_write& wr : current_outgoing_buffers_) {
1570
85890
      WriteWrap* wrap = wr.req_wrap;
1571
85890
      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
2603
        wrap->Done(0);
1576
      }
1577
27748
    }
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
58467
void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
1600
58467
  size_t offset = outgoing_storage_.size();
1601
58467
  outgoing_storage_.resize(offset + src_length);
1602
58467
  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
58467
  });
1611
58467
}
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
29109
uint8_t Http2Session::SendPendingData() {
1619
29109
  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
29109
  if (IsDestroyed())
1624
32
    return 0;
1625
29077
  flags_ &= ~SESSION_STATE_WRITE_SCHEDULED;
1626
1627
  // SendPendingData should not be called recursively.
1628
29077
  if (flags_ & SESSION_STATE_SENDING)
1629
539
    return 1;
1630
  // This is cleared by ClearOutgoing().
1631
28538
  flags_ |= SESSION_STATE_SENDING;
1632
1633
  ssize_t src_length;
1634
  const uint8_t* src;
1635
1636
28538
  CHECK_EQ(outgoing_buffers_.size(), 0);
1637
28538
  CHECK_EQ(outgoing_storage_.size(), 0);
1638
1639
  // Part One: Gather data from nghttp2
1640
1641
105307
  while ((src_length = nghttp2_session_mem_send(session_, &src)) > 0) {
1642
48231
    Debug(this, "nghttp2 has %d bytes to send", src_length);
1643
48231
    CopyDataIntoOutgoing(src, src_length);
1644
  }
1645
1646
28538
  CHECK_NE(src_length, NGHTTP2_ERR_NOMEM);
1647
1648
28538
  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
28526
  size_t count = outgoing_buffers_.size();
1659
28526
  if (count == 0) {
1660
788
    ClearOutgoing(0);
1661
788
    return 0;
1662
  }
1663
27738
  MaybeStackBuffer<uv_buf_t, 32> bufs;
1664
27738
  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
27738
  size_t offset = 0;
1670
27738
  size_t i = 0;
1671
113612
  for (const nghttp2_stream_write& write : outgoing_buffers_) {
1672
85874
    statistics_.data_sent += write.buf.len;
1673
85874
    if (write.buf.base == nullptr) {
1674
58448
      bufs[i++] = uv_buf_init(
1675
58448
          reinterpret_cast<char*>(outgoing_storage_.data() + offset),
1676
116896
          write.buf.len);
1677
58448
      offset += write.buf.len;
1678
    } else {
1679
27426
      bufs[i++] = write.buf;
1680
    }
1681
  }
1682
1683
27738
  chunks_sent_since_last_write_++;
1684
1685
27738
  StreamWriteResult res = underlying_stream()->Write(*bufs, count);
1686
27738
  if (!res.async) {
1687
27098
    ClearOutgoing(res.err);
1688
  }
1689
1690
27738
  MaybeStopReading();
1691
1692
27738
  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
10234
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
10234
  Http2Session* session = static_cast<Http2Session*>(user_data);
1708
10234
  Http2Stream* stream = GetStream(session, frame->hd.stream_id, source);
1709
1710
  // Send the frame header + a byte that indicates padding length.
1711
10234
  session->CopyDataIntoOutgoing(framehd, 9);
1712
10234
  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
40261
  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
27424
    CHECK(!stream->queue_.empty());
1723
1724
27424
    nghttp2_stream_write& write = stream->queue_.front();
1725
27424
    if (write.buf.len <= length) {
1726
      // This write does not suffice by itself, so we can consume it completely.
1727
19793
      length -= write.buf.len;
1728
19793
      session->outgoing_buffers_.emplace_back(std::move(write));
1729
19793
      stream->queue_.pop();
1730
19793
      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
10234
  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
10234
  return 0;
1750
}
1751
1752
// Creates a new Http2Stream and submits a new http2 request.
1753
10618
Http2Stream* Http2Session::SubmitRequest(
1754
    nghttp2_priority_spec* prispec,
1755
    nghttp2_nv* nva,
1756
    size_t len,
1757
    int32_t* ret,
1758
    int options) {
1759
10618
  Debug(this, "submitting request");
1760
10618
  Http2Scope h2scope(this);
1761
10618
  Http2Stream* stream = nullptr;
1762
21236
  Http2Stream::Provider::Stream prov(options);
1763
10618
  *ret = nghttp2_submit_request(session_, prispec, nva, len, *prov, nullptr);
1764
10618
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
1765
10618
  if (LIKELY(*ret > 0))
1766
10617
    stream = Http2Stream::New(this, *ret, NGHTTP2_HCAT_HEADERS, options);
1767
21236
  return stream;
1768
}
1769
1770
// Callback used to receive inbound data from the i/o stream
1771
27778
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1772
27778
  HandleScope handle_scope(env()->isolate());
1773
55530
  Context::Scope context_scope(env()->context());
1774
55530
  Http2Scope h2scope(this);
1775
27778
  CHECK_NOT_NULL(stream_);
1776
27778
  Debug(this, "receiving %d bytes", nread);
1777
55556
  CHECK(stream_buf_ab_.IsEmpty());
1778
1779
  // Only pass data on if nread > 0
1780
27778
  if (nread <= 0) {
1781
22
    free(buf.base);
1782
22
    if (nread < 0) {
1783
22
      PassReadErrorToPreviousListener(nread);
1784
    }
1785
22
    return;
1786
  }
1787
1788
  // Shrink to the actual amount of used data.
1789
27756
  char* base = Realloc(buf.base, nread);
1790
1791
27756
  IncrementCurrentSessionMemory(nread);
1792
27756
  OnScopeLeave on_scope_leave([&]() {
1793
    // Once finished handling this write, reset the stream buffer.
1794
    // The memory has either been free()d or was handed over to V8.
1795
27756
    DecrementCurrentSessionMemory(nread);
1796
55512
    stream_buf_ab_ = Local<ArrayBuffer>();
1797
27756
    stream_buf_ = uv_buf_init(nullptr, 0);
1798
83264
  });
1799
1800
  // Make sure that there was no read previously active.
1801
27756
  CHECK_NULL(stream_buf_.base);
1802
27756
  CHECK_EQ(stream_buf_.len, 0);
1803
1804
  // Remember the current buffer, so that OnDataChunkReceived knows the
1805
  // offset of a DATA frame's data into the socket read buffer.
1806
27756
  stream_buf_ = uv_buf_init(base, nread);
1807
1808
27756
  Isolate* isolate = env()->isolate();
1809
1810
  // Create an array buffer for the read data. DATA frames will be emitted
1811
  // as slices of this array buffer to avoid having to copy memory.
1812
  stream_buf_ab_ =
1813
      ArrayBuffer::New(isolate,
1814
                       base,
1815
                       nread,
1816
27756
                       ArrayBufferCreationMode::kInternalized);
1817
1818
27756
  statistics_.data_received += nread;
1819
27756
  ssize_t ret = Write(&stream_buf_, 1);
1820
1821
27756
  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
55504
  MaybeStopReading();
1829
}
1830
1831
21242
bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
1832
24560
  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
21240
  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
555
void Http2Session::Consume(Local<External> external) {
1844
555
  StreamBase* stream = static_cast<StreamBase*>(external->Value());
1845
555
  stream->PushStreamListener(this);
1846
555
  Debug(this, "i/o stream consumed");
1847
555
}
1848
1849
21248
Http2Stream* Http2Stream::New(Http2Session* session,
1850
                              int32_t id,
1851
                              nghttp2_headers_category category,
1852
                              int options) {
1853
  Local<Object> obj;
1854
42496
  if (!session->env()
1855
21248
           ->http2stream_constructor_template()
1856
84992
           ->NewInstance(session->env()->context())
1857
63744
           .ToLocal(&obj)) {
1858
    return nullptr;
1859
  }
1860
21248
  return new Http2Stream(session, obj, id, category, options);
1861
}
1862
1863
21248
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
21248
      current_headers_category_(category) {
1873
21248
  MakeWeak();
1874
21248
  statistics_.start_time = uv_hrtime();
1875
1876
  // Limit the number of header pairs
1877
21248
  max_header_pairs_ = session->GetMaxHeaderPairs();
1878
21248
  if (max_header_pairs_ == 0)
1879
  max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1880
21248
  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
21248
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1888
42496
      MAX_MAX_HEADER_LIST_SIZE);
1889
1890
21248
  if (options & STREAM_OPTION_GET_TRAILERS)
1891
2
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1892
1893
21248
  PushStreamListener(&stream_listener_);
1894
1895
21248
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1896
448
    Shutdown();
1897
21248
  session->AddStream(this);
1898
21248
}
1899
1900
1901


63744
Http2Stream::~Http2Stream() {
1902
21357
  for (nghttp2_header& header : current_headers_) {
1903
109
    nghttp2_rcbuf_decref(header.name);
1904
109
    nghttp2_rcbuf_decref(header.value);
1905
  }
1906
1907
21248
  if (session_ == nullptr)
1908
    return;
1909
21248
  Debug(this, "tearing down stream");
1910
21248
  session_->RemoveStream(this);
1911
21248
  session_ = nullptr;
1912
42496
}
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
10549
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
1922
10549
  Debug(this, "starting headers, category: %d", id_, category);
1923
10549
  CHECK(!this->IsDestroyed());
1924
10549
  current_headers_length_ = 0;
1925
10549
  current_headers_.clear();
1926
10549
  current_headers_category_ = category;
1927
10549
}
1928
1929
1930
11
nghttp2_stream* Http2Stream::operator*() {
1931
11
  return nghttp2_session_find_stream(**session_, id_);
1932
}
1933
1934
21177
void Http2Stream::Close(int32_t code) {
1935
21177
  CHECK(!this->IsDestroyed());
1936
21177
  flags_ |= NGHTTP2_STREAM_FLAG_CLOSED;
1937
21177
  code_ = code;
1938
21177
  Debug(this, "closed with code %d", code);
1939
21177
}
1940
1941
21607
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
1942
21607
  if (IsDestroyed())
1943
    return UV_EPIPE;
1944
1945
  {
1946
21607
    Http2Scope h2scope(this);
1947
21607
    flags_ |= NGHTTP2_STREAM_FLAG_SHUT;
1948
21607
    CHECK_NE(nghttp2_session_resume_data(**session_, id_),
1949
             NGHTTP2_ERR_NOMEM);
1950
43214
    Debug(this, "writable side shutdown");
1951
  }
1952
21607
  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
21242
void Http2Stream::Destroy() {
1959
  // Do nothing if this stream instance is already destroyed
1960
21242
  if (IsDestroyed())
1961
21242
    return;
1962
21242
  if (session_->HasPendingRstStream(id_))
1963
3
    FlushRstStream();
1964
21242
  flags_ |= NGHTTP2_STREAM_FLAG_DESTROYED;
1965
1966
21242
  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
63726
  env()->SetImmediate([](Environment* env, void* data) {
1971
21242
    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
42488
    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

42484
    if (stream->session() == nullptr ||
1986
21242
        !stream->session()->HasWritesOnSocketForStream(stream))
1987
21240
      delete stream;
1988
84968
  }, this, this->object());
1989
1990
21242
  statistics_.end_time = uv_hrtime();
1991
  session_->statistics_.stream_average_duration =
1992
21242
      ((statistics_.end_time - statistics_.start_time) /
1993
42484
          session_->statistics_.stream_count) / 1e6;
1994
21242
  EmitStatistics();
1995
}
1996
1997
1998
// Initiates a response on the Http2Stream using data provided via the
1999
// StreamBase Streams API.
2000
10548
int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) {
2001
10548
  CHECK(!this->IsDestroyed());
2002
10548
  Http2Scope h2scope(this);
2003
10548
  Debug(this, "submitting response");
2004
10548
  if (options & STREAM_OPTION_GET_TRAILERS)
2005
192
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
2006
2007
10548
  if (!IsWritable())
2008
8
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2009
2010
21096
  Http2Stream::Provider::Stream prov(this, options);
2011
10548
  int ret = nghttp2_submit_response(**session_, id_, nva, len, *prov);
2012
10548
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2013
21096
  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
120
void Http2Stream::SubmitRstStream(const uint32_t code) {
2079
120
  CHECK(!this->IsDestroyed());
2080
120
  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
120
  if (session_->SendPendingData() != 0) {
2086
4
    session_->AddPendingRstStream(id_);
2087
124
    return;
2088
  }
2089
2090
116
  FlushRstStream();
2091
}
2092
2093
123
void Http2Stream::FlushRstStream() {
2094
123
  if (IsDestroyed())
2095
148
    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
20867
int Http2Stream::ReadStart() {
2123
20867
  Http2Scope h2scope(this);
2124
20867
  CHECK(!this->IsDestroyed());
2125
20867
  flags_ |= NGHTTP2_STREAM_FLAG_READ_START;
2126
20867
  flags_ &= ~NGHTTP2_STREAM_FLAG_READ_PAUSED;
2127
2128
20867
  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
20867
                                 inbound_consumed_data_while_paused_);
2135
20867
  inbound_consumed_data_while_paused_ = 0;
2136
2137
20867
  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
2611
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2161
                         uv_buf_t* bufs,
2162
                         size_t nbufs,
2163
                         uv_stream_t* send_handle) {
2164
2611
  CHECK_NULL(send_handle);
2165
2611
  Http2Scope h2scope(this);
2166

2611
  if (!IsWritable() || IsDestroyed()) {
2167
    req_wrap->Done(UV_EOF);
2168
    return 0;
2169
  }
2170
2611
  Debug(this, "queuing %d buffers to send", id_, nbufs);
2171
22414
  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
19803
      i == nbufs - 1 ? req_wrap : nullptr,
2176
      bufs[i]
2177
19803
    });
2178
19803
    IncrementAvailableOutboundLength(bufs[i].len);
2179
  }
2180
2611
  CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM);
2181
2611
  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
63812
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2190
                            nghttp2_rcbuf* value,
2191
                            uint8_t flags) {
2192
63812
  CHECK(!this->IsDestroyed());
2193
63812
  if (this->statistics_.first_header == 0)
2194
21154
    this->statistics_.first_header = uv_hrtime();
2195
63812
  size_t length = nghttp2_rcbuf_get_buf(name).len +
2196
63812
                  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

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

127623
      current_headers_.size() == max_header_pairs_ ||
2201
63811
      current_headers_length_ + length > max_header_length_) {
2202
2
    return false;
2203
  }
2204
63810
  nghttp2_header header;
2205
63810
  header.name = name;
2206
63810
  header.value = value;
2207
63810
  header.flags = flags;
2208
63810
  current_headers_.push_back(header);
2209
63810
  nghttp2_rcbuf_incref(name);
2210
63810
  nghttp2_rcbuf_incref(value);
2211
63810
  current_headers_length_ += length;
2212
63810
  return true;
2213
}
2214
2215
// A Provider is the thing that provides outbound DATA frame data.
2216
10572
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2217
10572
  CHECK(!stream->IsDestroyed());
2218
10572
  provider_.source.ptr = stream;
2219
10572
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2220
10572
}
2221
2222
10618
Http2Stream::Provider::Provider(int options) {
2223
10618
  provider_.source.ptr = nullptr;
2224
10618
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2225
10618
}
2226
2227
21190
Http2Stream::Provider::~Provider() {
2228
21190
  provider_.source.ptr = nullptr;
2229
21190
}
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
10618
Http2Stream::Provider::Stream::Stream(int options)
2234
10618
    : Http2Stream::Provider(options) {
2235
10618
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2236
10618
}
2237
2238
10572
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2239
10572
    : Http2Stream::Provider(stream, options) {
2240
10572
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2241
10572
}
2242
2243
23412
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
23412
  Http2Session* session = static_cast<Http2Session*>(user_data);
2251
  Debug(session, "reading outbound data for stream %d", id);
2252
23412
  Http2Stream* stream = GetStream(session, id, source);
2253
23412
  if (stream->statistics_.first_byte_sent == 0)
2254
10550
    stream->statistics_.first_byte_sent = uv_hrtime();
2255
23412
  CHECK_EQ(id, stream->id());
2256
2257
23412
  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

46828
  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
23412
  if (!stream->queue_.empty()) {
2271
    Debug(session, "stream %d has pending outbound data", id);
2272
10234
    amount = std::min(stream->available_outbound_length_, length);
2273
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2274
10234
    if (amount > 0) {
2275
      // Just return the length, let Http2Session::OnSendData take care of
2276
      // actually taking the buffers out of the queue.
2277
10234
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2278
10234
      stream->DecrementAvailableOutboundLength(amount);
2279
    }
2280
  }
2281
2282

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

2638
    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
2638
    return NGHTTP2_ERR_DEFERRED;
2291
  }
2292
2293

20774
  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
20774
  stream->statistics_.sent_bytes += amount;
2303
20774
  return amount;
2304
}
2305
2306
19803
inline void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2307
19803
  available_outbound_length_ += amount;
2308
19803
  session_->IncrementCurrentSessionMemory(amount);
2309
19803
}
2310
2311
10234
inline void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2312
10234
  available_outbound_length_ -= amount;
2313
10234
  session_->DecrementCurrentSessionMemory(amount);
2314
10234
}
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
18255
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2375
18255
  Environment* env = Environment::GetCurrent(args);
2376
  Http2Session* session;
2377

36510
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2378
18255
  Http2Settings::Update(env, session, fn);
2379
18255
  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
555
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2419
555
  Environment* env = Environment::GetCurrent(args);
2420
555
  CHECK(args.IsConstructCall());
2421
2220
  int val = args[0]->IntegerValue(env->context()).ToChecked();
2422
555
  nghttp2_session_type type = static_cast<nghttp2_session_type>(val);
2423
555
  Http2Session* session = new Http2Session(env, args.This(), type);
2424
555
  session->get_async_id();  // avoid compiler warning
2425
  Debug(session, "session created");
2426
555
}
2427
2428
2429
// Binds the Http2Session with a StreamBase used for i/o
2430
555
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2431
  Http2Session* session;
2432
1110
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2433
1110
  CHECK(args[0]->IsExternal());
2434
1110
  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
10618
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2454
  Http2Session* session;
2455
10619
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2456
10618
  Environment* env = session->env();
2457
10618
  Local<Context> context = env->context();
2458
10618
  Isolate* isolate = env->isolate();
2459
2460
21236
  Local<Array> headers = args[0].As<Array>();
2461
31854
  int options = args[1]->IntegerValue(context).ToChecked();
2462
10618
  Http2Priority priority(env, args[2], args[3], args[4]);
2463
2464
10618
  Headers list(isolate, context, headers);
2465
2466
10618
  Debug(session, "request submitted");
2467
2468
10618
  int32_t ret = 0;
2469
  Http2Stream* stream =
2470
      session->Http2Session::SubmitRequest(*priority, *list, list.length(),
2471
10618
                                           &ret, options);
2472
2473

10618
  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
21234
  Debug(session, "request submitted, new stream id %d", stream->id());
2479
31851
  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
                          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
  Local<Value> opaqueData = args[2];
2513
485
  uint8_t* data = nullptr;
2514
485
  size_t length = 0;
2515
2516
485
  if (Buffer::HasInstance(opaqueData)) {
2517
1
    data = reinterpret_cast<uint8_t*>(Buffer::Data(opaqueData));
2518
1
    length = Buffer::Length(opaqueData);
2519
  }
2520
2521
485
  session->Goaway(code, lastStreamID, data, length);
2522
}
2523
2524
// Update accounting of data chunks. This is used primarily to manage timeout
2525
// logic when using the FD Provider.
2526
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2527
10
  Environment* env = Environment::GetCurrent(args);
2528
10
  Isolate* isolate = env->isolate();
2529
10
  HandleScope scope(isolate);
2530
  Http2Session* session;
2531
20
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2532
2533
10
  uint32_t length = session->chunks_sent_since_last_write_;
2534
2535
10
  session->object()->Set(env->context(),
2536
                         env->chunks_sent_since_last_write_string(),
2537
60
                         Integer::NewFromUnsigned(isolate, length)).FromJust();
2538
2539
20
  args.GetReturnValue().Set(length);
2540
}
2541
2542
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2543
// this *WILL* alter the state of the stream, causing the OnStreamClose
2544
// callback to the triggered.
2545
118
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2546
118
  Environment* env = Environment::GetCurrent(args);
2547
118
  Local<Context> context = env->context();
2548
  Http2Stream* stream;
2549
236
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2550
354
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2551
118
  Debug(stream, "sending rst_stream with code %d", code);
2552
118
  stream->SubmitRstStream(code);
2553
}
2554
2555
// Initiates a response on the Http2Stream using the StreamBase API to provide
2556
// outbound DATA frames.
2557
10548
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2558
10548
  Environment* env = Environment::GetCurrent(args);
2559
10548
  Local<Context> context = env->context();
2560
10548
  Isolate* isolate = env->isolate();
2561
  Http2Stream* stream;
2562
21096
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2563
2564
21096
  Local<Array> headers = args[0].As<Array>();
2565
31644
  int options = args[1]->IntegerValue(context).ToChecked();
2566
2567
10548
  Headers list(isolate, context, headers);
2568
2569
  args.GetReturnValue().Set(
2570
31644
      stream->SubmitResponse(*list, list.length(), options));
2571
21096
  Debug(stream, "response submitted");
2572
}
2573
2574
2575
// Submits informational headers on the Http2Stream
2576
5
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2577
5
  Environment* env = Environment::GetCurrent(args);
2578
5
  Local<Context> context = env->context();
2579
5
  Isolate* isolate = env->isolate();
2580
  Http2Stream* stream;
2581
10
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2582
2583
10
  Local<Array> headers = args[0].As<Array>();
2584
2585
5
  Headers list(isolate, context, headers);
2586
15
  args.GetReturnValue().Set(stream->SubmitInfo(*list, list.length()));
2587
10
  Debug(stream, "%d informational headers sent", list.length());
2588
}
2589
2590
// Submits trailing headers on the Http2Stream
2591
29
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2592
29
  Environment* env = Environment::GetCurrent(args);
2593
29
  Local<Context> context = env->context();
2594
29
  Isolate* isolate = env->isolate();
2595
  Http2Stream* stream;
2596
58
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2597
2598
58
  Local<Array> headers = args[0].As<Array>();
2599
2600
29
  Headers list(isolate, context, headers);
2601
87
  args.GetReturnValue().Set(stream->SubmitTrailers(*list, list.length()));
2602
58
  Debug(stream, "%d trailing headers sent", list.length());
2603
}
2604
2605
// Grab the numeric id of the Http2Stream
2606
10625
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2607
  Http2Stream* stream;
2608
21250
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2609
31875
  args.GetReturnValue().Set(stream->id());
2610
}
2611
2612
// Destroy the Http2Stream, rendering it no longer usable
2613
21206
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2614
  Http2Stream* stream;
2615
42412
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2616
21206
  Debug(stream, "destroying stream");
2617
21206
  stream->Destroy();
2618
}
2619
2620
// Prompt the Http2Stream to begin sending data to the JS land.
2621
void Http2Stream::FlushData(const FunctionCallbackInfo<Value>& args) {
2622
  Http2Stream* stream;
2623
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2624
  stream->ReadStart();
2625
  Debug(stream, "data flushed to js");
2626
}
2627
2628
// Initiate a Push Promise and create the associated Http2Stream
2629
8
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2630
8
  Environment* env = Environment::GetCurrent(args);
2631
8
  Local<Context> context = env->context();
2632
8
  Isolate* isolate = env->isolate();
2633
  Http2Stream* parent;
2634
8
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2635
2636
16
  Local<Array> headers = args[0].As<Array>();
2637
24
  int options = args[1]->IntegerValue(context).ToChecked();
2638
2639
8
  Headers list(isolate, context, headers);
2640
2641
8
  Debug(parent, "creating push promise");
2642
2643
8
  int32_t ret = 0;
2644
  Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(),
2645
8
                                                  &ret, options);
2646

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


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

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