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: 1466 1535 95.5 %
Date: 2020-06-24 22:13:30 Branches: 552 756 73.0 %

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
24342
bool HasHttp2Observer(Environment* env) {
50
24342
  AliasedUint32Array& observers = env->performance_state()->observers;
51
24342
  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
8798
const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = {
60
    Callbacks(false),
61
4399
    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
63269
Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {}
75
76
107485
Http2Scope::Http2Scope(Http2Session* session) : session_(session) {
77
107485
  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

107485
  if (session_->is_in_scope() || session_->is_write_scheduled()) {
82
74946
    session_.reset();
83
74946
    return;
84
  }
85
32539
  session_->set_in_scope();
86
}
87
88
214970
Http2Scope::~Http2Scope() {
89
107485
  if (!session_) return;
90
32539
  session_->set_in_scope(false);
91
32539
  session_->MaybeScheduleWrite();
92
107485
}
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
615
Http2Options::Http2Options(Http2State* http2_state, SessionType type) {
99
  nghttp2_option* option;
100
615
  CHECK_EQ(nghttp2_option_new(&option), 0);
101
615
  CHECK_NOT_NULL(option);
102
615
  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
615
  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
615
  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
615
  if (type == NGHTTP2_SESSION_CLIENT) {
119
299
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ALTSVC);
120
299
    nghttp2_option_set_builtin_recv_extension_type(option, NGHTTP2_ORIGIN);
121
  }
122
123
615
  AliasedUint32Array& buffer = http2_state->options_buffer;
124
615
  uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
125
126
615
  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
615
  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
615
  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
615
  nghttp2_option_set_peer_max_concurrent_streams(option, 100);
146
615
  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
615
  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
615
  if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS))
168
1
    set_max_header_pairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]);
169
170
  // The HTTP2 specification places no limits on the number of HTTP2
171
  // PING frames that can be sent. In order to prevent PINGS from being
172
  // abused as an attack vector, however, we place a strict upper limit
173
  // on the number of unacknowledged PINGS that can be sent at any given
174
  // time.
175
615
  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
615
  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
615
  if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY))
195
6
    set_max_session_memory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1000000);
196
197
615
  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
615
}
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
640
size_t Http2Settings::Init(
213
    Http2State* http2_state,
214
    nghttp2_settings_entry* entries) {
215
640
  AliasedUint32Array& buffer = http2_state->settings_buffer;
216
640
  uint32_t flags = buffer[IDX_SETTINGS_COUNT];
217
218
640
  size_t count = 0;
219
220
#define V(name) GRABSETTING(entries, count, name);
221



640
  HTTP2_SETTINGS(V)
222
#undef V
223
224
640
  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
625
Http2Settings::Http2Settings(Http2Session* session,
232
                             Local<Object> obj,
233
                             Local<Function> callback,
234
625
                             uint64_t start_time)
235
    : AsyncWrap(session->env(), obj, PROVIDER_HTTP2SETTINGS),
236
      session_(session),
237
1250
      startTime_(start_time) {
238
625
  callback_.Reset(env()->isolate(), callback);
239
625
  count_ = Init(session->http2_state(), entries_);
240
625
}
241
242
510
Local<Function> Http2Settings::callback() const {
243
1020
  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
530
void Http2Settings::Update(Http2Session* session, get_setting fn) {
284
530
  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
530
  HTTP2_SETTINGS(V)
290
#undef V
291
530
}
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
623
void Http2Settings::Send() {
311
1246
  Http2Scope h2scope(session_.get());
312
623
  CHECK_EQ(nghttp2_submit_settings(
313
      session_->session(),
314
      NGHTTP2_FLAG_NONE,
315
      &entries_[0],
316
      count_), 0);
317
623
}
318
319
510
void Http2Settings::Done(bool ack) {
320
510
  uint64_t end = uv_hrtime();
321
510
  double duration = (end - startTime_) / 1e6;
322
323
  Local<Value> argv[] = {
324
510
    ack ? v8::True(env()->isolate()) : v8::False(env()->isolate()),
325
    Number::New(env()->isolate(), duration)
326
1530
  };
327
510
  MakeCallback(callback(), arraysize(argv), argv);
328
510
}
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
11779
Http2Priority::Http2Priority(Environment* env,
334
                             Local<Value> parent,
335
                             Local<Value> weight,
336
11779
                             Local<Value> exclusive) {
337
11779
  Local<Context> context = env->context();
338
23558
  int32_t parent_ = parent->Int32Value(context).ToChecked();
339
23558
  int32_t weight_ = weight->Int32Value(context).ToChecked();
340
11779
  bool exclusive_ = exclusive->IsTrue();
341
  Debug(env, DebugCategory::HTTP2STREAM,
342
        "Http2Priority: parent: %d, weight: %d, exclusive: %s\n",
343
23558
        parent_, weight_, exclusive_ ? "yes" : "no");
344
11779
  nghttp2_priority_spec_init(this, parent_, weight_, exclusive_ ? 1 : 0);
345
11779
}
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
8798
Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) {
410
  nghttp2_session_callbacks* callbacks_;
411
8798
  CHECK_EQ(nghttp2_session_callbacks_new(&callbacks_), 0);
412
8798
  callbacks.reset(callbacks_);
413
414
  nghttp2_session_callbacks_set_on_begin_headers_callback(
415
8798
    callbacks_, OnBeginHeadersCallback);
416
  nghttp2_session_callbacks_set_on_header_callback2(
417
8798
    callbacks_, OnHeaderCallback);
418
  nghttp2_session_callbacks_set_on_frame_recv_callback(
419
8798
    callbacks_, OnFrameReceive);
420
  nghttp2_session_callbacks_set_on_stream_close_callback(
421
8798
    callbacks_, OnStreamClose);
422
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
423
8798
    callbacks_, OnDataChunkReceived);
424
  nghttp2_session_callbacks_set_on_frame_not_send_callback(
425
8798
    callbacks_, OnFrameNotSent);
426
  nghttp2_session_callbacks_set_on_invalid_header_callback2(
427
8798
    callbacks_, OnInvalidHeader);
428
  nghttp2_session_callbacks_set_error_callback(
429
8798
    callbacks_, OnNghttpError);
430
  nghttp2_session_callbacks_set_send_data_callback(
431
8798
    callbacks_, OnSendData);
432
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
433
8798
    callbacks_, OnInvalidFrame);
