GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_http2.cc Lines: 1470 1539 95.5 %
Date: 2020-07-19 22:14:24 Branches: 554 758 73.1 %

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

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



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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

52060
  if (stream &&
1281

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

3966
  if (is_reading_stopped() &&
1449

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

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

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


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

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

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

217155
  if (!session_->has_available_session_memory(length) ||
2226

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

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

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

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

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

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

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

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

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



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

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