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: 1470 1539 95.5 %
Date: 2020-08-07 22:13:19 Branches: 554 758 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
24261
bool HasHttp2Observer(Environment* env) {
50
24261
  AliasedUint32Array& observers = env->performance_state()->observers;
51
24261
  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
8882
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
60
    Callbacks(false),
61
4441
    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
63216
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
75
76
107457
Http2Scope::Http2Scope(Http2Session* session) : session_(session) {
77
107457
  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

107457
  if (session_->is_in_scope() || session_->is_write_scheduled()) {
82
74842
    session_.reset();
83
74842
    return;
84
  }
85
32615
  session_->set_in_scope();
86
}
87
88
214914
Http2Scope::~Http2Scope() {
89
107457
  if (!session_) return;
90
32615
  session_->set_in_scope(false);
91
32615
  session_->MaybeScheduleWrite();
92
107457
}
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
618
Http2Options::Http2Options(Http2State* http2_state, SessionType type) {
99
  nghttp2_option* option;
100
618
  CHECK_EQ(nghttp2_option_new(&option), 0);
101
618
  CHECK_NOT_NULL(option);
102
618
  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
618
  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
618
  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
618
  if (type == NGHTTP2_SESSION_CLIENT) {
119
301
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ALTSVC);
120
301
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ORIGIN);
121
  }
122
123
618
  AliasedUint32Array& buffer = http2_state->options_buffer;
124
618
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
125
126
618
  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
618
  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
618
  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
618
  nghttp2_option_set_peer_max_concurrent_streams(option, 100);
146
618
  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
618
  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
618
  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
618
  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
618
  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
618
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY))
195
6
    set_max_session_memory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1000000);
196
197
618
  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
