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: 1469 1538 95.5 %
Date: 2020-08-22 22:13:06 Branches: 553 756 73.1 %

Line Branch Exec Source
1
#include "aliased_buffer.h"
2
#include "allocated_buffer-inl.h"
3
#include "aliased_struct-inl.h"
4
#include "debug_utils-inl.h"
5
#include "memory_tracker-inl.h"
6
#include "node.h"
7
#include "node_buffer.h"
8
#include "node_http2.h"
9
#include "node_http_common-inl.h"
10
#include "node_mem-inl.h"
11
#include "node_perf.h"
12
#include "node_revert.h"
13
#include "stream_base-inl.h"
14
#include "util-inl.h"
15
16
#include <algorithm>
17
18
namespace node {
19
20
using v8::Array;
21
using v8::ArrayBuffer;
22
using v8::ArrayBufferView;
23
using v8::Boolean;
24
using v8::Context;
25
using v8::EscapableHandleScope;
26
using v8::Function;
27
using v8::FunctionCallbackInfo;
28
using v8::FunctionTemplate;
29
using v8::HandleScope;
30
using v8::Integer;
31
using v8::Isolate;
32
using v8::Local;
33
using v8::MaybeLocal;
34
using v8::Number;
35
using v8::Object;
36
using v8::ObjectTemplate;
37
using v8::String;
38
using v8::Uint8Array;
39
using v8::Undefined;
40
using v8::Value;
41
42
using node::performance::PerformanceEntry;
43
namespace http2 {
44
45
namespace {
46
47
const char zero_bytes_256[256] = {};
48
49
24258
bool HasHttp2Observer(Environment* env) {
50
24258
  AliasedUint32Array& observers = env->performance_state()->observers;
51
24258
  return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0;
52
}
53
54
}  // anonymous namespace
55
56
// These configure the callbacks required by nghttp2 itself. There are
57
// two sets of callback functions, one that is used if a padding callback
58
// is set, and other that does not include the padding callback.
59
8930
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
60
    Callbacks(false),
61
4465
    Callbacks(true)};
62
63
// The Http2Scope object is used to queue a write to the i/o stream. It is
64
// used whenever any action is take on the underlying nghttp2 API that may
65
// push data into nghttp2 outbound data queue.
66
//
67
// For example:
68
//
69
// Http2Scope h2scope(session);
70
// nghttp2_submit_ping(session->session(), ... );
71
//
72
// When the Http2Scope passes out of scope and is deconstructed, it will
73
// call Http2Session::MaybeScheduleWrite().
74
62970
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
75
76
107124
Http2Scope::Http2Scope(Http2Session* session) : session_(session) {
77
107124
  if (!session_) return;
78
79
  // If there is another scope further below on the stack, or
80
  // a write is already scheduled, there's nothing to do.
81

107124
  if (session_->is_in_scope() || session_->is_write_scheduled()) {
82
74794
    session_.reset();
83
74794
    return;
84
  }
85
32330
  session_->set_in_scope();
86
}
87
88
214248
Http2Scope::~Http2Scope() {
89
107124
  if (!session_) return;
90
32330
  session_->set_in_scope(false);
91
32330
  session_->MaybeScheduleWrite();
92
107124
}
93
94
// The Http2Options object is used during the construction of Http2Session
95
// instances to configure an appropriate nghttp2_options struct. The class
96
// uses a single TypedArray instance that is shared with the JavaScript side
97
// to more efficiently pass values back and forth.
98
630
Http2Options::Http2Options(Http2State* http2_state, SessionType type) {
99
  nghttp2_option* option;
100
630
  CHECK_EQ(nghttp2_option_new(&option), 0);
101
630
  CHECK_NOT_NULL(option);
102
630
  options_.reset(option);
103
104
  // Make sure closed connections aren't kept around, taking up memory.
105
  // Note that this breaks the priority tree, which we don't use.
106
630
  nghttp2_option_set_no_closed_streams(option, 1);
107
108
  // We manually handle flow control within a session in order to
109
  // implement backpressure -- that is, we only send WINDOW_UPDATE
110
  // frames to the remote peer as data is actually consumed by user
111
  // code. This ensures that the flow of data over the connection
112
  // does not move too quickly and limits the amount of data we
113
  // are required to buffer.
114
630
  nghttp2_option_set_no_auto_window_update(option, 1);
115
116
  // Enable built in support for receiving ALTSVC and ORIGIN frames (but
117
  // only on client side sessions
118
630
  if (type == NGHTTP2_SESSION_CLIENT) {
119
307
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ALTSVC);
120
307
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ORIGIN);
121
  }
122
123
630
  AliasedUint32Array& buffer = http2_state->options_buffer;
124
630
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
125
126
630
  if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) {
127
    nghttp2_option_set_max_deflate_dynamic_table_size(
128
        option,
129
        buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]);
130
  }
131
132
630
  if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) {
133
2
    nghttp2_option_set_max_reserved_remote_streams(
134
        option,
135
1
        buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]);
136
  }
137
138
630
  if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) {
139
1
    nghttp2_option_set_max_send_header_block_length(
140
        option,
141
2
        buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]);
142
  }
143
144
  // Recommended default
145
630
  nghttp2_option_set_peer_max_concurrent_streams(option, 100);
146
630
  if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) {
147
    nghttp2_option_set_peer_max_concurrent_streams(
148
        option,
149
        buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
150
  }
151
152
  // The padding strategy sets the mechanism by which we determine how much
153
  // additional frame padding to apply to DATA and HEADERS frames. Currently
154
  // this is set on a per-session basis, but eventually we may switch to
155
  // a per-stream setting, giving users greater control
156
630
  if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) {
157
    PaddingStrategy strategy =
158
        static_cast<PaddingStrategy>(
159
2
            buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY));
160
2
    set_padding_strategy(strategy);
161
  }
162
163
  // The max header list pairs option controls the maximum number of
164
  // header pairs the session may accept. This is a hard limit.. that is,
165
  // if the remote peer sends more than this amount, the stream will be
166
  // automatically closed with an RST_STREAM.
167
630
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS))
168
1
    set_max_header_pairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
169
170
  // The HTTP2 specification places no limits on the number of HTTP2
171
  // PING frames that can be sent. In order to prevent PINGS from being
172
  // abused as an attack vector, however, we place a strict upper limit
173
  // on the number of unacknowledged PINGS that can be sent at any given
174
  // time.
175
630
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS))
176
2
    set_max_outstanding_pings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]);
177
178
  // The HTTP2 specification places no limits on the number of HTTP2
179
  // SETTINGS frames that can be sent. In order to prevent PINGS from being
180
  // abused as an attack vector, however, we place a strict upper limit
181
  // on the number of unacknowledged SETTINGS that can be sent at any given
182
  // time.
183
630
  if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS))
184
2
    set_max_outstanding_settings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]);
185
186
  // The HTTP2 specification places no limits on the amount of memory
187
  // that a session can consume. In order to prevent abuse, we place a
188
  // cap on the amount of memory a session can consume at any given time.
189
  // this is a credit based system. Existing streams may cause the limit
190
  // to be temporarily exceeded but once over the limit, new streams cannot
191
  // created.
192
  // Important: The maxSessionMemory option in javascript is expressed in
193
  //            terms of MB increments (i.e. the value 1 == 1 MB)
194
630
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY))
195
6
    set_max_session_memory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1000000);
196
197
630
  if (flags & (1 << IDX_OPTIONS_MAX_SETTINGS)) {
198
1
    nghttp2_option_set_max_settings(
199
        option,
200
2
        static_cast<size_t>(buffer[IDX_OPTIONS_MAX_SETTINGS]));
201
  }
202
630
}
203
204
#define GRABSETTING(entries, count, name)                                      \
205
  do {                                                                         \
206
    if (flags & (1 << IDX_SETTINGS_ ## name)) {                                \
207
      uint32_t val = buffer[IDX_SETTINGS_ ## name];                            \
208
      entries[count++] =                                                       \
209
          nghttp2_settings_entry {NGHTTP2_SETTINGS_ ## name, val};             \
210
    } } while (0)
211
212
657
size_t Http2Settings::Init(
213
    Http2State* http2_state,
214
    nghttp2_settings_entry* entries) {
215
657
  AliasedUint32Array& buffer = http2_state->settings_buffer;
216
657
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
217
218
657
  size_t count = 0;
219
220
#define V(name) GRABSETTING(entries, count, name);
221



657
  HTTP2_SETTINGS(V)
222
#undef V
223
224
657
  return count;
225
}
226
#undef GRABSETTING
227
228
// The Http2Settings class is used to configure a SETTINGS frame that is
229
// to be sent to the connected peer. The settings are set using a TypedArray
230
// that is shared with the JavaScript side.
231
640
Http2Settings::Http2Settings(Http2Session* session,
232
                             Local<Object> obj,
233
                             Local<Function> callback,
234
640
                             uint64_t start_time)
235
    : AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
236
      session_(session),
237
1280
      startTime_(start_time) {
238
640
  callback_.Reset(env()->isolate(), callback);
239
640
  count_ = Init(session->http2_state(), entries_);
240
640
}
241
242
522
Local<Function> Http2Settings::callback() const {
243
1044
  return callback_.Get(env()->isolate());
244
}
245
246
4
void Http2Settings::MemoryInfo(MemoryTracker* tracker) const {
247
4
  tracker->TrackField("callback", callback_);
248
4
}
249
250
// Generates a Buffer that contains the serialized payload of a SETTINGS
251
// frame. This can be used, for instance, to create the Base64-encoded
252
// content of an Http2-Settings header field.
253
Local<Value> Http2Settings::Pack() {
254
  return Pack(session_->env(), count_, entries_);
255
}
256
257
17
Local<Value> Http2Settings::Pack(Http2State* state) {
258
  nghttp2_settings_entry entries[IDX_SETTINGS_COUNT];
259
17
  size_t count = Init(state, entries);
260
17
  return Pack(state->env(), count, entries);
261
}
262
263
17
Local<Value> Http2Settings::Pack(
264
    Environment* env,
265
    size_t count,
266
    const nghttp2_settings_entry* entries) {
267
17
  EscapableHandleScope scope(env->isolate());
268
17
  const size_t size = count * 6;
269
34
  AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
270
  ssize_t ret =
271
      nghttp2_pack_settings_payload(
272
17
          reinterpret_cast<uint8_t*>(buffer.data()),
273
          size,
274
          entries,
275
17
          count);
276
17
  Local<Value> buf = Undefined(env->isolate());
277
33
  if (ret >= 0) buf = buffer.ToBuffer().ToLocalChecked();
278
17
  return scope.Escape(buf);
279
}
280
281
// Updates the shared TypedArray with the current remote or local settings for
282
// the session.
283
543
void Http2Settings::Update(Http2Session* session, get_setting fn) {
284
543
  AliasedUint32Array& buffer = session->http2_state()->settings_buffer;
285
286
#define V(name)                                                                \
287
  buffer[IDX_SETTINGS_ ## name] =                                              \
288
      fn(session->session(), NGHTTP2_SETTINGS_ ## name);
289
543
  HTTP2_SETTINGS(V)
290
#undef V
291
543
}
292
293
// Initializes the shared TypedArray with the default settings values.
294
3
void Http2Settings::RefreshDefaults(Http2State* http2_state) {
295
3
  AliasedUint32Array& buffer = http2_state->settings_buffer;
296
3
  uint32_t flags = 0;
297
298
#define V(name)                                                            \
299
  do {                                                                     \
300
    buffer[IDX_SETTINGS_ ## name] = DEFAULT_SETTINGS_ ## name;             \
301
    flags |= 1 << IDX_SETTINGS_ ## name;                                   \
302
  } while (0);
303
3
  HTTP2_SETTINGS(V)
304
#undef V
305
306
3
  buffer[IDX_SETTINGS_COUNT] = flags;
307
3
}
308
309
310
638
void Http2Settings::Send() {
311
1276
  Http2Scope h2scope(session_.get());
312
638
  CHECK_EQ(nghttp2_submit_settings(
313
      session_->session(),
314
      NGHTTP2_FLAG_NONE,
315
      &entries_[0],
316
      count_), 0);
317
638
}
318
319
522
void Http2Settings::Done(bool ack) {
320
522
  uint64_t end = uv_hrtime();
321
522
  double duration = (end - startTime_) / 1e6;
322
323
  Local<Value> argv[] = {
324
522
    ack ? v8::True(env()->isolate()) : v8::False(env()->isolate()),
325
    Number::New(env()->isolate(), duration)
326
1566
  };
327
522
  MakeCallback(callback(), arraysize(argv), argv);
328
522
}
329
330
// The Http2Priority class initializes an appropriate nghttp2_priority_spec
331
// struct used when either creating a stream or updating its priority
332
// settings.
333
11770
Http2Priority::Http2Priority(Environment* env,
334
                             Local<Value> parent,
335
                             Local<Value> weight,
336
11770
                             Local<Value> exclusive) {
337
11770
  Local<Context> context = env->context();
338
23540
  int32_t parent_ = parent->Int32Value(context).ToChecked();
339
23540
  int32_t weight_ = weight->Int32Value(context).ToChecked();
340
11770
  bool exclusive_ = exclusive->IsTrue();
341
  Debug(env, DebugCategory::HTTP2STREAM,
342
        "Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
343
23540
        parent_, weight_, exclusive_ ? "yes" : "no");
344
11770
  nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
345
11770
}
346
347
348
118
const char* Http2Session::TypeName() const {
349
118
  switch (session_type_) {
350
59
    case NGHTTP2_SESSION_SERVER: return "server";
351
59
    case NGHTTP2_SESSION_CLIENT: return "client";
352
    default:
353
      // This should never happen
354
      ABORT();
355
  }
356
}
357
358
5
Origins::Origins(
359
    Environment* env,
360
    Local<String> origin_string,
361
5
    size_t origin_count)
362
5
    : count_(origin_count) {
363
5
  int origin_string_len = origin_string->Length();
364
5
  if (count_ == 0) {
365
    CHECK_EQ(origin_string_len, 0);
366
    return;
367
  }
368
369
10
  buf_ = AllocatedBuffer::AllocateManaged(
370
      env,
371
      (alignof(nghttp2_origin_entry) - 1) +
372
5
       count_ * sizeof(nghttp2_origin_entry) +
373
5
                              origin_string_len);
374
375
  // Make sure the start address is aligned appropriately for an nghttp2_nv*.
376
5
  char* start = AlignUp(buf_.data(), alignof(nghttp2_origin_entry));
377
5
  char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry));
378
  nghttp2_origin_entry* const nva =
379
5
      reinterpret_cast<nghttp2_origin_entry*>(start);
380
381
5
  CHECK_LE(origin_contents + origin_string_len, buf_.data() + buf_.size());
382
10
  CHECK_EQ(origin_string->WriteOneByte(
383
               env->isolate(),
384
               reinterpret_cast<uint8_t*>(origin_contents),
385
               0,
386
               origin_string_len,
387
               String::NO_NULL_TERMINATION),
388
           origin_string_len);
389
390
5
  size_t n = 0;
391
  char* p;
392
14
  for (p = origin_contents; p < origin_contents + origin_string_len; n++) {
393
9
    if (n >= count_) {
394
      static uint8_t zero = '\0';
395
      nva[0].origin = &zero;
396
      nva[0].origin_len = 1;
397
      count_ = 1;
398
      return;
399
    }
400
401
9
    nva[n].origin = reinterpret_cast<uint8_t*>(p);
402
9
    nva[n].origin_len = strlen(p);
403
9
    p += nva[n].origin_len + 1;
404
  }
405
}
406
407
// Sets the various callback functions that nghttp2 will use to notify us
408
// about significant events while processing http2 stuff.
409
8930
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
410
  nghttp2_session_callbacks* callbacks_;
411
8930
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
412
8930
  callbacks.reset(callbacks_);
413
414
  nghttp2_session_callbacks_set_on_begin_headers_callback(
415
8930
    callbacks_, OnBeginHeadersCallback);
416
  nghttp2_session_callbacks_set_on_header_callback2(
417
8930
    callbacks_, OnHeaderCallback);
418
  nghttp2_session_callbacks_set_on_frame_recv_callback(
419
8930
    callbacks_, OnFrameReceive);
420
  nghttp2_session_callbacks_set_on_stream_close_callback(
421
8930
    callbacks_, OnStreamClose);
422
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
423
8930
    callbacks_, OnDataChunkReceived);
424
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
425
8930
    callbacks_, OnFrameNotSent);
426
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
427
8930
    callbacks_, OnInvalidHeader);
428
  nghttp2_session_callbacks_set_error_callback(
429
8930
    callbacks_, OnNghttpError);
430
  nghttp2_session_callbacks_set_send_data_callback(
431
8930
    callbacks_, OnSendData);
432
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
433
8930
    callbacks_, OnInvalidFrame);
