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: 1587 1650 96.2 %
Date: 2020-02-27 22:14:15 Branches: 563 758 74.3 %

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

620
  GRABSETTING(HEADER_TABLE_SIZE, "header table size");
222

623
  GRABSETTING(MAX_CONCURRENT_STREAMS, "max concurrent streams");
223

621
  GRABSETTING(MAX_FRAME_SIZE, "max frame size");
224

633
  GRABSETTING(INITIAL_WINDOW_SIZE, "initial window size");
225

622
  GRABSETTING(MAX_HEADER_LIST_SIZE, "max header list size");
226

626
  GRABSETTING(ENABLE_PUSH, "enable push");
227

621
  GRABSETTING(ENABLE_CONNECT_PROTOCOL, "enable connect protocol");
228
229
#undef GRABSETTING
230
231
615
  count_ = n;
232
615
}
233
234
// The Http2Settings class is used to configure a SETTINGS frame that is
235
// to be sent to the connected peer. The settings are set using a TypedArray
236
// that is shared with the JavaScript side.
237
615
Http2Session::Http2Settings::Http2Settings(Environment* env,
238
                                           Http2Session* session,
239
                                           Local<Object> obj,
240
615
                                           uint64_t start_time)
241
    : AsyncWrap(env, obj, PROVIDER_HTTP2SETTINGS),
242
      session_(session),
243
615
      startTime_(start_time) {
244
615
  Init();
245
615
}
246
247
// Generates a Buffer that contains the serialized payload of a SETTINGS
248
// frame. This can be used, for instance, to create the Base64-encoded
249
// content of an Http2-Settings header field.
250
15
Local<Value> Http2Session::Http2Settings::Pack() {
251
15
  const size_t len = count_ * 6;
252
30
  Local<Value> buf = Buffer::New(env(), len).ToLocalChecked();
253
  ssize_t ret =
254
15
      nghttp2_pack_settings_payload(
255
15
        reinterpret_cast<uint8_t*>(Buffer::Data(buf)), len,
256
30
        &entries_[0], count_);
257
15
  if (ret >= 0)
258
14
    return buf;
259
  else
260
2
    return Undefined(env()->isolate());
261
}
262
263
// Updates the shared TypedArray with the current remote or local settings for
264
// the session.
265
512
void Http2Session::Http2Settings::Update(Environment* env,
266
                                         Http2Session* session,
267
                                         get_setting fn) {
268
512
  AliasedUint32Array& buffer = env->http2_state()->settings_buffer;
269
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
270
512
      fn(**session, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE);
271
  buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
272
512
      fn(**session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
273
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
274
512
      fn(**session, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE);
275
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
276
512
      fn(**session, NGHTTP2_SETTINGS_MAX_FRAME_SIZE);
277
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
278
512
      fn(**session, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE);
279
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
280
512
      fn(**session, NGHTTP2_SETTINGS_ENABLE_PUSH);
281
  buffer[IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL] =
282
512
      fn(**session, NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL);
283
512
}
284
285
// Initializes the shared TypedArray with the default settings values.
286
3
void Http2Session::Http2Settings::RefreshDefaults(Environment* env) {
287
3
  AliasedUint32Array& buffer = env->http2_state()->settings_buffer;
288
289
  buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] =
290
3
      DEFAULT_SETTINGS_HEADER_TABLE_SIZE;
291
  buffer[IDX_SETTINGS_ENABLE_PUSH] =
292
3
      DEFAULT_SETTINGS_ENABLE_PUSH;
293
  buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] =
294
3
      DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS;
295
  buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] =
296
3
      DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE;
297
  buffer[IDX_SETTINGS_MAX_FRAME_SIZE] =
298
3
      DEFAULT_SETTINGS_MAX_FRAME_SIZE;
299
  buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] =
300
3
      DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
301
  buffer[IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL] =
302
3
      DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL;
303
  buffer[IDX_SETTINGS_COUNT] =
304
    (1 << IDX_SETTINGS_HEADER_TABLE_SIZE) |
305
    (1 << IDX_SETTINGS_ENABLE_PUSH) |
306
    (1 << IDX_SETTINGS_MAX_CONCURRENT_STREAMS) |
307
    (1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE) |
308
    (1 << IDX_SETTINGS_MAX_FRAME_SIZE) |
309
6
    (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE) |
310
3
    (1 << IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL);
311
3
}
312
313
314
598
void Http2Session::Http2Settings::Send() {
315
1196
  Http2Scope h2scope(session_);
316
598
  CHECK_EQ(nghttp2_submit_settings(**session_, NGHTTP2_FLAG_NONE,
317
                                   &entries_[0], count_), 0);
318
598
}
319
320
492
void Http2Session::Http2Settings::Done(bool ack) {
321
492
  uint64_t end = uv_hrtime();
322
492
  double duration = (end - startTime_) / 1e6;
323
324
  Local<Value> argv[] = {
325
    Boolean::New(env()->isolate(), ack),
326
    Number::New(env()->isolate(), duration)
327
1476
  };
328
492
  MakeCallback(env()->ondone_string(), arraysize(argv), argv);
329
492
}
330
331
// The Http2Priority class initializes an appropriate nghttp2_priority_spec
332
// struct used when either creating a stream or updating its priority
333
// settings.
334
11697
Http2Priority::Http2Priority(Environment* env,
335
                             Local<Value> parent,
336
                             Local<Value> weight,
337
11697
                             Local<Value> exclusive) {
338
11697
  Local<Context> context = env->context();
339
23394
  int32_t parent_ = parent->Int32Value(context).ToChecked();
340
23394
  int32_t weight_ = weight->Int32Value(context).ToChecked();
341
23394
  bool exclusive_ = exclusive->BooleanValue(env->isolate());
342
  Debug(env, DebugCategory::HTTP2STREAM,
343
        "Http2Priority: parent: %d, weight: %d, exclusive: %d\n",
344
        parent_, weight_, exclusive_);
345
11697
  nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0);
346
11697
}
347
348
349
126
const char* Http2Session::TypeName() const {
350
126
  switch (session_type_) {
351
66
    case NGHTTP2_SESSION_SERVER: return "server";
352
60
    case NGHTTP2_SESSION_CLIENT: return "client";
353
    default:
354
      // This should never happen
355
      ABORT();
356
  }
357
}
358
359
// The Headers class initializes a proper array of nghttp2_nv structs
360
// containing the header name value pairs.
361
23355
Headers::Headers(Isolate* isolate,
362
                 Local<Context> context,
363
23355
                 Local<Array> headers) {
364
46710
  Local<Value> header_string = headers->Get(context, 0).ToLocalChecked();
365
46710
  Local<Value> header_count = headers->Get(context, 1).ToLocalChecked();
366
46710
  count_ = header_count.As<Uint32>()->Value();
367
46710
  int header_string_len = header_string.As<String>()->Length();
368
369
23355
  if (count_ == 0) {
370
25
    CHECK_EQ(header_string_len, 0);
371
51
    return;
372
  }
373
374
  // Allocate a single buffer with count_ nghttp2_nv structs, followed
375
  // by the raw header data as passed from JS. This looks like:
376
  // | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents |
377
23330
  buf_.AllocateSufficientStorage((alignof(nghttp2_nv) - 1) +
378
23330
                                 count_ * sizeof(nghttp2_nv) +
379
23330
                                 header_string_len);
380
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
381
  char* start = reinterpret_cast<char*>(
382
23330
      RoundUp(reinterpret_cast<uintptr_t>(*buf_), alignof(nghttp2_nv)));
383
23330
  char* header_contents = start + (count_ * sizeof(nghttp2_nv));
384
23330
  nghttp2_nv* const nva = reinterpret_cast<nghttp2_nv*>(start);
385
386
23330
  CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length());
387
69990
  CHECK_EQ(header_string.As<String>()->WriteOneByte(
388
               isolate,
389
               reinterpret_cast<uint8_t*>(header_contents),
390
               0,
391
               header_string_len,
392
               String::NO_NULL_TERMINATION),
393
           header_string_len);
394
395
23330
  size_t n = 0;
396
  char* p;
397
94740
  for (p = header_contents; p < header_contents + header_string_len; n++) {
398
71411
    if (n >= count_) {
399
      // This can happen if a passed header contained a null byte. In that
400
      // case, just provide nghttp2 with an invalid header to make it reject
401
      // the headers list.
402
      static uint8_t zero = '\0';
403
1
      nva[0].name = nva[0].value = &zero;
404
1
      nva[0].namelen = nva[0].valuelen = 1;
405
1
      count_ = 1;
406
1
      return;
407
    }
408
409
71410
    nva[n].flags = NGHTTP2_NV_FLAG_NONE;
410
71410
    nva[n].name = reinterpret_cast<uint8_t*>(p);
411
71410
    nva[n].namelen = strlen(p);
412
71410
    p += nva[n].namelen + 1;
413
71410
    nva[n].value = reinterpret_cast<uint8_t*>(p);
414
71410
    nva[n].valuelen = strlen(p);
415
71410
    p += nva[n].valuelen + 1;
416
  }
417
}
418
419
5
Origins::Origins(Isolate* isolate,
420
                 Local<Context> context,
421
                 Local<String> origin_string,
422
5
                 size_t origin_count) : count_(origin_count) {
423
5
  int origin_string_len = origin_string->Length();
424
5
  if (count_ == 0) {
425
    CHECK_EQ(origin_string_len, 0);
426
    return;
427
  }
428
429
  // Allocate a single buffer with count_ nghttp2_nv structs, followed
430
  // by the raw header data as passed from JS. This looks like:
431
  // | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents |
432
5
  buf_.AllocateSufficientStorage((alignof(nghttp2_origin_entry) - 1) +
433
5
                                 count_ * sizeof(nghttp2_origin_entry) +
434
5
                                 origin_string_len);
435
436
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
437
  char* start = reinterpret_cast<char*>(
438
5
      RoundUp(reinterpret_cast<uintptr_t>(*buf_),
439
5
              alignof(nghttp2_origin_entry)));
440
5
  char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
441
  nghttp2_origin_entry* const nva =
442
5
      reinterpret_cast<nghttp2_origin_entry*>(start);
443
444
5
  CHECK_LE(origin_contents + origin_string_len, *buf_ + buf_.length());
445
10
  CHECK_EQ(origin_string->WriteOneByte(
446
               isolate,
447
               reinterpret_cast<uint8_t*>(origin_contents),
448
               0,
449
               origin_string_len,
450
               String::NO_NULL_TERMINATION),
451
           origin_string_len);
452
453
5
  size_t n = 0;
454
  char* p;
455
14
  for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
456
9
    if (n >= count_) {
457
      static uint8_t zero = '\0';
458
      nva[0].origin = &zero;
459
      nva[0].origin_len = 1;
460
      count_ = 1;
461
      return;
462
    }
463
464
9
    nva[n].origin = reinterpret_cast<uint8_t*>(p);
465
9
    nva[n].origin_len = strlen(p);
466
9
    p += nva[n].origin_len + 1;
467
  }
468
}
469
470
// Sets the various callback functions that nghttp2 will use to notify us
471
// about significant events while processing http2 stuff.
472
8404
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
473
8404
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0);
474
475
8404
  nghttp2_session_callbacks_set_on_begin_headers_callback(
476
8404
    callbacks, OnBeginHeadersCallback);
477
8404
  nghttp2_session_callbacks_set_on_header_callback2(
478
8404
    callbacks, OnHeaderCallback);
479
8404
  nghttp2_session_callbacks_set_on_frame_recv_callback(
480
8404
    callbacks, OnFrameReceive);
481
8404
  nghttp2_session_callbacks_set_on_stream_close_callback(
482
8404
    callbacks, OnStreamClose);
483
8404
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
484
8404
    callbacks, OnDataChunkReceived);
485
8404
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
486
8404
    callbacks, OnFrameNotSent);
487
8404
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
488
8404
    callbacks, OnInvalidHeader);
489
8404
  nghttp2_session_callbacks_set_error_callback(
490
8404
    callbacks, OnNghttpError);
491
8404
  nghttp2_session_callbacks_set_send_data_callback(
492
8404
    callbacks, OnSendData);
493
8404
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
494
8404
    callbacks, OnInvalidFrame);
495
8404
  nghttp2_session_callbacks_set_on_frame_send_callback(
496
8404
    callbacks, OnFrameSent);