434
  nghttp2_session_callbacks_set_on_frame_send_callback(
435
8798
    callbacks_, OnFrameSent);
436
437
8798
  if (kHasGetPaddingCallback) {
438
    nghttp2_session_callbacks_set_select_padding_callback(
439
4399
      callbacks_, OnSelectPadding);
440
  }
441
8798
}
442
443
void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) {
444
  StopTrackingMemory(buf);
445
}
446
447
201424
void Http2Session::CheckAllocatedSize(size_t previous_size) const {
448
201424
  CHECK_GE(current_nghttp2_memory_, previous_size);
449
201424
}
450
451
101647
void Http2Session::IncreaseAllocatedSize(size_t size) {
452
101647
  current_nghttp2_memory_ += size;
453
101647
}
454
455
124914
void Http2Session::DecreaseAllocatedSize(size_t size) {
456
124914
  current_nghttp2_memory_ -= size;
457
124914
}
458
459
615
Http2Session::Http2Session(Http2State* http2_state,
460
                           Local<Object> wrap,
461
615
                           SessionType type)
462
    : AsyncWrap(http2_state->env(), wrap, AsyncWrap::PROVIDER_HTTP2SESSION),
463
      js_fields_(http2_state->env()->isolate()),
464
      session_type_(type),
465
1230
      http2_state_(http2_state) {
466
615
  MakeWeak();
467
615
  statistics_.start_time = uv_hrtime();
468
469
  // Capture the configuration options for this session
470
1230
  Http2Options opts(http2_state, type);
471
472
615
  max_session_memory_ = opts.max_session_memory();
473
474
615
  uint32_t maxHeaderPairs = opts.max_header_pairs();
475
615
  max_header_pairs_ =
476
      type == NGHTTP2_SESSION_SERVER
477
316
          ? GetServerMaxHeaderPairs(maxHeaderPairs)
478
931
          : GetClientMaxHeaderPairs(maxHeaderPairs);
479
480
615
  max_outstanding_pings_ = opts.max_outstanding_pings();
481
615
  max_outstanding_settings_ = opts.max_outstanding_settings();
482
483
615
  padding_strategy_ = opts.padding_strategy();
484
485
  bool hasGetPaddingCallback =
486
615
      padding_strategy_ != PADDING_STRATEGY_NONE;
487
488
615
  auto fn = type == NGHTTP2_SESSION_SERVER ?
489
      nghttp2_session_server_new3 :
490
615
      nghttp2_session_client_new3;
491
492
615
  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

615
  CHECK_EQ(fn(
501
      &session,
502
      callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks.get(),
503
      this,
504
      *opts,
505
      &alloc_info), 0);
506
615
  session_.reset(session);
507
508
615
  outgoing_storage_.reserve(1024);
509
615
  outgoing_buffers_.reserve(32);
510
511
  Local<Uint8Array> uint8_arr =
512
615
      Uint8Array::New(js_fields_.GetArrayBuffer(), 0, kSessionUint8FieldCount);
513
1845
  USE(wrap->Set(env()->context(), env()->fields_string(), uint8_arr));
514
615
}
515
516
2460
Http2Session::~Http2Session() {
517
615
  CHECK(!is_in_scope());
518
615
  Debug(this, "freeing nghttp2 session");
519
  // Explicitly reset session_ so the subsequent
520
  // current_nghttp2_memory_ check passes.
521
615
  session_.reset();
522
615
  CHECK_EQ(current_nghttp2_memory_, 0);
523
1230
}
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
23745
void Http2Stream::EmitStatistics() {
543
23745
  CHECK_NOT_NULL(session());
544
23745
  if (!HasHttp2Observer(env()))
545
23743
    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
593
void Http2Session::EmitStatistics() {
583
593
  if (!HasHttp2Observer(env()))
584
591
    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
593
void Http2Session::Close(uint32_t code, bool socket_closed) {
612
593
  Debug(this, "closing session");
613
614
593
  if (is_closing())
615
    return;
616
593
  set_closing();
617
618
  // Stop reading on the i/o stream
619
593
  if (stream_ != nullptr) {
620
583
    set_reading_stopped();
621
583
    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
593
  if (!socket_closed) {
629
554
    Debug(this, "terminating session with code %d", code);
630
554
    CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
631
554
    SendPendingData();
632
39
  } else if (stream_ != nullptr) {
633
29
    stream_->RemoveStreamListener(this);
634
  }
635
636
593
  set_destroyed();
637
638
  // If we are writing we will get to make the callback in OnStreamAfterWrite.
639
593
  if (!is_write_in_progress()) {
640
559
    Debug(this, "make done session callback");
641
1118
    HandleScope scope(env()->isolate());
642
559
    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
595
  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
593
  statistics_.end_time = uv_hrtime();
657
593
  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
247735
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
663
247735
  auto s = streams_.find(id);
664
247735
  return s != streams_.end() ? s->second : BaseObjectPtr<Http2Stream>();
665
}
666
667
11984
bool Http2Session::CanAddStream() {
668
  uint32_t maxConcurrentStreams =
669
11984
      nghttp2_session_get_local_settings(
670
11984
          session_.get(), NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
671
  size_t maxSize =
672
11984
      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

23968
  return streams_.size() < maxSize &&
676
23968
         has_available_session_memory(sizeof(Http2Stream));
677
}
678
679
23764
void Http2Session::AddStream(Http2Stream* stream) {
680
23764
  CHECK_GE(++statistics_.stream_count, 0);
681
23764
  streams_[stream->id()] = BaseObjectPtr<Http2Stream>(stream);
682
23764
  size_t size = streams_.size();
683
23764
  if (size > statistics_.max_concurrent_streams)
684
1329
    statistics_.max_concurrent_streams = size;
685
23764
  IncrementCurrentSessionMemory(sizeof(*stream));
686
23764
}
687
688
689
23745
BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
690
23745
  BaseObjectPtr<Http2Stream> stream;
691
23745
  if (streams_.empty())
692
    return stream;
693
23745
  stream = FindStream(id);
694
23745
  if (stream) {
695
23745
    streams_.erase(id);
696
23745
    DecrementCurrentSessionMemory(sizeof(*stream));
697
  }
698
23745
  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
31474
ssize_t Http2Session::ConsumeHTTP2Data() {
734
31474
  CHECK_NOT_NULL(stream_buf_.base);
735
31474
  CHECK_LT(stream_buf_offset_, stream_buf_.len);
736
31474
  size_t read_len = stream_buf_.len - stream_buf_offset_;
737
738
  // multiple side effects.
739
31474
  Debug(this, "receiving %d bytes [wants data? %d]",
740
        read_len,
741
62948
        nghttp2_session_want_read(session_.get()));
742
31474
  set_receive_paused(false);
743
  ssize_t ret =
744
62948
    nghttp2_session_mem_recv(session_.get(),
745
31474
                             reinterpret_cast<uint8_t*>(stream_buf_.base) +
746
31474
                                 stream_buf_offset_,
747
31474
                             read_len);
748
31474
  CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
749
750
31474
  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
30984
  DecrementCurrentSessionMemory(stream_buf_.len);
765
30984
  stream_buf_offset_ = 0;
766
30984
  stream_buf_ab_.Reset();
767
30984
  stream_buf_allocation_.clear();
768
30984
  stream_buf_ = uv_buf_init(nullptr, 0);
769
770
30984
  if (ret < 0)
771
6
    return ret;
772
773
  // Send any data that was queued up while processing the received data.
774
30978
  if (!is_destroyed()) {
775
30491
    SendPendingData();
776
  }
777
30978
  return ret;
778
}
779
780
781
144404
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
144404
  return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ?
784
      frame->push_promise.promised_stream_id :
785
144404
      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
23686
int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
794
                                         const nghttp2_frame* frame,
795
                                         void* user_data) {
796
23686
  Http2Session* session = static_cast<Http2Session*>(user_data);
797
23686
  int32_t id = GetFrameID(frame);
798
  Debug(session, "beginning headers for stream %d", id);
799
800
47372
  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
23686
  if (LIKELY(!stream)) {
804

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

71843
  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
71841
  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
56935
int Http2Session::OnFrameReceive(nghttp2_session* handle,
858
                                 const nghttp2_frame* frame,
859
                                 void* user_data) {
860
56935
  Http2Session* session = static_cast<Http2Session*>(user_data);
861
56935
  session->statistics_.frame_count++;
862
56935
  Debug(session, "complete frame received: type: %d",
863
        frame->hd.type);
864


56935
  switch (frame->hd.type) {
865
    case NGHTTP2_DATA:
866
25421
      return session->HandleDataFrame(frame);
867
    case NGHTTP2_PUSH_PROMISE:
868
      // Intentional fall-through, handled just like headers frames
869
    case NGHTTP2_HEADERS:
870
23445
      session->HandleHeadersFrame(frame);
871
23445
      break;
872
    case NGHTTP2_SETTINGS:
873
2068
      session->HandleSettingsFrame(frame);
874
2068
      break;
875
    case NGHTTP2_PRIORITY:
876
16
      session->HandlePriorityFrame(frame);
877
16
      break;
878
    case NGHTTP2_GOAWAY:
879
284
      session->HandleGoawayFrame(frame);
880
284
      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
4671
      break;
892
  }
893
31514
  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
2089
int Http2Session::OnFrameNotSent(nghttp2_session* handle,
931
                                 const nghttp2_frame* frame,
932
                                 int error_code,
933
                                 void* user_data) {
934
2089
  Http2Session* session = static_cast<Http2Session*>(user_data);
935
2089
  Environment* env = session->env();
936
2089
  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

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

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

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

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

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

27558
    if (session->outgoing_length_ > 4096 ||
1086
13779
        stream->available_outbound_length_ > 4096) {
1087
4
      session->SendPendingData();
1088
    }
1089
13779
  } 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
13779
  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
13171
  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
13779
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
13779
  return uv_buf_init(nullptr, size);
1155
}
1156
1157
26337
void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1158
26337
  Http2Stream* stream = static_cast<Http2Stream*>(stream_);
1159
26337
  Http2Session* session = stream->session();
1160
26337
  Environment* env = stream->env();
1161
40116
  HandleScope handle_scope(env->isolate());
1162
40116
  Context::Scope context_scope(env->context());
1163
1164
26337
  if (nread < 0) {
1165
12558
    PassReadErrorToPreviousListener(nread);
1166
12558
    return;
1167
  }
1168
1169
  Local<ArrayBuffer> ab;
1170
27558
  if (session->stream_buf_ab_.IsEmpty()) {
1171
5652
    ab = session->stream_buf_allocation_.ToArrayBuffer();
1172
5652
    session->stream_buf_ab_.Reset(env->isolate(), ab);
1173
  } else {
1174
8127
    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
13779
  size_t offset = buf.base - session->stream_buf_.base;
1181
1182
  // Verify that the data offset is inside the current read buffer.
1183
13779
  CHECK_GE(offset, session->stream_buf_offset_);
1184
13779
  CHECK_LE(offset, session->stream_buf_.len);
1185
13779
  CHECK_LE(offset + buf.len, session->stream_buf_.len);
1186
1187
13779
  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
23445
void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
1195
23445
  Isolate* isolate = env()->isolate();
1196
46890
  HandleScope scope(isolate);
1197
23445
  Local<Context> context = env()->context();
1198
23445
  Context::Scope context_scope(context);
1199
1200
23445
  int32_t id = GetFrameID(frame);
1201
23445
  Debug(this, "handle headers frame for stream %d", id);
1202
46890
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1203
1204
  // If the stream has already been destroyed, ignore.
1205

23445
  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
46890
  std::vector<Local<Value>> headers_v(stream->headers_count() * 2);
1217
118622
  stream->TransferHeaders([&](const Http2Header& header, size_t i) {
1218
286928
    headers_v[i * 2] = header.GetName(this).ToLocalChecked();
1219
286928
    headers_v[i * 2 + 1] = header.GetValue(this).ToLocalChecked();
1220
95177
  });
1221
23445
  CHECK_EQ(stream->headers_count(), 0);
1222
1223
23445
  DecrementCurrentSessionMemory(stream->current_headers_length_);
1224
23445
  stream->current_headers_length_ = 0;
1225
1226
  Local<Value> args[5] = {
1227
23445
      stream->object(),
1228
      Integer::New(isolate, id),
1229
23445
      Integer::New(isolate, stream->headers_category()),
1230
23445
      Integer::New(isolate, frame->hd.flags),
1231
211005
      Array::New(isolate, headers_v.data(), headers_v.size())};
1232
  MakeCallback(env()->http2session_on_headers_function(),
1233
23445
               arraysize(args), args);
1234
}
1235
1236
1237
// Called by OnFrameReceived when a complete PRIORITY frame has been
1238
// received. Notifies JS land about the priority change. Note that priorities
1239
// are considered advisory only, so this has no real effect other than to
1240
// simply let user code know that the priority has changed.
1241
16
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
1242
16
  if (js_fields_->priority_listener_count == 0) return;
1243
5
  Isolate* isolate = env()->isolate();
1244
10
  HandleScope scope(isolate);
1245
5
  Local<Context> context = env()->context();
1246
  Context::Scope context_scope(context);
1247
1248
5
  nghttp2_priority priority_frame = frame->priority;
1249
5
  int32_t id = GetFrameID(frame);
1250
5
  Debug(this, "handle priority frame for stream %d", id);
1251
  // Priority frame stream ID should never be <= 0. nghttp2 handles this for us
1252
5
  nghttp2_priority_spec spec = priority_frame.pri_spec;
1253
1254
  Local<Value> argv[4] = {
1255
    Integer::New(isolate, id),
1256
    Integer::New(isolate, spec.stream_id),
1257
    Integer::New(isolate, spec.weight),
1258
5
    Boolean::New(isolate, spec.exclusive)
1259
30
  };
1260
  MakeCallback(env()->http2session_on_priority_function(),
1261
5
               arraysize(argv), argv);
1262
}
1263
1264
1265
// Called by OnFrameReceived when a complete DATA frame has been received.
1266
// If we know that this was the last DATA frame (because the END_STREAM flag
1267
// is set), then we'll terminate the readable side of the StreamBase.
1268
25421
int Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
1269
25421
  int32_t id = GetFrameID(frame);
1270
25421
  Debug(this, "handling data frame for stream %d", id);
1271
50842
  BaseObjectPtr<Http2Stream> stream = FindStream(id);
1272
1273

50842
  if (stream &&
1274

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

3954
  if (is_reading_stopped() &&
1442

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

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

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


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

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

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

215529
  if (!session_->has_available_session_memory(length) ||
2223

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

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

29188
  if (amount == 0 && stream->is_writable()) {
2307
3673
    CHECK(stream->queue_.empty());
2308
    Debug(session, "deferring stream %d", id);
2309
3673
    stream->EmitWantsWrite(length);
2310

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

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

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

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

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

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



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

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