618
}
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
643
size_t Http2Settings::Init(
213
    Http2State* http2_state,
214
    nghttp2_settings_entry* entries) {
215
643
  AliasedUint32Array& buffer = http2_state->settings_buffer;
216
643
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
217
218
643
  size_t count = 0;
219
220
#define V(name) GRABSETTING(entries, count, name);
221



643
  HTTP2_SETTINGS(V)
222
#undef V
223
224
643
  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
628
Http2Settings::Http2Settings(Http2Session* session,
232
                             Local<Object> obj,
233
                             Local<Function> callback,
234
628
                             uint64_t start_time)
235
    : AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
236
      session_(session),
237
1256
      startTime_(start_time) {
238
628
  callback_.Reset(env()->isolate(), callback);
239
628
  count_ = Init(session->http2_state(), entries_);
240
628
}
241
242
514
Local<Function> Http2Settings::callback() const {
243
1028
  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
15
Local<Value> Http2Settings::Pack(Http2State* state) {
258
  nghttp2_settings_entry entries[IDX_SETTINGS_COUNT];
259
15
  size_t count = Init(state, entries);
260
15
  return Pack(state->env(), count, entries);
261
}
262
263
15
Local<Value> Http2Settings::Pack(
264
    Environment* env,
265
    size_t count,
266
    const nghttp2_settings_entry* entries) {
267
15
  EscapableHandleScope scope(env->isolate());
268
15
  const size_t size = count * 6;
269
30
  AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
270
  ssize_t ret =
271
      nghttp2_pack_settings_payload(
272
15
          reinterpret_cast<uint8_t*>(buffer.data()),
273
          size,
274
          entries,
275
15
          count);
276
15
  Local<Value> buf = Undefined(env->isolate());
277
29
  if (ret >= 0) buf = buffer.ToBuffer().ToLocalChecked();
278
15
  return scope.Escape(buf);
279
}
280
281
// Updates the shared TypedArray with the current remote or local settings for
282
// the session.
283
534
void Http2Settings::Update(Http2Session* session, get_setting fn) {
284
534
  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
534
  HTTP2_SETTINGS(V)
290
#undef V
291
534
}
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
626
void Http2Settings::Send() {
311
1252
  Http2Scope h2scope(session_.get());
312
626
  CHECK_EQ(nghttp2_submit_settings(
313
      session_->session(),
314
      NGHTTP2_FLAG_NONE,
315
      &entries_[0],
316
      count_), 0);
317
626
}
318
319
514
void Http2Settings::Done(bool ack) {
320
514
  uint64_t end = uv_hrtime();
321
514
  double duration = (end - startTime_) / 1e6;
322
323
  Local<Value> argv[] = {
324
514
    ack ? v8::True(env()->isolate()) : v8::False(env()->isolate()),
325
    Number::New(env()->isolate(), duration)
326
1542
  };
327
514
  MakeCallback(callback(), arraysize(argv), argv);
328
514
}
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
11783
Http2Priority::Http2Priority(Environment* env,
334
                             Local<Value> parent,
335
                             Local<Value> weight,
336
11783
                             Local<Value> exclusive) {
337
11783
  Local<Context> context = env->context();
338
23566
  int32_t parent_ = parent->Int32Value(context).ToChecked();
339
23566
  int32_t weight_ = weight->Int32Value(context).ToChecked();
340
11783
  bool exclusive_ = exclusive->IsTrue();
341
  Debug(env, DebugCategory::HTTP2STREAM,
342
        "Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
343
23566
        parent_, weight_, exclusive_ ? "yes" : "no");
344
11783
  nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
345
11783
}
346
347
348
127
const char* Http2Session::TypeName() const {
349
127
  switch (session_type_) {
350
66
    case NGHTTP2_SESSION_SERVER: return "server";
351
61
    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
8882
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
410
  nghttp2_session_callbacks* callbacks_;
411
8882
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
412
8882
  callbacks.reset(callbacks_);
413
414
  nghttp2_session_callbacks_set_on_begin_headers_callback(
415
8882
    callbacks_, OnBeginHeadersCallback);
416
  nghttp2_session_callbacks_set_on_header_callback2(
417
8882
    callbacks_, OnHeaderCallback);
418
  nghttp2_session_callbacks_set_on_frame_recv_callback(
419
8882
    callbacks_, OnFrameReceive);
420
  nghttp2_session_callbacks_set_on_stream_close_callback(
421
8882
    callbacks_, OnStreamClose);
422
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
423
8882
    callbacks_, OnDataChunkReceived);
424
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
425
8882
    callbacks_, OnFrameNotSent);
426
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
427
8882
    callbacks_, OnInvalidHeader);
428
  nghttp2_session_callbacks_set_error_callback(
429
8882
    callbacks_, OnNghttpError);
430
  nghttp2_session_callbacks_set_send_data_callback(
431
8882
    callbacks_, OnSendData);
432
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
433
8882
    callbacks_, OnInvalidFrame);
434
  nghttp2_session_callbacks_set_on_frame_send_callback(
435
8882
    callbacks_, OnFrameSent);
436
437
8882
  if (kHasGetPaddingCallback) {
438
    nghttp2_session_callbacks_set_select_padding_callback(
439
4441
      callbacks_, OnSelectPadding);
440
  }
441
8882
}
442
443
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
444
  StopTrackingMemory(buf);
445
}
446
447
201587
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
448
201587
  CHECK_GE(current_nghttp2_memory_, previous_size);
449
201587
}
450
451
101734
void Http2Session::IncreaseAllocatedSize(size_t size) {
452
101734
  current_nghttp2_memory_ += size;
453
101734
}
454
455
125006
void Http2Session::DecreaseAllocatedSize(size_t size) {
456
125006
  current_nghttp2_memory_ -= size;
457
125006
}
458
459
618
Http2Session::Http2Session(Http2State* http2_state,
460
                           Local<Object> wrap,
461
618
                           SessionType type)
462
    : AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
463
      js_fields_(http2_state->env()->isolate()),
464
      session_type_(type),