497
498
8404
  if (kHasGetPaddingCallback) {
499
4202
    nghttp2_session_callbacks_set_select_padding_callback(
500
4202
      callbacks, OnSelectPadding);
501
  }
502
8404
}
503
504
505
16808
Http2Session::Callbacks::~Callbacks() {
506
8404
  nghttp2_session_callbacks_del(callbacks);
507
8404
}
508
509
24832
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
510
24832
  StopTrackingMemory(buf);
511
24832
}
512
513
199720
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
514
199720
  CHECK_GE(current_nghttp2_memory_, previous_size);
515
199720
}
516
517
100728
void Http2Session::IncreaseAllocatedSize(size_t size) {
518
100728
  current_nghttp2_memory_ += size;
519
100728
}
520
521
123824
void Http2Session::DecreaseAllocatedSize(size_t size) {
522
123824
  current_nghttp2_memory_ -= size;
523
123824
}
524
525
590
Http2Session::Http2Session(Environment* env,
526
                           Local<Object> wrap,
527
590
                           nghttp2_session_type type)
528
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
529
1180
      session_type_(type) {
530
590
  MakeWeak();
531
590
  statistics_.start_time = uv_hrtime();
532
533
  // Capture the configuration options for this session
534
1180
  Http2Options opts(env, type);
535
536
590
  max_session_memory_ = opts.GetMaxSessionMemory();
537
538
590
  uint32_t maxHeaderPairs = opts.GetMaxHeaderPairs();
539
590
  max_header_pairs_ =
540
      type == NGHTTP2_SESSION_SERVER
541
1468
          ? std::max(maxHeaderPairs, 4U)     // minimum # of request headers
542
878
          : std::max(maxHeaderPairs, 1U);    // minimum # of response headers
543
544
590
  max_outstanding_pings_ = opts.GetMaxOutstandingPings();
545
590
  max_outstanding_settings_ = opts.GetMaxOutstandingSettings();
546
547
590
  padding_strategy_ = opts.GetPaddingStrategy();
548
549
  bool hasGetPaddingCallback =
550
590
      padding_strategy_ != PADDING_STRATEGY_NONE;
551
552
  nghttp2_session_callbacks* callbacks
553
590
      = callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks;
554
555
590
  auto fn = type == NGHTTP2_SESSION_SERVER ?
556
      nghttp2_session_server_new3 :
557
590
      nghttp2_session_client_new3;
558
559
590
  nghttp2_mem alloc_info = MakeAllocator();
560
561
  // This should fail only if the system is out of memory, which
562
  // is going to cause lots of other problems anyway, or if any
563
  // of the options are out of acceptable range, which we should
564
  // be catching before it gets this far. Either way, crash if this
565
  // fails.
566
590
  CHECK_EQ(fn(&session_, callbacks, this, *opts, &alloc_info), 0);
567
568
590
  outgoing_storage_.reserve(1024);
569
590
  outgoing_buffers_.reserve(32);
570
571
  // Make the js_fields_ property accessible to JS land.
572
  js_fields_store_ =
573
590
      ArrayBuffer::NewBackingStore(env->isolate(), sizeof(SessionJSFields));
574
590
  js_fields_ = new(js_fields_store_->Data()) SessionJSFields;
575
576
590
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), js_fields_store_);
577
  Local<Uint8Array> uint8_arr =
578
590
      Uint8Array::New(ab, 0, kSessionUint8FieldCount);
579
1770
  USE(wrap->Set(env->context(), env->fields_string(), uint8_arr));
580
590
}
581
582
2360
Http2Session::~Http2Session() {
583
590
  CHECK_EQ(flags_ & SESSION_STATE_HAS_SCOPE, 0);
584
590
  Debug(this, "freeing nghttp2 session");
585
590
  nghttp2_session_del(session_);
586
590
  CHECK_EQ(current_nghttp2_memory_, 0);
587
  js_fields_->~SessionJSFields();
588
1180
}
589
590
126
std::string Http2Session::diagnostic_name() const {
591
252
  return std::string("Http2Session ") + TypeName() + " (" +
592
378
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
593
}
594
595
24064
inline bool HasHttp2Observer(Environment* env) {
596
24064
  AliasedUint32Array& observers = env->performance_state()->observers;
597
24064
  return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
598
}
599
600
23491
void Http2Stream::EmitStatistics() {
601
23491
  if (!HasHttp2Observer(env()))
602
23489
    return;
603
  auto entry =
604
4
      std::make_unique<Http2StreamPerformanceEntry>(env(), id_, statistics_);
605
12
  env()->SetImmediate([entry = move(entry)](Environment* env) {
606
2
    if (!HasHttp2Observer(env))
607
      return;
608
4
    HandleScope handle_scope(env->isolate());
609
2
    AliasedFloat64Array& buffer = env->http2_state()->stream_stats_buffer;
610
2
    buffer[IDX_STREAM_STATS_ID] = entry->id();
611
2
    if (entry->first_byte() != 0) {
612
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] =
613
          (entry->first_byte() - entry->startTimeNano()) / 1e6;
614
    } else {
615
2
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0;
616
    }
617
2
    if (entry->first_header() != 0) {
618
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] =
619
2
          (entry->first_header() - entry->startTimeNano()) / 1e6;
620
    } else {
621
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0;
622
    }
623
2
    if (entry->first_byte_sent() != 0) {
624
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] =
625
1
          (entry->first_byte_sent() - entry->startTimeNano()) / 1e6;
626
    } else {
627
1
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0;
628
    }
629
2
    buffer[IDX_STREAM_STATS_SENTBYTES] = entry->sent_bytes();
630
2
    buffer[IDX_STREAM_STATS_RECEIVEDBYTES] = entry->received_bytes();
631
    Local<Object> obj;
632
6
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
633
2
  });
634
}
635
636
569
void Http2Session::EmitStatistics() {
637
569
  if (!HasHttp2Observer(env()))
638
567
    return;
639
  auto entry = std::make_unique<Http2SessionPerformanceEntry>(
640
4
      env(), statistics_, session_type_);
641
12
  env()->SetImmediate([entry = std::move(entry)](Environment* env) {
642
2
    if (!HasHttp2Observer(env))
643
      return;
644
4
    HandleScope handle_scope(env->isolate());
645
2
    AliasedFloat64Array& buffer = env->http2_state()->session_stats_buffer;
646
2
    buffer[IDX_SESSION_STATS_TYPE] = entry->type();
647
2
    buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6;
648
2
    buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count();
649
2
    buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent();
650
2
    buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count();
651
    buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] =
652
2
        entry->stream_average_duration();
653
2
    buffer[IDX_SESSION_STATS_DATA_SENT] = entry->data_sent();
654
2
    buffer[IDX_SESSION_STATS_DATA_RECEIVED] = entry->data_received();
655
    buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] =
656
2
        entry->max_concurrent_streams();
657
    Local<Object> obj;
658
6
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
659
2
  });
660
}
661
662
// Closes the session and frees the associated resources
663
569
void Http2Session::Close(uint32_t code, bool socket_closed) {
664
569
  Debug(this, "closing session");
665
666
569
  if (flags_ & SESSION_STATE_CLOSING)
667
    return;
668
569
  flags_ |= SESSION_STATE_CLOSING;
669
670
  // Stop reading on the i/o stream
671
569
  if (stream_ != nullptr) {
672
559
    flags_ |= SESSION_STATE_READING_STOPPED;
673
559
    stream_->ReadStop();
674
  }
675
676
  // If the socket is not closed, then attempt to send a closing GOAWAY
677
  // frame. There is no guarantee that this GOAWAY will be received by
678
  // the peer but the HTTP/2 spec recommends sending it anyway. We'll
679
  // make a best effort.
680
569
  if (!socket_closed) {
681
534
    Debug(this, "terminating session with code %d", code);
682
534
    CHECK_EQ(nghttp2_session_terminate_session(session_, code), 0);
683
534
    SendPendingData();
684
35
  } else if (stream_ != nullptr) {
685
25
    stream_->RemoveStreamListener(this);
686
  }
687
688
569
  flags_ |= SESSION_STATE_CLOSED;
689
690
  // If we are writing we will get to make the callback in OnStreamAfterWrite.
691
569
  if ((flags_ & SESSION_STATE_WRITE_IN_PROGRESS) == 0) {
692
536
    Debug(this, "make done session callback");
693
1072
    HandleScope scope(env()->isolate());
694
536
    MakeCallback(env()->ondone_string(), 0, nullptr);
695
  }
696
697
  // If there are outstanding pings, those will need to be canceled, do
698
  // so on the next iteration of the event loop to avoid calling out into
699
  // javascript since this may be called during garbage collection.
700
571
  while (BaseObjectPtr<Http2Ping> ping = PopPing()) {
701
1
    ping->DetachFromSession();
702
2
    env()->SetImmediate(
703
5
        [ping = std::move(ping)](Environment* env) {
704
1
          ping->Done(false);
705
2
        });
706
1
  }
707
708
569
  statistics_.end_time = uv_hrtime();
709
569
  EmitStatistics();
710
}
711
712
// Locates an existing known stream by ID. nghttp2 has a similar method
713
// but this is faster and does not fail if the stream is not found.
714
212648
inline Http2Stream* Http2Session::FindStream(int32_t id) {
715
212648
  auto s = streams_.find(id);
716
212648
  return s != streams_.end() ? s->second : nullptr;
717
}
718
719
11902
inline bool Http2Session::CanAddStream() {
720
  uint32_t maxConcurrentStreams =
721
11902
      nghttp2_session_get_local_settings(
722
11902
          session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
723
  size_t maxSize =
724
11902
      std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
725
  // We can add a new stream so long as we are less than the current
726
  // maximum on concurrent streams and there's enough available memory
727

23804
  return streams_.size() < maxSize &&
728
23804
         IsAvailableSessionMemory(sizeof(Http2Stream));
729
}
730
731
23600
inline void Http2Session::AddStream(Http2Stream* stream) {
732
23600
  CHECK_GE(++statistics_.stream_count, 0);
733
23600
  streams_[stream->id()] = stream;
734
23600
  size_t size = streams_.size();
735
23600
  if (size > statistics_.max_concurrent_streams)
736
1376
    statistics_.max_concurrent_streams = size;
737
23600
  IncrementCurrentSessionMemory(sizeof(*stream));
738
23600
}
739
740
741
23589
inline void Http2Session::RemoveStream(Http2Stream* stream) {
742

23589
  if (streams_.empty() || stream == nullptr)
743
    return;  // Nothing to remove, item was never added?
744
23589
  streams_.erase(stream->id());
745
23589
  DecrementCurrentSessionMemory(sizeof(*stream));
746
}
747
748
// Used as one of the Padding Strategy functions. Will attempt to ensure
749
// that the total frame size, including header bytes, are 8-byte aligned.
750
// If maxPayloadLen is smaller than the number of bytes necessary to align,
751
// will return maxPayloadLen instead.
752
4
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
753
                                            size_t maxPayloadLen) {
754
4
  size_t r = (frameLen + 9) % 8;
755
4
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
756
757
4
  size_t pad = frameLen + (8 - r);
758
759
  // If maxPayloadLen happens to be less than the calculated pad length,
760
  // use the max instead, even tho this means the frame will not be
761
  // aligned.
762
4
  pad = std::min(maxPayloadLen, pad);
763
4
  Debug(this, "using frame size padding: %d", pad);
764
4
  return pad;
765
}
766
767
// Used as one of the Padding Strategy functions. Uses the maximum amount
768
// of padding allowed for the current frame.
769
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
770
                                            size_t maxPayloadLen) {
771
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
772
  return maxPayloadLen;
773
}
774
775
// Write data received from the i/o stream to the underlying nghttp2_session.
776
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
777
// various callback functions. Each of these will typically result in a call
778
// out to JavaScript so this particular function is rather hot and can be
779
// quite expensive. This is a potential performance optimization target later.
780
31273
ssize_t Http2Session::ConsumeHTTP2Data() {
781
31273
  CHECK_NOT_NULL(stream_buf_.base);
782
31273
  CHECK_LT(stream_buf_offset_, stream_buf_.len);
783
31273
  size_t read_len = stream_buf_.len - stream_buf_offset_;
784
785
  // multiple side effects.
786
31273
  Debug(this, "receiving %d bytes [wants data? %d]",
787
        read_len,
788
62546
        nghttp2_session_want_read(session_));
789
31273
  flags_ &= ~SESSION_STATE_NGHTTP2_RECV_PAUSED;
790
  ssize_t ret =
791
62546
    nghttp2_session_mem_recv(session_,
792
31273
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
793
31273
                                 stream_buf_offset_,
794
31273
                             read_len);
795
31273
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
796
797
31273
  if (flags_ & SESSION_STATE_NGHTTP2_RECV_PAUSED) {
798
608
    CHECK_NE(flags_ & SESSION_STATE_READING_STOPPED, 0);
799
800
608
    CHECK_GT(ret, 0);
801
608
    CHECK_LE(static_cast<size_t>(ret), read_len);
802
803
608
    if (static_cast<size_t>(ret) < read_len) {
804
      // Mark the remainder of the data as available for later consumption.
805
490
      stream_buf_offset_ += ret;
806
490
      return ret;
807
    }
808
  }
809
810
  // We are done processing the current input chunk.
811
30783
  DecrementCurrentSessionMemory(stream_buf_.len);
812
30783
  stream_buf_offset_ = 0;
813
30783
  stream_buf_ab_.Reset();
814
30783
  stream_buf_allocation_.clear();
815
30783
  stream_buf_ = uv_buf_init(nullptr, 0);
816
817
30783
  if (ret < 0)
818
6
    return ret;
819
820
  // Send any data that was queued up while processing the received data.
821
30777
  if (!IsDestroyed()) {
822
30307
    SendPendingData();
823
  }
824
30777
  return ret;
825
}
826
827
828
143507
inline int32_t GetFrameID(const nghttp2_frame* frame) {
829
  // If this is a push promise, we want to grab the id of the promised stream
830
143507
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
831
      frame->push_promise.promised_stream_id :
832
143507
      frame->hd.stream_id;
833
}
834
835
836
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
837
// callback to determine if a new stream is being created or if we are simply
838
// adding a new block of headers to an existing stream. The header pairs
839
// themselves are set in the OnHeaderCallback
840
23522
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
841
                                         const nghttp2_frame* frame,
