GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_http2.h Lines: 142 154 92.2 %
Date: 2021-11-07 03:13:54 Branches: 33 40 82.5 %

Line Branch Exec Source
1
#ifndef SRC_NODE_HTTP2_H_
2
#define SRC_NODE_HTTP2_H_
3
4
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5
6
// FIXME(joyeecheung): nghttp2.h needs stdint.h to compile on Windows
7
#include <cstdint>
8
#include "nghttp2/nghttp2.h"
9
10
#include "env.h"
11
#include "aliased_struct.h"
12
#include "node_http2_state.h"
13
#include "node_http_common.h"
14
#include "node_mem.h"
15
#include "node_perf.h"
16
#include "stream_base.h"
17
#include "string_bytes.h"
18
19
#include <algorithm>
20
#include <queue>
21
22
namespace node {
23
namespace http2 {
24
25
// Constants in all caps are exported as user-facing constants
26
// in JavaScript. Constants using the kName pattern are internal
27
// only.
28
29
// We strictly limit the number of outstanding unacknowledged PINGS a user
30
// may send in order to prevent abuse. The current default cap is 10. The
31
// user may set a different limit using a per Http2Session configuration
32
// option.
33
constexpr size_t kDefaultMaxPings = 10;
34
35
// Also strictly limit the number of outstanding SETTINGS frames a user sends
36
constexpr size_t kDefaultMaxSettings = 10;
37
38
// Default maximum total memory cap for Http2Session.
39
constexpr uint64_t kDefaultMaxSessionMemory = 10000000;
40
41
// These are the standard HTTP/2 defaults as specified by the RFC
42
constexpr uint32_t DEFAULT_SETTINGS_HEADER_TABLE_SIZE = 4096;
43
constexpr uint32_t DEFAULT_SETTINGS_ENABLE_PUSH = 1;
44
constexpr uint32_t DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS = 0xffffffffu;
45
constexpr uint32_t DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE = 65535;
46
constexpr uint32_t DEFAULT_SETTINGS_MAX_FRAME_SIZE = 16384;
47
constexpr uint32_t DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE = 65535;
48
constexpr uint32_t DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL = 0;
49
constexpr uint32_t MAX_MAX_FRAME_SIZE = 16777215;
50
constexpr uint32_t MIN_MAX_FRAME_SIZE = DEFAULT_SETTINGS_MAX_FRAME_SIZE;
51
constexpr uint32_t MAX_INITIAL_WINDOW_SIZE = 2147483647;
52
53
// Stream is not going to have any DATA frames
54
constexpr int STREAM_OPTION_EMPTY_PAYLOAD = 0x1;
55
56
// Stream might have trailing headers
57
constexpr int STREAM_OPTION_GET_TRAILERS = 0x2;
58
59
// Http2Stream internal states
60
constexpr int kStreamStateNone = 0x0;
61
constexpr int kStreamStateShut = 0x1;
62
constexpr int kStreamStateReadStart = 0x2;
63
constexpr int kStreamStateReadPaused = 0x4;
64
constexpr int kStreamStateClosed = 0x8;
65
constexpr int kStreamStateDestroyed = 0x10;
66
constexpr int kStreamStateTrailers = 0x20;
67
68
// Http2Session internal states
69
constexpr int kSessionStateNone = 0x0;
70
constexpr int kSessionStateHasScope = 0x1;
71
constexpr int kSessionStateWriteScheduled = 0x2;
72
constexpr int kSessionStateClosed = 0x4;
73
constexpr int kSessionStateClosing = 0x8;
74
constexpr int kSessionStateSending = 0x10;
75
constexpr int kSessionStateWriteInProgress = 0x20;
76
constexpr int kSessionStateReadingStopped = 0x40;
77
constexpr int kSessionStateReceivePaused = 0x80;
78
79
// The Padding Strategy determines the method by which extra padding is
80
// selected for HEADERS and DATA frames. These are configurable via the
81
// options passed in to a Http2Session object.
82
enum PaddingStrategy {
83
  // No padding strategy. This is the default.
84
  PADDING_STRATEGY_NONE,
85
  // Attempts to ensure that the frame is 8-byte aligned
86
  PADDING_STRATEGY_ALIGNED,
87
  // Padding will ensure all data frames are maxFrameSize
88
  PADDING_STRATEGY_MAX,
89
  // Removed and turned into an alias because it is unreasonably expensive for
90
  // very little benefit.
91
  PADDING_STRATEGY_CALLBACK = PADDING_STRATEGY_ALIGNED
92
};
93
94
enum SessionType {
95
  NGHTTP2_SESSION_SERVER,
96
  NGHTTP2_SESSION_CLIENT
97
};
98
99
template <typename T, void(*fn)(T*)>
100
struct Nghttp2Deleter {
101
22428
  void operator()(T* ptr) const noexcept { fn(ptr); }
102
};
103
104
using Nghttp2OptionPointer =
105
    std::unique_ptr<nghttp2_option,
106
                    Nghttp2Deleter<nghttp2_option, nghttp2_option_del>>;
107
108
using Nghttp2SessionPointer =
109
    std::unique_ptr<nghttp2_session,
110
                    Nghttp2Deleter<nghttp2_session, nghttp2_session_del>>;
111
112
using Nghttp2SessionCallbacksPointer =
113
    std::unique_ptr<nghttp2_session_callbacks,
114
                    Nghttp2Deleter<nghttp2_session_callbacks,
115
                                   nghttp2_session_callbacks_del>>;
116
117
struct Http2HeadersTraits {
118
  typedef nghttp2_nv nv_t;
119
};
120
121
struct Http2RcBufferPointerTraits {
122
  typedef nghttp2_rcbuf rcbuf_t;
123
  typedef nghttp2_vec vector_t;
124
125
312003
  static void inc(rcbuf_t* buf) {
126
312003
    CHECK_NOT_NULL(buf);
127
312003
    nghttp2_rcbuf_incref(buf);
128
312003
  }
129
312003
  static void dec(rcbuf_t* buf) {
130
312003
    CHECK_NOT_NULL(buf);
131
312003
    nghttp2_rcbuf_decref(buf);
132
312003
  }
133
513006
  static vector_t get_vec(rcbuf_t* buf) {
134
513006
    CHECK_NOT_NULL(buf);
135
513006
    return nghttp2_rcbuf_get_buf(buf);
136
  }
137
143378
  static bool is_static(const rcbuf_t* buf) {
138
143378
    CHECK_NOT_NULL(buf);
139
143378
    return nghttp2_rcbuf_is_static(buf);
140
  }
141
};
142
143
using Http2Headers = NgHeaders<Http2HeadersTraits>;
144
using Http2RcBufferPointer = NgRcBufPointer<Http2RcBufferPointerTraits>;
145
146
struct NgHttp2StreamWrite : public MemoryRetainer {
147
  BaseObjectPtr<AsyncWrap> req_wrap;
148
  uv_buf_t buf;
149
150
66044
  inline explicit NgHttp2StreamWrite(uv_buf_t buf_) : buf(buf_) {}
151
27758
  inline NgHttp2StreamWrite(BaseObjectPtr<AsyncWrap> req_wrap, uv_buf_t buf_) :
152
27758
      req_wrap(std::move(req_wrap)), buf(buf_) {}
153
154
  void MemoryInfo(MemoryTracker* tracker) const override;
155
  SET_MEMORY_INFO_NAME(NgHttp2StreamWrite)
156
  SET_SELF_SIZE(NgHttp2StreamWrite)
157
};
158
159
typedef uint32_t(*get_setting)(nghttp2_session* session,
160
                               nghttp2_settings_id id);
161
162
class Http2Ping;
163
class Http2Session;
164
class Http2Settings;
165
class Http2Stream;
166
class Origins;
167
168
// This scope should be present when any call into nghttp2 that may schedule
169
// data to be written to the underlying transport is made, and schedules
170
// such a write automatically once the scope is exited.
171
class Http2Scope {
172
 public:
173
  explicit Http2Scope(Http2Stream* stream);
174
  explicit Http2Scope(Http2Session* session);
175
  ~Http2Scope();
176
177
 private:
178
  BaseObjectPtr<Http2Session> session_;
179
};
180
181
// The Http2Options class is used to parse the options object passed in to
182
// a Http2Session object and convert those into an appropriate nghttp2_option
183
// struct. This is the primary mechanism by which the Http2Session object is
184
// configured.
185
class Http2Options {
186
 public:
187
  Http2Options(Http2State* http2_state,
188
               SessionType type);
189
190
668
  ~Http2Options() = default;
191
192
668
  nghttp2_option* operator*() const {
193
668
    return options_.get();
194
  }
195
196
1
  void set_max_header_pairs(uint32_t max) {
197
1
    max_header_pairs_ = max;
198
1
  }
199
200
668
  uint32_t max_header_pairs() const {
201
668
    return max_header_pairs_;
202
  }
203
204
2
  void set_padding_strategy(PaddingStrategy val) {
205
2
    padding_strategy_ = val;
206
2
  }
207
208
668
  PaddingStrategy padding_strategy() const {
209
668
    return padding_strategy_;
210
  }
211
212
2
  void set_max_outstanding_pings(size_t max) {
213
2
    max_outstanding_pings_ = max;
214
2
  }
215
216
668
  size_t max_outstanding_pings() const {
217
668
    return max_outstanding_pings_;
218
  }
219
220
2
  void set_max_outstanding_settings(size_t max) {
221
2
    max_outstanding_settings_ = max;
222
2
  }
223
224
668
  size_t max_outstanding_settings() const {
225
668
    return max_outstanding_settings_;
226
  }
227
228
8
  void set_max_session_memory(uint64_t max) {
229
8
    max_session_memory_ = max;
230
8
  }
231
232
668
  uint64_t max_session_memory() const {
233
668
    return max_session_memory_;
234
  }
235
236
 private:
237
  Nghttp2OptionPointer options_;
238
  uint64_t max_session_memory_ = kDefaultMaxSessionMemory;
239
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
240
  PaddingStrategy padding_strategy_ = PADDING_STRATEGY_NONE;
241
  size_t max_outstanding_pings_ = kDefaultMaxPings;
242
  size_t max_outstanding_settings_ = kDefaultMaxSettings;
243
};
244
245
struct Http2Priority : public nghttp2_priority_spec {
246
  Http2Priority(Environment* env,
247
                v8::Local<v8::Value> parent,
248
                v8::Local<v8::Value> weight,
249
                v8::Local<v8::Value> exclusive);
250
};
251
252
class Http2StreamListener : public StreamListener {
253
 public:
254
  uv_buf_t OnStreamAlloc(size_t suggested_size) override;
255
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
256
};
257
258
struct Http2HeaderTraits {
259
  typedef Http2RcBufferPointer rcbufferpointer_t;
260
  typedef Http2Session allocator_t;
261
262
  // HTTP/2 does not support identifying header names by token id.
263
  // HTTP/3 will, however, so we prepare for that now.
264
71689
  static const char* ToHttpHeaderName(int32_t token) { return nullptr; }
265
};
266
267
using Http2Header = NgHeader<Http2HeaderTraits>;
268
269
class Http2Stream : public AsyncWrap,
270
                    public StreamBase {
271
 public:
272
  static Http2Stream* New(
273
      Http2Session* session,
274
      int32_t id,
275
      nghttp2_headers_category category = NGHTTP2_HCAT_HEADERS,
276
      int options = 0);
277
  ~Http2Stream() override;
278
279
  nghttp2_stream* operator*() const;
280
281
  nghttp2_stream* stream() const;
282
283
160822
  Http2Session* session() { return session_.get(); }
284
18
  const Http2Session* session() const { return session_.get(); }
285
286
  // Required for StreamBase
287
  int ReadStart() override;
288
289
  // Required for StreamBase
290
  int ReadStop() override;
291
292
  // Required for StreamBase
293
  ShutdownWrap* CreateShutdownWrap(v8::Local<v8::Object> object) override;
294
  int DoShutdown(ShutdownWrap* req_wrap) override;
295
296
15
  bool HasWantsWrite() const override { return true; }
297
298
  // Initiate a response on this stream.
299
  int SubmitResponse(const Http2Headers& headers, int options);
300
301
  // Submit informational headers for this stream
302
  int SubmitInfo(const Http2Headers& headers);
303
304
  // Submit trailing headers for this stream
305
  int SubmitTrailers(const Http2Headers& headers);
306
  void OnTrailers();
307
308
  // Submit a PRIORITY frame for this stream
309
  int SubmitPriority(const Http2Priority& priority, bool silent = false);
310
311
  // Submits an RST_STREAM frame using the given code
312
  void SubmitRstStream(const uint32_t code);
313
314
  void FlushRstStream();
315
316
  // Submits a PUSH_PROMISE frame with this stream as the parent.
317
  Http2Stream* SubmitPushPromise(
318
      const Http2Headers& headers,
319
      int32_t* ret,
320
      int options = 0);
321
322
323
  void Close(int32_t code);
324
325
  // Destroy this stream instance and free all held memory.
326
  void Destroy();
327
328
392231
  bool is_destroyed() const {
329
392231
    return flags_ & kStreamStateDestroyed;
330
  }
331
332
47769
  bool is_writable() const {
333
47769
    return !(flags_ & kStreamStateShut);
334
  }
335
336
28512
  bool is_paused() const {
337
28512
    return flags_ & kStreamStateReadPaused;
338
  }
339
340
  bool is_closed() const {
341
    return flags_ & kStreamStateClosed;
342
  }
343
344
12724
  bool has_trailers() const {
345
12724
    return flags_ & kStreamStateTrailers;
346
  }
347
348
191
  void set_has_trailers(bool on = true) {
349
191
    if (on)
350
154
      flags_ |= kStreamStateTrailers;
351
    else
352
37
      flags_ &= ~kStreamStateTrailers;
353
191
  }
354
355
23558
  void set_closed() {
356
23558
    flags_ |= kStreamStateClosed;
357
23558
  }
358
359
23638
  void set_destroyed() {
360
23638
    flags_ |= kStreamStateDestroyed;
361
23638
  }
362
363
24042
  void set_not_writable() {
364
24042
    flags_ |= kStreamStateShut;
365
24042
  }
366
367
23485
  void set_reading(bool on = true) {
368
23485
    if (on) {
369
23485
      flags_ |= kStreamStateReadStart;
370
23485
      set_paused(false);
371
    } else {}
372
23485
  }
373
374
39007
  void set_paused(bool on = true) {
375
39007
    if (on)
376
15522
      flags_ |= kStreamStateReadPaused;
377
    else
378
23485
      flags_ &= ~kStreamStateReadPaused;
379
39007
  }
380
381
  // Returns true if this stream is in the reading state, which occurs when
382
  // the kStreamStateReadStart flag has been set and the
383
  // kStreamStateReadPaused flag is *not* set.
384
31587
  bool is_reading() const {
385

31587
    return flags_ & kStreamStateReadStart && !is_paused();
386
  }
387
388
  // Returns the RST_STREAM code used to close this stream
389
  int32_t code() const { return code_; }
390
391
  // Returns the stream identifier for this stream
392
75235
  int32_t id() const { return id_; }
393
394
  void IncrementAvailableOutboundLength(size_t amount);
395
  void DecrementAvailableOutboundLength(size_t amount);
396
397
  bool AddHeader(nghttp2_rcbuf* name, nghttp2_rcbuf* value, uint8_t flags);
398
399
  template <typename Fn>
400
23420
  void TransferHeaders(Fn&& fn) {
401
23420
    size_t i = 0;
402
95109
    for (const auto& header : current_headers_ )
403
71689
      fn(header, i++);
404
23420
    current_headers_.clear();
405
23420
  }
406
407
70260
  size_t headers_count() const {
408
70260
    return current_headers_.size();
409
  }
410
411
23420
  nghttp2_headers_category headers_category() const {
412
23420
    return current_headers_category_;
413
  }
414
415
  void StartHeaders(nghttp2_headers_category category);
416
417
  // Required for StreamBase
418
68492
  bool IsAlive() override {
419
68492
    return true;
420
  }
421
422
  // Required for StreamBase
423
  bool IsClosing() override {
424
    return false;
425
  }
426
427
150623
  AsyncWrap* GetAsyncWrap() override { return this; }
428
429
  int DoWrite(WriteWrap* w, uv_buf_t* bufs, size_t count,
430
              uv_stream_t* send_handle) override;
431
432
  void MemoryInfo(MemoryTracker* tracker) const override;
433
  SET_MEMORY_INFO_NAME(Http2Stream)
434
  SET_SELF_SIZE(Http2Stream)
435
436
  std::string diagnostic_name() const override;
437
438
  // JavaScript API
439
  static void GetID(const v8::FunctionCallbackInfo<v8::Value>& args);
440
  static void Destroy(const v8::FunctionCallbackInfo<v8::Value>& args);
441
  static void Priority(const v8::FunctionCallbackInfo<v8::Value>& args);
442
  static void PushPromise(const v8::FunctionCallbackInfo<v8::Value>& args);
443
  static void RefreshState(const v8::FunctionCallbackInfo<v8::Value>& args);
444
  static void Info(const v8::FunctionCallbackInfo<v8::Value>& args);
445
  static void Trailers(const v8::FunctionCallbackInfo<v8::Value>& args);
446
  static void Respond(const v8::FunctionCallbackInfo<v8::Value>& args);
447
  static void RstStream(const v8::FunctionCallbackInfo<v8::Value>& args);
448
449
  class Provider;
450
451
  struct Statistics {
452
    uint64_t start_time;
453
    uint64_t end_time;
454
    uint64_t first_header;     // Time first header was received
455
    uint64_t first_byte;       // Time first DATA frame byte was received
456
    uint64_t first_byte_sent;  // Time first DATA frame byte was sent
457
    uint64_t sent_bytes;
458
    uint64_t received_bytes;
459
    uint64_t id;
460
  };
461
462
  Statistics statistics_ = {};
463
464
 private:
465
  Http2Stream(Http2Session* session,
466
              v8::Local<v8::Object> obj,
467
              int32_t id,
468
              nghttp2_headers_category category,
469
              int options);
470
471
  void EmitStatistics();
472
473
  BaseObjectWeakPtr<Http2Session> session_;     // The Parent HTTP/2 Session
474
  int32_t id_ = 0;                              // The Stream Identifier
475
  int32_t code_ = NGHTTP2_NO_ERROR;             // The RST_STREAM code (if any)
476
  int flags_ = kStreamStateNone;        // Internal state flags
477
478
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
479
  uint32_t max_header_length_ = DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
480
481
  // The Current Headers block... As headers are received for this stream,
482
  // they are temporarily stored here until the OnFrameReceived is called
483
  // signalling the end of the HEADERS frame
484
  nghttp2_headers_category current_headers_category_ = NGHTTP2_HCAT_HEADERS;
485
  uint32_t current_headers_length_ = 0;  // total number of octets
486
  std::vector<Http2Header> current_headers_;
487
488
  // This keeps track of the amount of data read from the socket while the
489
  // socket was in paused mode. When `ReadStart()` is called (and not before
490
  // then), we tell nghttp2 that we consumed that data to get proper
491
  // backpressure handling.
492
  size_t inbound_consumed_data_while_paused_ = 0;
493
494
  // Outbound Data... This is the data written by the JS layer that is
495
  // waiting to be written out to the socket.
496
  std::queue<NgHttp2StreamWrite> queue_;
497
  size_t available_outbound_length_ = 0;
498
499
  Http2StreamListener stream_listener_;
500
501
  friend class Http2Session;
502
};
503
504
class Http2Stream::Provider {
505
 public:
506
  Provider(Http2Stream* stream, int options);
507
  explicit Provider(int options);
508
  virtual ~Provider();
509
510
23479
  nghttp2_data_provider* operator*() {
511
23479
    return !empty_ ? &provider_ : nullptr;
512
  }
513
514
  class FD;
515
  class Stream;
516
 protected:
517
  nghttp2_data_provider provider_;
518
519
 private:
520
  bool empty_ = false;
521
};
522
523
class Http2Stream::Provider::Stream : public Http2Stream::Provider {
524
 public:
525
  Stream(Http2Stream* stream, int options);
526
  explicit Stream(int options);
527
528
  static ssize_t OnRead(nghttp2_session* session,
529
                        int32_t id,
530
                        uint8_t* buf,
531
                        size_t length,
532
                        uint32_t* flags,
533
                        nghttp2_data_source* source,
534
                        void* user_data);
535
};
536
537
struct SessionJSFields {
538
  uint8_t bitfield;
539
  uint8_t priority_listener_count;
540
  uint8_t frame_error_listener_count;
541
  uint32_t max_invalid_frames = 1000;
542
  uint32_t max_rejected_streams = 100;
543
};
544
545
// Indices for js_fields_, which serves as a way to communicate data with JS
546
// land fast. In particular, we store information about the number/presence
547
// of certain event listeners in JS, and skip calls from C++ into JS if they
548
// are missing.
549
enum SessionUint8Fields {
550
  kBitfield = offsetof(SessionJSFields, bitfield),  // See below
551
  kSessionPriorityListenerCount =
552
      offsetof(SessionJSFields, priority_listener_count),
553
  kSessionFrameErrorListenerCount =
554
      offsetof(SessionJSFields, frame_error_listener_count),
555
  kSessionMaxInvalidFrames = offsetof(SessionJSFields, max_invalid_frames),
556
  kSessionMaxRejectedStreams = offsetof(SessionJSFields, max_rejected_streams),
557
  kSessionUint8FieldCount = sizeof(SessionJSFields)
558
};
559
560
enum SessionBitfieldFlags {
561
  kSessionHasRemoteSettingsListeners,
562
  kSessionRemoteSettingsIsUpToDate,
563
  kSessionHasPingListeners,
564
  kSessionHasAltsvcListeners
565
};
566
567
class Http2Session : public AsyncWrap,
568
                     public StreamListener,
569
                     public mem::NgLibMemoryManager<Http2Session, nghttp2_mem> {
570
 public:
571
  Http2Session(Http2State* http2_state,
572
               v8::Local<v8::Object> wrap,
573
               SessionType type = NGHTTP2_SESSION_SERVER);
574
  ~Http2Session() override;
575
576
31365
  StreamBase* underlying_stream() {
577
31365
    return static_cast<StreamBase*>(stream_);
578
  }
579
580
  void Close(uint32_t code = NGHTTP2_NO_ERROR,
581
             bool socket_closed = false);
582
583
  void Consume(v8::Local<v8::Object> stream);
584
585
  void Goaway(uint32_t code, int32_t lastStreamID,
586
              const uint8_t* data, size_t len);
587
588
  void AltSvc(int32_t id,
589
              uint8_t* origin,
590
              size_t origin_len,
591
              uint8_t* value,
592
              size_t value_len);
593
594
  void Origin(const Origins& origins);
595
596
  uint8_t SendPendingData();
597
598
  // Submits a new request. If the request is a success, assigned
599
  // will be a pointer to the Http2Stream instance assigned.
600
  // This only works if the session is a client session.
601
  Http2Stream* SubmitRequest(
602
      const Http2Priority& priority,
603
      const Http2Headers& headers,
604
      int32_t* ret,
605
      int options = 0);
606
607
  SessionType type() const { return session_type_; }
608
609
91825
  nghttp2_session* session() const { return session_.get(); }
610
611
  nghttp2_session* operator*() { return session_.get(); }
612
613
23747
  uint32_t max_header_pairs() const { return max_header_pairs_; }
614
615
  const char* TypeName() const;
616
617
66955
  bool is_destroyed() {
618

66955
    return (flags_ & kSessionStateClosed) || session_ == nullptr;
619
  }
620
621
649
  void set_destroyed() {
622
649
    flags_ |= kSessionStateClosed;
623
649
  }
624
625
#define IS_FLAG(name, flag)                                                    \
626
  bool is_##name() const { return flags_ & flag; }                             \
627
  void set_##name(bool on = true) {                                            \
628
    if (on)                                                                    \
629
      flags_ |= flag;                                                          \
630
    else                                                                       \
631
      flags_ &= ~flag;                                                         \
632
  }
633
634
347584
  IS_FLAG(in_scope, kSessionStateHasScope)
635
141412
  IS_FLAG(write_scheduled, kSessionStateWriteScheduled)
636
1298
  IS_FLAG(closing, kSessionStateClosing)
637
129680
  IS_FLAG(sending, kSessionStateSending)
638
171471
  IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
639
68799
  IS_FLAG(reading_stopped, kSessionStateReadingStopped)
640
63541
  IS_FLAG(receive_paused, kSessionStateReceivePaused)
641
642
#undef IS_FLAG
643
644
  // Schedule a write if nghttp2 indicates it wants to write to the socket.
645
  void MaybeScheduleWrite();
646
647
  // Stop reading if nghttp2 doesn't want to anymore.
648
  void MaybeStopReading();
649
650
  // Returns pointer to the stream, or nullptr if stream does not exist
651
  BaseObjectPtr<Http2Stream> FindStream(int32_t id);
652
653
  bool CanAddStream();
654
655
  // Adds a stream instance to this session
656
  void AddStream(Http2Stream* stream);
657
658
  // Removes a stream instance from this session
659
  BaseObjectPtr<Http2Stream> RemoveStream(int32_t id);
660
661
  // Indicates whether there currently exist outgoing buffers for this stream.
662
  bool HasWritesOnSocketForStream(Http2Stream* stream);
663
664
  // Write data from stream_buf_ to the session.
665
  // This will call the error callback if an error occurs.
666
  void ConsumeHTTP2Data();
667
668
  void MemoryInfo(MemoryTracker* tracker) const override;
669
  SET_MEMORY_INFO_NAME(Http2Session)
670
  SET_SELF_SIZE(Http2Session)
671
672
  std::string diagnostic_name() const override;
673
674
  // Schedule an RstStream for after the current write finishes.
675
9
  void AddPendingRstStream(int32_t stream_id) {
676
9
    pending_rst_streams_.emplace_back(stream_id);
677
9
  }
678
679
23638
  bool has_pending_rststream(int32_t stream_id) {
680
23638
    return pending_rst_streams_.end() !=
681
23638
        std::find(pending_rst_streams_.begin(),
682
            pending_rst_streams_.end(),
683
47276
            stream_id);
684
  }
685
686
  // Handle reads/writes from the underlying network transport.
687
  uv_buf_t OnStreamAlloc(size_t suggested_size) override;
688
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
689
  void OnStreamAfterWrite(WriteWrap* w, int status) override;
690
691
  // Implementation for mem::NgLibMemoryManager
692
  void CheckAllocatedSize(size_t previous_size) const;
693
  void IncreaseAllocatedSize(size_t size);
694
  void DecreaseAllocatedSize(size_t size);
695
696
  // The JavaScript API
697
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
698
  static void Consume(const v8::FunctionCallbackInfo<v8::Value>& args);
699
  static void Receive(const v8::FunctionCallbackInfo<v8::Value>& args);
700
  static void Destroy(const v8::FunctionCallbackInfo<v8::Value>& args);
701
  static void Settings(const v8::FunctionCallbackInfo<v8::Value>& args);
702
  static void Request(const v8::FunctionCallbackInfo<v8::Value>& args);
703
  static void SetNextStreamID(const v8::FunctionCallbackInfo<v8::Value>& args);
704
  static void SetLocalWindowSize(
705
      const v8::FunctionCallbackInfo<v8::Value>& args);
706
  static void Goaway(const v8::FunctionCallbackInfo<v8::Value>& args);
707
  static void UpdateChunksSent(const v8::FunctionCallbackInfo<v8::Value>& args);
708
  static void RefreshState(const v8::FunctionCallbackInfo<v8::Value>& args);
709
  static void Ping(const v8::FunctionCallbackInfo<v8::Value>& args);
710
  static void AltSvc(const v8::FunctionCallbackInfo<v8::Value>& args);
711
  static void Origin(const v8::FunctionCallbackInfo<v8::Value>& args);
712
713
  template <get_setting fn>
714
  static void RefreshSettings(const v8::FunctionCallbackInfo<v8::Value>& args);
715
716
  uv_loop_t* event_loop() const {
717
    return env()->event_loop();
718
  }
719
720
1266
  Http2State* http2_state() const { return http2_state_.get(); }
721
722
  BaseObjectPtr<Http2Ping> PopPing();
723
  bool AddPing(const uint8_t* data, v8::Local<v8::Function> callback);
724
725
  BaseObjectPtr<Http2Settings> PopSettings();
726
  bool AddSettings(v8::Local<v8::Function> callback);
727
728
155174
  void IncrementCurrentSessionMemory(uint64_t amount) {
729
155174
    current_session_memory_ += amount;
730
155174
  }
731
732
104336
  void DecrementCurrentSessionMemory(uint64_t amount) {
733
    DCHECK_LE(amount, current_session_memory_);
734
104336
    current_session_memory_ -= amount;
735
104336
  }
736
737
  // Tell our custom memory allocator that this rcbuf is independent of
738
  // this session now, and may outlive it.
739
  void StopTrackingRcbuf(nghttp2_rcbuf* buf);
740
741
  // Returns the current session memory including memory allocated by nghttp2,
742
  // the current outbound storage queue, and pending writes.
743
83776
  uint64_t current_session_memory() const {
744
83776
    uint64_t total = current_session_memory_ + sizeof(Http2Session);
745
83776
    total += current_nghttp2_memory_;
746
83776
    total += outgoing_storage_.size();
747
83776
    return total;
748
  }
749
750
  // Return true if current_session_memory + amount is less than the max
751
83776
  bool has_available_session_memory(uint64_t amount) const {
752
83776
    return current_session_memory() + amount <= max_session_memory_;
753
  }
754
755
  struct Statistics {
756
    uint64_t start_time;
757
    uint64_t end_time;
758
    uint64_t ping_rtt;
759
    uint64_t data_sent;
760
    uint64_t data_received;
761
    uint32_t frame_count;
762
    uint32_t frame_sent;
763
    int32_t stream_count;
764
    size_t max_concurrent_streams;
765
    double stream_average_duration;
766
    SessionType session_type;
767
  };
768
769
  Statistics statistics_ = {};
770
771
 private:
772
  void EmitStatistics();
773
774
  // Frame Padding Strategies
775
  ssize_t OnDWordAlignedPadding(size_t frameLength,
776
                                size_t maxPayloadLen);
777
  ssize_t OnMaxFrameSizePadding(size_t frameLength,
778
                                size_t maxPayloadLen);
779
780
  // Frame Handler
781
  int HandleDataFrame(const nghttp2_frame* frame);
782
  void HandleGoawayFrame(const nghttp2_frame* frame);
783
  void HandleHeadersFrame(const nghttp2_frame* frame);
784
  void HandlePriorityFrame(const nghttp2_frame* frame);
785
  void HandleSettingsFrame(const nghttp2_frame* frame);
786
  void HandlePingFrame(const nghttp2_frame* frame);
787
  void HandleAltSvcFrame(const nghttp2_frame* frame);
788
  void HandleOriginFrame(const nghttp2_frame* frame);
789
790
  // nghttp2 callbacks
791
  static int OnBeginHeadersCallback(
792
      nghttp2_session* session,
793
      const nghttp2_frame* frame,
794
      void* user_data);
795
  static int OnHeaderCallback(
796
      nghttp2_session* session,
797
      const nghttp2_frame* frame,
798
      nghttp2_rcbuf* name,
799
      nghttp2_rcbuf* value,
800
      uint8_t flags,
801
      void* user_data);
802
  static int OnFrameReceive(
803
      nghttp2_session* session,
804
      const nghttp2_frame* frame,
805
      void* user_data);
806
  static int OnFrameNotSent(
807
      nghttp2_session* session,
808
      const nghttp2_frame* frame,
809
      int error_code,
810
      void* user_data);
811
  static int OnFrameSent(
812
      nghttp2_session* session,
813
      const nghttp2_frame* frame,
814
      void* user_data);
815
  static int OnStreamClose(
816
      nghttp2_session* session,
817
      int32_t id,
818
      uint32_t code,
819
      void* user_data);
820
  static int OnInvalidHeader(
821
      nghttp2_session* session,
822
      const nghttp2_frame* frame,
823
      nghttp2_rcbuf* name,
824
      nghttp2_rcbuf* value,
825
      uint8_t flags,
826
      void* user_data);
827
  static int OnDataChunkReceived(
828
      nghttp2_session* session,
829
      uint8_t flags,
830
      int32_t id,
831
      const uint8_t* data,
832
      size_t len,
833
      void* user_data);
834
  static ssize_t OnSelectPadding(
835
      nghttp2_session* session,
836
      const nghttp2_frame* frame,
837
      size_t maxPayloadLen,
838
      void* user_data);
839
  static int OnNghttpError(
840
      nghttp2_session* session,
841
      const char* message,
842
      size_t len,
843
      void* user_data);
844
  static int OnSendData(
845
      nghttp2_session* session,
846
      nghttp2_frame* frame,
847
      const uint8_t* framehd,
848
      size_t length,
849
      nghttp2_data_source* source,
850
      void* user_data);
851
  static int OnInvalidFrame(
852
      nghttp2_session* session,
853
      const nghttp2_frame* frame,
854
      int lib_error_code,
855
      void* user_data);
856
857
  struct Callbacks {
858
    explicit Callbacks(bool kHasGetPaddingCallback);
859
860
    Nghttp2SessionCallbacksPointer callbacks;
861
  };
862
863
  /* Use callback_struct_saved[kHasGetPaddingCallback ? 1 : 0] */
864
  static const Callbacks callback_struct_saved[2];
865
866
  // The underlying nghttp2_session handle
867
  Nghttp2SessionPointer session_;
868
869
  // JS-accessible numeric fields, as indexed by SessionUint8Fields.
870
  AliasedStruct<SessionJSFields> js_fields_;
871
872
  // The session type: client or server
873
  SessionType session_type_;
874
875
  // The maximum number of header pairs permitted for streams on this session
876
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
877
878
  // The maximum amount of memory allocated for this session
879
  uint64_t max_session_memory_ = kDefaultMaxSessionMemory;
880
  uint64_t current_session_memory_ = 0;
881
  // The amount of memory allocated by nghttp2 internals
882
  uint64_t current_nghttp2_memory_ = 0;
883
884
  // The collection of active Http2Streams associated with this session
885
  std::unordered_map<int32_t, BaseObjectPtr<Http2Stream>> streams_;
886
887
  int flags_ = kSessionStateNone;
888
889
  // The StreamBase instance being used for i/o
890
  PaddingStrategy padding_strategy_ = PADDING_STRATEGY_NONE;
891
892
  // use this to allow timeout tracking during long-lasting writes
893
  uint32_t chunks_sent_since_last_write_ = 0;
894
895
  uv_buf_t stream_buf_ = uv_buf_init(nullptr, 0);
896
  // When processing input data, either stream_buf_ab_ or stream_buf_allocation_
897
  // will be set. stream_buf_ab_ is lazily created from stream_buf_allocation_.
898
  v8::Global<v8::ArrayBuffer> stream_buf_ab_;
899
  std::unique_ptr<v8::BackingStore> stream_buf_allocation_;
900
  size_t stream_buf_offset_ = 0;
901
  // Custom error code for errors that originated inside one of the callbacks
902
  // called by nghttp2_session_mem_recv.
903
  const char* custom_recv_error_code_ = nullptr;
904
905
  size_t max_outstanding_pings_ = kDefaultMaxPings;
906
  std::queue<BaseObjectPtr<Http2Ping>> outstanding_pings_;
907
908
  size_t max_outstanding_settings_ = kDefaultMaxSettings;
909
  std::queue<BaseObjectPtr<Http2Settings>> outstanding_settings_;
910
911
  std::vector<NgHttp2StreamWrite> outgoing_buffers_;
912
  std::vector<uint8_t> outgoing_storage_;
913
  size_t outgoing_length_ = 0;
914
  std::vector<int32_t> pending_rst_streams_;
915
  // Count streams that have been rejected while being opened. Exceeding a fixed
916
  // limit will result in the session being destroyed, as an indication of a
917
  // misbehaving peer. This counter is reset once new streams are being
918
  // accepted again.
919
  uint32_t rejected_stream_count_ = 0;
920
  // Also use the invalid frame count as a measure for rejecting input frames.
921
  uint32_t invalid_frame_count_ = 0;
922
923
  void PushOutgoingBuffer(NgHttp2StreamWrite&& write);
924
925
  BaseObjectPtr<Http2State> http2_state_;
926
927
  void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length);
928
  void ClearOutgoing(int status);
929
930
  friend class Http2Scope;
931
  friend class Http2StreamListener;
932
};
933
934
struct Http2SessionPerformanceEntryTraits {
935
  static constexpr performance::PerformanceEntryType kType =
936
      performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2;
937
938
  using Details = Http2Session::Statistics;
939
940
  static v8::MaybeLocal<v8::Object> GetDetails(
941
      Environment* env,
942
      const performance::PerformanceEntry<Http2SessionPerformanceEntryTraits>&
943
          entry);
944
};
945
946
struct Http2StreamPerformanceEntryTraits {
947
  static constexpr performance::PerformanceEntryType kType =
948
      performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2;
949
950
  using Details = Http2Stream::Statistics;
951
952
  static v8::MaybeLocal<v8::Object> GetDetails(
953
      Environment* env,
954
      const performance::PerformanceEntry<Http2StreamPerformanceEntryTraits>&
955
          entry);
956
};
957
958
using Http2SessionPerformanceEntry =
959
    performance::PerformanceEntry<Http2SessionPerformanceEntryTraits>;