434
  nghttp2_session_callbacks_set_on_frame_send_callback(
435
8930
    callbacks_, OnFrameSent);
436
437
8930
  if (kHasGetPaddingCallback) {
438
    nghttp2_session_callbacks_set_select_padding_callback(
439
4465
      callbacks_, OnSelectPadding);
440
  }
441
8930
}
442
443
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
444
  StopTrackingMemory(buf);
445
}
446
447
201613
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
448
201613
  CHECK_GE(current_nghttp2_memory_, previous_size);
449
201613
}
450
451
101745
void Http2Session::IncreaseAllocatedSize(size_t size) {
452
101745
  current_nghttp2_memory_ += size;
453
101745
}
454
455
124979
void Http2Session::DecreaseAllocatedSize(size_t size) {
456
124979
  current_nghttp2_memory_ -= size;
457
124979
}
458
459
630
Http2Session::Http2Session(Http2State* http2_state,
460
                           Local<Object> wrap,
461
630
                           SessionType type)
462
    : AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
463
      js_fields_(http2_state->env()->isolate()),
464
      session_type_(type),
465
1260
      http2_state_(http2_state) {
466
630
  MakeWeak();
467
630
  statistics_.start_time = uv_hrtime();
468
469
  // Capture the configuration options for this session
470
1260
  Http2Options opts(http2_state, type);
471
472
630
  max_session_memory_ = opts.max_session_memory();
473
474
630
  uint32_t maxHeaderPairs = opts.max_header_pairs();
475
630
  max_header_pairs_ =
476
      type == NGHTTP2_SESSION_SERVER
477
323
          ? GetServerMaxHeaderPairs(maxHeaderPairs)
478
953
          : GetClientMaxHeaderPairs(maxHeaderPairs);
479
480
630
  max_outstanding_pings_ = opts.max_outstanding_pings();
481
630
  max_outstanding_settings_ = opts.max_outstanding_settings();
482
483
630
  padding_strategy_ = opts.padding_strategy();
484
485
  bool hasGetPaddingCallback =
486
630
      padding_strategy_ != PADDING_STRATEGY_NONE;
487
488
630
  auto fn = type == NGHTTP2_SESSION_SERVER ?
489
      nghttp2_session_server_new3 :
490
630
      nghttp2_session_client_new3;
491
492
630
  nghttp2_mem alloc_info = MakeAllocator();
493
494
  // This should fail only if the system is out of memory, which
495
  // is going to cause lots of other problems anyway, or if any
496
  // of the options are out of acceptable range, which we should
497
  // be catching before it gets this far. Either way, crash if this
498
  // fails.
499
  nghttp2_session* session;
500

630
  CHECK_EQ(fn(
501
      &session,
502
      callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks.get(),
503
      this,
504
      *opts,
505
      &alloc_info), 0);
506
630
  session_.reset(session);
507
508
630
  outgoing_storage_.reserve(1024);
509
630
  outgoing_buffers_.reserve(32);
510
511
  Local<Uint8Array> uint8_arr =
512
630
      Uint8Array::New(js_fields_.GetArrayBuffer(), 0, kSessionUint8FieldCount);
513
1890
  USE(wrap->Set(env()->context(), env()->fields_string(), uint8_arr));
514
630
}
515
516
2520
Http2Session::~Http2Session() {
517
630
  CHECK(!is_in_scope());
518
630
  Debug(this, "freeing nghttp2 session");
519
  // Explicitly reset session_ so the subsequent
520
  // current_nghttp2_memory_ check passes.
521
630
  session_.reset();
522
630
  CHECK_EQ(current_nghttp2_memory_, 0);
523
1260
}
524
525
4
void Http2Session::MemoryInfo(MemoryTracker* tracker) const {
526
4
  tracker->TrackField("streams", streams_);
527
4
  tracker->TrackField("outstanding_pings", outstanding_pings_);
528
4
  tracker->TrackField("outstanding_settings", outstanding_settings_);
529
4
  tracker->TrackField("outgoing_buffers", outgoing_buffers_);
530
4
  tracker->TrackFieldWithSize("stream_buf", stream_buf_.len);
531
4
  tracker->TrackFieldWithSize("outgoing_storage", outgoing_storage_.size());
532
4
  tracker->TrackFieldWithSize("pending_rst_streams",
533
8
                              pending_rst_streams_.size() * sizeof(int32_t));
534
4
  tracker->TrackFieldWithSize("nghttp2_memory", current_nghttp2_memory_);
535
4
}
536
537
118
std::string Http2Session::diagnostic_name() const {
538
236
  return std::string("Http2Session ") + TypeName() + " (" +
539
354
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
540
}
541
542
23637
void Http2Stream::EmitStatistics() {
543
23637
  CHECK_NOT_NULL(session());
544
23637
  if (!HasHttp2Observer(env()))
545
23629
    return;
546
  auto entry =
547
      std::make_unique<Http2StreamPerformanceEntry>(
548
16
          session()->http2_state(), id_, statistics_);
549
48
  env()->SetImmediate([entry = move(entry)](Environment* env) {
550
8
    if (!HasHttp2Observer(env))
551
      return;
552
16
    HandleScope handle_scope(env->isolate());
553
8
    AliasedFloat64Array& buffer = entry->http2_state()->stream_stats_buffer;
554
8
    buffer[IDX_STREAM_STATS_ID] = entry->id();
555
8
    if (entry->first_byte() != 0) {
556
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] =
557
          (entry->first_byte() - entry->startTimeNano()) / 1e6;
558
    } else {
559
8
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0;
560
    }
561
8
    if (entry->first_header() != 0) {
562
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] =
563
8
          (entry->first_header() - entry->startTimeNano()) / 1e6;
564
    } else {
565
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0;
566
    }
567
8
    if (entry->first_byte_sent() != 0) {
568
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] =
569
4
          (entry->first_byte_sent() - entry->startTimeNano()) / 1e6;
570
    } else {
571
4
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0;
572
    }
573
    buffer[IDX_STREAM_STATS_SENTBYTES] =
574
8
        static_cast<double>(entry->sent_bytes());
575
    buffer[IDX_STREAM_STATS_RECEIVEDBYTES] =
576
8
        static_cast<double>(entry->received_bytes());
577
    Local<Object> obj;
578
24
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
579
8
  });
580
}
581
582
606
void Http2Session::EmitStatistics() {
583
606
  if (!HasHttp2Observer(env()))
584
599
    return;
585
  auto entry = std::make_unique<Http2SessionPerformanceEntry>(
586
14
      http2_state(), statistics_, session_type_);
587
42
  env()->SetImmediate([entry = std::move(entry)](Environment* env) {
588
7
    if (!HasHttp2Observer(env))
589
      return;
590
14
    HandleScope handle_scope(env->isolate());
591
7
    AliasedFloat64Array& buffer = entry->http2_state()->session_stats_buffer;
592
7
    buffer[IDX_SESSION_STATS_TYPE] = entry->type();
593
7
    buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6;
594
7
    buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count();
595
7
    buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent();
596
7
    buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count();
597
    buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] =
598
7
        entry->stream_average_duration();
599
    buffer[IDX_SESSION_STATS_DATA_SENT] =
600
7
        static_cast<double>(entry->data_sent());
601
    buffer[IDX_SESSION_STATS_DATA_RECEIVED] =
602
7
        static_cast<double>(entry->data_received());
603
    buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] =
604
7
        static_cast<double>(entry->max_concurrent_streams());
605
    Local<Object> obj;
606
21
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
607
7
  });
608
}
609
610
// Closes the session and frees the associated resources
611
606
void Http2Session::Close(uint32_t code, bool socket_closed) {
612
606
  Debug(this, "closing session");
613
614
606
  if (is_closing())
615
    return;
616
606
  set_closing();
617
618
  // Stop reading on the i/o stream
619
606
  if (stream_ != nullptr) {
620
596
    set_reading_stopped();
621
596
    stream_->ReadStop();
622
  }
623
624
  // If the socket is not closed, then attempt to send a closing GOAWAY
625
  // frame. There is no guarantee that this GOAWAY will be received by
626
  // the peer but the HTTP/2 spec recommends sending it anyway. We'll
627
  // make a best effort.
628
606
  if (!socket_closed) {
629
571
    Debug(this, "terminating session with code %d", code);
630
571
    CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
631
571
    SendPendingData();
632
35
  } else if (stream_ != nullptr) {
633
25
    stream_->RemoveStreamListener(this);
634
  }
635
636
606
  set_destroyed();
637
638
  // If we are writing we will get to make the callback in OnStreamAfterWrite.
639
606
  if (!is_write_in_progress()) {
640
570
    Debug(this, "make done session callback");
641
1140
    HandleScope scope(env()->isolate());
642
570
    MakeCallback(env()->ondone_string(), 0, nullptr);
643
  }
644
645
  // If there are outstanding pings, those will need to be canceled, do
646
  // so on the next iteration of the event loop to avoid calling out into
647
  // javascript since this may be called during garbage collection.
648
608
  while (BaseObjectPtr<Http2Ping> ping = PopPing()) {
649
1
    ping->DetachFromSession();
650
2
    env()->SetImmediate(
651
5
        [ping = std::move(ping)](Environment* env) {
652
1
          ping->Done(false);
653
2
        });
654
1
  }
655
656
606
  statistics_.end_time = uv_hrtime();
657
606
  EmitStatistics();
658
}
659
660
// Locates an existing known stream by ID. nghttp2 has a similar method
661
// but this is faster and does not fail if the stream is not found.
662
243381
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
663
243381
  auto s = streams_.find(id);
664
243381
  return s != streams_.end() ? s->second : BaseObjectPtr<Http2Stream>();
665
}
666
667
11975
bool Http2Session::CanAddStream() {
668
  uint32_t maxConcurrentStreams =
669
11975
      nghttp2_session_get_local_settings(
670
11975
          session_.get(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
671
  size_t maxSize =
672
11975
      std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams));
673
  // We can add a new stream so long as we are less than the current
674
  // maximum on concurrent streams and there's enough available memory
675

23950
  return streams_.size() < maxSize &&
676
23950
         has_available_session_memory(sizeof(Http2Stream));
677
}
678
679
23746
void Http2Session::AddStream(Http2Stream* stream) {
680
23746
  CHECK_GE(++statistics_.stream_count, 0);
681
23746
  streams_[stream->id()] = BaseObjectPtr<Http2Stream>(stream);
682
23746
  size_t size = streams_.size();
683
23746
  if (size > statistics_.max_concurrent_streams)
684
1398
    statistics_.max_concurrent_streams = size;
685
23746
  IncrementCurrentSessionMemory(sizeof(*stream));
686
23746
}
687
688
689
23637
BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
690
23637
  BaseObjectPtr<Http2Stream> stream;
691
23637
  if (streams_.empty())
692
    return stream;
693
23637
  stream = FindStream(id);
694
23637
  if (stream) {
695
23637
    streams_.erase(id);
696
23637
    DecrementCurrentSessionMemory(sizeof(*stream));
697
  }
698
23637
  return stream;