842
                                         void* user_data) {
843
23522
  Http2Session* session = static_cast<Http2Session*>(user_data);
844
23522
  int32_t id = GetFrameID(frame);
845
  Debug(session, "beginning headers for stream %d", id);
846
847
23522
  Http2Stream* stream = session->FindStream(id);
848
  // The common case is that we're creating a new stream. The less likely
849
  // case is that we're receiving a set of trailers
850
23522
  if (LIKELY(stream == nullptr)) {
851

11902
    if (UNLIKELY(!session->CanAddStream() ||
852
                 Http2Stream::New(session, id, frame->headers.cat) ==
853
                     nullptr)) {
854
2
      if (session->rejected_stream_count_++ >
855
1
          session->js_fields_->max_rejected_streams)
856
        return NGHTTP2_ERR_CALLBACK_FAILURE;
857
      // Too many concurrent streams being opened
858
1
      nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id,
859
2
                                NGHTTP2_ENHANCE_YOUR_CALM);
860
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
861
    }
862
863
11901
    session->rejected_stream_count_ = 0;
864
11620
  } else if (!stream->IsDestroyed()) {
865
11620
    stream->StartHeaders(frame->headers.cat);
866
  }
867
23521
  return 0;
868
}
869
870
// Called by nghttp2 for each header name/value pair in a HEADERS block.
871
// This had to have been preceded by a call to OnBeginHeadersCallback so
872
// the Http2Stream is guaranteed to already exist.
873
71345
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
874
                                   const nghttp2_frame* frame,
875
                                   nghttp2_rcbuf* name,
876
                                   nghttp2_rcbuf* value,
877
                                   uint8_t flags,
878
                                   void* user_data) {
879
71345
  Http2Session* session = static_cast<Http2Session*>(user_data);
880
71345
  int32_t id = GetFrameID(frame);
881
71345
  Http2Stream* stream = session->FindStream(id);
882
  // If stream is null at this point, either something odd has happened
883
  // or the stream was closed locally while header processing was occurring.
884
  // either way, do not proceed and close the stream.
885
71345
  if (UNLIKELY(stream == nullptr))
886
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
887
888
  // If the stream has already been destroyed, ignore.
889

71345
  if (!stream->IsDestroyed() && !stream->AddHeader(name, value, flags)) {
890
    // This will only happen if the connected peer sends us more
891
    // than the allowed number of header items at any given time
892
2
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
893
2
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
894
  }
895
71343
  return 0;
896
}
897
898
899
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
900
// only a handful of frame types that we care about handling here.
901
56648
int Http2Session::OnFrameReceive(nghttp2_session* handle,
902
                                 const nghttp2_frame* frame,
903
                                 void* user_data) {
904
56648
  Http2Session* session = static_cast<Http2Session*>(user_data);
905
56648
  session->statistics_.frame_count++;
906
56648
  Debug(session, "complete frame received: type: %d",
907
        frame->hd.type);
908


56648
  switch (frame->hd.type) {
909
    case NGHTTP2_DATA:
910
25350
      return session->HandleDataFrame(frame);
911
    case NGHTTP2_PUSH_PROMISE:
912
      // Intentional fall-through, handled just like headers frames
913
    case NGHTTP2_HEADERS:
914
23281
      session->HandleHeadersFrame(frame);
915
23281
      break;
916
    case NGHTTP2_SETTINGS:
917
2031
      session->HandleSettingsFrame(frame);
918
2031
      break;
919
    case NGHTTP2_PRIORITY:
920
16
      session->HandlePriorityFrame(frame);
921
16
      break;
922
    case NGHTTP2_GOAWAY:
923
274
      session->HandleGoawayFrame(frame);
924
274
      break;
925
    case NGHTTP2_PING:
926
1021
      session->HandlePingFrame(frame);
927
1021
      break;
928
    case NGHTTP2_ALTSVC:
929
4
      session->HandleAltSvcFrame(frame);
930
4
      break;
931
    case NGHTTP2_ORIGIN:
932
5
      session->HandleOriginFrame(frame);
933
5
      break;
934
    default:
935
4666
      break;
936
  }
937
31298
  return 0;
938
}
939
940
242
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
941
                                 const nghttp2_frame* frame,
942
                                 int lib_error_code,
943
                                 void* user_data) {
944
242
  Http2Session* session = static_cast<Http2Session*>(user_data);
945
946
242
  Debug(session,
947
        "invalid frame received (%u/%u), code: %d",
948
        session->invalid_frame_count_,
949
242
        session->js_fields_->max_invalid_frames,
950
        lib_error_code);
951
242
  if (session->invalid_frame_count_++ > session->js_fields_->max_invalid_frames)
952
2
    return 1;
953
954
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
955

480
  if (nghttp2_is_fatal(lib_error_code) ||
956
240
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
957
1
    Environment* env = session->env();
958
1
    Isolate* isolate = env->isolate();
959
2
    HandleScope scope(isolate);
960
1
    Local<Context> context = env->context();
961
    Context::Scope context_scope(context);
962
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
963
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
964
  }
965
240
  return 0;
966
}
967
968
// If nghttp2 is unable to send a queued up frame, it will call this callback
969
// to let us know. If the failure occurred because we are in the process of
970
// closing down the session or stream, we go ahead and ignore it. We don't
971
// really care about those and there's nothing we can reasonably do about it
972
// anyway. Other types of failures are reported up to JavaScript. This should
973
// be exceedingly rare.
974
2180
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
975
                                 const nghttp2_frame* frame,
976
                                 int error_code,
977
                                 void* user_data) {
978
2180
  Http2Session* session = static_cast<Http2Session*>(user_data);
979
2180
  Environment* env = session->env();
980
2180
  Debug(session, "frame type %d was not sent, code: %d",
981
        frame->hd.type, error_code);
982
983
  // Do not report if the frame was not sent due to the session closing
984

2184
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
985
7
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
986
5
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
987
2
      session->js_fields_->frame_error_listener_count == 0) {
988
2179
    return 0;
989
  }
990
991
1
  Isolate* isolate = env->isolate();
992
2
  HandleScope scope(isolate);
993
1
  Local<Context> context = env->context();
994
  Context::Scope context_scope(context);
995
996
  Local<Value> argv[3] = {
997
1
    Integer::New(isolate, frame->hd.stream_id),
998
1
    Integer::New(isolate, frame->hd.type),
999
    Integer::New(isolate, error_code)
1000
6
  };
1001
  session->MakeCallback(
1002
      env->http2session_on_frame_error_function(),
1003
1
      arraysize(argv), argv);
1004
1
  return 0;
1005
}
1006
1007
55737
int Http2Session::OnFrameSent(nghttp2_session* handle,
1008
                              const nghttp2_frame* frame,
1009
                              void* user_data) {
1010
55737
  Http2Session* session = static_cast<Http2Session*>(user_data);
1011
55737
  session->statistics_.frame_sent += 1;
1012
55737
  return 0;
1013
}
1014
1015
// Called by nghttp2 when a stream closes.
1016
23460
int Http2Session::OnStreamClose(nghttp2_session* handle,
1017
                                int32_t id,
1018
                                uint32_t code,
1019
                                void* user_data) {
1020
23460
  Http2Session* session = static_cast<Http2Session*>(user_data);
1021
23460
  Environment* env = session->env();
1022
23460
  Isolate* isolate = env->isolate();
1023
46920
  HandleScope scope(isolate);
1024
23460
  Local<Context> context = env->context();
1025
  Context::Scope context_scope(context);
1026
  Debug(session, "stream %d closed with code: %d", id, code);
1027
23460
  Http2Stream* stream = session->FindStream(id);
1028
  // Intentionally ignore the callback if the stream does not exist or has
1029
  // already been destroyed
1030

23460
  if (stream == nullptr || stream->IsDestroyed())
1031
53
    return 0;
1032
1033
23407
  stream->Close(code);
1034
1035
  // It is possible for the stream close to occur before the stream is
1036
  // ever passed on to the javascript side. If that happens, the callback
1037
  // will return false.
1038
23407
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
1039
  MaybeLocal<Value> answer =
1040
    stream->MakeCallback(env->http2session_on_stream_close_function(),
1041
23407
                          1, &arg);
1042

70221
  if (answer.IsEmpty() ||
1043
93628
      !(answer.ToLocalChecked()->BooleanValue(env->isolate()))) {
1044
    // Skip to destroy
1045
136
    stream->Destroy();
1046
  }
1047
23407
  return 0;
1048
}
1049
1050
// Called by nghttp2 when an invalid header has been received. For now, we
1051
// ignore these. If this callback was not provided, nghttp2 would handle
1052
// invalid headers strictly and would shut down the stream. We are intentionally
1053
// being more lenient here although we may want to revisit this choice later.
1054
4
int Http2Session::OnInvalidHeader(nghttp2_session* session,
1055
                                  const nghttp2_frame* frame,
1056
                                  nghttp2_rcbuf* name,
1057
                                  nghttp2_rcbuf* value,
1058
                                  uint8_t flags,
1059
                                  void* user_data) {
1060
  // Ignore invalid header fields by default.
1061
4
  return 0;
1062
}
1063
1064
// When nghttp2 receives a DATA frame, it will deliver the data payload to
1065
// us in discrete chunks. We push these into a linked list stored in the
1066
// Http2Sttream which is flushed out to JavaScript as quickly as possible.
1067
// This can be a particularly hot path.
1068
13707
int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
1069
                                      uint8_t flags,
1070
                                      int32_t id,
1071
                                      const uint8_t* data,
1072
                                      size_t len,
