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

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

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