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: 1464 1533 95.5 %
Date: 2020-05-27 22:15:15 Branches: 550 754 72.9 %

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

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



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

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

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

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

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


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

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

4362
  if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
937
7
      error_code == NGHTTP2_ERR_STREAM_CLOSED ||
938

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

23676
  if (!stream || stream->is_destroyed())
983
52
    return 0;
984
985
23624
  stream->Close(code);
986
987
  // It is possible for the stream close to occur before the stream is
988
  // ever passed on to the javascript side. If that happens, the callback
989
  // will return false.
990
23624
  Local<Value> arg = Integer::NewFromUnsigned(isolate, code);
991
  MaybeLocal<Value> answer =
992
23624
    stream->MakeCallback(env->http2session_on_stream_close_function(),
993
47248
                          1, &arg);
994

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

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

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

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

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

50762
  if (stream &&
1270

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

3954
  if (is_reading_stopped() &&
1438

2631
      !is_write_in_progress() &&
1439
1313
      nghttp2_session_want_read(session_.get())) {
1440
1282
    set_reading_stopped(false);
1441
1282
    stream_->ReadStart();
1442
  }
1443
1444
1318
  if (is_destroyed()) {
1445
68
    HandleScope scope(env()->isolate());
1446
34
    MakeCallback(env()->ondone_string(), 0, nullptr);
1447
34
    return;
1448
  }
1449
1450
  // If there is more incoming data queued up, consume it.
1451
1284
  if (stream_buf_offset_ > 0) {
1452
257
    ConsumeHTTP2Data();
1453
  }
1454
1455
1284
  if (!is_write_scheduled()) {
1456
    // Schedule a new write if nghttp2 wants to send data.
1457
1098
    MaybeScheduleWrite();
1458
  }
1459
}
1460
1461
// If the underlying nghttp2_session struct has data pending in its outbound
1462
// queue, MaybeScheduleWrite will schedule a SendPendingData() call to occur
1463
// on the next iteration of the Node.js event loop (using the SetImmediate
1464
// queue), but only if a write has not already been scheduled.
1465
33647
void Http2Session::MaybeScheduleWrite() {
1466
33647
  CHECK(!is_write_scheduled());
1467
33647
  if (UNLIKELY(!session_))
1468
    return;
1469
1470
33647
  if (nghttp2_session_want_write(session_.get())) {
1471
5274
    HandleScope handle_scope(env()->isolate());
1472
2637
    Debug(this, "scheduling write");
1473
2637
    set_write_scheduled();
1474
5274
    BaseObjectPtr<Http2Session> strong_ref{this};
1475
22983
    env()->SetImmediate([this, strong_ref](Environment* env) {
1476

5274
      if (!session_ || !is_write_scheduled()) {
1477
        // This can happen e.g. when a stream was reset before this turn
1478
        // of the event loop, in which case SendPendingData() is called early,
1479
        // or the session was destroyed in the meantime.
1480
375
        return;
1481
      }
1482
1483
      // Sending data may call arbitrary JS code, so keep track of
1484
      // async context.
1485
4524
      HandleScope handle_scope(env->isolate());
1486
4524
      InternalCallbackScope callback_scope(this);
1487
2262
      SendPendingData();
1488
2637
    });
1489
  }
1490
}
1491
1492
63547
void Http2Session::MaybeStopReading() {
1493
63547
  if (is_reading_stopped()) return;
1494
60952
  int want_read = nghttp2_session_want_read(session_.get());
1495
60952
  Debug(this, "wants read? %d", want_read);
1496

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


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

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

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

215949
  if (!session_->has_available_session_memory(length) ||
2218

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

29116
  while (!stream->queue_.empty() && stream->queue_.front().buf.len == 0) {
2283
4
    WriteWrap* finished = stream->queue_.front().req_wrap;
2284
4
    stream->queue_.pop();
2285
4
    if (finished != nullptr)
2286
2
      finished->Done(0);
2287
  }
2288
2289
29108
  if (!stream->queue_.empty()) {
2290
    Debug(session, "stream %d has pending outbound data", id);
2291
12862
    amount = std::min(stream->available_outbound_length_, length);
2292
    Debug(session, "sending %d bytes for data frame on stream %d", amount, id);
2293
12862
    if (amount > 0) {
2294
      // Just return the length, let Http2Session::OnSendData take care of
2295
      // actually taking the buffers out of the queue.
2296
12862
      *flags |= NGHTTP2_DATA_FLAG_NO_COPY;
2297
12862
      stream->DecrementAvailableOutboundLength(amount);
2298
    }
2299
  }
2300
2301

29108
  if (amount == 0 && stream->is_writable()) {
2302
3634
    CHECK(stream->queue_.empty());
2303
    Debug(session, "deferring stream %d", id);
2304
3634
    stream->EmitWantsWrite(length);
2305

3634
    if (stream->available_outbound_length_ > 0 || !stream->is_writable()) {
2306
      // EmitWantsWrite() did something interesting synchronously, restart:
2307
      return OnRead(handle, id, buf, length, flags, source, user_data);
2308
    }
2309
3634
    return NGHTTP2_ERR_DEFERRED;
2310
  }
2311
2312

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

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

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

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

10
  if (origin_str.IsEmpty() || value_str.IsEmpty())
2722
    return;
2723
2724
5
  size_t origin_len = origin_str->Length();
2725
5
  size_t value_len = value_str->Length();
2726
2727
5
  CHECK_LE(origin_len + value_len, 16382);  // Max permitted for ALTSVC
2728
  // Verify that origin len != 0 if stream id == 0, or
2729
  // that origin len == 0 if stream id != 0
2730



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

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