1073
                                      void* user_data) {
1074
13707
  Http2Session* session = static_cast<Http2Session*>(user_data);
1075
  Debug(session, "buffering data chunk for stream %d, size: "
1076
        "%d, flags: %d", id, len, flags);
1077
13707
  Environment* env = session->env();
1078
27414
  HandleScope scope(env->isolate());
1079
1080
  // We should never actually get a 0-length chunk so this check is
1081
  // only a precaution at this point.
1082
13707
  if (len == 0)
1083
    return 0;
1084
1085
  // Notify nghttp2 that we've consumed a chunk of data on the connection
1086
  // so that it can send a WINDOW_UPDATE frame. This is a critical part of
1087
  // the flow control process in http2
1088
13707
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1089
13707
  Http2Stream* stream = session->FindStream(id);
1090
  // If the stream has been destroyed, ignore this chunk
1091
13707
  if (stream->IsDestroyed())
1092
1
    return 0;
1093
1094
13706
  stream->statistics_.received_bytes += len;
1095
1096
  // Repeatedly ask the stream's owner for memory, and copy the read data
1097
  // into those buffers.
1098
  // The typical case is actually the exception here; Http2StreamListeners
1099
  // know about the HTTP2 session associated with this stream, so they know
1100
  // about the larger from-socket read buffer, so they do not require copying.
1101
  do {
1102
13706
    uv_buf_t buf = stream->EmitAlloc(len);
1103
13706
    ssize_t avail = len;
1104
13706
    if (static_cast<ssize_t>(buf.len) < avail)
1105
      avail = buf.len;
1106
1107
    // `buf.base == nullptr` is the default Http2StreamListener's way
1108
    // of saying that it wants a pointer to the raw original.
1109
    // Since it has access to the original socket buffer from which the data
1110
    // was read in the first place, it can use that to minimize ArrayBuffer
1111
    // allocations.
1112
13706
    if (LIKELY(buf.base == nullptr))
1113
13706
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1114
    else
1115
      memcpy(buf.base, data, avail);
1116
13706
    data += avail;
1117
13706
    len -= avail;
1118
13706
    stream->EmitRead(avail, buf);
1119
1120
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1121
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1122
    // more data is being requested.
1123
13706
    if (stream->IsReading())
1124
12599
      nghttp2_session_consume_stream(handle, id, avail);
1125
    else
1126
1107
      stream->inbound_consumed_data_while_paused_ += avail;
1127
1128
    // If we have a gathered a lot of data for output, try sending it now.
1129

27412
    if (session->outgoing_length_ > 4096 ||
1130
13706
        stream->available_outbound_length_ > 4096) {
1131
4
      session->SendPendingData();
1132
    }
1133
13706
  } while (len != 0);
1134
1135
  // If we are currently waiting for a write operation to finish, we should
1136
  // tell nghttp2 that we want to wait before we process more input data.
1137
13706
  if (session->flags_ & SESSION_STATE_WRITE_IN_PROGRESS) {
1138
608
    CHECK_NE(session->flags_ & SESSION_STATE_READING_STOPPED, 0);
1139
608
    session->flags_ |= SESSION_STATE_NGHTTP2_RECV_PAUSED;
1140
608
    return NGHTTP2_ERR_PAUSE;
1141
  }
1142
1143
13098
  return 0;
1144
}
1145
1146
// Called by nghttp2 when it needs to determine how much padding to use in
1147
// a DATA or HEADERS frame.
1148
4
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1149
                                      const nghttp2_frame* frame,
1150
                                      size_t maxPayloadLen,
1151
                                      void* user_data) {
1152
4
  Http2Session* session = static_cast<Http2Session*>(user_data);
1153
4
  ssize_t padding = frame->hd.length;
1154
1155

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

25350
  if (!stream->IsDestroyed() && frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1322
12559
    stream->EmitRead(UV_EOF);
1323
12791
  } else if (frame->hd.length == 0) {
1324
    return 1;  // Consider 0-length frame without END_STREAM an error.
1325
  }
1326
25350
  return 0;
1327
}
1328
1329
1330
// Called by OnFrameReceived when a complete GOAWAY frame has been received.
1331
274
void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
1332
274
  Isolate* isolate = env()->isolate();
1333
548
  HandleScope scope(isolate);
1334
274
  Local<Context> context = env()->context();
1335
  Context::Scope context_scope(context);
1336
1337
274
  nghttp2_goaway goaway_frame = frame->goaway;
1338
274
  Debug(this, "handling goaway frame");
1339
1340
  Local<Value> argv[3] = {
1341
    Integer::NewFromUnsigned(isolate, goaway_frame.error_code),
1342
    Integer::New(isolate, goaway_frame.last_stream_id),
1343
    Undefined(isolate)
1344
1096
  };
1345
1346
274
  size_t length = goaway_frame.opaque_data_len;
1347
274
  if (length > 0) {
1348
6
    argv[2] = Buffer::Copy(isolate,
1349
2
                           reinterpret_cast<char*>(goaway_frame.opaque_data),
1350
2
                           length).ToLocalChecked();
1351
  }
1352
1353
  MakeCallback(env()->http2session_on_goaway_data_function(),
1354
274
               arraysize(argv), argv);
1355
274
}
1356
1357
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
1358
4
void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
1359
4
  if (!(js_fields_->bitfield & (1 << kSessionHasAltsvcListeners))) return;
1360
4
  Isolate* isolate = env()->isolate();
1361
8
  HandleScope scope(isolate);
1362
4
  Local<Context> context = env()->context();
1363
  Context::Scope context_scope(context);
1364
1365
4
  int32_t id = GetFrameID(frame);
1366
1367
4
  nghttp2_extension ext = frame->ext;
1368
4
  nghttp2_ext_altsvc* altsvc = static_cast<nghttp2_ext_altsvc*>(ext.payload);
1369
4
  Debug(this, "handling altsvc frame");
1370
1371
  Local<Value> argv[3] = {
1372
    Integer::New(isolate, id),
1373
8
    String::NewFromOneByte(isolate,
1374
4
                           altsvc->origin,
1375
                           NewStringType::kNormal,
1376
4
                           altsvc->origin_len).ToLocalChecked(),
1377
8
    String::NewFromOneByte(isolate,
1378
4
                           altsvc->field_value,
1379
                           NewStringType::kNormal,
1380
4
                           altsvc->field_value_len).ToLocalChecked(),
1381
16
  };
1382
1383
  MakeCallback(env()->http2session_on_altsvc_function(),
1384
4
               arraysize(argv), argv);
1385
}
1386
1387
5
void Http2Session::HandleOriginFrame(const nghttp2_frame* frame) {
1388
5
  Isolate* isolate = env()->isolate();
1389
10
  HandleScope scope(isolate);
1390
5
  Local<Context> context = env()->context();
1391
  Context::Scope context_scope(context);
1392
1393
5
  Debug(this, "handling origin frame");
1394
1395
5
  nghttp2_extension ext = frame->ext;
1396
5
  nghttp2_ext_origin* origin = static_cast<nghttp2_ext_origin*>(ext.payload);
1397
1398
5
  size_t nov = origin->nov;
1399
10
  std::vector<Local<Value>> origin_v(nov);
1400
1401
14
  for (size_t i = 0; i < nov; ++i) {
1402
9
    const nghttp2_origin_entry& entry = origin->ov[i];
1403
18
    origin_v[i] =
1404
18
        String::NewFromOneByte(
1405
9
            isolate, entry.origin, NewStringType::kNormal, entry.origin_len)
1406
9
            .ToLocalChecked();
1407
  }
1408
5
  Local<Value> holder = Array::New(isolate, origin_v.data(), origin_v.size());
1409
5
  MakeCallback(env()->http2session_on_origin_function(), 1, &holder);
1410
5
}
1411
1412
// Called by OnFrameReceived when a complete PING frame has been received.
1413
1021
void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
1414
1021
  Isolate* isolate = env()->isolate();
1415
1023
  HandleScope scope(isolate);
1416
1021
  Local<Context> context = env()->context();
1417
2
  Context::Scope context_scope(context);
1418
  Local<Value> arg;
1419
1021
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1420
1021
  if (ack) {
1421
22
    BaseObjectPtr<Http2Ping> ping = PopPing();
1422
1423
11
    if (!ping) {
1424
      // PING Ack is unsolicited. Treat as a connection error. The HTTP/2
1425
      // spec does not require this, but there is no legitimate reason to
1426
      // receive an unsolicited PING ack on a connection. Either the peer
1427
      // is buggy or malicious, and we're not going to tolerate such
1428
      // nonsense.
1429
2
      arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1430
1
      MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1431
1
      return;
1432
    }
1433
1434
10
    ping->Done(true, frame->ping.opaque_data);
1435
10
    return;
1436
  }
1437
1438
1010
  if (!(js_fields_->bitfield & (1 << kSessionHasPingListeners))) return;
1439
  // Notify the session that a ping occurred
1440
6
  arg = Buffer::Copy(env(),
1441
                      reinterpret_cast<const char*>(frame->ping.opaque_data),
1442
4
                      8).ToLocalChecked();
1443
2
  MakeCallback(env()->http2session_on_ping_function(), 1, &arg);
1444
}
1445
1446
// Called by OnFrameReceived when a complete SETTINGS frame has been received.
1447
2031
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
1448
2031
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1449
2031
  if (!ack) {
1450
1541
    js_fields_->bitfield &= ~(1 << kSessionRemoteSettingsIsUpToDate);
1451
1541
    if (!(js_fields_->bitfield & (1 << kSessionHasRemoteSettingsListeners)))
1452
3561
      return;
1453
    // This is not a SETTINGS acknowledgement, notify and return
1454
11
    MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
1455
11
    return;
1456
  }
1457
1458
  // If this is an acknowledgement, we should have an Http2Settings
1459
  // object for it.
1460
490
  BaseObjectPtr<Http2Settings> settings = PopSettings();
1461
490
  if (settings) {
1462
490
    settings->Done(true);
1463
490
    return;
1464
  }
1465
  // SETTINGS Ack is unsolicited. Treat as a connection error. The HTTP/2
1466
  // spec does not require this, but there is no legitimate reason to
1467
  // receive an unsolicited SETTINGS ack on a connection. Either the peer
1468
  // is buggy or malicious, and we're not going to tolerate such
1469
  // nonsense.
1470
  // Note that nghttp2 currently prevents this from happening for SETTINGS
1471
  // frames, so this block is purely defensive just in case that behavior
1472
  // changes. Specifically, unlike unsolicited PING acks, unsolicited
1473
  // SETTINGS acks should *never* make it this far.
1474
  Isolate* isolate = env()->isolate();
1475
  HandleScope scope(isolate);
1476
  Local<Context> context = env()->context();
1477
  Context::Scope context_scope(context);
1478
  Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1479
  MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1480
}
1481
1482
// Callback used when data has been written to the stream.
1483
1317
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
1484
1317
  Debug(this, "write finished with status %d", status);
1485
1486
1317
  CHECK_NE(flags_ & SESSION_STATE_WRITE_IN_PROGRESS, 0);
1487
1317
  flags_ &= ~SESSION_STATE_WRITE_IN_PROGRESS;
1488
1489
  // Inform all pending writes about their completion.
1490
1317
  ClearOutgoing(status);
1491
1492

3951
  if ((flags_ & SESSION_STATE_READING_STOPPED) &&
1493

2629
      !(flags_ & SESSION_STATE_WRITE_IN_PROGRESS) &&
1494
1312
      nghttp2_session_want_read(session_)) {
1495
1282
    flags_ &= ~SESSION_STATE_READING_STOPPED;
1496
1282
    stream_->ReadStart();
1497
  }
1498
1499
1317
  if ((flags_ & SESSION_STATE_CLOSED) != 0) {
1500
66
    HandleScope scope(env()->isolate());
1501
33
    MakeCallback(env()->ondone_string(), 0, nullptr);
1502
33
    return;
1503
  }
1504
1505
  // If there is more incoming data queued up, consume it.
1506
1284
  if (stream_buf_offset_ > 0) {
1507
257
    ConsumeHTTP2Data();
1508
  }