699
}
700
701
// Used as one of the Padding Strategy functions. Will attempt to ensure
702
// that the total frame size, including header bytes, are 8-byte aligned.
703
// If maxPayloadLen is smaller than the number of bytes necessary to align,
704
// will return maxPayloadLen instead.
705
3
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
706
                                            size_t maxPayloadLen) {
707
3
  size_t r = (frameLen + 9) % 8;
708
3
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
709
710
3
  size_t pad = frameLen + (8 - r);
711
712
  // If maxPayloadLen happens to be less than the calculated pad length,
713
  // use the max instead, even tho this means the frame will not be
714
  // aligned.
715
3
  pad = std::min(maxPayloadLen, pad);
716
3
  Debug(this, "using frame size padding: %d", pad);
717
3
  return pad;
718
}
719
720
// Used as one of the Padding Strategy functions. Uses the maximum amount
721
// of padding allowed for the current frame.
722
ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen,
723
                                            size_t maxPayloadLen) {
724
  Debug(this, "using max frame size padding: %d", maxPayloadLen);
725
  return maxPayloadLen;
726
}
727
728
// Write data received from the i/o stream to the underlying nghttp2_session.
729
// On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the
730
// various callback functions. Each of these will typically result in a call
731
// out to JavaScript so this particular function is rather hot and can be
732
// quite expensive. This is a potential performance optimization target later.
733
31440
ssize_t Http2Session::ConsumeHTTP2Data() {
734
31440
  CHECK_NOT_NULL(stream_buf_.base);
735
31440
  CHECK_LE(stream_buf_offset_, stream_buf_.len);
736
31440
  size_t read_len = stream_buf_.len - stream_buf_offset_;
737
738
  // multiple side effects.
739
31440
  Debug(this, "receiving %d bytes [wants data? %d]",
740
        read_len,
741
62880
        nghttp2_session_want_read(session_.get()));
742
31440
  set_receive_paused(false);
743
  ssize_t ret =
744
62880
    nghttp2_session_mem_recv(session_.get(),
745
31440
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
746
31440
                                 stream_buf_offset_,
747
31440
                             read_len);
748
31440
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
749
750
31440
  if (is_receive_paused()) {
751
558
    CHECK(is_reading_stopped());
752
753
558
    CHECK_GT(ret, 0);
754
558
    CHECK_LE(static_cast<size_t>(ret), read_len);
755
756
    // Mark the remainder of the data as available for later consumption.
757
    // Even if all bytes were received, a paused stream may delay the
758
    // nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
759
558
    stream_buf_offset_ += ret;
760
558
    return ret;
761
  }
762
763
  // We are done processing the current input chunk.
764
30882
  DecrementCurrentSessionMemory(stream_buf_.len);
765
30882
  stream_buf_offset_ = 0;
766
30882
  stream_buf_ab_.Reset();
767
30882
  stream_buf_allocation_.clear();
768
30882
  stream_buf_ = uv_buf_init(nullptr, 0);
769
770
30882
  if (ret < 0)
771
6
    return ret;
772
773
  // Send any data that was queued up while processing the received data.
774
30876
  if (!is_destroyed()) {
775
30375
    SendPendingData();
776
  }
777
30876
  return ret;
778
}
779
780
781
143004
int32_t GetFrameID(const nghttp2_frame* frame) {
782
  // If this is a push promise, we want to grab the id of the promised stream
783
143004
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
784
      frame->push_promise.promised_stream_id :
785
143004
      frame->hd.stream_id;
786
}
787
788
789
// Called by nghttp2 at the start of receiving a HEADERS frame. We use this
790
// callback to determine if a new stream is being created or if we are simply
791
// adding a new block of headers to an existing stream. The header pairs
792
// themselves are set in the OnHeaderCallback
793
23667
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
794
                                         const nghttp2_frame* frame,
795
                                         void* user_data) {
796
23667
  Http2Session* session = static_cast<Http2Session*>(user_data);
797
23667
  int32_t id = GetFrameID(frame);
798
  Debug(session, "beginning headers for stream %d", id);
799
800
47334
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
801
  // The common case is that we're creating a new stream. The less likely
802
  // case is that we're receiving a set of trailers
803
23667
  if (LIKELY(!stream)) {
804

11975
    if (UNLIKELY(!session->CanAddStream() ||
805
                 Http2Stream::New(session, id, frame->headers.cat) ==
806
                     nullptr)) {
807
2
      if (session->rejected_stream_count_++ >
808
1
          session->js_fields_->max_rejected_streams)
809
        return NGHTTP2_ERR_CALLBACK_FAILURE;
810
      // Too many concurrent streams being opened
811
1
      nghttp2_submit_rst_stream(
812
          session->session(),
813
          NGHTTP2_FLAG_NONE,
814
          id,
815
2
          NGHTTP2_ENHANCE_YOUR_CALM);
816
1
      return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
817
    }
818
819
11974
    session->rejected_stream_count_ = 0;
820
11692
  } else if (!stream->is_destroyed()) {
821
11692
    stream->StartHeaders(frame->headers.cat);
822
  }
823
23666
  return 0;
824
}
825
826
// Called by nghttp2 for each header name/value pair in a HEADERS block.
827
// This had to have been preceded by a call to OnBeginHeadersCallback so
828
// the Http2Stream is guaranteed to already exist.
829
71791
int Http2Session::OnHeaderCallback(nghttp2_session* handle,
830
                                   const nghttp2_frame* frame,
831
                                   nghttp2_rcbuf* name,
832
                                   nghttp2_rcbuf* value,
833
                                   uint8_t flags,
834
                                   void* user_data) {
835
71791
  Http2Session* session = static_cast<Http2Session*>(user_data);
836
71791
  int32_t id = GetFrameID(frame);
837
143582
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
838
  // If stream is null at this point, either something odd has happened
839
  // or the stream was closed locally while header processing was occurring.
840
  // either way, do not proceed and close the stream.
841
71791
  if (UNLIKELY(!stream))
842
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
843
844
  // If the stream has already been destroyed, ignore.
845

71791
  if (!stream->is_destroyed() && !stream->AddHeader(name, value, flags)) {
846
    // This will only happen if the connected peer sends us more
847
    // than the allowed number of header items at any given time
848
3
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
849
3
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
850
  }
851
71788
  return 0;
852
}
853
854
855
// Called by nghttp2 when a complete HTTP2 frame has been received. There are
856
// only a handful of frame types that we care about handling here.
857
55547
int Http2Session::OnFrameReceive(nghttp2_session* handle,
858
                                 const nghttp2_frame* frame,
859
                                 void* user_data) {
860
55547
  Http2Session* session = static_cast<Http2Session*>(user_data);
861
55547
  session->statistics_.frame_count++;
862
55547
  Debug(session, "complete frame received: type: %d",
863
        frame->hd.type);
864


55547
  switch (frame->hd.type) {
865
    case NGHTTP2_DATA:
866
24112
      return session->HandleDataFrame(frame);
867
    case NGHTTP2_PUSH_PROMISE:
868
      // Intentional fall-through, handled just like headers frames
869
    case NGHTTP2_HEADERS:
870
23425
      session->HandleHeadersFrame(frame);
871
23425
      break;
872
    case NGHTTP2_SETTINGS:
873
2096
      session->HandleSettingsFrame(frame);
874
2096
      break;
875
    case NGHTTP2_PRIORITY:
876
16
      session->HandlePriorityFrame(frame);
877
16
      break;
878
    case NGHTTP2_GOAWAY:
879
293
      session->HandleGoawayFrame(frame);
880
293
      break;
881
    case NGHTTP2_PING:
882
1020
      session->HandlePingFrame(frame);
883
1020
      break;
884
    case NGHTTP2_ALTSVC:
885
4
      session->HandleAltSvcFrame(frame);
886
4
      break;
887
    case NGHTTP2_ORIGIN:
888
5
      session->HandleOriginFrame(frame);
889
5
      break;
890
    default:
891
4576
      break;
892
  }
893
31435
  return 0;
894
}
895
896
242
int Http2Session::OnInvalidFrame(nghttp2_session* handle,
897
                                 const nghttp2_frame* frame,
898
                                 int lib_error_code,
899
                                 void* user_data) {
900
242
  Http2Session* session = static_cast<Http2Session*>(user_data);
901
902
242
  Debug(session,
903
        "invalid frame received (%u/%u), code: %d",
904
        session->invalid_frame_count_,
905
242
        session->js_fields_->max_invalid_frames,
906
        lib_error_code);
907
242
  if (session->invalid_frame_count_++ > session->js_fields_->max_invalid_frames)
908
2
    return 1;
909
910
  // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
911

480
  if (nghttp2_is_fatal(lib_error_code) ||
912
240
      lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) {
913
1
    Environment* env = session->env();
914
1
    Isolate* isolate = env->isolate();
915
2
    HandleScope scope(isolate);
916
1
    Local<Context> context = env->context();
917
    Context::Scope context_scope(context);
918
1
    Local<Value> arg = Integer::New(isolate, lib_error_code);
919
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
920
  }
921
240
  return 0;
922
}
923
924
// If nghttp2 is unable to send a queued up frame, it will call this callback
925
// to let us know. If the failure occurred because we are in the process of
926
// closing down the session or stream, we go ahead and ignore it. We don't
927
// really care about those and there's nothing we can reasonably do about it
928
// anyway. Other types of failures are reported up to JavaScript. This should
929
// be exceedingly rare.
930
2181
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
931
                                 const nghttp2_frame* frame,
932
                                 int error_code,
933
                                 void* user_data) {
934
2181
  Http2Session* session = static_cast<Http2Session*>(user_data);
935
2181
  Environment* env = session->env();
936
2181
  Debug(session, "frame type %d was not sent, code: %d",
937
        frame->hd.type, error_code);
938
939
  // Do not report if the frame was not sent due to the session closing
940

4366
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
941
7
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
942

2186
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
943
2
      session->js_fields_->frame_error_listener_count == 0) {
944
2180
    return 0;
945
  }
946
947
1
  Isolate* isolate = env->isolate();
948
2
  HandleScope scope(isolate);
949
1
  Local<Context> context = env->context();
950
  Context::Scope context_scope(context);
951
952
  Local<Value> argv[3] = {
953
1
    Integer::New(isolate, frame->hd.stream_id),
954
1
    Integer::New(isolate, frame->hd.type),
955
    Integer::New(isolate, error_code)
956
6
  };
957
  session->MakeCallback(
958
      env->http2session_on_frame_error_function(),
959
1
      arraysize(argv), argv);
960
1
  return 0;
961
}
962
963
54698
int Http2Session::OnFrameSent(nghttp2_session* handle,
964
                              const nghttp2_frame* frame,
965
                              void* user_data) {
966
54698
  Http2Session* session = static_cast<Http2Session*>(user_data);
967
54698
  session->statistics_.frame_sent += 1;
968
54698
  return 0;
969
}
970
971
// Called by nghttp2 when a stream closes.
972
23610
int Http2Session::OnStreamClose(nghttp2_session* handle,
973
                                int32_t id,
974
                                uint32_t code,
975
                                void* user_data) {
976
23610
  Http2Session* session = static_cast<Http2Session*>(user_data);
977
23610
  Environment* env = session->env();
978
23610
  Isolate* isolate = env->isolate();
979
47220
  HandleScope scope(isolate);
980
23610
  Local<Context> context = env->context();
981
  Context::Scope context_scope(context);
982
  Debug(session, "stream %d closed with code: %d", id, code);
983
47220
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
984
  // Intentionally ignore the callback if the stream does not exist or has
985
  // already been destroyed
986

23610
  if (!stream || stream->is_destroyed())
987
51
    return 0;
988
989
23559
  stream->Close(code);
990
991
  // It is possible for the stream close to occur before the stream is
992
  // ever passed on to the javascript side. If that happens, the callback
993
  // will return false.
994
23559
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
995
  MaybeLocal<Value> answer =
996
23559
    stream->MakeCallback(env->http2session_on_stream_close_function(),
997
47118
                          1, &arg);
998

70677
  if (answer.IsEmpty() || answer.ToLocalChecked()->IsFalse()) {
999
    // Skip to destroy
1000
138
    stream->Destroy();
1001
  }
1002
23559
  return 0;
1003
}
1004
1005
// Called by nghttp2 when an invalid header has been received. For now, we
1006
// ignore these. If this callback was not provided, nghttp2 would handle
1007
// invalid headers strictly and would shut down the stream. We are intentionally
1008
// being more lenient here although we may want to revisit this choice later.
1009
4
int Http2Session::OnInvalidHeader(nghttp2_session* session,
1010
                                  const nghttp2_frame* frame,
1011
                                  nghttp2_rcbuf* name,
1012
                                  nghttp2_rcbuf* value,
1013
                                  uint8_t flags,
1014
                                  void* user_data) {
1015
  // Ignore invalid header fields by default.
1016
4
  return 0;
1017
}
1018
1019
// When nghttp2 receives a DATA frame, it will deliver the data payload to
1020
// us in discrete chunks. We push these into a linked list stored in the
1021
// Http2Sttream which is flushed out to JavaScript as quickly as possible.
1022
// This can be a particularly hot path.
1023
13726
int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
1024
                                      uint8_t flags,
1025
                                      int32_t id,
1026
                                      const uint8_t* data,
1027
                                      size_t len,