960
using Http2StreamPerformanceEntry =
961
    performance::PerformanceEntry<Http2StreamPerformanceEntryTraits>;
962
963
class Http2Ping : public AsyncWrap {
964
 public:
965
  explicit Http2Ping(
966
      Http2Session* session,
967
      v8::Local<v8::Object> obj,
968
      v8::Local<v8::Function> callback);
969
970
  void MemoryInfo(MemoryTracker* tracker) const override;
971
  SET_MEMORY_INFO_NAME(Http2Ping)
972
  SET_SELF_SIZE(Http2Ping)
973
974
  void Send(const uint8_t* payload);
975
  void Done(bool ack, const uint8_t* payload = nullptr);
976
  void DetachFromSession();
977
978
  v8::Local<v8::Function> callback() const;
979
980
 private:
981
  BaseObjectWeakPtr<Http2Session> session_;
982
  v8::Global<v8::Function> callback_;
983
  uint64_t startTime_;
984
};
985
986
// The Http2Settings class is used to parse the settings passed in for
987
// an Http2Session, converting those into an array of nghttp2_settings_entry
988
// structs.
989
class Http2Settings : public AsyncWrap {
990
 public:
991
  Http2Settings(Http2Session* session,
992
                v8::Local<v8::Object> obj,
993
                v8::Local<v8::Function> callback,
994
                uint64_t start_time = uv_hrtime());
995
996
  void MemoryInfo(MemoryTracker* tracker) const override;
997
  SET_MEMORY_INFO_NAME(Http2Settings)
998
  SET_SELF_SIZE(Http2Settings)
999
1000
  void Send();
1001
  void Done(bool ack);
1002
1003
  v8::Local<v8::Function> callback() const;
1004
1005
  // Returns a Buffer instance with the serialized SETTINGS payload
1006
  v8::Local<v8::Value> Pack();
1007
1008
  static v8::Local<v8::Value> Pack(Http2State* state);
1009
1010
  // Resets the default values in the settings buffer
1011
  static void RefreshDefaults(Http2State* http2_state);
1012
1013
  // Update the local or remote settings for the given session
1014
  static void Update(Http2Session* session,
1015
                     get_setting fn);
1016
1017
 private:
1018
  static size_t Init(
1019
      Http2State* http2_state,
1020
      nghttp2_settings_entry* entries);
1021
1022
  static v8::Local<v8::Value> Pack(
1023
      Environment* env,
1024
      size_t count,
1025
      const nghttp2_settings_entry* entries);
1026
1027
  BaseObjectWeakPtr<Http2Session> session_;
1028
  v8::Global<v8::Function> callback_;
1029
  uint64_t startTime_;
1030
  size_t count_ = 0;
1031
  nghttp2_settings_entry entries_[IDX_SETTINGS_COUNT];
1032
};
1033
1034
class Origins {
1035
 public:
1036
  Origins(Environment* env,
1037
          v8::Local<v8::String> origin_string,
1038
          size_t origin_count);
1039
5
  ~Origins() = default;
1040
1041
5
  const nghttp2_origin_entry* operator*() const {
1042
5
    return static_cast<const nghttp2_origin_entry*>(bs_->Data());
1043
  }
1044
1045
5
  size_t length() const {
1046
5
    return count_;
1047
  }
1048
1049
 private:
1050
  size_t count_;
1051
  std::unique_ptr<v8::BackingStore> bs_;
1052
};
1053
1054
#define HTTP2_HIDDEN_CONSTANTS(V)                                              \
1055
  V(NGHTTP2_HCAT_REQUEST)                                                      \