1509
1510
1284
  if (!(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1511
    // Schedule a new write if nghttp2 wants to send data.
1512
1100
    MaybeScheduleWrite();
1513
  }
1514
}
1515
1516
// If the underlying nghttp2_session struct has data pending in its outbound
1517
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1518
// on the next iteration of the Node.js event loop (using the SetImmediate
1519
// queue), but only if a write has not already been scheduled.
1520
33382
void Http2Session::MaybeScheduleWrite() {
1521
33382
  CHECK_EQ(flags_ & SESSION_STATE_WRITE_SCHEDULED, 0);
1522
33382
  if (UNLIKELY(session_ == nullptr))
1523
    return;
1524
1525
33382
  if (nghttp2_session_want_write(session_)) {
1526
5222
    HandleScope handle_scope(env()->isolate());
1527
2611
    Debug(this, "scheduling write");
1528
2611
    flags_ |= SESSION_STATE_WRITE_SCHEDULED;
1529
5222
    BaseObjectPtr<Http2Session> strong_ref{this};
1530
22761
    env()->SetImmediate([this, strong_ref](Environment* env) {
1531

5222
      if (session_ == nullptr || !(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
1532
        // This can happen e.g. when a stream was reset before this turn
1533
        // of the event loop, in which case SendPendingData() is called early,
1534
        // or the session was destroyed in the meantime.
1535
369
        return;
1536
      }
1537
1538
      // Sending data may call arbitrary JS code, so keep track of
1539
      // async context.
1540
4484
      HandleScope handle_scope(env->isolate());
1541
4484
      InternalCallbackScope callback_scope(this);
1542
2242
      SendPendingData();
1543
2611
    });
1544
  }
1545
}
1546
1547
63064
void Http2Session::MaybeStopReading() {
1548
63064
  if (flags_ & SESSION_STATE_READING_STOPPED) return;
1549
60488
  int want_read = nghttp2_session_want_read(session_);
1550
60488
  Debug(this, "wants read? %d", want_read);
1551

60488
  if (want_read == 0 || (flags_ & SESSION_STATE_WRITE_IN_PROGRESS)) {
1552
1292
    flags_ |= SESSION_STATE_READING_STOPPED;
1553
1292
    stream_->ReadStop();
1554
  }
1555
}
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
33023
void Http2Session::ClearOutgoing(int status) {
1560
33023
  CHECK_NE(flags_ & SESSION_STATE_SENDING, 0);
1561
1562
33023
  flags_ &= ~SESSION_STATE_SENDING;
1563
1564
33023
  if (outgoing_buffers_.size() > 0) {
1565
32060
    outgoing_storage_.clear();
1566
32060
    outgoing_length_ = 0;
1567
1568
64120
    std::vector<nghttp2_stream_write> current_outgoing_buffers_;
1569
32060
    current_outgoing_buffers_.swap(outgoing_buffers_);
1570
124680
    for (const nghttp2_stream_write& wr : current_outgoing_buffers_) {
1571
92620
      WriteWrap* wrap = wr.req_wrap;
1572
92620
      if (wrap != nullptr) {
1573
        // TODO(addaleax): Pass `status` instead of 0, so that we actually error
1574
        // out with the error from the write to the underlying protocol,
1575
        // if one occurred.
1576
3669
        wrap->Done(0);
1577
      }
1578
    }
1579
  }
1580
1581
  // Now that we've finished sending queued data, if there are any pending
1582
  // RstStreams we should try sending again and then flush them one by one.
1583
33023
  if (pending_rst_streams_.size() > 0) {
1584
12
    std::vector<int32_t> current_pending_rst_streams;
1585
6
    pending_rst_streams_.swap(current_pending_rst_streams);
1586
1587
6
    SendPendingData();
1588
1589
14
    for (int32_t stream_id : current_pending_rst_streams) {
1590
8
      Http2Stream* stream = FindStream(stream_id);
1591
8
      if (LIKELY(stream != nullptr))
1592
8
        stream->FlushRstStream();
1593
    }
1594
  }
1595
33023
}
1596
1597
92633
void Http2Session::PushOutgoingBuffer(nghttp2_stream_write&& write) {
1598
92633
  outgoing_length_ += write.buf.len;
1599
92633
  outgoing_buffers_.emplace_back(std::move(write));
1600
92633
}
1601
1602
// Queue a given block of data for sending. This always creates a copy,
1603
// so it is used for the cases in which nghttp2 requests sending of a
1604
// small chunk of data.
1605
56026
void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
1606
56026
  size_t offset = outgoing_storage_.size();
1607
56026
  outgoing_storage_.resize(offset + src_length);
1608
56026
  memcpy(&outgoing_storage_[offset], src, src_length);
1609
1610
  // Store with a base of `nullptr` initially, since future resizes
1611
  // of the outgoing_buffers_ vector may invalidate the pointer.
1612
  // The correct base pointers will be set later, before writing to the
1613
  // underlying socket.
1614
112052
  PushOutgoingBuffer(nghttp2_stream_write {
1615
    uv_buf_init(nullptr, src_length)
1616
56026
  });
1617
56026
}
1618
1619
// Prompts nghttp2 to begin serializing it's pending data and pushes each
1620
// chunk out to the i/o socket to be sent. This is a particularly hot method
1621
// that will generally be called at least twice be event loop iteration.
1622
// This is a potential performance optimization target later.
1623
// Returns non-zero value if a write is already in progress.
1624
33300
uint8_t Http2Session::SendPendingData() {
1625
33300
  Debug(this, "sending pending data");
1626
  // Do not attempt to send data on the socket if the destroying flag has
1627
  // been set. That means everything is shutting down and the socket
1628
  // will not be usable.
1629
33300
  if (IsDestroyed())
1630
28
    return 0;
1631
33272
  flags_ &= ~SESSION_STATE_WRITE_SCHEDULED;
1632
1633
  // SendPendingData should not be called recursively.
1634
33272
  if (flags_ & SESSION_STATE_SENDING)
1635
244
    return 1;
1636
  // This is cleared by ClearOutgoing().
1637
33028
  flags_ |= SESSION_STATE_SENDING;
1638
1639
  ssize_t src_length;
1640
  const uint8_t* src;
1641
1642
33028
  CHECK_EQ(outgoing_buffers_.size(), 0);
1643
33028
  CHECK_EQ(outgoing_storage_.size(), 0);
1644
1645
  // Part One: Gather data from nghttp2
1646
1647
43196
  while ((src_length = nghttp2_session_mem_send(session_, &src)) > 0) {
1648
43196
    Debug(this, "nghttp2 has %d bytes to send", src_length);
1649
43196
    CopyDataIntoOutgoing(src, src_length);
1650
  }
1651
1652
33028
  CHECK_NE(src_length, NGHTTP2_ERR_NOMEM);
1653
1654
33028
  if (stream_ == nullptr) {
1655
    // It would seem nice to bail out earlier, but `nghttp2_session_mem_send()`
1656
    // does take care of things like closing the individual streams after
1657
    // a socket has been torn down, so we still need to call it.
1658
11
    ClearOutgoing(UV_ECANCELED);
1659
11
    return 0;
1660
  }
1661
1662
  // Part Two: Pass Data to the underlying stream
1663
1664
33017
  size_t count = outgoing_buffers_.size();
1665
33017
  if (count == 0) {
1666
963
    ClearOutgoing(0);
1667
963
    return 0;
1668
  }
1669
64108
  MaybeStackBuffer<uv_buf_t, 32> bufs;
1670
32054
  bufs.AllocateSufficientStorage(count);
1671
1672
  // Set the buffer base pointers for copied data that ended up in the
1673
  // sessions's own storage since it might have shifted around during gathering.
1674
  // (Those are marked by having .base == nullptr.)
1675
32054
  size_t offset = 0;
1676
32054
  size_t i = 0;
1677
124672
  for (const nghttp2_stream_write& write : outgoing_buffers_) {
1678
92618
    statistics_.data_sent += write.buf.len;
1679
92618
    if (write.buf.base == nullptr) {
1680
56011
      bufs[i++] = uv_buf_init(
1681
56011
          reinterpret_cast<char*>(outgoing_storage_.data() + offset),
1682
112022
          write.buf.len);
1683
56011
      offset += write.buf.len;
1684
    } else {
1685
36607
      bufs[i++] = write.buf;
1686
    }
1687
  }
1688
1689
32054
  chunks_sent_since_last_write_++;
1690
1691
32054
  CHECK_EQ(flags_ & SESSION_STATE_WRITE_IN_PROGRESS, 0);
1692
32054
  flags_ |= SESSION_STATE_WRITE_IN_PROGRESS;
1693
32054
  StreamWriteResult res = underlying_stream()->Write(*bufs, count);
1694
32054
  if (!res.async) {
1695
30732
    flags_ &= ~SESSION_STATE_WRITE_IN_PROGRESS;
1696
30732
    ClearOutgoing(res.err);
1697
  }
1698
1699
32054
  MaybeStopReading();
1700
1701
32054
  return 0;
1702
}
1703
1704
1705
// This callback is called from nghttp2 when it wants to send DATA frames for a
1706
// given Http2Stream, when we set the `NGHTTP2_DATA_FLAG_NO_COPY` flag earlier
1707
// in the Http2Stream::Provider::Stream::OnRead callback.
1708
// We take the write information directly out of the stream's data queue.
1709
12829
int Http2Session::OnSendData(
1710
      nghttp2_session* session_,
1711
      nghttp2_frame* frame,
1712
      const uint8_t* framehd,
1713
      size_t length,
1714
      nghttp2_data_source* source,
1715
      void* user_data) {
1716
12829
  Http2Session* session = static_cast<Http2Session*>(user_data);
1717
12829
  Http2Stream* stream = GetStream(session, frame->hd.stream_id, source);
1718
1719
  // Send the frame header + a byte that indicates padding length.
1720
12829
  session->CopyDataIntoOutgoing(framehd, 9);
1721
12829
  if (frame->data.padlen > 0) {
1722
1
    uint8_t padding_byte = frame->data.padlen - 1;
1723
1
    CHECK_EQ(padding_byte, frame->data.padlen - 1);
1724
1
    session->CopyDataIntoOutgoing(&padding_byte, 1);
1725
  }
1726
1727
  Debug(session, "nghttp2 has %d bytes to send directly", length);
1728
67725
  while (length > 0) {
1729
    // nghttp2 thinks that there is data available (length > 0), which means
1730
    // we told it so, which means that we *should* have data available.
1731
36606
    CHECK(!stream->queue_.empty());
1732
1733
36606
    nghttp2_stream_write& write = stream->queue_.front();
1734
36606
    if (write.buf.len <= length) {
1735
      // This write does not suffice by itself, so we can consume it completely.
1736
27448
      length -= write.buf.len;
1737
27448
      session->PushOutgoingBuffer(std::move(write));
1738
27448
      stream->queue_.pop();
1739
27448
      continue;
1740
    }
1741
1742
    // Slice off `length` bytes of the first write in the queue.
1743
18316
    session->PushOutgoingBuffer(nghttp2_stream_write {
1744
      uv_buf_init(write.buf.base, length)
1745
9158
    });
1746
9158
    write.buf.base += length;
1747
9158
    write.buf.len -= length;
1748
9158
    break;
1749
  }
1750
1751
12829
  if (frame->data.padlen > 0) {
1752
    // Send padding if that was requested.
1753
2
    session->PushOutgoingBuffer(nghttp2_stream_write {
1754
1
      uv_buf_init(const_cast<char*>(zero_bytes_256), frame->data.padlen - 1)
1755
1
    });
1756
  }
1757
1758
12829
  return 0;
1759
}
1760
1761
// Creates a new Http2Stream and submits a new http2 request.
1762
11691
Http2Stream* Http2Session::SubmitRequest(
1763
    nghttp2_priority_spec* prispec,
1764
    nghttp2_nv* nva,
1765
    size_t len,
1766
    int32_t* ret,
1767
    int options) {
1768
11691
  Debug(this, "submitting request");
1769
23382
  Http2Scope h2scope(this);
1770
11691
  Http2Stream* stream = nullptr;
1771
23382
  Http2Stream::Provider::Stream prov(options);
1772
11691
  *ret = nghttp2_submit_request(session_, prispec, nva, len, *prov, nullptr);
1773
11691
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
1774
11691
  if (LIKELY(*ret > 0))
1775
11690
    stream = Http2Stream::New(this, *ret, NGHTTP2_HCAT_HEADERS, options);
1776
23382
  return stream;
1777
}
1778
1779
31035
uv_buf_t Http2Session::OnStreamAlloc(size_t suggested_size) {
1780
31035
  return env()->AllocateManaged(suggested_size).release();
1781
}
1782
1783
// Callback used to receive inbound data from the i/o stream
1784
31057
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
1785
62067
  HandleScope handle_scope(env()->isolate());
1786
62067
  Context::Scope context_scope(env()->context());
1787
62067
  Http2Scope h2scope(this);
1788
31057
  CHECK_NOT_NULL(stream_);
1789
31057
  Debug(this, "receiving %d bytes, offset %d", nread, stream_buf_offset_);
1790
62067
  AllocatedBuffer buf(env(), buf_);
1791
1792
  // Only pass data on if nread > 0
1793
31057
  if (nread <= 0) {
1794
41
    if (nread < 0) {
1795
41
      PassReadErrorToPreviousListener(nread);
1796
    }
1797
41
    return;
1798
  }
1799
1800
31016
  statistics_.data_received += nread;