465
1236
      http2_state_(http2_state) {
466
618
  MakeWeak();
467
618
  statistics_.start_time = uv_hrtime();
468
469
  // Capture the configuration options for this session
470
1236
  Http2Options opts(http2_state, type);
471
472
618
  max_session_memory_ = opts.max_session_memory();
473
474
618
  uint32_t maxHeaderPairs = opts.max_header_pairs();
475
618
  max_header_pairs_ =
476
      type == NGHTTP2_SESSION_SERVER
477
317
          ? GetServerMaxHeaderPairs(maxHeaderPairs)
478
935
          : GetClientMaxHeaderPairs(maxHeaderPairs);
479
480
618
  max_outstanding_pings_ = opts.max_outstanding_pings();
481
618
  max_outstanding_settings_ = opts.max_outstanding_settings();
482
483
618
  padding_strategy_ = opts.padding_strategy();
484
485
  bool hasGetPaddingCallback =
486
618
      padding_strategy_ != PADDING_STRATEGY_NONE;
487
488
618
  auto fn = type == NGHTTP2_SESSION_SERVER ?
489
      nghttp2_session_server_new3 :
490
618
      nghttp2_session_client_new3;
491
492
618
  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

618
  CHECK_EQ(fn(
501
      &session,
502
      callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks.get(),
503
      this,
504
      *opts,
505
      &alloc_info), 0);
506
618
  session_.reset(session);
507
508
618
  outgoing_storage_.reserve(1024);
509
618
  outgoing_buffers_.reserve(32);
510
511
  Local<Uint8Array> uint8_arr =
512
618
      Uint8Array::New(js_fields_.GetArrayBuffer(), 0, kSessionUint8FieldCount);
513
1854
  USE(wrap->Set(env()->context(), env()->fields_string(), uint8_arr));
514
618
}
515
516
2472
Http2Session::~Http2Session() {
517
618
  CHECK(!is_in_scope());
518
618
  Debug(this, "freeing nghttp2 session");
519
  // Explicitly reset session_ so the subsequent
520
  // current_nghttp2_memory_ check passes.
521
618
  session_.reset();
522
618
  CHECK_EQ(current_nghttp2_memory_, 0);
523
1236
}
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
127
std::string Http2Session::diagnostic_name() const {
538
254
  return std::string("Http2Session ") + TypeName() + " (" +
539
381
      std::to_string(static_cast<int64_t>(get_async_id())) + ")";
540
}
541
542
23663
void Http2Stream::EmitStatistics() {
543
23663
  CHECK_NOT_NULL(session());
544
23663
  if (!HasHttp2Observer(env()))
545
23661
    return;
546
  auto entry =
547
      std::make_unique<Http2StreamPerformanceEntry>(
548
4
          session()->http2_state(), id_, statistics_);
549
12
  env()->SetImmediate([entry = move(entry)](Environment* env) {
550
2
    if (!HasHttp2Observer(env))
551
      return;
552
4
    HandleScope handle_scope(env->isolate());
553
2
    AliasedFloat64Array& buffer = entry->http2_state()->stream_stats_buffer;
554
2
    buffer[IDX_STREAM_STATS_ID] = entry->id();
555
2
    if (entry->first_byte() != 0) {
556
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] =
557
          (entry->first_byte() - entry->startTimeNano()) / 1e6;
558
    } else {
559
2
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0;
560
    }
561
2
    if (entry->first_header() != 0) {
562
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] =
563
2
          (entry->first_header() - entry->startTimeNano()) / 1e6;
564
    } else {
565
      buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0;
566
    }
567
2
    if (entry->first_byte_sent() != 0) {
568
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] =
569
1
          (entry->first_byte_sent() - entry->startTimeNano()) / 1e6;
570
    } else {
571
1
      buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0;
572
    }
573
    buffer[IDX_STREAM_STATS_SENTBYTES] =
574
2
        static_cast<double>(entry->sent_bytes());
575
    buffer[IDX_STREAM_STATS_RECEIVEDBYTES] =
576
2
        static_cast<double>(entry->received_bytes());
577
    Local<Object> obj;
578
6
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
579
2
  });