1056
  V(NGHTTP2_HCAT_RESPONSE)                                                     \
1057
  V(NGHTTP2_HCAT_PUSH_RESPONSE)                                                \
1058
  V(NGHTTP2_HCAT_HEADERS)                                                      \
1059
  V(NGHTTP2_NV_FLAG_NONE)                                                      \
1060
  V(NGHTTP2_NV_FLAG_NO_INDEX)                                                  \
1061
  V(NGHTTP2_ERR_DEFERRED)                                                      \
1062
  V(NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE)                                       \
1063
  V(NGHTTP2_ERR_INVALID_ARGUMENT)                                              \
1064
  V(NGHTTP2_ERR_STREAM_CLOSED)                                                 \
1065
  V(NGHTTP2_ERR_NOMEM)                                                         \
1066
  V(STREAM_OPTION_EMPTY_PAYLOAD)                                               \
1067
  V(STREAM_OPTION_GET_TRAILERS)
1068
1069
#define HTTP2_ERROR_CODES(V)                                                   \
1070
  V(NGHTTP2_NO_ERROR)                                                          \
1071
  V(NGHTTP2_PROTOCOL_ERROR)                                                    \
1072
  V(NGHTTP2_INTERNAL_ERROR)                                                    \
1073
  V(NGHTTP2_FLOW_CONTROL_ERROR)                                                \