1801
1802
31016
  if (LIKELY(stream_buf_offset_ == 0)) {
1803
    // Shrink to the actual amount of used data.
1804
30784
    buf.Resize(nread);
1805
30784
    IncrementCurrentSessionMemory(nread);
1806
  } else {
1807
    // This is a very unlikely case, and should only happen if the ReadStart()
1808
    // call in OnStreamAfterWrite() immediately provides data. If that does
1809
    // happen, we concatenate the data we received with the already-stored
1810
    // pending input data, slicing off the already processed part.
1811
232
    size_t pending_len = stream_buf_.len - stream_buf_offset_;
1812
464
    AllocatedBuffer new_buf = env()->AllocateManaged(pending_len + nread);
1813
232
    memcpy(new_buf.data(), stream_buf_.base + stream_buf_offset_, pending_len);
1814
232
    memcpy(new_buf.data() + pending_len, buf.data(), nread);
1815
1816
    // The data in stream_buf_ is already accounted for, add nread received
1817
    // bytes to session memory but remove the already processed
1818
    // stream_buf_offset_ bytes.
1819
232
    IncrementCurrentSessionMemory(nread - stream_buf_offset_);
1820
1821
232
    buf = std::move(new_buf);
1822
232
    nread = buf.size();
1823
232
    stream_buf_offset_ = 0;
1824
232
    stream_buf_ab_.Reset();
1825
  }
1826
1827
  // Remember the current buffer, so that OnDataChunkReceived knows the
1828
  // offset of a DATA frame's data into the socket read buffer.
1829
31016
  stream_buf_ = uv_buf_init(buf.data(), nread);
1830
1831
31016
  Isolate* isolate = env()->isolate();
1832
1833
  // Store this so we can create an ArrayBuffer for read data from it.
1834
  // DATA frames will be emitted as slices of that ArrayBuffer to avoid having
1835
  // to copy memory.
1836
31016
  stream_buf_allocation_ = std::move(buf);
1837
1838
31016
  ssize_t ret = ConsumeHTTP2Data();
1839
1840
31016
  if (UNLIKELY(ret < 0)) {
1841
6
    Debug(this, "fatal error receiving data: %d", ret);
1842
6
    Local<Value> arg = Integer::New(isolate, ret);
1843
6
    MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1844
6
    return;
1845
  }
1846
1847
31010
  MaybeStopReading();
1848
}
1849
1850
23481
bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
1851
23669
  for (const nghttp2_stream_write& wr : outgoing_buffers_) {
1852


189
    if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream)
1853
1
      return true;
1854
  }
1855
23480
  return false;
1856
}
1857
1858
// Every Http2Session session is tightly bound to a single i/o StreamBase
1859
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1860
// tightly coupled with all data transfer between the two happening at the
1861
// C++ layer via the StreamBase API.
1862
590
void Http2Session::Consume(Local<Object> stream_obj) {
1863
590
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1864
590
  stream->PushStreamListener(this);
1865
590
  Debug(this, "i/o stream consumed");
1866
590
}
1867
1868
23600
Http2Stream* Http2Stream::New(Http2Session* session,
1869
                              int32_t id,
1870
                              nghttp2_headers_category category,
1871
                              int options) {
1872
  Local<Object> obj;
1873
47200
  if (!session->env()
1874
47200
           ->http2stream_constructor_template()
1875
70800
           ->NewInstance(session->env()->context())
1876
23600
           .ToLocal(&obj)) {
1877
    return nullptr;
1878
  }
1879
23600
  return new Http2Stream(session, obj, id, category, options);
1880
}
1881
1882
23600
Http2Stream::Http2Stream(Http2Session* session,
1883
                         Local<Object> obj,
1884
                         int32_t id,
1885
                         nghttp2_headers_category category,
1886
23600
                         int options)
1887
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
1888
      StreamBase(session->env()),
1889
      session_(session),
1890
      id_(id),
1891
23600
      current_headers_category_(category) {
1892
23600
  MakeWeak();
1893
23600
  StreamBase::AttachToObject(GetObject());
1894
23600
  statistics_.start_time = uv_hrtime();
1895
1896
  // Limit the number of header pairs
1897
23600
  max_header_pairs_ = session->GetMaxHeaderPairs();
1898
23600
  if (max_header_pairs_ == 0) {
1899
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1900
  }
1901
23600
  current_headers_.reserve(std::min(max_header_pairs_, 12u));
1902
1903
  // Limit the number of header octets
1904
23600
  max_header_length_ =
1905
23600
      std::min(
1906
47200
        nghttp2_session_get_local_settings(
1907
          session->session(),
1908
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1909
70800
      MAX_MAX_HEADER_LIST_SIZE);
1910
1911
23600
  if (options & STREAM_OPTION_GET_TRAILERS)
1912
2
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
1913
1914
23600
  PushStreamListener(&stream_listener_);
1915
1916
23600
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1917
521
    Shutdown();
1918
23600
  session->AddStream(this);
1919
23600
}
1920
1921
1922



70800
Http2Stream::~Http2Stream() {
1923
23709
  for (nghttp2_header& header : current_headers_) {
1924
109
    nghttp2_rcbuf_decref(header.name);
1925
109
    nghttp2_rcbuf_decref(header.value);
1926
  }
1927
1928
23600
  if (!session_)
1929
11
    return;
1930
23589
  Debug(this, "tearing down stream");
1931
23589
  session_->DecrementCurrentSessionMemory(current_headers_length_);
1932
23589
  session_->RemoveStream(this);
1933
47200
}
1934
1935
17
std::string Http2Stream::diagnostic_name() const {
1936
34
  return "HttpStream " + std::to_string(id()) + " (" +
1937
68
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
1938
51
      session()->diagnostic_name() + "]";
1939
}
1940
1941
// Notify the Http2Stream that a new block of HEADERS is being processed.
1942
11620
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
1943
11620
  Debug(this, "starting headers, category: %d", category);
1944
11620
  CHECK(!this->IsDestroyed());
1945
11620
  session_->DecrementCurrentSessionMemory(current_headers_length_);
1946
11620
  current_headers_length_ = 0;
1947
11620
  current_headers_.clear();
1948
11620
  current_headers_category_ = category;
1949
11620
}
1950
1951
1952
11
nghttp2_stream* Http2Stream::operator*() {
1953
11
  return nghttp2_session_find_stream(**session_, id_);
1954
}
1955
1956
23407
void Http2Stream::Close(int32_t code) {
1957
23407
  CHECK(!this->IsDestroyed());
1958
23407
  flags_ |= NGHTTP2_STREAM_FLAG_CLOSED;
1959
23407
  code_ = code;
1960
23407
  Debug(this, "closed with code %d", code);
1961
23407
}
1962
1963
23811
ShutdownWrap* Http2Stream::CreateShutdownWrap(v8::Local<v8::Object> object) {
1964
  // DoShutdown() always finishes synchronously, so there's no need to create
1965
  // a structure to store asynchronous context.
1966
23811
  return nullptr;
1967
}
1968
1969
23811
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
1970
23811
  if (IsDestroyed())
1971
    return UV_EPIPE;
1972
1973
  {
1974
47622
    Http2Scope h2scope(this);
1975
23811
    flags_ |= NGHTTP2_STREAM_FLAG_SHUT;
1976
23811
    CHECK_NE(nghttp2_session_resume_data(**session_, id_),
1977
             NGHTTP2_ERR_NOMEM);
1978
23811
    Debug(this, "writable side shutdown");
1979
  }
1980
23811
  return 1;