580
}
581
582
594
void Http2Session::EmitStatistics() {
583
594
  if (!HasHttp2Observer(env()))
584
592
    return;
585
  auto entry = std::make_unique<Http2SessionPerformanceEntry>(
586
4
      http2_state(), statistics_, session_type_);
587
12
  env()->SetImmediate([entry = std::move(entry)](Environment* env) {
588
2
    if (!HasHttp2Observer(env))
589
      return;
590
4
    HandleScope handle_scope(env->isolate());
591
2
    AliasedFloat64Array& buffer = entry->http2_state()->session_stats_buffer;
592
2
    buffer[IDX_SESSION_STATS_TYPE] = entry->type();
593
2
    buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6;
594
2
    buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count();
595
2
    buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent();
596
2
    buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count();
597
    buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] =
598
2
        entry->stream_average_duration();
599
    buffer[IDX_SESSION_STATS_DATA_SENT] =
600
2
        static_cast<double>(entry->data_sent());
601
    buffer[IDX_SESSION_STATS_DATA_RECEIVED] =
602
2
        static_cast<double>(entry->data_received());
603
    buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] =
604
2
        static_cast<double>(entry->max_concurrent_streams());
605
    Local<Object> obj;
606
6
    if (entry->ToObject().ToLocal(&obj)) entry->Notify(obj);
607
2
  });