1074
  V(NGHTTP2_SETTINGS_TIMEOUT)                                                  \
1075
  V(NGHTTP2_STREAM_CLOSED)                                                     \
1076
  V(NGHTTP2_FRAME_SIZE_ERROR)                                                  \
1077
  V(NGHTTP2_REFUSED_STREAM)                                                    \
1078
  V(NGHTTP2_CANCEL)                                                            \
1079
  V(NGHTTP2_COMPRESSION_ERROR)                                                 \
1080
  V(NGHTTP2_CONNECT_ERROR)                                                     \
1081
  V(NGHTTP2_ENHANCE_YOUR_CALM)                                                 \
1082
  V(NGHTTP2_INADEQUATE_SECURITY)                                               \
1083
  V(NGHTTP2_HTTP_1_1_REQUIRED)                                                 \
1084
1085
#define HTTP2_CONSTANTS(V)                                                     \
1086
  V(NGHTTP2_ERR_FRAME_SIZE_ERROR)                                              \
1087
  V(NGHTTP2_SESSION_SERVER)                                                    \
1088
  V(NGHTTP2_SESSION_CLIENT)                                                    \
1089
  V(NGHTTP2_STREAM_STATE_IDLE)                                                 \
1090
  V(NGHTTP2_STREAM_STATE_OPEN)                                                 \