1028
                                      void* user_data) {
1029
13726
  Http2Session* session = static_cast<Http2Session*>(user_data);
1030
  Debug(session, "buffering data chunk for stream %d, size: "
1031
        "%d, flags: %d", id, len, flags);
1032
13726
  Environment* env = session->env();
1033
27452
  HandleScope scope(env->isolate());
1034
1035
  // We should never actually get a 0-length chunk so this check is
1036
  // only a precaution at this point.
1037
13726
  if (len == 0)
1038
    return 0;
1039
1040
  // Notify nghttp2 that we've consumed a chunk of data on the connection
1041
  // so that it can send a WINDOW_UPDATE frame. This is a critical part of
1042
  // the flow control process in http2
1043
13726
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1044
27452
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1045
1046
  // If the stream has been destroyed, ignore this chunk
1047

13726
  if (!stream || stream->is_destroyed())
1048
1
    return 0;
1049
1050
13725
  stream->statistics_.received_bytes += len;
1051
1052
  // Repeatedly ask the stream's owner for memory, and copy the read data
1053
  // into those buffers.
1054
  // The typical case is actually the exception here; Http2StreamListeners
1055
  // know about the HTTP2 session associated with this stream, so they know
1056
  // about the larger from-socket read buffer, so they do not require copying.
1057
  do {
1058
13725
    uv_buf_t buf = stream->EmitAlloc(len);
1059
13725
    ssize_t avail = len;
1060
13725
    if (static_cast<ssize_t>(buf.len) < avail)
1061
      avail = buf.len;
1062
1063
    // `buf.base == nullptr` is the default Http2StreamListener's way
1064
    // of saying that it wants a pointer to the raw original.
1065
    // Since it has access to the original socket buffer from which the data
1066
    // was read in the first place, it can use that to minimize ArrayBuffer
1067
    // allocations.
1068
13725
    if (LIKELY(buf.base == nullptr))
1069
13725
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1070
    else
1071
      memcpy(buf.base, data, avail);
1072
13725
    data += avail;
1073
13725
    len -= avail;
1074
13725
    stream->EmitRead(avail, buf);
1075
1076
    // If the stream owner (e.g. the JS Http2Stream) wants more data, just
1077
    // tell nghttp2 that all data has been consumed. Otherwise, defer until
1078
    // more data is being requested.
1079
13725
    if (stream->is_reading())
1080
12617
      nghttp2_session_consume_stream(handle, id, avail);
1081
    else
1082
1108
      stream->inbound_consumed_data_while_paused_ += avail;
1083
1084
    // If we have a gathered a lot of data for output, try sending it now.
1085

27450
    if (session->outgoing_length_ > 4096 ||
1086
13725
        stream->available_outbound_length_ > 4096) {
1087
4
      session->SendPendingData();
1088
    }
1089
13725
  } while (len != 0);
1090
1091
  // If we are currently waiting for a write operation to finish, we should
1092
  // tell nghttp2 that we want to wait before we process more input data.
1093
13725
  if (session->is_write_in_progress()) {
1094
558
    CHECK(session->is_reading_stopped());
1095
558
    session->set_receive_paused();
1096
    Debug(session, "receive paused");
1097
558
    return NGHTTP2_ERR_PAUSE;
1098
  }
1099
1100
13167
  return 0;
1101
}
1102
1103
// Called by nghttp2 when it needs to determine how much padding to use in
1104
// a DATA or HEADERS frame.
1105
3
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1106
                                      const nghttp2_frame* frame,
1107
                                      size_t maxPayloadLen,
1108
                                      void* user_data) {
1109
3
  Http2Session* session = static_cast<Http2Session*>(user_data);
1110
3
  ssize_t padding = frame->hd.length;
1111
1112

3
  switch (session->padding_strategy_) {
1113
    case PADDING_STRATEGY_NONE:
1114
      // Fall-through
1115
      break;
1116
    case PADDING_STRATEGY_MAX:
1117
      padding = session->OnMaxFrameSizePadding(padding, maxPayloadLen);
1118
      break;
1119
    case PADDING_STRATEGY_ALIGNED:
1120
3
      padding = session->OnDWordAlignedPadding(padding, maxPayloadLen);
1121
3
      break;
1122
  }
1123
3
  return padding;
1124
}
1125
1126
#define BAD_PEER_MESSAGE "Remote peer returned unexpected data while we "     \
1127
                         "expected SETTINGS frame.  Perhaps, peer does not "  \
1128
                         "support HTTP/2 properly."
1129
1130
// We use this currently to determine when an attempt is made to use the http2
1131
// protocol with a non-http2 peer.
1132
239
int Http2Session::OnNghttpError(nghttp2_session* handle,
1133
                                const char* message,
1134
                                size_t len,
1135
                                void* user_data) {
1136
  // Unfortunately, this is currently the only way for us to know if
1137
  // the session errored because the peer is not an http2 peer.
1138
239
  Http2Session* session = static_cast<Http2Session*>(user_data);
1139
  Debug(session, "Error '%.*s'", len, message);
1140
239
  if (strncmp(message, BAD_PEER_MESSAGE, len) == 0) {
1141
1
    Environment* env = session->env();
1142
1
    Isolate* isolate = env->isolate();
1143
2
    HandleScope scope(isolate);
1144
1
    Local<Context> context = env->context();
1145
    Context::Scope context_scope(context);
1146
1
    Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1147
1
    session->MakeCallback(env->http2session_on_error_function(), 1, &arg);
1148
  }
1149
239
  return 0;
1150
}
1151
1152
13725
uv_buf_t Http2StreamListener::OnStreamAlloc(size_t size) {
1153
  // See the comments in Http2Session::OnDataChunkReceived
1154
  // (which is the only possible call site for this method).
1155
13725
  return uv_buf_init(nullptr, size);
1156
}
1157
1158
26383
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1159
26383
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1160
26383
  Http2Session* session = stream->session();
1161
26383
  Environment* env = stream->env();
1162
40108
  HandleScope handle_scope(env->isolate());
1163
40108
  Context::Scope context_scope(env->context());
1164
1165
26383
  if (nread < 0) {
1166
12658
    PassReadErrorToPreviousListener(nread);
1167
12658
    return;
1168
  }
1169
1170
  Local<ArrayBuffer> ab;
1171
27450
  if (session->stream_buf_ab_.IsEmpty()) {
1172
5606
    ab = session->stream_buf_allocation_.ToArrayBuffer();
1173
5606
    session->stream_buf_ab_.Reset(env->isolate(), ab);
1174
  } else {
1175
8119
    ab = PersistentToLocal::Strong(session->stream_buf_ab_);
1176
  }
1177
1178
  // There is a single large array buffer for the entire data read from the
1179
  // network; create a slice of that array buffer and emit it as the
1180
  // received data buffer.
1181
13725
  size_t offset = buf.base - session->stream_buf_.base;
1182
1183
  // Verify that the data offset is inside the current read buffer.
1184
13725
  CHECK_GE(offset, session->stream_buf_offset_);
1185
13725
  CHECK_LE(offset, session->stream_buf_.len);
1186
13725
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1187
1188
13725
  stream->CallJSOnreadMethod(nread, ab, offset);
1189
}
1190
1191
1192
// Called by OnFrameReceived to notify JavaScript land that a complete
1193
// HEADERS frame has been received and processed. This method converts the
1194
// received headers into a JavaScript array and pushes those out to JS.
1195
23425
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1196
23425
  Isolate* isolate = env()->isolate();
1197
46850
  HandleScope scope(isolate);
1198
23425
  Local<Context> context = env()->context();
1199
23425
  Context::Scope context_scope(context);
1200
1201
23425
  int32_t id = GetFrameID(frame);
1202
23425
  Debug(this, "handle headers frame for stream %d", id);
1203
46850
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1204
1205
  // If the stream has already been destroyed, ignore.
1206

23425
  if (!stream || stream->is_destroyed())
1207
    return;
1208
1209
  // The headers are stored as a vector of Http2Header instances.
1210
  // The following converts that into a JS array with the structure:
1211
  // [name1, value1, name2, value2, name3, value3, name3, value4] and so on.
1212
  // That array is passed up to the JS layer and converted into an Object form
1213
  // like {name1: value1, name2: value2, name3: [value3, value4]}. We do it
1214
  // this way for performance reasons (it's faster to generate and pass an
1215
  // array than it is to generate and pass the object).
1216
1217
46850
  MaybeStackBuffer<Local<Value>, 64> headers_v(stream->headers_count() * 2);
1218
46850
  MaybeStackBuffer<Local<Value>, 32> sensitive_v(stream->headers_count());
1219
23425
  size_t sensitive_count = 0;
1220
1221
118527
  stream->TransferHeaders([&](const Http2Header& header, size_t i) {
1222
286713
    headers_v[i * 2] = header.GetName(this).ToLocalChecked();
1223
286708
    headers_v[i * 2 + 1] = header.GetValue(this).ToLocalChecked();
1224
71677
    if (header.flags() & NGHTTP2_NV_FLAG_NO_INDEX)
1225
10
      sensitive_v[sensitive_count++] = headers_v[i * 2];
1226
95102
  });
1227
23425
  CHECK_EQ(stream->headers_count(), 0);
1228
1229
23425
  DecrementCurrentSessionMemory(stream->current_headers_length_);
1230
23425
  stream->current_headers_length_ = 0;
1231
1232
  Local<Value> args[] = {
1233
23425
    stream->object(),
1234
    Integer::New(isolate, id),
1235
23425
    Integer::New(isolate, stream->headers_category()),
1236
23425
    Integer::New(isolate, frame->hd.flags),
1237
    Array::New(isolate, headers_v.out(), headers_v.length()),
1238
    Array::New(isolate, sensitive_v.out(), sensitive_count),
1239
234250
  };
1240
  MakeCallback(env()->http2session_on_headers_function(),
1241
23425
               arraysize(args), args);
1242
}
1243
1244
1245
// Called by OnFrameReceived when a complete PRIORITY frame has been
1246
// received. Notifies JS land about the priority change. Note that priorities
1247
// are considered advisory only, so this has no real effect other than to
1248
// simply let user code know that the priority has changed.
1249
16
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
1250
16
  if (js_fields_->priority_listener_count == 0) return;
1251
5
  Isolate* isolate = env()->isolate();
1252
10
  HandleScope scope(isolate);
1253
5
  Local<Context> context = env()->context();
1254
  Context::Scope context_scope(context);
1255
1256
5
  nghttp2_priority priority_frame = frame->priority;
1257
5
  int32_t id = GetFrameID(frame);
1258
5
  Debug(this, "handle priority frame for stream %d", id);
1259
  // Priority frame stream ID should never be <= 0. nghttp2 handles this for us
1260
5
  nghttp2_priority_spec spec = priority_frame.pri_spec;
1261
1262
  Local<Value> argv[4] = {
1263
    Integer::New(isolate, id),
1264
    Integer::New(isolate, spec.stream_id),
1265
    Integer::New(isolate, spec.weight),
1266
5
    Boolean::New(isolate, spec.exclusive)
1267
30
  };
1268
  MakeCallback(env()->http2session_on_priority_function(),
1269
5
               arraysize(argv), argv);
1270
}
1271
1272
1273
// Called by OnFrameReceived when a complete DATA frame has been received.
1274
// If we know that this was the last DATA frame (because the END_STREAM flag
1275
// is set), then we'll terminate the readable side of the StreamBase.
1276
24112
int Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1277
24112
  int32_t id = GetFrameID(frame);
1278
24112
  Debug(this, "handling data frame for stream %d", id);
1279
48224
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1280
1281

48224
  if (stream &&
1282

48224
      !stream->is_destroyed() &&
1283
24112
      frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1284
12658
    stream->EmitRead(UV_EOF);
1285
11454
  } else if (frame->hd.length == 0) {
1286
    return 1;  // Consider 0-length frame without END_STREAM an error.
1287
  }
1288
24112
  return 0;
1289
}
1290
1291
1292
// Called by OnFrameReceived when a complete GOAWAY frame has been received.
1293
293
void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
1294
293
  Isolate* isolate = env()->isolate();
1295
586
  HandleScope scope(isolate);
1296
293
  Local<Context> context = env()->context();
1297
  Context::Scope context_scope(context);
1298
1299
293
  nghttp2_goaway goaway_frame = frame->goaway;
1300
293
  Debug(this, "handling goaway frame");
1301
1302
  Local<Value> argv[3] = {
1303
    Integer::NewFromUnsigned(isolate, goaway_frame.error_code),
1304
    Integer::New(isolate, goaway_frame.last_stream_id),
1305
    Undefined(isolate)
1306
1172
  };
1307
1308
293
  size_t length = goaway_frame.opaque_data_len;
1309
293
  if (length > 0) {
1310
    // If the copy fails for any reason here, we just ignore it.
1311
    // The additional goaway data is completely optional and we
1312
    // shouldn't fail if we're not able to process it.
1313
9
    argv[2] = Buffer::Copy(isolate,
1314
3
                           reinterpret_cast<char*>(goaway_frame.opaque_data),
1315
3
                           length).ToLocalChecked();
1316
  }
1317
1318
  MakeCallback(env()->http2session_on_goaway_data_function(),
1319
293
               arraysize(argv), argv);
1320
293
}
1321
1322
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
1323
4
void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
1324
4
  if (!(js_fields_->bitfield & (1 << kSessionHasAltsvcListeners))) return;
1325
4
  Isolate* isolate = env()->isolate();
1326
8
  HandleScope scope(isolate);
1327
4
  Local<Context> context = env()->context();
1328
  Context::Scope context_scope(context);
1329
1330
4
  int32_t id = GetFrameID(frame);
1331
1332
4
  nghttp2_extension ext = frame->ext;
1333
4
  nghttp2_ext_altsvc* altsvc = static_cast<nghttp2_ext_altsvc*>(ext.payload);
1334
4
  Debug(this, "handling altsvc frame");
1335
1336
  Local<Value> argv[3] = {
1337
    Integer::New(isolate, id),
1338
8
    OneByteString(isolate, altsvc->origin, altsvc->origin_len),
1339
8
    OneByteString(isolate, altsvc->field_value, altsvc->field_value_len)
1340
32
  };
1341
1342
  MakeCallback(env()->http2session_on_altsvc_function(),
1343
4
               arraysize(argv), argv);
1344
}
1345
1346
5
void Http2Session::HandleOriginFrame(const nghttp2_frame* frame) {
1347
5
  Isolate* isolate = env()->isolate();
1348
10
  HandleScope scope(isolate);
1349
5
  Local<Context> context = env()->context();
1350
  Context::Scope context_scope(context);
1351
1352
5
  Debug(this, "handling origin frame");
1353
1354
5
  nghttp2_extension ext = frame->ext;
1355
5
  nghttp2_ext_origin* origin = static_cast<nghttp2_ext_origin*>(ext.payload);
1356
1357
5
  size_t nov = origin->nov;
1358
10
  std::vector<Local<Value>> origin_v(nov);
1359
1360
14
  for (size_t i = 0; i < nov; ++i) {
1361
9
    const nghttp2_origin_entry& entry = origin->ov[i];
1362
18
    origin_v[i] = OneByteString(isolate, entry.origin, entry.origin_len);
1363
  }
1364
5
  Local<Value> holder = Array::New(isolate, origin_v.data(), origin_v.size());
1365
5
  MakeCallback(env()->http2session_on_origin_function(), 1, &holder);
1366
5
}
1367
1368
// Called by OnFrameReceived when a complete PING frame has been received.
1369
1020
void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
1370
1020
  Isolate* isolate = env()->isolate();