608
}
609
610
// Closes the session and frees the associated resources
611
594
void Http2Session::Close(uint32_t code, bool socket_closed) {
612
594
  Debug(this, "closing session");
613
614
594
  if (is_closing())
615
    return;
616
594
  set_closing();
617
618
  // Stop reading on the i/o stream
619
594
  if (stream_ != nullptr) {
620
584
    set_reading_stopped();
621
584
    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
594
  if (!socket_closed) {
629
556
    Debug(this, "terminating session with code %d", code);
630
556
    CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
631
556
    SendPendingData();
632
38
  } else if (stream_ != nullptr) {
633
28
    stream_->RemoveStreamListener(this);
634
  }
635
636
594
  set_destroyed();
637
638
  // If we are writing we will get to make the callback in OnStreamAfterWrite.
639
594
  if (!is_write_in_progress()) {
640
560
    Debug(this, "make done session callback");
641
1120
    HandleScope scope(env()->isolate());
642
560
    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
596
  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
594
  statistics_.end_time = uv_hrtime();
657
594
  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
247436
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
663
247436
  auto s = streams_.find(id);
664
247436
  return s != streams_.end() ? s->second : BaseObjectPtr<Http2Stream>();
665
}
666
667
11988
bool Http2Session::CanAddStream() {
668
  uint32_t maxConcurrentStreams =
669
11988
      nghttp2_session_get_local_settings(
670
11988
          session_.get(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
671
  size_t maxSize =
672
11988
      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

23976
  return streams_.size() < maxSize &&
676
23976
         has_available_session_memory(sizeof(Http2Stream));
677
}
678
679
23772
void Http2Session::AddStream(Http2Stream* stream) {
680
23772
  CHECK_GE(++statistics_.stream_count, 0);
681
23772
  streams_[stream->id()] = BaseObjectPtr<Http2Stream>(stream);
682
23772
  size_t size = streams_.size();
683
23772
  if (size > statistics_.max_concurrent_streams)
684
1386
    statistics_.max_concurrent_streams = size;
685
23772
  IncrementCurrentSessionMemory(sizeof(*stream));
686
23772
}
687
688
689
23663
BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
690
23663
  BaseObjectPtr<Http2Stream> stream;
691
23663
  if (streams_.empty())
692
    return stream;
693
23663
  stream = FindStream(id);
694
23663
  if (stream) {
695
23663
    streams_.erase(id);
696
23663
    DecrementCurrentSessionMemory(sizeof(*stream));
697
  }
698
23663
  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
4
ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen,
706
                                            size_t maxPayloadLen) {
707
4
  size_t r = (frameLen + 9) % 8;
708
4
  if (r == 0) return frameLen;  // If already a multiple of 8, return.
709
710
4
  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
4
  pad = std::min(maxPayloadLen, pad);
716
4
  Debug(this, "using frame size padding: %d", pad);
717
4
  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
31494
ssize_t Http2Session::ConsumeHTTP2Data() {
734
31494
  CHECK_NOT_NULL(stream_buf_.base);
735
31494
  CHECK_LT(stream_buf_offset_, stream_buf_.len);
736
31494
  size_t read_len = stream_buf_.len - stream_buf_offset_;
737
738
  // multiple side effects.
739
31494
  Debug(this, "receiving %d bytes [wants data? %d]",
740
        read_len,
741
62988
        nghttp2_session_want_read(session_.get()));
742
31494
  set_receive_paused(false);
743
  ssize_t ret =
744
62988
    nghttp2_session_mem_recv(session_.get(),
745
31494
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
746
31494
                                 stream_buf_offset_,
747
31494
                             read_len);
748
31494
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
749
750
31494
  if (is_receive_paused()) {
751
608
    CHECK(is_reading_stopped());
752
753
608
    CHECK_GT(ret, 0);
754
608
    CHECK_LE(static_cast<size_t>(ret), read_len);
755
756
608
    if (static_cast<size_t>(ret) < read_len) {
757
      // Mark the remainder of the data as available for later consumption.
758
490
      stream_buf_offset_ += ret;
759
490
      return ret;
760
    }
761
  }
762
763
  // We are done processing the current input chunk.
764
31004
  DecrementCurrentSessionMemory(stream_buf_.len);
765
31004
  stream_buf_offset_ = 0;
766
31004
  stream_buf_ab_.Reset();
767
31004
  stream_buf_allocation_.clear();
768
31004
  stream_buf_ = uv_buf_init(nullptr, 0);
769
770
31004
  if (ret < 0)
771
6
    return ret;
772
773
  // Send any data that was queued up while processing the received data.
774
30998
  if (!is_destroyed()) {
775
30511
    SendPendingData();
776
  }
777
30998
  return ret;
778
}
779
780
781
144413
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
144413
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
784
      frame->push_promise.promised_stream_id :
785
144413
      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
23694
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
794
                                         const nghttp2_frame* frame,
795
                                         void* user_data) {
796
23694
  Http2Session* session = static_cast<Http2Session*>(user_data);
797
23694
  int32_t id = GetFrameID(frame);
798
  Debug(session, "beginning headers for stream %d", id);
799
800
47388
  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
23694
  if (LIKELY(!stream)) {
804

11988
    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
11987
    session->rejected_stream_count_ = 0;
820
11706
  } else if (!stream->is_destroyed()) {
821
11706
    stream->StartHeaders(frame->headers.cat);
822
  }
823
23693
  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
71871
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
71871
  Http2Session* session = static_cast<Http2Session*>(user_data);
836
71871
  int32_t id = GetFrameID(frame);
837
143742
  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
71871
  if (UNLIKELY(!stream))
842
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
843
844
  // If the stream has already been destroyed, ignore.
845

71871
  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
2
    stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM);
849
2
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
850
  }
851
71869
  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
56918
int Http2Session::OnFrameReceive(nghttp2_session* handle,
858
                                 const nghttp2_frame* frame,
859
                                 void* user_data) {
860
56918
  Http2Session* session = static_cast<Http2Session*>(user_data);
861
56918
  session->statistics_.frame_count++;
862
56918
  Debug(session, "complete frame received: type: %d",
863
        frame->hd.type);
864


56918
  switch (frame->hd.type) {
865
    case NGHTTP2_DATA:
866
25386
      return session->HandleDataFrame(frame);
867
    case NGHTTP2_PUSH_PROMISE:
868
      // Intentional fall-through, handled just like headers frames
869
    case NGHTTP2_HEADERS:
870
23453
      session->HandleHeadersFrame(frame);
871
23453
      break;
872
    case NGHTTP2_SETTINGS:
873
2076
      session->HandleSettingsFrame(frame);
874
2076
      break;
875
    case NGHTTP2_PRIORITY:
876
16
      session->HandlePriorityFrame(frame);
877
16
      break;
878
    case NGHTTP2_GOAWAY:
879
285
      session->HandleGoawayFrame(frame);
880
285
      break;
881
    case NGHTTP2_PING:
882
1021
      session->HandlePingFrame(frame);
883
1021
      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
4672
      break;
892
  }
893
31532
  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
2179
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
931
                                 const nghttp2_frame* frame,
932
                                 int error_code,
933
                                 void* user_data) {
934
2179
  Http2Session* session = static_cast<Http2Session*>(user_data);
935
2179
  Environment* env = session->env();
936
2179
  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

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

2184
      error_code == NGHTTP2_ERR_STREAM_CLOSING ||
943
2
      session->js_fields_->frame_error_listener_count == 0) {
944
2178
    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
56048
int Http2Session::OnFrameSent(nghttp2_session* handle,
964
                              const nghttp2_frame* frame,
965
                              void* user_data) {
966
56048
  Http2Session* session = static_cast<Http2Session*>(user_data);
967
56048
  session->statistics_.frame_sent += 1;
968
56048
  return 0;
969
}
970
971
// Called by nghttp2 when a stream closes.
972
23636
int Http2Session::OnStreamClose(nghttp2_session* handle,
973
                                int32_t id,
974
                                uint32_t code,
975
                                void* user_data) {
976
23636
  Http2Session* session = static_cast<Http2Session*>(user_data);
977
23636
  Environment* env = session->env();
978
23636
  Isolate* isolate = env->isolate();
979
47272
  HandleScope scope(isolate);
980
23636
  Local<Context> context = env->context();
981
  Context::Scope context_scope(context);
982
  Debug(session, "stream %d closed with code: %d", id, code);
983
47272
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
984
  // Intentionally ignore the callback if the stream does not exist or has
985
  // already been destroyed
986

23636
  if (!stream || stream->is_destroyed())
987
52
    return 0;
988
989
23584
  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
23584
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
995
  MaybeLocal<Value> answer =
996
23584
    stream->MakeCallback(env->http2session_on_stream_close_function(),
997
47168
                          1, &arg);
998

70752
  if (answer.IsEmpty() || answer.ToLocalChecked()->IsFalse()) {
999
    // Skip to destroy
1000
137
    stream->Destroy();
1001
  }
1002
23584
  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
13743
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
13743
  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
13743
  Environment* env = session->env();
1033
27486
  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
13743
  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
13743
  CHECK_EQ(nghttp2_session_consume_connection(handle, len), 0);
1044
27486
  BaseObjectPtr<Http2Stream> stream = session->FindStream(id);
1045
1046
  // If the stream has been destroyed, ignore this chunk
1047

13743
  if (!stream || stream->is_destroyed())
1048
1
    return 0;
1049
1050
13742
  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
13742
    uv_buf_t buf = stream->EmitAlloc(len);
1059
13742
    ssize_t avail = len;
1060
13742
    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
13742
    if (LIKELY(buf.base == nullptr))
1069
13742
      buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
1070
    else
1071
      memcpy(buf.base, data, avail);
1072
13742
    data += avail;
1073
13742
    len -= avail;
1074
13742
    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
13742
    if (stream->is_reading())
1080
12634
      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

27484
    if (session->outgoing_length_ > 4096 ||
1086
13742
        stream->available_outbound_length_ > 4096) {
1087
4
      session->SendPendingData();
1088
    }
1089
13742
  } 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
13742
  if (session->is_write_in_progress()) {
1094
608
    CHECK(session->is_reading_stopped());
1095
608
    session->set_receive_paused();
1096
608
    return NGHTTP2_ERR_PAUSE;
1097
  }
1098
1099
13134
  return 0;
1100
}
1101
1102
// Called by nghttp2 when it needs to determine how much padding to use in
1103
// a DATA or HEADERS frame.
1104
4
ssize_t Http2Session::OnSelectPadding(nghttp2_session* handle,
1105
                                      const nghttp2_frame* frame,
1106
                                      size_t maxPayloadLen,
1107
                                      void* user_data) {
1108
4
  Http2Session* session = static_cast<Http2Session*>(user_data);
1109
4
  ssize_t padding = frame->hd.length;
1110
1111

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

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

50772
  if (stream &&
1281

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

3969
  if (is_reading_stopped() &&
1449

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

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

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


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

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

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

215613
  if (!session_->has_available_session_memory(length) ||
2227

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

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

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

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

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

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

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

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

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



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

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