1981
}
1982
1983
// Destroy the Http2Stream and render it unusable. Actual resources for the
1984
// Stream will not be freed until the next tick of the Node.js event loop
1985
// using the SetImmediate queue.
1986
23491
void Http2Stream::Destroy() {
1987
  // Do nothing if this stream instance is already destroyed
1988
23491
  if (IsDestroyed())
1989
    return;
1990
23491
  if (session_->HasPendingRstStream(id_))
1991
7
    FlushRstStream();
1992
23491
  flags_ |= NGHTTP2_STREAM_FLAG_DESTROYED;
1993
1994
23491
  Debug(this, "destroying stream");
1995
1996
  // Wait until the start of the next loop to delete because there
1997
  // may still be some pending operations queued for this stream.
1998
46982
  BaseObjectPtr<Http2Stream> strong_ref{this};
1999
211423
  env()->SetImmediate([this, strong_ref](Environment* env) {
2000
    // Free any remaining outgoing data chunks here. This should be done
2001
    // here because it's possible for destroy to have been called while
2002
    // we still have queued outbound writes.
2003
23501
    while (!queue_.empty()) {
2004
5
      nghttp2_stream_write& head = queue_.front();
2005
5
      if (head.req_wrap != nullptr)
2006
5
        head.req_wrap->Done(UV_ECANCELED);
2007
5
      queue_.pop();
2008
    }
2009
2010
    // We can destroy the stream now if there are no writes for it
2011
    // already on the socket. Otherwise, we'll wait for the garbage collector
2012
    // to take care of cleaning up.
2013

46972
    if (session() == nullptr || !session()->HasWritesOnSocketForStream(this)) {
2014
      // Delete once strong_ref goes out of scope.
2015
23490
      Detach();
2016
    }
2017
46982
  });
2018
2019
23491
  statistics_.end_time = uv_hrtime();
2020
46982
  session_->statistics_.stream_average_duration =
2021
46982
      ((statistics_.end_time - statistics_.start_time) /
2022
46982
          session_->statistics_.stream_count) / 1e6;
2023
23491
  EmitStatistics();
2024
}
2025
2026
2027
// Initiates a response on the Http2Stream using data provided via the
2028
// StreamBase Streams API.
2029
11620
int Http2Stream::SubmitResponse(nghttp2_nv* nva, size_t len, int options) {
2030
11620
  CHECK(!this->IsDestroyed());
2031
23240
  Http2Scope h2scope(this);
2032
11620
  Debug(this, "submitting response");
2033
11620
  if (options & STREAM_OPTION_GET_TRAILERS)
2034
93
    flags_ |= NGHTTP2_STREAM_FLAG_TRAILERS;
2035
2036
11620
  if (!IsWritable())
2037
8
    options |= STREAM_OPTION_EMPTY_PAYLOAD;
2038
2039
23240
  Http2Stream::Provider::Stream prov(this, options);
2040
11620
  int ret = nghttp2_submit_response(**session_, id_, nva, len, *prov);
2041
11620
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2042
23240
  return ret;
2043
}
2044
2045
2046
// Submit informational headers for a stream.
2047
5
int Http2Stream::SubmitInfo(nghttp2_nv* nva, size_t len) {
2048
5
  CHECK(!this->IsDestroyed());
2049
10
  Http2Scope h2scope(this);
2050
5
  Debug(this, "sending %d informational headers", len);
2051
5
  int ret = nghttp2_submit_headers(**session_,
2052
                                   NGHTTP2_FLAG_NONE,
2053
                                   id_, nullptr,
2054
5
                                   nva, len, nullptr);
2055
5
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2056
10
  return ret;
2057
}
2058
2059
32
void Http2Stream::OnTrailers() {
2060
32
  Debug(this, "let javascript know we are ready for trailers");
2061
32
  CHECK(!this->IsDestroyed());
2062
32
  Isolate* isolate = env()->isolate();
2063
64
  HandleScope scope(isolate);
2064
32
  Local<Context> context = env()->context();
2065
  Context::Scope context_scope(context);
2066
32
  flags_ &= ~NGHTTP2_STREAM_FLAG_TRAILERS;
2067
32
  MakeCallback(env()->http2session_on_stream_trailers_function(), 0, nullptr);
2068
32
}
2069
2070
// Submit informational headers for a stream.
2071
30
int Http2Stream::SubmitTrailers(nghttp2_nv* nva, size_t len) {
2072
30
  CHECK(!this->IsDestroyed());
2073
60
  Http2Scope h2scope(this);
2074
30
  Debug(this, "sending %d trailers", len);
2075
  int ret;
2076
  // Sending an empty trailers frame poses problems in Safari, Edge & IE.
2077
  // Instead we can just send an empty data frame with NGHTTP2_FLAG_END_STREAM
2078
  // to indicate that the stream is ready to be closed.
2079
30
  if (len == 0) {
2080
50
    Http2Stream::Provider::Stream prov(this, 0);
2081
25
    ret = nghttp2_submit_data(**session_, NGHTTP2_FLAG_END_STREAM, id_, *prov);
2082
  } else {
2083
5
    ret = nghttp2_submit_trailer(**session_, id_, nva, len);
2084
  }
2085
30
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2086
60
  return ret;
2087
}
2088
2089
// Submit a PRIORITY frame to the connected peer.
2090
6
int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec,
2091
                                bool silent) {
2092
6
  CHECK(!this->IsDestroyed());
2093
12
  Http2Scope h2scope(this);
2094
6
  Debug(this, "sending priority spec");
2095
12
  int ret = silent ?
2096
      nghttp2_session_change_stream_priority(**session_,
2097
                                             id_, prispec) :
2098
6
      nghttp2_submit_priority(**session_,
2099
                              NGHTTP2_FLAG_NONE,
2100
6
                              id_, prispec);
2101
6
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2102
12
  return ret;
2103
}
2104
2105
// Closes the Http2Stream by submitting an RST_STREAM frame to the connected
2106
// peer.
2107
207
void Http2Stream::SubmitRstStream(const uint32_t code) {
2108
207
  CHECK(!this->IsDestroyed());
2109
207
  code_ = code;
2110
  // If possible, force a purge of any currently pending data here to make sure
2111
  // it is sent before closing the stream. If it returns non-zero then we need
2112
  // to wait until the current write finishes and try again to avoid nghttp2
2113
  // behaviour where it prioritizes RstStream over everything else.
2114
207
  if (session_->SendPendingData() != 0) {
2115
8
    session_->AddPendingRstStream(id_);
2116
8
    return;
2117
  }
2118
2119
199
  FlushRstStream();
2120
}
2121
2122
214
void Http2Stream::FlushRstStream() {
2123
214
  if (IsDestroyed())
2124
8
    return;
2125
412
  Http2Scope h2scope(this);
2126
206
  CHECK_EQ(nghttp2_submit_rst_stream(**session_, NGHTTP2_FLAG_NONE,
2127
                                     id_, code_), 0);
2128
}
2129
2130
2131
// Submit a push promise and create the associated Http2Stream if successful.
2132
9
Http2Stream* Http2Stream::SubmitPushPromise(nghttp2_nv* nva,
2133
                                            size_t len,
2134
                                            int32_t* ret,
2135
                                            int options) {
2136
9
  CHECK(!this->IsDestroyed());
2137
18
  Http2Scope h2scope(this);
2138
9
  Debug(this, "sending push promise");
2139
9
  *ret = nghttp2_submit_push_promise(**session_, NGHTTP2_FLAG_NONE,
2140
                                     id_, nva, len, nullptr);
2141
9
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
2142
9
  Http2Stream* stream = nullptr;
2143
9
  if (*ret > 0) {
2144
9
    stream = Http2Stream::New(
2145
9
        session_.get(), *ret, NGHTTP2_HCAT_HEADERS, options);
2146
  }
2147
2148
18
  return stream;
2149
}
2150
2151
// Switch the StreamBase into flowing mode to begin pushing chunks of data
2152
// out to JS land.
2153
23345
int Http2Stream::ReadStart() {
2154
46690
  Http2Scope h2scope(this);
2155
23345
  CHECK(!this->IsDestroyed());
2156
23345
  flags_ |= NGHTTP2_STREAM_FLAG_READ_START;
2157
23345
  flags_ &= ~NGHTTP2_STREAM_FLAG_READ_PAUSED;
2158
2159
23345
  Debug(this, "reading starting");
2160
2161
  // Tell nghttp2 about our consumption of the data that was handed
2162
  // off to JS land.
2163
23345
  nghttp2_session_consume_stream(**session_,
2164
                                 id_,
2165
23345
                                 inbound_consumed_data_while_paused_);
2166
23345
  inbound_consumed_data_while_paused_ = 0;
2167
2168
46690
  return 0;
2169
}
2170
2171
// Switch the StreamBase into paused mode.
2172
135
int Http2Stream::ReadStop() {
2173
135
  CHECK(!this->IsDestroyed());
2174
135
  if (!IsReading())
2175
93
    return 0;
2176
42
  flags_ |= NGHTTP2_STREAM_FLAG_READ_PAUSED;
2177
42
  Debug(this, "reading stopped");
2178
42
  return 0;
2179
}
2180
2181
// The Http2Stream class is a subclass of StreamBase. The DoWrite method
2182
// receives outbound chunks of data to send as outbound DATA frames. These
2183
// are queued in an internal linked list of uv_buf_t structs that are sent
2184
// when nghttp2 is ready to serialize the data frame.
2185
//
2186
// Queue the given set of uv_but_t handles for writing to an
2187
// nghttp2_stream. The WriteWrap's Done callback will be invoked once the
2188
// chunks of data have been flushed to the underlying nghttp2_session.
2189
// Note that this does *not* mean that the data has been flushed
2190
// to the socket yet.
2191
3677
int Http2Stream::DoWrite(WriteWrap* req_wrap,
2192
                         uv_buf_t* bufs,
2193
                         size_t nbufs,
2194
                         uv_stream_t* send_handle) {
2195
3677
  CHECK_NULL(send_handle);
2196
7354
  Http2Scope h2scope(this);
2197

3677
  if (!IsWritable() || IsDestroyed()) {
2198
    req_wrap->Done(UV_EOF);
2199
    return 0;
2200
  }
2201
3677
  Debug(this, "queuing %d buffers to send", nbufs);
2202
31135
  for (size_t i = 0; i < nbufs; ++i) {
2203
    // Store the req_wrap on the last write info in the queue, so that it is
2204
    // only marked as finished once all buffers associated with it are finished.
2205
82374
    queue_.emplace(nghttp2_stream_write {
2206
27458
      i == nbufs - 1 ? req_wrap : nullptr,
2207
27458
      bufs[i]
2208
27458
    });
2209
27458
    IncrementAvailableOutboundLength(bufs[i].len);
2210
  }
2211
3677
  CHECK_NE(nghttp2_session_resume_data(**session_, id_), NGHTTP2_ERR_NOMEM);
2212
3677
  return 0;
2213
}
2214
2215
// Ads a header to the Http2Stream. Note that the header name and value are
2216
// provided using a buffer structure provided by nghttp2 that allows us to
2217
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2218
// is incremented here and are decremented when the header name and values
2219
// are garbage collected later.
2220
71345
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2221
                            nghttp2_rcbuf* value,
2222
                            uint8_t flags) {
2223
71345
  CHECK(!this->IsDestroyed());
2224
71345
  if (this->statistics_.first_header == 0)
2225
23299
    this->statistics_.first_header = uv_hrtime();
2226
71345
  size_t name_len = nghttp2_rcbuf_get_buf(name).len;
2227
71345
  if (name_len == 0) return true;  // Ignore headers with empty names.
2228
71345
  size_t value_len = nghttp2_rcbuf_get_buf(value).len;
2229
71345
  size_t length = name_len + value_len + 32;
2230
  // A header can only be added if we have not exceeded the maximum number
2231
  // of headers and the session has memory available for it.
2232

214035
  if (!session_->IsAvailableSessionMemory(length) ||
2233

142689
      current_headers_.size() == max_header_pairs_ ||
2234
71344
      current_headers_length_ + length > max_header_length_) {
2235
2
    return false;
2236
  }
2237
142686
  nghttp2_header header;
2238
71343
  header.name = name;
2239
71343
  header.value = value;
2240
71343
  header.flags = flags;
2241
71343
  current_headers_.push_back(header);
2242
71343
  nghttp2_rcbuf_incref(name);
2243
71343
  nghttp2_rcbuf_incref(value);
2244
71343
  current_headers_length_ += length;
2245
71343
  session_->IncrementCurrentSessionMemory(length);
2246
71343
  return true;
2247
}
2248
2249
// A Provider is the thing that provides outbound DATA frame data.
2250
11645
Http2Stream::Provider::Provider(Http2Stream* stream, int options) {
2251
11645
  CHECK(!stream->IsDestroyed());
2252
11645
  provider_.source.ptr = stream;
2253
11645
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2254
11645
}
2255
2256
11691
Http2Stream::Provider::Provider(int options) {
2257
11691
  provider_.source.ptr = nullptr;
2258
11691
  empty_ = options & STREAM_OPTION_EMPTY_PAYLOAD;
2259
11691
}
2260
2261
46672
Http2Stream::Provider::~Provider() {
2262
23336
  provider_.source.ptr = nullptr;
2263
23336
}
2264
2265
// The Stream Provider pulls data from a linked list of uv_buf_t structs
2266
// built via the StreamBase API and the Streams js API.
2267
11691
Http2Stream::Provider::Stream::Stream(int options)
2268
11691
    : Http2Stream::Provider(options) {
2269
11691
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2270
11691
}
2271
2272
11645
Http2Stream::Provider::Stream::Stream(Http2Stream* stream, int options)
2273
11645
    : Http2Stream::Provider(stream, options) {
2274
11645
  provider_.read_callback = Http2Stream::Provider::Stream::OnRead;
2275
11645
}
2276
2277
29044
ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle,
2278
                                              int32_t id,
2279
                                              uint8_t* buf,
2280
                                              size_t length,
2281
                                              uint32_t* flags,
2282
                                              nghttp2_data_source* source,
2283
                                              void* user_data) {
2284
29044
  Http2Session* session = static_cast<Http2Session*>(user_data);
2285
  Debug(session, "reading outbound data for stream %d", id);
2286
29044
  Http2Stream* stream = GetStream(session, id, source);
2287
29044
  if (stream->statistics_.first_byte_sent == 0)
2288
12723
    stream->statistics_.first_byte_sent = uv_hrtime();
2289
29044
  CHECK_EQ(id, stream->id());
2290
2291
29044
  size_t amount = 0;          // amount of data being sent in this data frame.
2292
2293
  // Remove all empty chunks from the head of the queue.
2294
  // This is done here so that .write('', cb) is still a meaningful way to
2295
  // find out when the HTTP2 stream wants to consume data, and because the
2296
  // StreamBase API allows empty input chunks.
2297

29052
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2298
4
    WriteWrap* finished = stream->queue_.front().req_wrap;
2299
4
    stream->queue_.pop();
2300
4
    if (finished != nullptr)
2301
2
      finished->Done(0);
2302
  }
2303
2304
29044
  if (!stream->queue_.empty()) {
2305
    Debug(session, "stream %d has pending outbound data", id);
2306
12829
    amount = std::min(stream->available_outbound_length_, length);
2307
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2308
12829
    if (amount > 0) {
2309
      // Just return the length, let Http2Session::OnSendData take care of
2310
      // actually taking the buffers out of the queue.
2311
12829
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2312
12829
      stream->DecrementAvailableOutboundLength(amount);
2313
    }
2314
  }
2315
2316

29044
  if (amount == 0 && stream->IsWritable()) {
2317
3606
    CHECK(stream->queue_.empty());
2318
    Debug(session, "deferring stream %d", id);
2319
3606
    stream->EmitWantsWrite(length);
2320

3606
    if (stream->available_outbound_length_ > 0 || !stream->IsWritable()) {
2321
      // EmitWantsWrite() did something interesting synchronously, restart:
2322
      return OnRead(handle, id, buf, length, flags, source, user_data);
2323
    }
2324
3606
    return NGHTTP2_ERR_DEFERRED;
2325
  }
2326
2327

25438
  if (stream->queue_.empty() && !stream->IsWritable()) {
2328
    Debug(session, "no more data for stream %d", id);
2329
12609
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2330
12609
    if (stream->HasTrailers()) {
2331
32
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2332
32
      stream->OnTrailers();
2333
    }
2334
  }
2335
2336
25438
  stream->statistics_.sent_bytes += amount;
2337
25438
  return amount;
2338
}
2339
2340
27458
inline void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2341
27458
  available_outbound_length_ += amount;
2342
27458
  session_->IncrementCurrentSessionMemory(amount);
2343
27458
}
2344
2345
12829
inline void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2346
12829
  available_outbound_length_ -= amount;
2347
12829
  session_->DecrementCurrentSessionMemory(amount);
2348
12829
}
2349
2350
2351
// Implementation of the JavaScript API
2352
2353
// Fetches the string description of a nghttp2 error code and passes that
2354
// back to JS land
2355
54
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2356
54
  Environment* env = Environment::GetCurrent(args);
2357
216
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2358
108
  args.GetReturnValue().Set(
2359
108
      String::NewFromOneByte(
2360
          env->isolate(),
2361
54
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val)),
2362
54
          NewStringType::kInternalized).ToLocalChecked());
2363
54
}
2364
2365
2366
// Serializes the settings object into a Buffer instance that
2367
// would be suitable, for instance, for creating the Base64
2368
// output for an HTTP2-Settings header field.
2369
15
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2370
15
  Environment* env = Environment::GetCurrent(args);