1371
1022
  HandleScope scope(isolate);
1372
1020
  Local<Context> context = env()->context();
1373
2
  Context::Scope context_scope(context);
1374
  Local<Value> arg;
1375
1020
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1376
1020
  if (ack) {
1377
22
    BaseObjectPtr<Http2Ping> ping = PopPing();
1378
1379
11
    if (!ping) {
1380
      // PING Ack is unsolicited. Treat as a connection error. The HTTP/2
1381
      // spec does not require this, but there is no legitimate reason to
1382
      // receive an unsolicited PING ack on a connection. Either the peer
1383
      // is buggy or malicious, and we're not going to tolerate such
1384
      // nonsense.
1385
2
      arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1386
1
      MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1387
1
      return;
1388
    }
1389
1390
10
    ping->Done(true, frame->ping.opaque_data);
1391
10
    return;
1392
  }
1393
1394
1009
  if (!(js_fields_->bitfield & (1 << kSessionHasPingListeners))) return;
1395
  // Notify the session that a ping occurred
1396
6
  arg = Buffer::Copy(
1397
      env(),
1398
      reinterpret_cast<const char*>(frame->ping.opaque_data),
1399
4
      8).ToLocalChecked();
1400
2
  MakeCallback(env()->http2session_on_ping_function(), 1, &arg);
1401
}
1402
1403
// Called by OnFrameReceived when a complete SETTINGS frame has been received.
1404
2096
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
1405
2096
  bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
1406
2096
  if (!ack) {
1407
1576
    js_fields_->bitfield &= ~(1 << kSessionRemoteSettingsIsUpToDate);
1408
1576
    if (!(js_fields_->bitfield & (1 << kSessionHasRemoteSettingsListeners)))
1409
3660
      return;
1410
    // This is not a SETTINGS acknowledgement, notify and return
1411
12
    MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
1412
12
    return;
1413
  }
1414
1415
  // If this is an acknowledgement, we should have an Http2Settings
1416
  // object for it.
1417
520
  BaseObjectPtr<Http2Settings> settings = PopSettings();
1418
520
  if (settings) {
1419
520
    settings->Done(true);
1420
520
    return;
1421
  }
1422
  // SETTINGS Ack is unsolicited. Treat as a connection error. The HTTP/2
1423
  // spec does not require this, but there is no legitimate reason to
1424
  // receive an unsolicited SETTINGS ack on a connection. Either the peer
1425
  // is buggy or malicious, and we're not going to tolerate such
1426
  // nonsense.
1427
  // Note that nghttp2 currently prevents this from happening for SETTINGS
1428
  // frames, so this block is purely defensive just in case that behavior
1429
  // changes. Specifically, unlike unsolicited PING acks, unsolicited
1430
  // SETTINGS acks should *never* make it this far.
1431
  Isolate* isolate = env()->isolate();
1432
  HandleScope scope(isolate);
1433
  Local<Context> context = env()->context();
1434
  Context::Scope context_scope(context);
1435
  Local<Value> arg = Integer::New(isolate, NGHTTP2_ERR_PROTO);
1436
  MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1437
}
1438
1439
// Callback used when data has been written to the stream.
1440
1267
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
1441
1267
  Debug(this, "write finished with status %d", status);
1442
1443
1267
  CHECK(is_write_in_progress());
1444
1267
  set_write_in_progress(false);
1445
1446
  // Inform all pending writes about their completion.
1447
1267
  ClearOutgoing(status);
1448
1449

3799
  if (is_reading_stopped() &&
1450

2528
      !is_write_in_progress() &&
1451
1261
      nghttp2_session_want_read(session_.get())) {
1452
1226
    set_reading_stopped(false);
1453
1226
    stream_->ReadStart();
1454
  }
1455
1456
1267
  if (is_destroyed()) {
1457
72
    HandleScope scope(env()->isolate());
1458
36
    MakeCallback(env()->ondone_string(), 0, nullptr);
1459
36
    return;
1460
  }
1461
1462
  // If there is more incoming data queued up, consume it.
1463
1231
  if (stream_buf_offset_ > 0) {
1464
300
    ConsumeHTTP2Data();
1465
  }
1466
1467
1231
  if (!is_write_scheduled()) {
1468
    // Schedule a new write if nghttp2 wants to send data.
1469
1124
    MaybeScheduleWrite();
1470
  }
1471
}
1472
1473
// If the underlying nghttp2_session struct has data pending in its outbound
1474
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1475
// on the next iteration of the Node.js event loop (using the SetImmediate
1476
// queue), but only if a write has not already been scheduled.
1477
33454
void Http2Session::MaybeScheduleWrite() {
1478
33454
  CHECK(!is_write_scheduled());
1479
33454
  if (UNLIKELY(!session_))
1480
    return;
1481
1482
33454
  if (nghttp2_session_want_write(session_.get())) {
1483
2868
    HandleScope handle_scope(env()->isolate());
1484
1434
    Debug(this, "scheduling write");
1485
1434
    set_write_scheduled();
1486
2868
    BaseObjectPtr<Http2Session> strong_ref{this};
1487
12348
    env()->SetImmediate([this, strong_ref](Environment* env) {
1488

2868
      if (!session_ || !is_write_scheduled()) {
1489
        // This can happen e.g. when a stream was reset before this turn
1490
        // of the event loop, in which case SendPendingData() is called early,
1491
        // or the session was destroyed in the meantime.
1492
279
        return;
1493
      }
1494
1495
      // Sending data may call arbitrary JS code, so keep track of
1496
      // async context.
1497
2310
      HandleScope handle_scope(env->isolate());
1498
2310
      InternalCallbackScope callback_scope(this);
1499
1155
      SendPendingData();
1500
1434
    });
1501
  }
1502
}
1503
1504
62195
void Http2Session::MaybeStopReading() {
1505
62195
  if (is_reading_stopped()) return;
1506
59598
  int want_read = nghttp2_session_want_read(session_.get());
1507
59598
  Debug(this, "wants read? %d", want_read);
1508

59598
  if (want_read == 0 || is_write_in_progress()) {
1509
1236
    set_reading_stopped();
1510
1236
    stream_->ReadStop();
1511
  }
1512
}
1513
1514
// Unset the sending state, finish up all current writes, and reset
1515
// storage for data and metadata that was associated with these writes.
1516
32061
void Http2Session::ClearOutgoing(int status) {
1517
32061
  CHECK(is_sending());
1518
1519
32061
  set_sending(false);
1520
1521
32061
  if (!outgoing_buffers_.empty()) {
1522
31067
    outgoing_storage_.clear();
1523
31067
    outgoing_length_ = 0;
1524
1525
62134
    std::vector<NgHttp2StreamWrite> current_outgoing_buffers_;
1526
31067
    current_outgoing_buffers_.swap(outgoing_buffers_);
1527
122688
    for (const NgHttp2StreamWrite& wr : current_outgoing_buffers_) {
1528
91621
      WriteWrap* wrap = wr.req_wrap;
1529
91621
      if (wrap != nullptr) {
1530
        // TODO(addaleax): Pass `status` instead of 0, so that we actually error
1531
        // out with the error from the write to the underlying protocol,
1532
        // if one occurred.
1533
3683
        wrap->Done(0);
1534
      }
1535
    }
1536
  }
1537
1538
  // Now that we've finished sending queued data, if there are any pending
1539
  // RstStreams we should try sending again and then flush them one by one.
1540
32061
  if (!pending_rst_streams_.empty()) {
1541
12
    std::vector<int32_t> current_pending_rst_streams;
1542
6
    pending_rst_streams_.swap(current_pending_rst_streams);
1543
1544
6
    SendPendingData();
1545
1546
14
    for (int32_t stream_id : current_pending_rst_streams) {
1547
16
      BaseObjectPtr<Http2Stream> stream = FindStream(stream_id);
1548
8
      if (LIKELY(stream))
1549
1
        stream->FlushRstStream();
1550
    }
1551
  }
1552
32061
}
1553
1554
91633
void Http2Session::PushOutgoingBuffer(NgHttp2StreamWrite&& write) {
1555
91633
  outgoing_length_ += write.buf.len;
1556
91633
  outgoing_buffers_.emplace_back(std::move(write));
1557
91633
}
1558
1559
// Queue a given block of data for sending. This always creates a copy,
1560
// so it is used for the cases in which nghttp2 requests sending of a
1561
// small chunk of data.
1562
55006
void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
1563
55006
  size_t offset = outgoing_storage_.size();
1564
55006
  outgoing_storage_.resize(offset + src_length);
1565
55006
  memcpy(&outgoing_storage_[offset], src, src_length);
1566
1567
  // Store with a base of `nullptr` initially, since future resizes
1568
  // of the outgoing_buffers_ vector may invalidate the pointer.
1569
  // The correct base pointers will be set later, before writing to the
1570
  // underlying socket.
1571
110012
  PushOutgoingBuffer(NgHttp2StreamWrite {
1572
    uv_buf_init(nullptr, src_length)
1573
55006
  });
1574
55006
}
1575
1576
// Prompts nghttp2 to begin serializing it's pending data and pushes each
1577
// chunk out to the i/o socket to be sent. This is a particularly hot method
1578
// that will generally be called at least twice be event loop iteration.
1579
// This is a potential performance optimization target later.
1580
// Returns non-zero value if a write is already in progress.
1581
32221
uint8_t Http2Session::SendPendingData() {
1582
32221
  Debug(this, "sending pending data");
1583
  // Do not attempt to send data on the socket if the destroying flag has
1584
  // been set. That means everything is shutting down and the socket
1585
  // will not be usable.
1586
32221
  if (is_destroyed())
1587
31
    return 0;
1588
32190
  set_write_scheduled(false);
1589
1590
  // SendPendingData should not be called recursively.
1591
32190
  if (is_sending())
1592
125
    return 1;
1593
  // This is cleared by ClearOutgoing().
1594
32065
  set_sending();
1595
1596
  ssize_t src_length;
1597
  const uint8_t* src;
1598
1599
32065
  CHECK(outgoing_buffers_.empty());
1600
32065
  CHECK(outgoing_storage_.empty());
1601
1602
  // Part One: Gather data from nghttp2
1603
1604
42158
  while ((src_length = nghttp2_session_mem_send(session_.get(), &src)) > 0) {
1605
42158
    Debug(this, "nghttp2 has %d bytes to send", src_length);
1606
42158
    CopyDataIntoOutgoing(src, src_length);
1607
  }
1608
1609
32065
  CHECK_NE(src_length, NGHTTP2_ERR_NOMEM);
1610
1611
32065
  if (stream_ == nullptr) {
1612
    // It would seem nice to bail out earlier, but `nghttp2_session_mem_send()`
1613
    // does take care of things like closing the individual streams after
1614
    // a socket has been torn down, so we still need to call it.
1615
10
    ClearOutgoing(UV_ECANCELED);
1616
10
    return 0;
1617
  }
1618
1619
  // Part Two: Pass Data to the underlying stream
1620
1621
32055
  size_t count = outgoing_buffers_.size();
1622
32055
  if (count == 0) {
1623
994
    ClearOutgoing(0);
1624
994
    return 0;
1625
  }
1626
62122
  MaybeStackBuffer<uv_buf_t, 32> bufs;
1627
31061
  bufs.AllocateSufficientStorage(count);
1628
1629
  // Set the buffer base pointers for copied data that ended up in the
1630
  // sessions's own storage since it might have shifted around during gathering.
1631
  // (Those are marked by having .base == nullptr.)
1632
31061
  size_t offset = 0;
1633
31061
  size_t i = 0;
1634
122680
  for (const NgHttp2StreamWrite& write : outgoing_buffers_) {
1635
91619
    statistics_.data_sent += write.buf.len;
1636
91619
    if (write.buf.base == nullptr) {
1637
54992
      bufs[i++] = uv_buf_init(
1638
54992
          reinterpret_cast<char*>(outgoing_storage_.data() + offset),
1639
109984
          write.buf.len);
1640
54992
      offset += write.buf.len;
1641
    } else {
1642
36627
      bufs[i++] = write.buf;
1643
    }
1644
  }
1645
1646
31061
  chunks_sent_since_last_write_++;
1647
1648
31061
  CHECK(!is_write_in_progress());
1649
31061
  set_write_in_progress();
1650
31061
  StreamWriteResult res = underlying_stream()->Write(*bufs, count);
1651
31061
  if (!res.async) {
1652
29790
    set_write_in_progress(false);
1653
29790
    ClearOutgoing(res.err);
1654
  }
1655
1656
31061
  MaybeStopReading();
1657
1658
31061
  return 0;
1659
}
1660
1661
1662
// This callback is called from nghttp2 when it wants to send DATA frames for a
1663
// given Http2Stream, when we set the `NGHTTP2_DATA_FLAG_NO_COPY` flag earlier
1664
// in the Http2Stream::Provider::Stream::OnRead callback.
1665
// We take the write information directly out of the stream's data queue.
1666
12847
int Http2Session::OnSendData(
1667
      nghttp2_session* session_,
1668
      nghttp2_frame* frame,
1669
      const uint8_t* framehd,
1670
      size_t length,
1671
      nghttp2_data_source* source,
1672
      void* user_data) {
1673
12847
  Http2Session* session = static_cast<Http2Session*>(user_data);
1674
25694
  BaseObjectPtr<Http2Stream> stream = session->FindStream(frame->hd.stream_id);
1675
12847
  if (!stream) return 0;
1676
1677
  // Send the frame header + a byte that indicates padding length.
1678
12847
  session->CopyDataIntoOutgoing(framehd, 9);
1679
12847
  if (frame->data.padlen > 0) {
1680
1
    uint8_t padding_byte = frame->data.padlen - 1;
1681
1
    CHECK_EQ(padding_byte, frame->data.padlen - 1);
1682
1
    session->CopyDataIntoOutgoing(&padding_byte, 1);
1683
  }
1684
1685
  Debug(session, "nghttp2 has %d bytes to send directly", length);
1686
67775
  while (length > 0) {
1687
    // nghttp2 thinks that there is data available (length > 0), which means
1688
    // we told it so, which means that we *should* have data available.
1689
36626
    CHECK(!stream->queue_.empty());
1690
1691
36626
    NgHttp2StreamWrite& write = stream->queue_.front();
1692
36626
    if (write.buf.len <= length) {
1693
      // This write does not suffice by itself, so we can consume it completely.
1694
27464
      length -= write.buf.len;
1695
27464
      session->PushOutgoingBuffer(std::move(write));
1696
27464
      stream->queue_.pop();
1697
27464
      continue;
1698
    }
1699
1700
    // Slice off `length` bytes of the first write in the queue.
1701
18324
    session->PushOutgoingBuffer(NgHttp2StreamWrite {
1702
      uv_buf_init(write.buf.base, length)
1703
9162
    });
1704
9162
    write.buf.base += length;
1705
9162
    write.buf.len -= length;
1706
9162
    break;
1707
  }
1708
1709
12847
  if (frame->data.padlen > 0) {
1710
    // Send padding if that was requested.
1711
2
    session->PushOutgoingBuffer(NgHttp2StreamWrite {
1712
1
      uv_buf_init(const_cast<char*>(zero_bytes_256), frame->data.padlen - 1)
1713
1
    });
1714
  }
1715
1716
12847
  return 0;
1717
}
1718
1719
// Creates a new Http2Stream and submits a new http2 request.
1720
11764
Http2Stream* Http2Session::SubmitRequest(
1721
    const Http2Priority& priority,
1722
    const Http2Headers& headers,
1723
    int32_t* ret,
1724
    int options) {
1725
11764
  Debug(this, "submitting request");
1726
23528
  Http2Scope h2scope(this);
1727
11764
  Http2Stream* stream = nullptr;
1728
23528
  Http2Stream::Provider::Stream prov(options);
1729
11764
  *ret = nghttp2_submit_request(
1730
      session_.get(),
1731
      &priority,
1732
      headers.data(),
1733
      headers.length(),
1734
11764
      *prov,
1735
      nullptr);
1736
11764
  CHECK_NE(*ret, NGHTTP2_ERR_NOMEM);
1737
11764
  if (LIKELY(*ret > 0))
1738
11763
    stream = Http2Stream::New(this, *ret, NGHTTP2_HCAT_HEADERS, options);
1739
23528
  return stream;
1740
}
1741
1742
31162
uv_buf_t Http2Session::OnStreamAlloc(size_t suggested_size) {
1743
31162
  return AllocatedBuffer::AllocateManaged(env(), suggested_size).release();
1744
}
1745
1746
// Callback used to receive inbound data from the i/o stream
1747
31181
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
1748
62315
  HandleScope handle_scope(env()->isolate());