1091
  V(NGHTTP2_STREAM_STATE_RESERVED_LOCAL)                                       \
1092
  V(NGHTTP2_STREAM_STATE_RESERVED_REMOTE)                                      \
1093
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL)                                    \
1094
  V(NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE)                                   \
1095
  V(NGHTTP2_STREAM_STATE_CLOSED)                                               \
1096
  V(NGHTTP2_FLAG_NONE)                                                         \
1097
  V(NGHTTP2_FLAG_END_STREAM)                                                   \
1098
  V(NGHTTP2_FLAG_END_HEADERS)                                                  \
1099
  V(NGHTTP2_FLAG_ACK)                                                          \
1100
  V(NGHTTP2_FLAG_PADDED)                                                       \
1101
  V(NGHTTP2_FLAG_PRIORITY)                                                     \
1102
  V(DEFAULT_SETTINGS_HEADER_TABLE_SIZE)                                        \
1103
  V(DEFAULT_SETTINGS_ENABLE_PUSH)                                              \
1104
  V(DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS)                                   \
1105
  V(DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE)                                      \
1106
  V(DEFAULT_SETTINGS_MAX_FRAME_SIZE)                                           \
1107
  V(DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE)                                     \
1108
  V(DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL)                                  \
1109
  V(MAX_MAX_FRAME_SIZE)                                                        \