2371
  // TODO(addaleax): We should not be creating a full AsyncWrap for this.
2372
  Local<Object> obj;
2373
45
  if (!env->http2settings_constructor_template()
2374
45
           ->NewInstance(env->context())
2375
15
           .ToLocal(&obj)) {
2376
    return;
2377
  }
2378
30
  Http2Session::Http2Settings settings(env, nullptr, obj);
2379
45
  args.GetReturnValue().Set(settings.Pack());
2380
}
2381
2382
// A TypedArray instance is shared between C++ and JS land to contain the
2383
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2384
// default values.
2385
3
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2386
3
  Environment* env = Environment::GetCurrent(args);
2387
3
  Http2Session::Http2Settings::RefreshDefaults(env);
2388
3
}
2389
2390
// Sets the next stream ID the Http2Session. If successful, returns true.
2391
1
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2392
1
  Environment* env = Environment::GetCurrent(args);
2393
  Http2Session* session;
2394
1
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2395
4
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2396
1
  if (nghttp2_session_set_next_stream_id(**session, id) < 0) {
2397
    Debug(session, "failed to set next stream id to %d", id);
2398
    return args.GetReturnValue().Set(false);
2399
  }
2400
2
  args.GetReturnValue().Set(true);
2401
1
  Debug(session, "set next stream id to %d", id);
2402
}
2403
2404
// A TypedArray instance is shared between C++ and JS land to contain the
2405
// SETTINGS (either remote or local). RefreshSettings updates the current
2406
// values established for each of the settings so those can be read in JS land.
2407
template <get_setting fn>
2408
512
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2409
512
  Environment* env = Environment::GetCurrent(args);
2410
  Http2Session* session;
2411

512
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2412
512
  Http2Settings::Update(env, session, fn);
2413
512
  Debug(session, "settings refreshed for session");
2414
}
2415
2416
// A TypedArray instance is shared between C++ and JS land to contain state
2417
// information of the current Http2Session. This updates the values in the
2418
// TypedArray so those can be read in JS land.
2419
3
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2420
3
  Environment* env = Environment::GetCurrent(args);
2421
  Http2Session* session;
2422
3
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2423
3
  Debug(session, "refreshing state");
2424
2425
3
  AliasedFloat64Array& buffer = env->http2_state()->session_state_buffer;
2426
2427
3
  nghttp2_session* s = **session;
2428
2429
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2430
3
      nghttp2_session_get_effective_local_window_size(s);
2431
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2432
3
      nghttp2_session_get_effective_recv_data_length(s);
2433
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2434
3
      nghttp2_session_get_next_stream_id(s);
2435
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2436
3
      nghttp2_session_get_local_window_size(s);
2437
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2438
3
      nghttp2_session_get_last_proc_stream_id(s);
2439
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2440
3
      nghttp2_session_get_remote_window_size(s);
2441
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2442
3
      nghttp2_session_get_outbound_queue_size(s);
2443
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2444
3
      nghttp2_session_get_hd_deflate_dynamic_table_size(s);
2445
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2446
3
      nghttp2_session_get_hd_inflate_dynamic_table_size(s);
2447
}
2448
2449
2450
// Constructor for new Http2Session instances.
2451
590
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2452
590
  Environment* env = Environment::GetCurrent(args);
2453
590
  CHECK(args.IsConstructCall());
2454
2360
  int val = args[0]->IntegerValue(env->context()).ToChecked();
2455
590
  nghttp2_session_type type = static_cast<nghttp2_session_type>(val);
2456
590
  Http2Session* session = new Http2Session(env, args.This(), type);
2457
590
  session->get_async_id();  // avoid compiler warning
2458
  Debug(session, "session created");
2459
590
}
2460
2461
2462
// Binds the Http2Session with a StreamBase used for i/o
2463
590
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2464
  Http2Session* session;
2465
590
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2466
1180
  CHECK(args[0]->IsObject());
2467
1180
  session->Consume(args[0].As<Object>());
2468
}
2469
2470
// Destroys the Http2Session instance and renders it unusable
2471
569
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2472
  Http2Session* session;
2473
569
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2474
569
  Debug(session, "destroying session");
2475
569
  Environment* env = Environment::GetCurrent(args);
2476
569
  Local<Context> context = env->context();
2477
2478
1707
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2479
1707
  bool socketDestroyed = args[1]->BooleanValue(env->isolate());
2480
2481
569
  session->Close(code, socketDestroyed);
2482
}
2483
2484
// Submits a new request on the Http2Session and returns either an error code
2485
// or the Http2Stream object.
2486
11691
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2487
  Http2Session* session;
2488
11692
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2489
11691
  Environment* env = session->env();
2490
11691
  Local<Context> context = env->context();
2491
11691
  Isolate* isolate = env->isolate();
2492
2493
23382
  Local<Array> headers = args[0].As<Array>();
2494
35073
  int options = args[1]->IntegerValue(context).ToChecked();
2495
11691
  Http2Priority priority(env, args[2], args[3], args[4]);
2496
2497
23381
  Headers list(isolate, context, headers);
2498
2499
11691
  Debug(session, "request submitted");
2500
2501
11691
  int32_t ret = 0;
2502
  Http2Stream* stream =
2503
11691
      session->Http2Session::SubmitRequest(*priority, *list, list.length(),
2504
11691
                                           &ret, options);
2505
2506

11691
  if (ret <= 0 || stream == nullptr) {
2507
2
    Debug(session, "could not submit request: %s", nghttp2_strerror(ret));
2508
3
    return args.GetReturnValue().Set(ret);
2509
  }
2510
2511
23380
  Debug(session, "request submitted, new stream id %d", stream->id());
2512
35070
  args.GetReturnValue().Set(stream->object());
2513
}
2514
2515
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2516
// of shutting down. Note that this function does not actually alter the
2517
// state of the Http2Session, it's simply a notification.
2518
515
void Http2Session::Goaway(uint32_t code,
2519
                          int32_t lastStreamID,
2520
                          const uint8_t* data,
2521
                          size_t len) {
2522
515
  if (IsDestroyed())
2523
    return;
2524
2525
1030
  Http2Scope h2scope(this);
2526
  // the last proc stream id is the most recently created Http2Stream.
2527
515
  if (lastStreamID <= 0)
2528
515
    lastStreamID = nghttp2_session_get_last_proc_stream_id(session_);
2529
515
  Debug(this, "submitting goaway");
2530
515
  nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE,
2531
515
                        lastStreamID, code, data, len);
2532
}
2533
2534
// Submits a GOAWAY frame to signal that the Http2Session is in the process
2535
// of shutting down. The opaque data argument is an optional TypedArray that
2536
// can be used to send debugging data to the connected peer.
2537
515
void Http2Session::Goaway(const FunctionCallbackInfo<Value>& args) {
2538
515
  Environment* env = Environment::GetCurrent(args);
2539
515
  Local<Context> context = env->context();
2540
  Http2Session* session;
2541
515
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2542
2543
1545
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2544
1545
  int32_t lastStreamID = args[1]->Int32Value(context).ToChecked();
2545
515
  ArrayBufferViewContents<uint8_t> opaque_data;
2546
2547
1030
  if (args[2]->IsArrayBufferView()) {
2548
2
    opaque_data.Read(args[2].As<ArrayBufferView>());
2549
  }
2550
2551
515
  session->Goaway(code, lastStreamID, opaque_data.data(), opaque_data.length());
2552
}
2553
2554
// Update accounting of data chunks. This is used primarily to manage timeout
2555
// logic when using the FD Provider.
2556
10
void Http2Session::UpdateChunksSent(const FunctionCallbackInfo<Value>& args) {
2557
10
  Environment* env = Environment::GetCurrent(args);
2558
10
  Isolate* isolate = env->isolate();
2559
20
  HandleScope scope(isolate);
2560
  Http2Session* session;
2561
10
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2562
2563
10
  uint32_t length = session->chunks_sent_since_last_write_;
2564
2565
30
  session->object()->Set(env->context(),
2566
                         env->chunks_sent_since_last_write_string(),
2567
50
                         Integer::NewFromUnsigned(isolate, length)).Check();
2568
2569
20
  args.GetReturnValue().Set(length);
2570
}
2571
2572
// Submits an RST_STREAM frame effectively closing the Http2Stream. Note that
2573
// this *WILL* alter the state of the stream, causing the OnStreamClose
2574
// callback to the triggered.
2575
205
void Http2Stream::RstStream(const FunctionCallbackInfo<Value>& args) {
2576
205
  Environment* env = Environment::GetCurrent(args);
2577
205
  Local<Context> context = env->context();
2578
  Http2Stream* stream;
2579
205
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2580
615
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2581
205
  Debug(stream, "sending rst_stream with code %d", code);
2582
205
  stream->SubmitRstStream(code);
2583
}
2584
2585
// Initiates a response on the Http2Stream using the StreamBase API to provide
2586
// outbound DATA frames.
2587
11620
void Http2Stream::Respond(const FunctionCallbackInfo<Value>& args) {
2588
11620
  Environment* env = Environment::GetCurrent(args);
2589
11620
  Local<Context> context = env->context();
2590
11620
  Isolate* isolate = env->isolate();
2591
  Http2Stream* stream;
2592
11620
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2593
2594
23240
  Local<Array> headers = args[0].As<Array>();
2595
34860
  int options = args[1]->IntegerValue(context).ToChecked();
2596
2597
23240
  Headers list(isolate, context, headers);
2598
2599
34860
  args.GetReturnValue().Set(
2600
      stream->SubmitResponse(*list, list.length(), options));
2601
11620
  Debug(stream, "response submitted");
2602
}
2603
2604
2605
// Submits informational headers on the Http2Stream
2606
5
void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
2607
5
  Environment* env = Environment::GetCurrent(args);
2608
5
  Local<Context> context = env->context();
2609
5
  Isolate* isolate = env->isolate();
2610
  Http2Stream* stream;
2611
5
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2612
2613
10
  Local<Array> headers = args[0].As<Array>();
2614
2615
10
  Headers list(isolate, context, headers);
2616
15
  args.GetReturnValue().Set(stream->SubmitInfo(*list, list.length()));
2617
10
  Debug(stream, "%d informational headers sent", list.length());
2618
}
2619
2620
// Submits trailing headers on the Http2Stream
2621
30
void Http2Stream::Trailers(const FunctionCallbackInfo<Value>& args) {
2622
30
  Environment* env = Environment::GetCurrent(args);
2623
30
  Local<Context> context = env->context();
2624
30
  Isolate* isolate = env->isolate();
2625
  Http2Stream* stream;
2626
30
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2627
2628
60
  Local<Array> headers = args[0].As<Array>();
2629
2630
60
  Headers list(isolate, context, headers);
2631
90
  args.GetReturnValue().Set(stream->SubmitTrailers(*list, list.length()));
2632
60
  Debug(stream, "%d trailing headers sent", list.length());
2633
}
2634
2635
// Grab the numeric id of the Http2Stream
2636
11699
void Http2Stream::GetID(const FunctionCallbackInfo<Value>& args) {
2637
  Http2Stream* stream;
2638
11699
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2639
35097
  args.GetReturnValue().Set(stream->id());
2640
}
2641
2642
// Destroy the Http2Stream, rendering it no longer usable
2643
23355
void Http2Stream::Destroy(const FunctionCallbackInfo<Value>& args) {
2644
  Http2Stream* stream;
2645
23355
  ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
2646
23355
  Debug(stream, "destroying stream");
2647
23355
  stream->Destroy();
2648
}
2649
2650
// Initiate a Push Promise and create the associated Http2Stream
2651
9
void Http2Stream::PushPromise(const FunctionCallbackInfo<Value>& args) {
2652
9
  Environment* env = Environment::GetCurrent(args);
2653
9
  Local<Context> context = env->context();
2654
9
  Isolate* isolate = env->isolate();
2655
  Http2Stream* parent;
2656
9
  ASSIGN_OR_RETURN_UNWRAP(&parent, args.Holder());
2657
2658
18
  Local<Array> headers = args[0].As<Array>();
2659
27
  int options = args[1]->IntegerValue(context).ToChecked();
2660
2661
18
  Headers list(isolate, context, headers);
2662
2663
9
  Debug(parent, "creating push promise");
2664
2665
9
  int32_t ret = 0;
2666
9
  Http2Stream* stream = parent->SubmitPushPromise(*list, list.length(),
2667
9
                                                  &ret, options);
2668

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



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

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