1749
62315
  Context::Scope context_scope(env()->context());
1750
62315
  Http2Scope h2scope(this);
1751
31181
  CHECK_NOT_NULL(stream_);
1752
31181
  Debug(this, "receiving %d bytes, offset %d", nread, stream_buf_offset_);
1753
62315
  AllocatedBuffer buf(env(), buf_);
1754
1755
  // Only pass data on if nread > 0
1756
31181
  if (nread <= 0) {
1757
41
    if (nread < 0) {
1758
41
      PassReadErrorToPreviousListener(nread);
1759
    }
1760
41
    return;
1761
  }
1762
1763
31140
  statistics_.data_received += nread;
1764
1765
31140
  if (LIKELY(stream_buf_offset_ == 0)) {
1766
    // Shrink to the actual amount of used data.
1767
30883
    buf.Resize(nread);
1768
  } else {
1769
    // This is a very unlikely case, and should only happen if the ReadStart()
1770
    // call in OnStreamAfterWrite() immediately provides data. If that does
1771
    // happen, we concatenate the data we received with the already-stored
1772
    // pending input data, slicing off the already processed part.
1773
257
    size_t pending_len = stream_buf_.len - stream_buf_offset_;
1774
    AllocatedBuffer new_buf =
1775
514
        AllocatedBuffer::AllocateManaged(env(), pending_len + nread);
1776
257
    memcpy(new_buf.data(), stream_buf_.base + stream_buf_offset_, pending_len);
1777
257
    memcpy(new_buf.data() + pending_len, buf.data(), nread);
1778
1779
257
    buf = std::move(new_buf);
1780
257
    nread = buf.size();
1781
257
    stream_buf_offset_ = 0;
1782
257
    stream_buf_ab_.Reset();
1783
1784
    // We have now fully processed the stream_buf_ input chunk (by moving the
1785
    // remaining part into buf, which will be accounted for below).
1786
257
    DecrementCurrentSessionMemory(stream_buf_.len);
1787
  }
1788
1789
31140
  IncrementCurrentSessionMemory(nread);
1790
1791
  // Remember the current buffer, so that OnDataChunkReceived knows the
1792
  // offset of a DATA frame's data into the socket read buffer.
1793
31140
  stream_buf_ = uv_buf_init(buf.data(), static_cast<unsigned int>(nread));
1794
1795
31140
  Isolate* isolate = env()->isolate();
1796
1797
  // Store this so we can create an ArrayBuffer for read data from it.
1798
  // DATA frames will be emitted as slices of that ArrayBuffer to avoid having
1799
  // to copy memory.
1800
31140
  stream_buf_allocation_ = std::move(buf);
1801
1802
31140
  ssize_t ret = ConsumeHTTP2Data();
1803
1804
31140
  if (UNLIKELY(ret < 0)) {
1805
6
    Debug(this, "fatal error receiving data: %d", ret);
1806
6
    Local<Value> arg = Integer::New(isolate, static_cast<int32_t>(ret));
1807
6
    MakeCallback(env()->http2session_on_error_function(), 1, &arg);
1808
6
    return;
1809
  }
1810
1811
31134
  MaybeStopReading();
1812
}
1813
1814
23626
bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
1815
23891
  for (const NgHttp2StreamWrite& wr : outgoing_buffers_) {
1816


326
    if (wr.req_wrap != nullptr && wr.req_wrap->stream() == stream)
1817
61
      return true;
1818
  }
1819
23565
  return false;
1820
}
1821
1822
// Every Http2Session session is tightly bound to a single i/o StreamBase
1823
// (typically a net.Socket or tls.TLSSocket). The lifecycle of the two is
1824
// tightly coupled with all data transfer between the two happening at the
1825
// C++ layer via the StreamBase API.
1826
630
void Http2Session::Consume(Local<Object> stream_obj) {
1827
630
  StreamBase* stream = StreamBase::FromObject(stream_obj);
1828
630
  stream->PushStreamListener(this);
1829
630
  Debug(this, "i/o stream consumed");
1830
630
}
1831
1832
23746
Http2Stream* Http2Stream::New(Http2Session* session,
1833
                              int32_t id,
1834
                              nghttp2_headers_category category,
1835
                              int options) {
1836
  Local<Object> obj;
1837
47492
  if (!session->env()
1838
47492
           ->http2stream_constructor_template()
1839
71238
           ->NewInstance(session->env()->context())
1840
23746
           .ToLocal(&obj)) {
1841
    return nullptr;
1842
  }
1843
23746
  return new Http2Stream(session, obj, id, category, options);
1844
}
1845
1846
23746
Http2Stream::Http2Stream(Http2Session* session,
1847
                         Local<Object> obj,
1848
                         int32_t id,
1849
                         nghttp2_headers_category category,
1850
23746
                         int options)
1851
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2STREAM),
1852
      StreamBase(session->env()),
1853
      session_(session),
1854
      id_(id),
1855
23746
      current_headers_category_(category) {
1856
23746
  MakeWeak();
1857
23746
  StreamBase::AttachToObject(GetObject());
1858
23746
  statistics_.start_time = uv_hrtime();
1859
1860
  // Limit the number of header pairs
1861
23746
  max_header_pairs_ = session->max_header_pairs();
1862
23746
  if (max_header_pairs_ == 0) {
1863
    max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
1864
  }
1865
23746
  current_headers_.reserve(std::min(max_header_pairs_, 12u));
1866
1867
  // Limit the number of header octets
1868
23746
  max_header_length_ =
1869
23746
      std::min(
1870
47492
        nghttp2_session_get_local_settings(
1871
          session->session(),
1872
          NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE),
1873
71238
      MAX_MAX_HEADER_LIST_SIZE);
1874
1875
23746
  if (options & STREAM_OPTION_GET_TRAILERS)
1876
2
    set_has_trailers();
1877
1878
23746
  PushStreamListener(&stream_listener_);
1879
1880
23746
  if (options & STREAM_OPTION_EMPTY_PAYLOAD)
1881
594
    Shutdown();
1882
23746
  session->AddStream(this);
1883
23746
}
1884
1885
71238
Http2Stream::~Http2Stream() {
1886
23746
  Debug(this, "tearing down stream");
1887
47492
}
1888
1889
void Http2Stream::MemoryInfo(MemoryTracker* tracker) const {
1890
  tracker->TrackField("current_headers", current_headers_);
1891
  tracker->TrackField("queue", queue_);
1892
}
1893
1894
18
std::string Http2Stream::diagnostic_name() const {
1895
36
  return "HttpStream " + std::to_string(id()) + " (" +
1896
72
      std::to_string(static_cast<int64_t>(get_async_id())) + ") [" +
1897
54
      session()->diagnostic_name() + "]";
1898
}
1899
1900
// Notify the Http2Stream that a new block of HEADERS is being processed.
1901
11692
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
1902
11692
  Debug(this, "starting headers, category: %d", category);
1903
11692
  CHECK(!this->is_destroyed());
1904
11692
  session_->DecrementCurrentSessionMemory(current_headers_length_);
1905
11692
  current_headers_length_ = 0;
1906
11692
  current_headers_.clear();
1907
11692
  current_headers_category_ = category;