1110
  V(MIN_MAX_FRAME_SIZE)                                                        \
1111
  V(MAX_INITIAL_WINDOW_SIZE)                                                   \
1112
  V(NGHTTP2_SETTINGS_HEADER_TABLE_SIZE)                                        \
1113
  V(NGHTTP2_SETTINGS_ENABLE_PUSH)                                              \
1114
  V(NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS)                                   \
1115
  V(NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE)                                      \
1116
  V(NGHTTP2_SETTINGS_MAX_FRAME_SIZE)                                           \
1117
  V(NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE)                                     \
1118
  V(NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL)                                  \
1119
  V(PADDING_STRATEGY_NONE)                                                     \
1120
  V(PADDING_STRATEGY_ALIGNED)                                                  \
1121
  V(PADDING_STRATEGY_MAX)                                                      \
1122
  V(PADDING_STRATEGY_CALLBACK)                                                 \
1123
  HTTP2_ERROR_CODES(V)
1124
1125
#define HTTP2_SETTINGS(V)                                                      \
1126
  V(HEADER_TABLE_SIZE)                                                         \
1127
  V(ENABLE_PUSH)                                                               \
1128
  V(MAX_CONCURRENT_STREAMS)                                                    \
1129
  V(INITIAL_WINDOW_SIZE)                                                       \
1130
  V(MAX_FRAME_SIZE)                                                            \
1131
  V(MAX_HEADER_LIST_SIZE)                                                      \
1132
  V(ENABLE_CONNECT_PROTOCOL)                                                   \
1133
1134
}  // namespace http2
1135
}  // namespace node
1136
1137
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1138
1139
#endif  // SRC_NODE_HTTP2_H_