1908
11692
}
1909
1910
1911
nghttp2_stream* Http2Stream::operator*() const { return stream(); }
1912
1913
11
nghttp2_stream* Http2Stream::stream() const {
1914
11
  return nghttp2_session_find_stream(session_->session(), id_);
1915
}
1916
1917
23559
void Http2Stream::Close(int32_t code) {
1918
23559
  CHECK(!this->is_destroyed());
1919
23559
  set_closed();
1920
23559
  code_ = code;
1921
23559
  Debug(this, "closed with code %d", code);
1922
23559
}
1923
1924
24054
ShutdownWrap* Http2Stream::CreateShutdownWrap(v8::Local<v8::Object> object) {
1925
  // DoShutdown() always finishes synchronously, so there's no need to create
1926
  // a structure to store asynchronous context.
1927
24054
  return nullptr;
1928
}
1929
1930
24054
int Http2Stream::DoShutdown(ShutdownWrap* req_wrap) {
1931
24054
  if (is_destroyed())
1932
    return UV_EPIPE;
1933
1934
  {
1935
48108
    Http2Scope h2scope(this);
1936
24054
    set_not_writable();
1937
24054
    CHECK_NE(nghttp2_session_resume_data(
1938
        session_->session(), id_),
1939
        NGHTTP2_ERR_NOMEM);
1940
24054
    Debug(this, "writable side shutdown");
1941
  }
1942
24054
  return 1;
1943
}
1944
1945
// Destroy the Http2Stream and render it unusable. Actual resources for the
1946
// Stream will not be freed until the next tick of the Node.js event loop
1947
// using the SetImmediate queue.
1948
23638
void Http2Stream::Destroy() {
1949
  // Do nothing if this stream instance is already destroyed
1950
23638
  if (is_destroyed())
1951
1
    return;
1952
23637
  if (session_->has_pending_rststream(id_))
1953
7
    FlushRstStream();
1954
23637
  set_destroyed();
1955
1956
23637
  Debug(this, "destroying stream");
1957
1958
  // Wait until the start of the next loop to delete because there
1959
  // may still be some pending operations queued for this stream.
1960
47274
  BaseObjectPtr<Http2Stream> strong_ref = session_->RemoveStream(id_);
1961
23637
  if (strong_ref) {
1962
118185
    env()->SetImmediate([this, strong_ref = std::move(strong_ref)](
1963
94491
        Environment* env) {
1964
      // Free any remaining outgoing data chunks here. This should be done
1965
      // here because it's possible for destroy to have been called while
1966
      // we still have queued outbound writes.
1967
23647
      while (!queue_.empty()) {
1968
5
        NgHttp2StreamWrite& head = queue_.front();
1969
5
        if (head.req_wrap != nullptr)
1970
5
          head.req_wrap->Done(UV_ECANCELED);
1971
5
        queue_.pop();
1972
      }
1973
1974
      // We can destroy the stream now if there are no writes for it
1975
      // already on the socket. Otherwise, we'll wait for the garbage collector
1976
      // to take care of cleaning up.
1977

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

3692
  if (!is_writable() || is_destroyed()) {
2191
    req_wrap->Done(UV_EOF);
2192
    return 0;
2193
  }
2194
3692
  Debug(this, "queuing %d buffers to send", nbufs);
2195
31167
  for (size_t i = 0; i < nbufs; ++i) {
2196
    // Store the req_wrap on the last write info in the queue, so that it is
2197
    // only marked as finished once all buffers associated with it are finished.
2198
82425
    queue_.emplace(NgHttp2StreamWrite {
2199
27475
      i == nbufs - 1 ? req_wrap : nullptr,
2200
27475
      bufs[i]
2201
27475
    });
2202
27475
    IncrementAvailableOutboundLength(bufs[i].len);
2203
  }
2204
3692
  CHECK_NE(nghttp2_session_resume_data(
2205
      session_->session(),
2206
      id_), NGHTTP2_ERR_NOMEM);
2207
3692
  return 0;
2208
}
2209
2210
// Ads a header to the Http2Stream. Note that the header name and value are
2211
// provided using a buffer structure provided by nghttp2 that allows us to
2212
// avoid unnecessary memcpy's. Those buffers are ref counted. The ref count
2213
// is incremented here and are decremented when the header name and values
2214
// are garbage collected later.
2215
71791
bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
2216
                            nghttp2_rcbuf* value,
2217
                            uint8_t flags) {
2218
71791
  CHECK(!this->is_destroyed());
2219
2220
71791
  if (Http2RcBufferPointer::IsZeroLength(name))
2221
    return true;  // Ignore empty headers.
2222
2223
143582
  Http2Header header(env(), name, value, flags);
2224
71791
  size_t length = header.length() + 32;
2225
  // A header can only be added if we have not exceeded the maximum number
2226
  // of headers and the session has memory available for it.
2227

215373
  if (!session_->has_available_session_memory(length) ||
2228

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

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

26558
  if (amount == 0 && stream->is_writable()) {
2312
2354
    CHECK(stream->queue_.empty());
2313
    Debug(session, "deferring stream %d", id);
2314
2354
    stream->EmitWantsWrite(length);
2315

2354
    if (stream->available_outbound_length_ > 0 || !stream->is_writable()) {
2316
      // EmitWantsWrite() did something interesting synchronously, restart:
2317
      return OnRead(handle, id, buf, length, flags, source, user_data);
2318
    }
2319
2354
    return NGHTTP2_ERR_DEFERRED;
2320
  }
2321
2322

24204
  if (stream->available_outbound_length_ == 0 && !stream->is_writable()) {
2323
    Debug(session, "no more data for stream %d", id);
2324
12717
    *flags |= NGHTTP2_DATA_FLAG_EOF;
2325
12717
    if (stream->has_trailers()) {
2326
36
      *flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
2327
36
      stream->OnTrailers();
2328
    }
2329
  }
2330
2331
24204
  stream->statistics_.sent_bytes += amount;
2332
24204
  return amount;
2333
}
2334
2335
27475
void Http2Stream::IncrementAvailableOutboundLength(size_t amount) {
2336
27475
  available_outbound_length_ += amount;
2337
27475
  session_->IncrementCurrentSessionMemory(amount);
2338
27475
}
2339
2340
12847
void Http2Stream::DecrementAvailableOutboundLength(size_t amount) {
2341
12847
  available_outbound_length_ -= amount;
2342
12847
  session_->DecrementCurrentSessionMemory(amount);
2343
12847
}
2344
2345
2346
// Implementation of the JavaScript API
2347
2348
// Fetches the string description of a nghttp2 error code and passes that
2349
// back to JS land
2350
54
void HttpErrorString(const FunctionCallbackInfo<Value>& args) {
2351
54
  Environment* env = Environment::GetCurrent(args);
2352
216
  uint32_t val = args[0]->Uint32Value(env->context()).ToChecked();
2353
162
  args.GetReturnValue().Set(
2354
      OneByteString(
2355
          env->isolate(),
2356
54
          reinterpret_cast<const uint8_t*>(nghttp2_strerror(val))));
2357
54
}
2358
2359
2360
// Serializes the settings object into a Buffer instance that
2361
// would be suitable, for instance, for creating the Base64
2362
// output for an HTTP2-Settings header field.
2363
17
void PackSettings(const FunctionCallbackInfo<Value>& args) {
2364
17
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2365
51
  args.GetReturnValue().Set(Http2Settings::Pack(state));
2366
17
}
2367
2368
// A TypedArray instance is shared between C++ and JS land to contain the
2369
// default SETTINGS. RefreshDefaultSettings updates that TypedArray with the
2370
// default values.
2371
3
void RefreshDefaultSettings(const FunctionCallbackInfo<Value>& args) {
2372
3
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2373
3
  Http2Settings::RefreshDefaults(state);
2374
3
}
2375
2376
// Sets the next stream ID the Http2Session. If successful, returns true.
2377
1
void Http2Session::SetNextStreamID(const FunctionCallbackInfo<Value>& args) {
2378
1
  Environment* env = Environment::GetCurrent(args);
2379
  Http2Session* session;
2380
1
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2381
4
  int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2382
1
  if (nghttp2_session_set_next_stream_id(session->session(), id) < 0) {
2383
    Debug(session, "failed to set next stream id to %d", id);
2384
    return args.GetReturnValue().Set(false);
2385
  }
2386
2
  args.GetReturnValue().Set(true);
2387
1
  Debug(session, "set next stream id to %d", id);
2388
}
2389
2390
// A TypedArray instance is shared between C++ and JS land to contain the
2391
// SETTINGS (either remote or local). RefreshSettings updates the current
2392
// values established for each of the settings so those can be read in JS land.
2393
template <get_setting fn>
2394
543
void Http2Session::RefreshSettings(const FunctionCallbackInfo<Value>& args) {
2395
  Http2Session* session;
2396

543
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2397
543
  Http2Settings::Update(session, fn);
2398
543
  Debug(session, "settings refreshed for session");
2399
}
2400
2401
// A TypedArray instance is shared between C++ and JS land to contain state
2402
// information of the current Http2Session. This updates the values in the
2403
// TypedArray so those can be read in JS land.
2404
3
void Http2Session::RefreshState(const FunctionCallbackInfo<Value>& args) {
2405
  Http2Session* session;
2406
3
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2407
3
  Debug(session, "refreshing state");
2408
2409
3
  AliasedFloat64Array& buffer = session->http2_state()->session_state_buffer;
2410
2411
3
  nghttp2_session* s = session->session();
2412
2413
  buffer[IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE] =
2414
3
      nghttp2_session_get_effective_local_window_size(s);
2415
  buffer[IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH] =
2416
3
      nghttp2_session_get_effective_recv_data_length(s);
2417
  buffer[IDX_SESSION_STATE_NEXT_STREAM_ID] =
2418
3
      nghttp2_session_get_next_stream_id(s);
2419
  buffer[IDX_SESSION_STATE_LOCAL_WINDOW_SIZE] =
2420
3
      nghttp2_session_get_local_window_size(s);
2421
  buffer[IDX_SESSION_STATE_LAST_PROC_STREAM_ID] =
2422
3
      nghttp2_session_get_last_proc_stream_id(s);
2423
  buffer[IDX_SESSION_STATE_REMOTE_WINDOW_SIZE] =
2424
3
      nghttp2_session_get_remote_window_size(s);
2425
  buffer[IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE] =
2426
3
      static_cast<double>(nghttp2_session_get_outbound_queue_size(s));
2427
  buffer[IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE] =
2428
3
      static_cast<double>(nghttp2_session_get_hd_deflate_dynamic_table_size(s));
2429
  buffer[IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE] =
2430
3
      static_cast<double>(nghttp2_session_get_hd_inflate_dynamic_table_size(s));
2431
}
2432
2433
2434
// Constructor for new Http2Session instances.
2435
630
void Http2Session::New(const FunctionCallbackInfo<Value>& args) {
2436
630
  Http2State* state = Environment::GetBindingData<Http2State>(args);
2437
630
  Environment* env = state->env();
2438
630
  CHECK(args.IsConstructCall());
2439
  SessionType type =
2440
      static_cast<SessionType>(
2441
2520
          args[0]->Int32Value(env->context()).ToChecked());
2442
630
  Http2Session* session = new Http2Session(state, args.This(), type);
2443
630
  session->get_async_id();  // avoid compiler warning
2444
  Debug(session, "session created");
2445
630
}
2446
2447
2448
// Binds the Http2Session with a StreamBase used for i/o
2449
630
void Http2Session::Consume(const FunctionCallbackInfo<Value>& args) {
2450
  Http2Session* session;
2451
630
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2452
1260
  CHECK(args[0]->IsObject());
2453
1260
  session->Consume(args[0].As<Object>());
2454
}
2455
2456
// Destroys the Http2Session instance and renders it unusable
2457
606
void Http2Session::Destroy(const FunctionCallbackInfo<Value>& args) {
2458
  Http2Session* session;
2459
606
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2460
606
  Debug(session, "destroying session");
2461
606
  Environment* env = Environment::GetCurrent(args);
2462
606
  Local<Context> context = env->context();
2463
2464
1818
  uint32_t code = args[0]->Uint32Value(context).ToChecked();
2465
1212
  session->Close(code, args[1]->IsTrue());
2466
}
2467
2468
// Submits a new request on the Http2Session and returns either an error code
2469
// or the Http2Stream object.
2470
11764
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
2471
  Http2Session* session;
2472
11765
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2473
11764
  Environment* env = session->env();
2474
2475
23528
  Local<Array> headers = args[0].As<Array>();
2476
47056
  int32_t options = args[1]->Int32Value(env->context()).ToChecked();
2477
2478
11764
  Debug(session, "request submitted");
2479
2480
11764
  int32_t ret = 0;
2481
  Http2Stream* stream =
2482
11764
      session->Http2Session::SubmitRequest(
2483
23528
          Http2Priority(env, args[2], args[3], args[4]),
2484
23528
          Http2Headers(env, headers),
2485
          &ret,
2486
11764
          static_cast<int>(options));
2487
2488

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

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

10
  if (origin_str.IsEmpty() || value_str.IsEmpty())
2732
    return;
2733
2734
5
  size_t origin_len = origin_str->Length();
2735
5
  size_t value_len = value_str->Length();
2736
2737
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2738
  // Verify that origin len != 0 if stream id == 0, or
2739
  // that origin len == 0 if stream id != 0
2740



5
  CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2741
2742
10
  MaybeStackBuffer<uint8_t> origin(origin_len);
2743
10
  MaybeStackBuffer<uint8_t> value(value_len);
2744
10
  origin_str->WriteOneByte(env->isolate(), *origin);
2745
10
  value_str->WriteOneByte(env->isolate(), *value);
2746
2747
5
  session->AltSvc(id, *origin, origin_len, *value, value_len);
2748
}
2749
2750
5
void Http2Session::Origin(const FunctionCallbackInfo<Value>& args) {
2751
5
  Environment* env = Environment::GetCurrent(args);
2752
5
  Local<Context> context = env->context();
2753
  Http2Session* session;
2754
5
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2755
2756
10
  Local<String> origin_string = args[0].As<String>();
2757
15
  size_t count = args[1]->Int32Value(context).ToChecked();
2758
2759
5
  session->Origin(Origins(env, origin_string, count));
2760
}
2761
2762
// Submits a PING frame to be sent to the connected peer.
2763
13
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
2764
  Http2Session* session;
2765
13
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2766
2767
  // A PING frame may have exactly 8 bytes of payload data. If not provided,
2768
  // then the current hrtime will be used as the payload.
2769
13
  ArrayBufferViewContents<uint8_t, 8> payload;
2770
26
  if (args[0]->IsArrayBufferView()) {
2771
12
    payload.Read(args[0].As<ArrayBufferView>());
2772
6
    CHECK_EQ(payload.length(), 8);
2773
  }
2774
2775
26
  CHECK(args[1]->IsFunction());
2776
39
  args.GetReturnValue().Set(
2777
39
      session->AddPing(payload.data(), args[1].As<Function>()));
2778
}
2779
2780
// Submits a SETTINGS frame for the Http2Session
2781
640
void Http2Session::Settings(const FunctionCallbackInfo<Value>& args) {
2782
  Http2Session* session;
2783
640
  ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2784
1280
  CHECK(args[0]->IsFunction());
2785
2560
  args.GetReturnValue().Set(session->AddSettings(args[0].As<Function>()));
2786
}
2787
2788
618
BaseObjectPtr<Http2Ping> Http2Session::PopPing() {
2789
618
  BaseObjectPtr<Http2Ping> ping;
2790
618
  if (!outstanding_pings_.empty()) {
2791
11
    ping = std::move(outstanding_pings_.front());
2792
11
    outstanding_pings_.pop();
2793
11
    DecrementCurrentSessionMemory(sizeof(*ping));
2794
  }
2795
618
  return ping;
2796
}
2797
2798
13
bool Http2Session::AddPing(const uint8_t* payload, Local<Function> callback) {
2799
  Local<Object> obj;
2800
39
  if (!env()->http2ping_constructor_template()
2801
39
          ->NewInstance(env()->context())
2802
13
              .ToLocal(&obj)) {
2803
    return false;
2804
  }
2805
2806
  BaseObjectPtr<Http2Ping> ping =
2807
26
      MakeDetachedBaseObject<Http2Ping>(this, obj, callback);
2808
13
  if (!ping)
2809
    return false;
2810
2811
13
  if (outstanding_pings_.size() == max_outstanding_pings_) {
2812
2
    ping->Done(false);
2813
2
    return false;
2814
  }
2815
2816
11
  IncrementCurrentSessionMemory(sizeof(*ping));
2817
  // The Ping itself is an Async resource. When the acknowledgement is received,
2818
  // the callback will be invoked and a notification sent out to JS land. The
2819
  // notification will include the duration of the ping, allowing the round
2820
  // trip to be measured.
2821
11
  ping->Send(payload);
2822
2823
11
  outstanding_pings_.emplace(std::move(ping));
2824
11
  return true;
2825
}
2826
2827
520
BaseObjectPtr<Http2Settings> Http2Session::PopSettings() {
2828
520
  BaseObjectPtr<Http2Settings> settings;
2829
520
  if (!outstanding_settings_.empty()) {
2830
520
    settings = std::move(outstanding_settings_.front());
2831
520
    outstanding_settings_.pop();
2832
520
    DecrementCurrentSessionMemory(sizeof(*settings));
2833
  }
2834
520
  return settings;
2835
}
2836
2837
640
bool Http2Session::AddSettings(Local<Function> callback) {
2838
  Local<Object> obj;
2839
1920
  if (!env()->http2settings_constructor_template()
2840
1920
          ->NewInstance(env()->context())
2841
640
              .ToLocal(&obj)) {
2842
    return false;
2843
  }
2844
2845
  BaseObjectPtr<Http2Settings> settings =
2846
1280
      MakeDetachedBaseObject<Http2Settings>(this, obj, callback, 0);
2847
640
  if (!settings)
2848
    return false;
2849
2850
640
  if (outstanding_settings_.size() == max_outstanding_settings_) {
2851
2
    settings->Done(false);
2852
2
    return false;
2853
  }
2854
2855
638
  IncrementCurrentSessionMemory(sizeof(*settings));
2856
638
  settings->Send();
2857
638
  outstanding_settings_.emplace(std::move(settings));
2858
638
  return true;
2859
}
2860
2861
13
Http2Ping::Http2Ping(
2862
    Http2Session* session,
2863
    Local<Object> obj,
2864
13
    Local<Function> callback)
2865
    : AsyncWrap(session->env(), obj, AsyncWrap::PROVIDER_HTTP2PING),
2866
      session_(session),
2867
26
      startTime_(uv_hrtime()) {
2868
13
  callback_.Reset(env()->isolate(), callback);
2869
13
}
2870
2871
void Http2Ping::MemoryInfo(MemoryTracker* tracker) const {
2872
  tracker->TrackField("callback", callback_);
2873
}
2874
2875
13
Local<Function> Http2Ping::callback() const {
2876
26
  return callback_.Get(env()->isolate());
2877
}
2878
2879
11
void Http2Ping::Send(const uint8_t* payload) {
2880
11
  CHECK(session_);
2881
  uint8_t data[8];
2882
11
  if (payload == nullptr) {
2883
5
    memcpy(&data, &startTime_, arraysize(data));
2884
5
    payload = data;
2885
  }
2886
22
  Http2Scope h2scope(session_.get());
2887
11
  CHECK_EQ(nghttp2_submit_ping(
2888
      session_->session(),
2889
      NGHTTP2_FLAG_NONE,
2890
      payload), 0);
2891
11
}
2892
2893
13
void Http2Ping::Done(bool ack, const uint8_t* payload) {
2894
13
  uint64_t duration_ns = uv_hrtime() - startTime_;
2895
13
  double duration_ms = duration_ns / 1e6;
2896
13
  if (session_) session_->statistics_.ping_rtt = duration_ns;
2897
2898
13
  Isolate* isolate = env()->isolate();
2899
26
  HandleScope handle_scope(isolate);
2900
13
  Context::Scope context_scope(env()->context());
2901
2902
  Local<Value> buf = Undefined(isolate);
2903
13
  if (payload != nullptr) {
2904
30
    buf = Buffer::Copy(isolate,
2905
                       reinterpret_cast<const char*>(payload),
2906
10
                       8).ToLocalChecked();
2907
  }
2908
2909
  Local<Value> argv[] = {
2910
    ack ? v8::True(isolate) : v8::False(isolate),
2911
    Number::New(isolate, duration_ms),
2912
    buf
2913
39
  };
2914
13
  MakeCallback(callback(), arraysize(argv), argv);
2915
13
}
2916
2917
1
void Http2Ping::DetachFromSession() {
2918
1
  session_.reset();
2919
1
}
2920
2921
void NgHttp2StreamWrite::MemoryInfo(MemoryTracker* tracker) const {
2922
  if (req_wrap != nullptr)
2923
    tracker->TrackField("req_wrap", req_wrap->GetAsyncWrap());
2924
  tracker->TrackField("buf", buf);
2925
}
2926
2927
234
void SetCallbackFunctions(const FunctionCallbackInfo<Value>& args) {
2928
234
  Environment* env = Environment::GetCurrent(args);
2929
234
  CHECK_EQ(args.Length(), 11);
2930
2931
#define SET_FUNCTION(arg, name)                                               \
2932
  CHECK(args[arg]->IsFunction());                                             \
2933
  env->set_http2session_on_ ## name ## _function(args[arg].As<Function>());
2934
2935
936
  SET_FUNCTION(0, error)
2936
936
  SET_FUNCTION(1, priority)
2937
936
  SET_FUNCTION(2, settings)
2938
936
  SET_FUNCTION(3, ping)
2939
936
  SET_FUNCTION(4, headers)
2940
936
  SET_FUNCTION(5, frame_error)
2941
936
  SET_FUNCTION(6, goaway_data)
2942
936
  SET_FUNCTION(7, altsvc)
2943
936
  SET_FUNCTION(8, origin)
2944
936
  SET_FUNCTION(9, stream_trailers)
2945
936
  SET_FUNCTION(10, stream_close)
2946
2947
#undef SET_FUNCTION
2948
234
}
2949
2950
2
void Http2State::MemoryInfo(MemoryTracker* tracker) const {
2951
2
  tracker->TrackField("root_buffer", root_buffer);
2952
2
}
2953
2954
// TODO(addaleax): Remove once we're on C++17.
2955
constexpr FastStringKey Http2State::binding_data_name;
2956
2957
// Set up the process.binding('http2') binding.
2958
239
void Initialize(Local<Object> target,
2959
                Local<Value> unused,
2960
                Local<Context> context,
2961
                void* priv) {
2962
239
  Environment* env = Environment::GetCurrent(context);
2963
239
  Isolate* isolate = env->isolate();
2964
478
  HandleScope handle_scope(isolate);
2965
2966
239
  Http2State* const state = env->AddBindingData<Http2State>(context, target);
2967
239
  if (state == nullptr) return;
2968
2969
#define SET_STATE_TYPEDARRAY(name, field)             \
2970
  target->Set(context,                                \
2971
              FIXED_ONE_BYTE_STRING(isolate, (name)), \
2972
              (field)).FromJust()
2973
2974
  // Initialize the buffer used to store the session state
2975
956
  SET_STATE_TYPEDARRAY(
2976
    "sessionState", state->session_state_buffer.GetJSArray());
2977
  // Initialize the buffer used to store the stream state
2978
956
  SET_STATE_TYPEDARRAY(
2979
    "streamState", state->stream_state_buffer.GetJSArray());
2980
956
  SET_STATE_TYPEDARRAY(
2981
    "settingsBuffer", state->settings_buffer.GetJSArray());
2982
956
  SET_STATE_TYPEDARRAY(
2983
    "optionsBuffer", state->options_buffer.GetJSArray());
2984
956
  SET_STATE_TYPEDARRAY(
2985
    "streamStats", state->stream_stats_buffer.GetJSArray());
2986
956
  SET_STATE_TYPEDARRAY(
2987
    "sessionStats", state->session_stats_buffer.GetJSArray());
2988
#undef SET_STATE_TYPEDARRAY
2989
2990
956
  NODE_DEFINE_CONSTANT(target, kBitfield);
2991
956
  NODE_DEFINE_CONSTANT(target, kSessionPriorityListenerCount);
2992
956
  NODE_DEFINE_CONSTANT(target, kSessionFrameErrorListenerCount);
2993
956
  NODE_DEFINE_CONSTANT(target, kSessionMaxInvalidFrames);
2994
956
  NODE_DEFINE_CONSTANT(target, kSessionMaxRejectedStreams);
2995
956
  NODE_DEFINE_CONSTANT(target, kSessionUint8FieldCount);
2996
2997
956
  NODE_DEFINE_CONSTANT(target, kSessionHasRemoteSettingsListeners);
2998
956
  NODE_DEFINE_CONSTANT(target, kSessionRemoteSettingsIsUpToDate);
2999
956
  NODE_DEFINE_CONSTANT(target, kSessionHasPingListeners);
3000
956
  NODE_DEFINE_CONSTANT(target, kSessionHasAltsvcListeners);
3001
3002
  // Method to fetch the nghttp2 string description of an nghttp2 error code
3003
239
  env->SetMethod(target, "nghttp2ErrorString", HttpErrorString);
3004
239
  env->SetMethod(target, "refreshDefaultSettings", RefreshDefaultSettings);
3005
239
  env->SetMethod(target, "packSettings", PackSettings);
3006
239
  env->SetMethod(target, "setCallbackFunctions", SetCallbackFunctions);
3007
3008
  Local<String> http2SessionClassName =
3009
239
    FIXED_ONE_BYTE_STRING(isolate, "Http2Session");
3010
3011
239
  Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate());
3012
478
  ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping"));
3013
478
  ping->Inherit(AsyncWrap::GetConstructorTemplate(env));
3014
239
  Local<ObjectTemplate> pingt = ping->InstanceTemplate();
3015
239
  pingt->SetInternalFieldCount(Http2Ping::kInternalFieldCount);
3016
239
  env->set_http2ping_constructor_template(pingt);
3017
3018
239
  Local<FunctionTemplate> setting = FunctionTemplate::New(env->isolate());
3019
478
  setting->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Setting"));
3020
478
  setting->Inherit(AsyncWrap::GetConstructorTemplate(env));
3021
239
  Local<ObjectTemplate> settingt = setting->InstanceTemplate();
3022
239
  settingt->SetInternalFieldCount(AsyncWrap::kInternalFieldCount);
3023
239
  env->set_http2settings_constructor_template(settingt);
3024
3025
239
  Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
3026
478
  stream->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"));
3027
239
  env->SetProtoMethod(stream, "id", Http2Stream::GetID);
3028
239
  env->SetProtoMethod(stream, "destroy", Http2Stream::Destroy);
3029
239
  env->SetProtoMethod(stream, "priority", Http2Stream::Priority);
3030
239
  env->SetProtoMethod(stream, "pushPromise", Http2Stream::PushPromise);
3031
239
  env->SetProtoMethod(stream, "info", Http2Stream::Info);
3032
239
  env->SetProtoMethod(stream, "trailers", Http2Stream::Trailers);
3033
239
  env->SetProtoMethod(stream, "respond", Http2Stream::Respond);
3034
239
  env->SetProtoMethod(stream, "rstStream", Http2Stream::RstStream);
3035
239
  env->SetProtoMethod(stream, "refreshState", Http2Stream::RefreshState);
3036
478
  stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
3037
239
  StreamBase::AddMethods(env, stream);
3038
239
  Local<ObjectTemplate> streamt = stream->InstanceTemplate();
3039
239
  streamt->SetInternalFieldCount(StreamBase::kInternalFieldCount);
3040
239
  env->set_http2stream_constructor_template(streamt);
3041
478
  target->Set(context,
3042
              FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Stream"),
3043
1195
              stream->GetFunction(env->context()).ToLocalChecked()).Check();
3044
3045
  Local<FunctionTemplate> session =
3046
239
      env->NewFunctionTemplate(Http2Session::New);
3047
239
  session->SetClassName(http2SessionClassName);
3048
717
  session->InstanceTemplate()->SetInternalFieldCount(
3049
239
      Http2Session::kInternalFieldCount);
3050
478
  session->Inherit(AsyncWrap::GetConstructorTemplate(env));
3051
239
  env->SetProtoMethod(session, "origin", Http2Session::Origin);
3052
239
  env->SetProtoMethod(session, "altsvc", Http2Session::AltSvc);
3053
239
  env->SetProtoMethod(session, "ping", Http2Session::Ping);
3054
239
  env->SetProtoMethod(session, "consume", Http2Session::Consume);
3055
239
  env->SetProtoMethod(session, "destroy", Http2Session::Destroy);
3056
239
  env->SetProtoMethod(session, "goaway", Http2Session::Goaway);
3057
239
  env->SetProtoMethod(session, "settings", Http2Session::Settings);
3058
239
  env->SetProtoMethod(session, "request", Http2Session::Request);
3059
  env->SetProtoMethod(session, "setNextStreamID",
3060
239
                      Http2Session::SetNextStreamID);
3061
  env->SetProtoMethod(session, "updateChunksSent",
3062
239
                      Http2Session::UpdateChunksSent);
3063
239
  env->SetProtoMethod(session, "refreshState", Http2Session::RefreshState);
3064
  env->SetProtoMethod(
3065
      session, "localSettings",
3066
239
      Http2Session::RefreshSettings<nghttp2_session_get_local_settings>);
3067
  env->SetProtoMethod(
3068
      session, "remoteSettings",
3069
239
      Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>);
3070
478
  target->Set(context,
3071
              http2SessionClassName,
3072
956
              session->GetFunction(env->context()).ToLocalChecked()).Check();
3073
3074
239
  Local<Object> constants = Object::New(isolate);
3075
3076
  // This does alocate one more slot than needed but it's not used.
3077
#define V(name) FIXED_ONE_BYTE_STRING(isolate, #name),
3078
  Local<Value> error_code_names[] = {
3079
    HTTP2_ERROR_CODES(V)
3080
3585
  };
3081
#undef V
3082
3083
  Local<Array> name_for_error_code =
3084
      Array::New(
3085
          isolate,
3086
          error_code_names,
3087
239
          arraysize(error_code_names));
3088
3089
478
  target->Set(context,
3090
              FIXED_ONE_BYTE_STRING(isolate, "nameForErrorCode"),
3091
717
              name_for_error_code).Check();
3092
3093
#define V(constant) NODE_DEFINE_HIDDEN_CONSTANT(constants, constant);
3094
11472
  HTTP2_HIDDEN_CONSTANTS(V)
3095
#undef V
3096
3097
#define V(constant) NODE_DEFINE_CONSTANT(constants, constant);
3098
48756
  HTTP2_CONSTANTS(V)
3099
#undef V
3100
3101
  // NGHTTP2_DEFAULT_WEIGHT is a macro and not a regular define
3102
  // it won't be set properly on the constants object if included
3103
  // in the HTTP2_CONSTANTS macro.
3104
956
  NODE_DEFINE_CONSTANT(constants, NGHTTP2_DEFAULT_WEIGHT);
3105
3106
#define V(NAME, VALUE)                                          \
3107
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_HEADER_" # NAME, VALUE);
3108
121890
  HTTP_KNOWN_HEADERS(V)
3109
#undef V
3110
3111
#define V(NAME, VALUE)                                          \
3112
  NODE_DEFINE_STRING_CONSTANT(constants, "HTTP2_METHOD_" # NAME, VALUE);
3113
55926
  HTTP_KNOWN_METHODS(V)
3114
#undef V
3115
3116
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
3117
60228
  HTTP_STATUS_CODES(V)
3118
#undef V
3119
3120
717
  target->Set(context, env->constants_string(), constants).Check();
3121
}
3122
}  // namespace http2
3123
}  // namespace node
3124
3125

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