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.h Lines: 184 195 94.4 %
Date: 2019-08-17 22:35:23 Branches: 31 50 62.0 %

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 "node_http2_state.h"
11
#include "node_perf.h"
12
#include "stream_base-inl.h"
13
#include "string_bytes.h"
14
15
#include <algorithm>
16
#include <queue>
17
18
namespace node {
19
namespace http2 {
20
21
using v8::Array;
22
using v8::Context;
23
using v8::Isolate;
24
using v8::MaybeLocal;
25
26
using performance::PerformanceEntry;
27
28
// We strictly limit the number of outstanding unacknowledged PINGS a user
29
// may send in order to prevent abuse. The current default cap is 10. The
30
// user may set a different limit using a per Http2Session configuration
31
// option.
32
#define DEFAULT_MAX_PINGS 10
33
34
// Also strictly limit the number of outstanding SETTINGS frames a user sends
35
#define DEFAULT_MAX_SETTINGS 10
36
37
// Default maximum total memory cap for Http2Session.
38
#define DEFAULT_MAX_SESSION_MEMORY 1e7
39
40
// These are the standard HTTP/2 defaults as specified by the RFC
41
#define DEFAULT_SETTINGS_HEADER_TABLE_SIZE 4096
42
#define DEFAULT_SETTINGS_ENABLE_PUSH 1
43
#define DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE 65535
44
#define DEFAULT_SETTINGS_MAX_FRAME_SIZE 16384
45
#define DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE 65535
46
#define MAX_MAX_FRAME_SIZE 16777215
47
#define MIN_MAX_FRAME_SIZE DEFAULT_SETTINGS_MAX_FRAME_SIZE
48
#define MAX_INITIAL_WINDOW_SIZE 2147483647
49
50
#define MAX_MAX_HEADER_LIST_SIZE 16777215u
51
#define DEFAULT_MAX_HEADER_LIST_PAIRS 128u
52
53
enum nghttp2_session_type {
54
  NGHTTP2_SESSION_SERVER,
55
  NGHTTP2_SESSION_CLIENT
56
};
57
58
enum nghttp2_stream_flags {
59
  NGHTTP2_STREAM_FLAG_NONE = 0x0,
60
  // Writable side has ended
61
  NGHTTP2_STREAM_FLAG_SHUT = 0x1,
62
  // Reading has started
63
  NGHTTP2_STREAM_FLAG_READ_START = 0x2,
64
  // Reading is paused
65
  NGHTTP2_STREAM_FLAG_READ_PAUSED = 0x4,
66
  // Stream is closed
67
  NGHTTP2_STREAM_FLAG_CLOSED = 0x8,
68
  // Stream is destroyed
69
  NGHTTP2_STREAM_FLAG_DESTROYED = 0x10,
70
  // Stream has trailers
71
  NGHTTP2_STREAM_FLAG_TRAILERS = 0x20,
72
  // Stream has received all the data it can
73
  NGHTTP2_STREAM_FLAG_EOS = 0x40
74
};
75
76
enum nghttp2_stream_options {
77
  // Stream is not going to have any DATA frames
78
  STREAM_OPTION_EMPTY_PAYLOAD = 0x1,
79
  // Stream might have trailing headers
80
  STREAM_OPTION_GET_TRAILERS = 0x2,
81
};
82
83
450121
struct nghttp2_stream_write : public MemoryRetainer {
84
  WriteWrap* req_wrap = nullptr;
85
  uv_buf_t buf;
86
87
64211
  inline explicit nghttp2_stream_write(uv_buf_t buf_) : buf(buf_) {}
88
24178
  inline nghttp2_stream_write(WriteWrap* req, uv_buf_t buf_) :
89
24178
      req_wrap(req), buf(buf_) {}
90
91
  void MemoryInfo(MemoryTracker* tracker) const override;
92
  SET_MEMORY_INFO_NAME(nghttp2_stream_write)
93
  SET_SELF_SIZE(nghttp2_stream_write)
94
};
95
96
215265
struct nghttp2_header : public MemoryRetainer {
97
  nghttp2_rcbuf* name = nullptr;
98
  nghttp2_rcbuf* value = nullptr;
99
  uint8_t flags = 0;
100
101
  void MemoryInfo(MemoryTracker* tracker) const override;
102
  SET_MEMORY_INFO_NAME(nghttp2_header)
103
  SET_SELF_SIZE(nghttp2_header)
104
};
105
106
107
// Unlike the HTTP/1 implementation, the HTTP/2 implementation is not limited
108
// to a fixed number of known supported HTTP methods. These constants, therefore
109
// are provided strictly as a convenience to users and are exposed via the
110
// require('http2').constants object.
111
#define HTTP_KNOWN_METHODS(V)                                                 \
112
  V(ACL, "ACL")                                                               \
113
  V(BASELINE_CONTROL, "BASELINE-CONTROL")                                     \
114
  V(BIND, "BIND")                                                             \
115
  V(CHECKIN, "CHECKIN")                                                       \
116
  V(CHECKOUT, "CHECKOUT")                                                     \
117
  V(CONNECT, "CONNECT")                                                       \
118
  V(COPY, "COPY")                                                             \
119
  V(DELETE, "DELETE")                                                         \
120
  V(GET, "GET")                                                               \
121
  V(HEAD, "HEAD")                                                             \
122
  V(LABEL, "LABEL")                                                           \
123
  V(LINK, "LINK")                                                             \
124
  V(LOCK, "LOCK")                                                             \
125
  V(MERGE, "MERGE")                                                           \
126
  V(MKACTIVITY, "MKACTIVITY")                                                 \
127
  V(MKCALENDAR, "MKCALENDAR")                                                 \
128
  V(MKCOL, "MKCOL")                                                           \
129
  V(MKREDIRECTREF, "MKREDIRECTREF")                                           \
130
  V(MKWORKSPACE, "MKWORKSPACE")                                               \
131
  V(MOVE, "MOVE")                                                             \
132
  V(OPTIONS, "OPTIONS")                                                       \
133
  V(ORDERPATCH, "ORDERPATCH")                                                 \
134
  V(PATCH, "PATCH")                                                           \
135
  V(POST, "POST")                                                             \
136
  V(PRI, "PRI")                                                               \
137
  V(PROPFIND, "PROPFIND")                                                     \
138
  V(PROPPATCH, "PROPPATCH")                                                   \
139
  V(PUT, "PUT")                                                               \
140
  V(REBIND, "REBIND")                                                         \
141
  V(REPORT, "REPORT")                                                         \
142
  V(SEARCH, "SEARCH")                                                         \
143
  V(TRACE, "TRACE")                                                           \
144
  V(UNBIND, "UNBIND")                                                         \
145
  V(UNCHECKOUT, "UNCHECKOUT")                                                 \
146
  V(UNLINK, "UNLINK")                                                         \
147
  V(UNLOCK, "UNLOCK")                                                         \
148
  V(UPDATE, "UPDATE")                                                         \
149
  V(UPDATEREDIRECTREF, "UPDATEREDIRECTREF")                                   \
150
  V(VERSION_CONTROL, "VERSION-CONTROL")
151
152
// These are provided strictly as a convenience to users and are exposed via the
153
// require('http2').constants objects
154
#define HTTP_KNOWN_HEADERS(V)                                                 \
155
  V(STATUS, ":status")                                                        \
156
  V(METHOD, ":method")                                                        \
157
  V(AUTHORITY, ":authority")                                                  \
158
  V(SCHEME, ":scheme")                                                        \
159
  V(PATH, ":path")                                                            \
160
  V(PROTOCOL, ":protocol")                                                    \
161
  V(ACCEPT_CHARSET, "accept-charset")                                         \
162
  V(ACCEPT_ENCODING, "accept-encoding")                                       \
163
  V(ACCEPT_LANGUAGE, "accept-language")                                       \
164
  V(ACCEPT_RANGES, "accept-ranges")                                           \
165
  V(ACCEPT, "accept")                                                         \
166
  V(ACCESS_CONTROL_ALLOW_CREDENTIALS, "access-control-allow-credentials")     \
167
  V(ACCESS_CONTROL_ALLOW_HEADERS, "access-control-allow-headers")             \
168
  V(ACCESS_CONTROL_ALLOW_METHODS, "access-control-allow-methods")             \
169
  V(ACCESS_CONTROL_ALLOW_ORIGIN, "access-control-allow-origin")               \
170
  V(ACCESS_CONTROL_EXPOSE_HEADERS, "access-control-expose-headers")           \
171
  V(ACCESS_CONTROL_MAX_AGE, "access-control-max-age")                         \
172
  V(ACCESS_CONTROL_REQUEST_HEADERS, "access-control-request-headers")         \
173
  V(ACCESS_CONTROL_REQUEST_METHOD, "access-control-request-method")           \
174
  V(AGE, "age")                                                               \
175
  V(ALLOW, "allow")                                                           \
176
  V(AUTHORIZATION, "authorization")                                           \
177
  V(CACHE_CONTROL, "cache-control")                                           \
178
  V(CONNECTION, "connection")                                                 \
179
  V(CONTENT_DISPOSITION, "content-disposition")                               \
180
  V(CONTENT_ENCODING, "content-encoding")                                     \
181
  V(CONTENT_LANGUAGE, "content-language")                                     \
182
  V(CONTENT_LENGTH, "content-length")                                         \
183
  V(CONTENT_LOCATION, "content-location")                                     \
184
  V(CONTENT_MD5, "content-md5")                                               \
185
  V(CONTENT_RANGE, "content-range")                                           \
186
  V(CONTENT_TYPE, "content-type")                                             \
187
  V(COOKIE, "cookie")                                                         \
188
  V(DATE, "date")                                                             \
189
  V(DNT, "dnt")                                                               \
190
  V(ETAG, "etag")                                                             \
191
  V(EXPECT, "expect")                                                         \
192
  V(EXPIRES, "expires")                                                       \
193
  V(FORWARDED, "forwarded")                                                   \
194
  V(FROM, "from")                                                             \
195
  V(HOST, "host")                                                             \
196
  V(IF_MATCH, "if-match")                                                     \
197
  V(IF_MODIFIED_SINCE, "if-modified-since")                                   \
198
  V(IF_NONE_MATCH, "if-none-match")                                           \
199
  V(IF_RANGE, "if-range")                                                     \
200
  V(IF_UNMODIFIED_SINCE, "if-unmodified-since")                               \
201
  V(LAST_MODIFIED, "last-modified")                                           \
202
  V(LINK, "link")                                                             \
203
  V(LOCATION, "location")                                                     \
204
  V(MAX_FORWARDS, "max-forwards")                                             \
205
  V(PREFER, "prefer")                                                         \
206
  V(PROXY_AUTHENTICATE, "proxy-authenticate")                                 \
207
  V(PROXY_AUTHORIZATION, "proxy-authorization")                               \
208
  V(RANGE, "range")                                                           \
209
  V(REFERER, "referer")                                                       \
210
  V(REFRESH, "refresh")                                                       \
211
  V(RETRY_AFTER, "retry-after")                                               \
212
  V(SERVER, "server")                                                         \
213
  V(SET_COOKIE, "set-cookie")                                                 \
214
  V(STRICT_TRANSPORT_SECURITY, "strict-transport-security")                   \
215
  V(TRAILER, "trailer")                                                       \
216
  V(TRANSFER_ENCODING, "transfer-encoding")                                   \
217
  V(TE, "te")                                                                 \
218
  V(TK, "tk")                                                                 \
219
  V(UPGRADE_INSECURE_REQUESTS, "upgrade-insecure-requests")                   \
220
  V(UPGRADE, "upgrade")                                                       \
221
  V(USER_AGENT, "user-agent")                                                 \
222
  V(VARY, "vary")                                                             \
223
  V(VIA, "via")                                                               \
224
  V(WARNING, "warning")                                                       \
225
  V(WWW_AUTHENTICATE, "www-authenticate")                                     \
226
  V(X_CONTENT_TYPE_OPTIONS, "x-content-type-options")                         \
227
  V(X_FRAME_OPTIONS, "x-frame-options")                                       \
228
  V(HTTP2_SETTINGS, "http2-settings")                                         \
229
  V(KEEP_ALIVE, "keep-alive")                                                 \
230
  V(PROXY_CONNECTION, "proxy-connection")
231
232
enum http_known_headers {
233
  HTTP_KNOWN_HEADER_MIN,
234
#define V(name, value) HTTP_HEADER_##name,
235
  HTTP_KNOWN_HEADERS(V)
236
#undef V
237
  HTTP_KNOWN_HEADER_MAX
238
};
239
240
// While some of these codes are used within the HTTP/2 implementation in
241
// core, they are provided strictly as a convenience to users and are exposed
242
// via the require('http2').constants object.
243
#define HTTP_STATUS_CODES(V)                                                  \
244
  V(CONTINUE, 100)                                                            \
245
  V(SWITCHING_PROTOCOLS, 101)                                                 \
246
  V(PROCESSING, 102)                                                          \
247
  V(EARLY_HINTS, 103)                                                         \
248
  V(OK, 200)                                                                  \
249
  V(CREATED, 201)                                                             \
250
  V(ACCEPTED, 202)                                                            \
251
  V(NON_AUTHORITATIVE_INFORMATION, 203)                                       \
252
  V(NO_CONTENT, 204)                                                          \
253
  V(RESET_CONTENT, 205)                                                       \
254
  V(PARTIAL_CONTENT, 206)                                                     \
255
  V(MULTI_STATUS, 207)                                                        \
256
  V(ALREADY_REPORTED, 208)                                                    \
257
  V(IM_USED, 226)                                                             \
258
  V(MULTIPLE_CHOICES, 300)                                                    \
259
  V(MOVED_PERMANENTLY, 301)                                                   \
260
  V(FOUND, 302)                                                               \
261
  V(SEE_OTHER, 303)                                                           \
262
  V(NOT_MODIFIED, 304)                                                        \
263
  V(USE_PROXY, 305)                                                           \
264
  V(TEMPORARY_REDIRECT, 307)                                                  \
265
  V(PERMANENT_REDIRECT, 308)                                                  \
266
  V(BAD_REQUEST, 400)                                                         \
267
  V(UNAUTHORIZED, 401)                                                        \
268
  V(PAYMENT_REQUIRED, 402)                                                    \
269
  V(FORBIDDEN, 403)                                                           \
270
  V(NOT_FOUND, 404)                                                           \
271
  V(METHOD_NOT_ALLOWED, 405)                                                  \
272
  V(NOT_ACCEPTABLE, 406)                                                      \
273
  V(PROXY_AUTHENTICATION_REQUIRED, 407)                                       \
274
  V(REQUEST_TIMEOUT, 408)                                                     \
275
  V(CONFLICT, 409)                                                            \
276
  V(GONE, 410)                                                                \
277
  V(LENGTH_REQUIRED, 411)                                                     \
278
  V(PRECONDITION_FAILED, 412)                                                 \
279
  V(PAYLOAD_TOO_LARGE, 413)                                                   \
280
  V(URI_TOO_LONG, 414)                                                        \
281
  V(UNSUPPORTED_MEDIA_TYPE, 415)                                              \
282
  V(RANGE_NOT_SATISFIABLE, 416)                                               \
283
  V(EXPECTATION_FAILED, 417)                                                  \
284
  V(TEAPOT, 418)                                                              \
285
  V(MISDIRECTED_REQUEST, 421)                                                 \
286
  V(UNPROCESSABLE_ENTITY, 422)                                                \
287
  V(LOCKED, 423)                                                              \
288
  V(FAILED_DEPENDENCY, 424)                                                   \
289
  V(UNORDERED_COLLECTION, 425)                                                \
290
  V(UPGRADE_REQUIRED, 426)                                                    \
291
  V(PRECONDITION_REQUIRED, 428)                                               \
292
  V(TOO_MANY_REQUESTS, 429)                                                   \
293
  V(REQUEST_HEADER_FIELDS_TOO_LARGE, 431)                                     \
294
  V(UNAVAILABLE_FOR_LEGAL_REASONS, 451)                                       \
295
  V(INTERNAL_SERVER_ERROR, 500)                                               \
296
  V(NOT_IMPLEMENTED, 501)                                                     \
297
  V(BAD_GATEWAY, 502)                                                         \
298
  V(SERVICE_UNAVAILABLE, 503)                                                 \
299
  V(GATEWAY_TIMEOUT, 504)                                                     \
300
  V(HTTP_VERSION_NOT_SUPPORTED, 505)                                          \
301
  V(VARIANT_ALSO_NEGOTIATES, 506)                                             \
302
  V(INSUFFICIENT_STORAGE, 507)                                                \
303
  V(LOOP_DETECTED, 508)                                                       \
304
  V(BANDWIDTH_LIMIT_EXCEEDED, 509)                                            \
305
  V(NOT_EXTENDED, 510)                                                        \
306
  V(NETWORK_AUTHENTICATION_REQUIRED, 511)
307
308
enum http_status_codes {
309
#define V(name, code) HTTP_STATUS_##name = code,
310
  HTTP_STATUS_CODES(V)
311
#undef V
312
};
313
314
// The Padding Strategy determines the method by which extra padding is
315
// selected for HEADERS and DATA frames. These are configurable via the
316
// options passed in to a Http2Session object.
317
enum padding_strategy_type {
318
  // No padding strategy. This is the default.
319
  PADDING_STRATEGY_NONE,
320
  // Attempts to ensure that the frame is 8-byte aligned
321
  PADDING_STRATEGY_ALIGNED,
322
  // Padding will ensure all data frames are maxFrameSize
323
  PADDING_STRATEGY_MAX,
324
  // Padding will be determined via a JS callback. Note that this can be
325
  // expensive because the callback is called once for every DATA and
326
  // HEADERS frame. For performance reasons, this strategy should be
327
  // avoided.
328
  PADDING_STRATEGY_CALLBACK
329
};
330
331
enum session_state_flags {
332
  SESSION_STATE_NONE = 0x0,
333
  SESSION_STATE_HAS_SCOPE = 0x1,
334
  SESSION_STATE_WRITE_SCHEDULED = 0x2,
335
  SESSION_STATE_CLOSED = 0x4,
336
  SESSION_STATE_CLOSING = 0x8,
337
  SESSION_STATE_SENDING = 0x10,
338
  SESSION_STATE_WRITE_IN_PROGRESS = 0x20,
339
  SESSION_STATE_READING_STOPPED = 0x40,
340
  SESSION_STATE_NGHTTP2_RECV_PAUSED = 0x80
341
};
342
343
typedef uint32_t(*get_setting)(nghttp2_session* session,
344
                               nghttp2_settings_id id);
345
346
class Http2Session;
347
class Http2Stream;
348
349
// This scope should be present when any call into nghttp2 that may schedule
350
// data to be written to the underlying transport is made, and schedules
351
// such a write automatically once the scope is exited.
352
class Http2Scope {
353
 public:
354
  explicit Http2Scope(Http2Stream* stream);
355
  explicit Http2Scope(Http2Session* session);
356
  ~Http2Scope();
357
358
 private:
359
  Http2Session* session_ = nullptr;
360
  Local<Object> session_handle_;
361
};
362
363
// The Http2Options class is used to parse the options object passed in to
364
// a Http2Session object and convert those into an appropriate nghttp2_option
365
// struct. This is the primary mechanism by which the Http2Session object is
366
// configured.
367
class Http2Options {
368
 public:
369
  Http2Options(Environment* env, nghttp2_session_type type);
370
371
582
  ~Http2Options() {
372
582
    nghttp2_option_del(options_);
373
582
  }
374
375
582
  nghttp2_option* operator*() const {
376
582
    return options_;
377
  }
378
379
3
  void SetMaxHeaderPairs(uint32_t max) {
380
3
    max_header_pairs_ = max;
381
3
  }
382
383
582
  uint32_t GetMaxHeaderPairs() const {
384
582
    return max_header_pairs_;
385
  }
386
387
4
  void SetPaddingStrategy(padding_strategy_type val) {
388
4
    padding_strategy_ = val;
389
4
  }
390
391
582
  padding_strategy_type GetPaddingStrategy() const {
392
582
    return padding_strategy_;
393
  }
394
395
2
  void SetMaxOutstandingPings(size_t max) {
396
2
    max_outstanding_pings_ = max;
397
2
  }
398
399
582
  size_t GetMaxOutstandingPings() {
400
582
    return max_outstanding_pings_;
401
  }
402
403
2
  void SetMaxOutstandingSettings(size_t max) {
404
2
    max_outstanding_settings_ = max;
405
2
  }
406
407
582
  size_t GetMaxOutstandingSettings() {
408
582
    return max_outstanding_settings_;
409
  }
410
411
5
  void SetMaxSessionMemory(uint64_t max) {
412
5
    max_session_memory_ = max;
413
5
  }
414
415
582
  uint64_t GetMaxSessionMemory() {
416
582
    return max_session_memory_;
417
  }
418
419
 private:
420
  nghttp2_option* options_;
421
  uint64_t max_session_memory_ = DEFAULT_MAX_SESSION_MEMORY;
422
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
423
  padding_strategy_type padding_strategy_ = PADDING_STRATEGY_NONE;
424
  size_t max_outstanding_pings_ = DEFAULT_MAX_PINGS;
425
  size_t max_outstanding_settings_ = DEFAULT_MAX_SETTINGS;
426
};
427
428
class Http2Priority {
429
 public:
430
  Http2Priority(Environment* env,
431
                Local<Value> parent,
432
                Local<Value> weight,
433
                Local<Value> exclusive);
434
435
11758
  nghttp2_priority_spec* operator*() {
436
11758
    return &spec;
437
  }
438
 private:
439
  nghttp2_priority_spec spec;
440
};
441
442
49036
class Http2StreamListener : public StreamListener {
443
 public:
444
  uv_buf_t OnStreamAlloc(size_t suggested_size) override;
445
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
446
};
447
448
class Http2Stream : public AsyncWrap,
449
                    public StreamBase {
450
 public:
451
  static Http2Stream* New(
452
      Http2Session* session,
453
      int32_t id,
454
      nghttp2_headers_category category = NGHTTP2_HCAT_HEADERS,
455
      int options = 0);
456
  ~Http2Stream() override;
457
458
  nghttp2_stream* operator*();
459
460
136276
  Http2Session* session() { return session_; }
461
17
  const Http2Session* session() const { return session_; }
462
463
  void EmitStatistics();
464
465
  // Required for StreamBase
466
  int ReadStart() override;
467
468
  // Required for StreamBase
469
  int ReadStop() override;
470
471
  // Required for StreamBase
472
  int DoShutdown(ShutdownWrap* req_wrap) override;
473
474
15
  bool HasWantsWrite() const override { return true; }
475
476
  // Initiate a response on this stream.
477
  int SubmitResponse(nghttp2_nv* nva, size_t len, int options);
478
479
  // Submit informational headers for this stream
480
  int SubmitInfo(nghttp2_nv* nva, size_t len);
481
482
  // Submit trailing headers for this stream
483
  int SubmitTrailers(nghttp2_nv* nva, size_t len);
484
  void OnTrailers();
485
486
  // Submit a PRIORITY frame for this stream
487
  int SubmitPriority(nghttp2_priority_spec* prispec, bool silent = false);
488
489
  // Submits an RST_STREAM frame using the given code
490
  void SubmitRstStream(const uint32_t code);
491
492
  void FlushRstStream();
493
494
  // Submits a PUSH_PROMISE frame with this stream as the parent.
495
  Http2Stream* SubmitPushPromise(
496
      nghttp2_nv* nva,
497
      size_t len,
498
      int32_t* ret,
499
      int options = 0);
500
501
502
  void Close(int32_t code);
503
504
  // Destroy this stream instance and free all held memory.
505
  void Destroy();
506
507
375086
  inline bool IsDestroyed() const {
508
375086
    return flags_ & NGHTTP2_STREAM_FLAG_DESTROYED;
509
  }
510
511
47785
  inline bool IsWritable() const {
512
47785
    return !(flags_ & NGHTTP2_STREAM_FLAG_SHUT);
513
  }
514
515
  inline bool IsPaused() const {
516
    return flags_ & NGHTTP2_STREAM_FLAG_READ_PAUSED;
517
  }
518
519
  inline bool IsClosed() const {
520
    return flags_ & NGHTTP2_STREAM_FLAG_CLOSED;
521
  }
522
523
12559
  inline bool HasTrailers() const {
524
12559
    return flags_ & NGHTTP2_STREAM_FLAG_TRAILERS;
525
  }
526
527
  // Returns true if this stream is in the reading state, which occurs when
528
  // the NGHTTP2_STREAM_FLAG_READ_START flag has been set and the
529
  // NGHTTP2_STREAM_FLAG_READ_PAUSED flag is *not* set.
530
12863
  inline bool IsReading() const {
531

24690
    return flags_ & NGHTTP2_STREAM_FLAG_READ_START &&
532
24690
           !(flags_ & NGHTTP2_STREAM_FLAG_READ_PAUSED);
533
  }
534
535
  // Returns the RST_STREAM code used to close this stream
536
  inline int32_t code() const { return code_; }
537
538
  // Returns the stream identifier for this stream
539
141426
  inline int32_t id() const { return id_; }
540
541
  inline void IncrementAvailableOutboundLength(size_t amount);
542
  inline void DecrementAvailableOutboundLength(size_t amount);
543
544
  bool AddHeader(nghttp2_rcbuf* name, nghttp2_rcbuf* value, uint8_t flags);
545
546
23403
  inline std::vector<nghttp2_header> move_headers() {
547
23403
    return std::move(current_headers_);
548
  }
549
550
23403
  inline nghttp2_headers_category headers_category() const {
551
23403
    return current_headers_category_;
552
  }
553
554
  void StartHeaders(nghttp2_headers_category category);
555
556
  // Required for StreamBase
557
49474
  bool IsAlive() override {
558
49474
    return true;
559
  }
560
561
  // Required for StreamBase
562
  bool IsClosing() override {
563
    return false;
564
  }
565
566
130464
  AsyncWrap* GetAsyncWrap() override { return this; }
567
568
  int DoWrite(WriteWrap* w, uv_buf_t* bufs, size_t count,
569
              uv_stream_t* send_handle) override;
570
571
4
  void MemoryInfo(MemoryTracker* tracker) const override {
572
4
    tracker->TrackField("current_headers", current_headers_);
573
4
    tracker->TrackField("queue", queue_);
574
4
  }
575
576
4
  SET_MEMORY_INFO_NAME(Http2Stream)
577
4
  SET_SELF_SIZE(Http2Stream)
578
579
  std::string diagnostic_name() const override;
580
581
  // JavaScript API
582
  static void GetID(const FunctionCallbackInfo<Value>& args);
583
  static void Destroy(const FunctionCallbackInfo<Value>& args);
584
  static void Priority(const FunctionCallbackInfo<Value>& args);
585
  static void PushPromise(const FunctionCallbackInfo<Value>& args);
586
  static void RefreshState(const FunctionCallbackInfo<Value>& args);
587
  static void Info(const FunctionCallbackInfo<Value>& args);
588
  static void Trailers(const FunctionCallbackInfo<Value>& args);
589
  static void Respond(const FunctionCallbackInfo<Value>& args);
590
  static void RstStream(const FunctionCallbackInfo<Value>& args);
591
592
  class Provider;
593
594
  struct Statistics {
595
    uint64_t start_time;
596
    uint64_t end_time;
597
    uint64_t first_header;     // Time first header was received
598
    uint64_t first_byte;       // Time first DATA frame byte was received
599
    uint64_t first_byte_sent;  // Time first DATA frame byte was sent
600
    uint64_t sent_bytes;
601
    uint64_t received_bytes;
602
  };
603
604
  Statistics statistics_ = {};
605
606
 private:
607
  Http2Stream(Http2Session* session,
608
              v8::Local<v8::Object> obj,
609
              int32_t id,
610
              nghttp2_headers_category category,
611
              int options);
612
613
  Http2Session* session_ = nullptr;             // The Parent HTTP/2 Session
614
  int32_t id_ = 0;                              // The Stream Identifier
615
  int32_t code_ = NGHTTP2_NO_ERROR;             // The RST_STREAM code (if any)
616
  int flags_ = NGHTTP2_STREAM_FLAG_NONE;        // Internal state flags
617
618
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
619
  uint32_t max_header_length_ = DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
620
621
  // The Current Headers block... As headers are received for this stream,
622
  // they are temporarily stored here until the OnFrameReceived is called
623
  // signalling the end of the HEADERS frame
624
  nghttp2_headers_category current_headers_category_ = NGHTTP2_HCAT_HEADERS;
625
  uint32_t current_headers_length_ = 0;  // total number of octets
626
  std::vector<nghttp2_header> current_headers_;
627
628
  // This keeps track of the amount of data read from the socket while the
629
  // socket was in paused mode. When `ReadStart()` is called (and not before
630
  // then), we tell nghttp2 that we consumed that data to get proper
631
  // backpressure handling.
632
  size_t inbound_consumed_data_while_paused_ = 0;
633
634
  // Outbound Data... This is the data written by the JS layer that is
635
  // waiting to be written out to the socket.
636
  std::queue<nghttp2_stream_write> queue_;
637
  size_t available_outbound_length_ = 0;
638
639
  Http2StreamListener stream_listener_;
640
641
  friend class Http2Session;
642
};
643
644
class Http2Stream::Provider {
645
 public:
646
  Provider(Http2Stream* stream, int options);
647
  explicit Provider(int options);
648
  virtual ~Provider();
649
650
23456
  nghttp2_data_provider* operator*() {
651
23456
    return !empty_ ? &provider_ : nullptr;
652
  }
653
654
  class FD;
655
  class Stream;
656
 protected:
657
  nghttp2_data_provider provider_;
658
659
 private:
660
  bool empty_ = false;
661
};
662
663
23456
class Http2Stream::Provider::Stream : public Http2Stream::Provider {
664
 public:
665
  Stream(Http2Stream* stream, int options);
666
  explicit Stream(int options);
667
668
  static ssize_t OnRead(nghttp2_session* session,
669
                        int32_t id,
670
                        uint8_t* buf,
671
                        size_t length,
672
                        uint32_t* flags,
673
                        nghttp2_data_source* source,
674
                        void* user_data);
675
};
676
677
// Indices for js_fields_, which serves as a way to communicate data with JS
678
// land fast. In particular, we store information about the number/presence
679
// of certain event listeners in JS, and skip calls from C++ into JS if they
680
// are missing.
681
enum SessionUint8Fields {
682
  kBitfield,  // See below
683
  kSessionPriorityListenerCount,
684
  kSessionFrameErrorListenerCount,
685
  kSessionUint8FieldCount
686
};
687
688
enum SessionBitfieldFlags {
689
  kSessionHasRemoteSettingsListeners,
690
  kSessionRemoteSettingsIsUpToDate,
691
  kSessionHasPingListeners,
692
  kSessionHasAltsvcListeners
693
};
694
695
class Http2Session : public AsyncWrap, public StreamListener {
696
 public:
697
  Http2Session(Environment* env,
698
               Local<Object> wrap,
699
               nghttp2_session_type type = NGHTTP2_SESSION_SERVER);
700
  ~Http2Session() override;
701
702
  class Http2Ping;
703
  class Http2Settings;
704
  class MemoryAllocatorInfo;
705
706
  void EmitStatistics();
707
708
31556
  inline StreamBase* underlying_stream() {
709
31556
    return static_cast<StreamBase*>(stream_);
710
  }
711
712
  void Close(uint32_t code = NGHTTP2_NO_ERROR,
713
             bool socket_closed = false);
714
  void Consume(Local<Object> stream);
715
  void Goaway(uint32_t code, int32_t lastStreamID,
716
              const uint8_t* data, size_t len);
717
  void AltSvc(int32_t id,
718
              uint8_t* origin,
719
              size_t origin_len,
720
              uint8_t* value,
721
              size_t value_len);
722
  void Origin(nghttp2_origin_entry* ov, size_t count);
723
724
  uint8_t SendPendingData();
725
726
  // Submits a new request. If the request is a success, assigned
727
  // will be a pointer to the Http2Stream instance assigned.
728
  // This only works if the session is a client session.
729
  Http2Stream* SubmitRequest(
730
      nghttp2_priority_spec* prispec,
731
      nghttp2_nv* nva,
732
      size_t len,
733
      int32_t* ret,
734
      int options = 0);
735
736
  inline nghttp2_session_type type() const { return session_type_; }
737
738
24518
  inline nghttp2_session* session() const { return session_; }
739
740
66214
  inline nghttp2_session* operator*() { return session_; }
741
742
24518
  inline uint32_t GetMaxHeaderPairs() const { return max_header_pairs_; }
743
744
  inline const char* TypeName() const;
745
746
63104
  inline bool IsDestroyed() {
747

63104
    return (flags_ & SESSION_STATE_CLOSED) || session_ == nullptr;
748
  }
749
750
  // Schedule a write if nghttp2 indicates it wants to write to the socket.
751
  void MaybeScheduleWrite();
752
753
  // Stop reading if nghttp2 doesn't want to anymore.
754
  void MaybeStopReading();
755
756
  // Returns pointer to the stream, or nullptr if stream does not exist
757
  inline Http2Stream* FindStream(int32_t id);
758
759
  inline bool CanAddStream();
760
761
  // Adds a stream instance to this session
762
  inline void AddStream(Http2Stream* stream);
763
764
  // Removes a stream instance from this session
765
  inline void RemoveStream(Http2Stream* stream);
766
767
  // Indicates whether there currently exist outgoing buffers for this stream.
768
  bool HasWritesOnSocketForStream(Http2Stream* stream);
769
770
  // Write data from stream_buf_ to the session
771
  ssize_t ConsumeHTTP2Data();
772
773
9
  void MemoryInfo(MemoryTracker* tracker) const override {
774
9
    tracker->TrackField("streams", streams_);
775
9
    tracker->TrackField("outstanding_pings", outstanding_pings_);
776
9
    tracker->TrackField("outstanding_settings", outstanding_settings_);
777
9
    tracker->TrackField("outgoing_buffers", outgoing_buffers_);
778
9
    tracker->TrackFieldWithSize("stream_buf", stream_buf_.len);
779
9
    tracker->TrackFieldWithSize("outgoing_storage", outgoing_storage_.size());
780
    tracker->TrackFieldWithSize("pending_rst_streams",
781
9
                                pending_rst_streams_.size() * sizeof(int32_t));
782
9
  }
783
784
9
  SET_MEMORY_INFO_NAME(Http2Session)
785
9
  SET_SELF_SIZE(Http2Session)
786
787
  std::string diagnostic_name() const override;
788
789
  // Schedule an RstStream for after the current write finishes.
790
2
  inline void AddPendingRstStream(int32_t stream_id) {
791
2
    pending_rst_streams_.emplace_back(stream_id);
792
2
  }
793
794
24475
  inline bool HasPendingRstStream(int32_t stream_id) {
795
48950
    return pending_rst_streams_.end() != std::find(pending_rst_streams_.begin(),
796
                                                   pending_rst_streams_.end(),
797
73425
                                                   stream_id);
798
  }
799
800
  // Handle reads/writes from the underlying network transport.
801
  uv_buf_t OnStreamAlloc(size_t suggested_size) override;
802
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
803
  void OnStreamAfterWrite(WriteWrap* w, int status) override;
804
805
  // The JavaScript API
806
  static void New(const FunctionCallbackInfo<Value>& args);
807
  static void Consume(const FunctionCallbackInfo<Value>& args);
808
  static void Destroy(const FunctionCallbackInfo<Value>& args);
809
  static void Settings(const FunctionCallbackInfo<Value>& args);
810
  static void Request(const FunctionCallbackInfo<Value>& args);
811
  static void SetNextStreamID(const FunctionCallbackInfo<Value>& args);
812
  static void Goaway(const FunctionCallbackInfo<Value>& args);
813
  static void UpdateChunksSent(const FunctionCallbackInfo<Value>& args);
814
  static void RefreshState(const FunctionCallbackInfo<Value>& args);
815
  static void Ping(const FunctionCallbackInfo<Value>& args);
816
  static void AltSvc(const FunctionCallbackInfo<Value>& args);
817
  static void Origin(const FunctionCallbackInfo<Value>& args);
818
819
  template <get_setting fn>
820
  static void RefreshSettings(const FunctionCallbackInfo<Value>& args);
821
822
  uv_loop_t* event_loop() const {
823
    return env()->event_loop();
824
  }
825
826
  std::unique_ptr<Http2Ping> PopPing();
827
  Http2Ping* AddPing(std::unique_ptr<Http2Ping> ping);
828
829
  std::unique_ptr<Http2Settings> PopSettings();
830
  Http2Settings* AddSettings(std::unique_ptr<Http2Settings> settings);
831
832
151117
  void IncrementCurrentSessionMemory(uint64_t amount) {
833
151117
    current_session_memory_ += amount;
834
151117
  }
835
836
126798
  void DecrementCurrentSessionMemory(uint64_t amount) {
837
    DCHECK_LE(amount, current_session_memory_);
838
126798
    current_session_memory_ -= amount;
839
126798
  }
840
841
  // Tell our custom memory allocator that this rcbuf is independent of
842
  // this session now, and may outlive it.
843
  void StopTrackingRcbuf(nghttp2_rcbuf* buf);
844
845
  // Returns the current session memory including memory allocated by nghttp2,
846
  // the current outbound storage queue, and pending writes.
847
84479
  uint64_t GetCurrentSessionMemory() {
848
84479
    uint64_t total = current_session_memory_ + sizeof(Http2Session);
849
84479
    total += current_nghttp2_memory_;
850
84479
    total += outgoing_storage_.size();
851
84479
    return total;
852
  }
853
854
  // Return true if current_session_memory + amount is less than the max
855
84479
  bool IsAvailableSessionMemory(uint64_t amount) {
856
84479
    return GetCurrentSessionMemory() + amount <= max_session_memory_;
857
  }
858
859
  struct Statistics {
860
    uint64_t start_time;
861
    uint64_t end_time;
862
    uint64_t ping_rtt;
863
    uint64_t data_sent;
864
    uint64_t data_received;
865
    uint32_t frame_count;
866
    uint32_t frame_sent;
867
    int32_t stream_count;
868
    size_t max_concurrent_streams;
869
    double stream_average_duration;
870
  };
871
872
  Statistics statistics_ = {};
873
874
 private:
875
  // Frame Padding Strategies
876
  ssize_t OnDWordAlignedPadding(size_t frameLength,
877
                                size_t maxPayloadLen);
878
  ssize_t OnMaxFrameSizePadding(size_t frameLength,
879
                                size_t maxPayloadLen);
880
  ssize_t OnCallbackPadding(size_t frameLength,
881
                            size_t maxPayloadLen);
882
883
  // Frame Handler
884
  int HandleDataFrame(const nghttp2_frame* frame);
885
  void HandleGoawayFrame(const nghttp2_frame* frame);
886
  void HandleHeadersFrame(const nghttp2_frame* frame);
887
  void HandlePriorityFrame(const nghttp2_frame* frame);
888
  void HandleSettingsFrame(const nghttp2_frame* frame);
889
  void HandlePingFrame(const nghttp2_frame* frame);
890
  void HandleAltSvcFrame(const nghttp2_frame* frame);
891
  void HandleOriginFrame(const nghttp2_frame* frame);
892
893
  // nghttp2 callbacks
894
  static int OnBeginHeadersCallback(
895
      nghttp2_session* session,
896
      const nghttp2_frame* frame,
897
      void* user_data);
898
  static int OnHeaderCallback(
899
      nghttp2_session* session,
900
      const nghttp2_frame* frame,
901
      nghttp2_rcbuf* name,
902
      nghttp2_rcbuf* value,
903
      uint8_t flags,
904
      void* user_data);
905
  static int OnFrameReceive(
906
      nghttp2_session* session,
907
      const nghttp2_frame* frame,
908
      void* user_data);
909
  static int OnFrameNotSent(
910
      nghttp2_session* session,
911
      const nghttp2_frame* frame,
912
      int error_code,
913
      void* user_data);
914
  static int OnFrameSent(
915
      nghttp2_session* session,
916
      const nghttp2_frame* frame,
917
      void* user_data);
918
  static int OnStreamClose(
919
      nghttp2_session* session,
920
      int32_t id,
921
      uint32_t code,
922
      void* user_data);
923
  static int OnInvalidHeader(
924
      nghttp2_session* session,
925
      const nghttp2_frame* frame,
926
      nghttp2_rcbuf* name,
927
      nghttp2_rcbuf* value,
928
      uint8_t flags,
929
      void* user_data);
930
  static int OnDataChunkReceived(
931
      nghttp2_session* session,
932
      uint8_t flags,
933
      int32_t id,
934
      const uint8_t* data,
935
      size_t len,
936
      void* user_data);
937
  static ssize_t OnSelectPadding(
938
      nghttp2_session* session,
939
      const nghttp2_frame* frame,
940
      size_t maxPayloadLen,
941
      void* user_data);
942
  static int OnNghttpError(
943
      nghttp2_session* session,
944
      const char* message,
945
      size_t len,
946
      void* user_data);
947
  static int OnSendData(
948
      nghttp2_session* session,
949
      nghttp2_frame* frame,
950
      const uint8_t* framehd,
951
      size_t length,
952
      nghttp2_data_source* source,
953
      void* user_data);
954
  static int OnInvalidFrame(
955
      nghttp2_session* session,
956
      const nghttp2_frame* frame,
957
      int lib_error_code,
958
      void* user_data);
959
960
  struct Callbacks {
961
    inline explicit Callbacks(bool kHasGetPaddingCallback);
962
    inline ~Callbacks();
963
964
    nghttp2_session_callbacks* callbacks;
965
  };
966
967
  /* Use callback_struct_saved[kHasGetPaddingCallback ? 1 : 0] */
968
  static const Callbacks callback_struct_saved[2];
969
970
  // The underlying nghttp2_session handle
971
  nghttp2_session* session_;
972
973
  // JS-accessible numeric fields, as indexed by SessionUint8Fields.
974
  uint8_t js_fields_[kSessionUint8FieldCount] = {};
975
976
  // The session type: client or server
977
  nghttp2_session_type session_type_;
978
979
  // The maximum number of header pairs permitted for streams on this session
980
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
981
982
  // The maximum amount of memory allocated for this session
983
  uint64_t max_session_memory_ = DEFAULT_MAX_SESSION_MEMORY;
984
  uint64_t current_session_memory_ = 0;
985
  // The amount of memory allocated by nghttp2 internals
986
  uint64_t current_nghttp2_memory_ = 0;
987
988
  // The collection of active Http2Streams associated with this session
989
  std::unordered_map<int32_t, Http2Stream*> streams_;
990
991
  int flags_ = SESSION_STATE_NONE;
992
993
  // The StreamBase instance being used for i/o
994
  padding_strategy_type padding_strategy_ = PADDING_STRATEGY_NONE;
995
996
  // use this to allow timeout tracking during long-lasting writes
997
  uint32_t chunks_sent_since_last_write_ = 0;
998
999
  uv_buf_t stream_buf_ = uv_buf_init(nullptr, 0);
1000
  // When processing input data, either stream_buf_ab_ or stream_buf_allocation_
1001
  // will be set. stream_buf_ab_ is lazily created from stream_buf_allocation_.
1002
  v8::Global<v8::ArrayBuffer> stream_buf_ab_;
1003
  AllocatedBuffer stream_buf_allocation_;
1004
  size_t stream_buf_offset_ = 0;
1005
1006
  size_t max_outstanding_pings_ = DEFAULT_MAX_PINGS;
1007
  std::queue<std::unique_ptr<Http2Ping>> outstanding_pings_;
1008
1009
  size_t max_outstanding_settings_ = DEFAULT_MAX_SETTINGS;
1010
  std::queue<std::unique_ptr<Http2Settings>> outstanding_settings_;
1011
1012
  std::vector<nghttp2_stream_write> outgoing_buffers_;
1013
  std::vector<uint8_t> outgoing_storage_;
1014
  size_t outgoing_length_ = 0;
1015
  std::vector<int32_t> pending_rst_streams_;
1016
  // Count streams that have been rejected while being opened. Exceeding a fixed
1017
  // limit will result in the session being destroyed, as an indication of a
1018
  // misbehaving peer. This counter is reset once new streams are being
1019
  // accepted again.
1020
  int32_t rejected_stream_count_ = 0;
1021
  // Also use the invalid frame count as a measure for rejecting input frames.
1022
  int32_t invalid_frame_count_ = 0;
1023
1024
  void PushOutgoingBuffer(nghttp2_stream_write&& write);
1025
  void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length);
1026
  void ClearOutgoing(int status);
1027
1028
  friend class Http2Scope;
1029
  friend class Http2StreamListener;
1030
};
1031
1032
4
class Http2SessionPerformanceEntry : public PerformanceEntry {
1033
 public:
1034
2
  Http2SessionPerformanceEntry(
1035
      Environment* env,
1036
      const Http2Session::Statistics& stats,
1037
      nghttp2_session_type type) :
1038
          PerformanceEntry(env, "Http2Session", "http2",
1039
                           stats.start_time,
1040
                           stats.end_time),
1041
          ping_rtt_(stats.ping_rtt),
1042
          data_sent_(stats.data_sent),
1043
          data_received_(stats.data_received),
1044
          frame_count_(stats.frame_count),
1045
          frame_sent_(stats.frame_sent),
1046
          stream_count_(stats.stream_count),
1047
          max_concurrent_streams_(stats.max_concurrent_streams),
1048
          stream_average_duration_(stats.stream_average_duration),
1049
2
          session_type_(type) { }
1050
1051
2
  uint64_t ping_rtt() const { return ping_rtt_; }
1052
2
  uint64_t data_sent() const { return data_sent_; }
1053
2
  uint64_t data_received() const { return data_received_; }
1054
2
  uint32_t frame_count() const { return frame_count_; }
1055
2
  uint32_t frame_sent() const { return frame_sent_; }
1056
2
  int32_t stream_count() const { return stream_count_; }
1057
2
  size_t max_concurrent_streams() const { return max_concurrent_streams_; }
1058
2
  double stream_average_duration() const { return stream_average_duration_; }
1059
2
  nghttp2_session_type type() const { return session_type_; }
1060
1061
2
  void Notify(Local<Value> obj) {
1062
2
    PerformanceEntry::Notify(env(), kind(), obj);
1063
2
  }
1064
1065
 private:
1066
  uint64_t ping_rtt_;
1067
  uint64_t data_sent_;
1068
  uint64_t data_received_;
1069
  uint32_t frame_count_;
1070
  uint32_t frame_sent_;
1071
  int32_t stream_count_;
1072
  size_t max_concurrent_streams_;
1073
  double stream_average_duration_;
1074
  nghttp2_session_type session_type_;
1075
};
1076
1077
4
class Http2StreamPerformanceEntry : public PerformanceEntry {
1078
 public:
1079
2
  Http2StreamPerformanceEntry(
1080
      Environment* env,
1081
      int32_t id,
1082
      const Http2Stream::Statistics& stats) :
1083
          PerformanceEntry(env, "Http2Stream", "http2",
1084
                           stats.start_time,
1085
                           stats.end_time),
1086
          id_(id),
1087
          first_header_(stats.first_header),
1088
          first_byte_(stats.first_byte),
1089
          first_byte_sent_(stats.first_byte_sent),
1090
          sent_bytes_(stats.sent_bytes),
1091
2
          received_bytes_(stats.received_bytes) { }
1092
1093
2
  int32_t id() const { return id_; }
1094
4
  uint64_t first_header() const { return first_header_; }
1095
2
  uint64_t first_byte() const { return first_byte_; }
1096
3
  uint64_t first_byte_sent() const { return first_byte_sent_; }
1097
2
  uint64_t sent_bytes() const { return sent_bytes_; }
1098
2
  uint64_t received_bytes() const { return received_bytes_; }
1099
1100
2
  void Notify(Local<Value> obj) {
1101
2
    PerformanceEntry::Notify(env(), kind(), obj);
1102
2
  }
1103
1104
 private:
1105
  int32_t id_;
1106
  uint64_t first_header_;
1107
  uint64_t first_byte_;
1108
  uint64_t first_byte_sent_;
1109
  uint64_t sent_bytes_;
1110
  uint64_t received_bytes_;
1111
};
1112
1113
26
class Http2Session::Http2Ping : public AsyncWrap {
1114
 public:
1115
  explicit Http2Ping(Http2Session* session, v8::Local<v8::Object> obj);
1116
1117
  void MemoryInfo(MemoryTracker* tracker) const override {
1118
    tracker->TrackField("session", session_);
1119
  }
1120
1121
  SET_MEMORY_INFO_NAME(Http2Ping)
1122
  SET_SELF_SIZE(Http2Ping)
1123
1124
  void Send(const uint8_t* payload);
1125
  void Done(bool ack, const uint8_t* payload = nullptr);
1126
  void DetachFromSession();
1127
1128
 private:
1129
  Http2Session* session_;
1130
  uint64_t startTime_;
1131
};
1132
1133
// The Http2Settings class is used to parse the settings passed in for
1134
// an Http2Session, converting those into an array of nghttp2_settings_entry
1135
// structs.
1136
1197
class Http2Session::Http2Settings : public AsyncWrap {
1137
 public:
1138
  Http2Settings(Environment* env,
1139
                Http2Session* session,
1140
                v8::Local<v8::Object> obj,
1141
                uint64_t start_time = uv_hrtime());
1142
1143
6
  void MemoryInfo(MemoryTracker* tracker) const override {
1144
6
    tracker->TrackField("session", session_);
1145
6
  }
1146
1147
6
  SET_MEMORY_INFO_NAME(Http2Settings)
1148
6
  SET_SELF_SIZE(Http2Settings)
1149
1150
  void Send();
1151
  void Done(bool ack);
1152
1153
  // Returns a Buffer instance with the serialized SETTINGS payload
1154
  Local<Value> Pack();
1155
1156
  // Resets the default values in the settings buffer
1157
  static void RefreshDefaults(Environment* env);
1158
1159
  // Update the local or remote settings for the given session
1160
  static void Update(Environment* env,
1161
                     Http2Session* session,
1162
                     get_setting fn);
1163
1164
 private:
1165
  void Init();
1166
  Http2Session* session_;
1167
  uint64_t startTime_;
1168
  size_t count_ = 0;
1169
  nghttp2_settings_entry entries_[IDX_SETTINGS_COUNT];
1170
};
1171
1172
class ExternalHeader :
1173
    public String::ExternalOneByteStringResource {
1174
 public:
1175
25072
  explicit ExternalHeader(nghttp2_rcbuf* buf)
1176
25072
     : buf_(buf), vec_(nghttp2_rcbuf_get_buf(buf)) {
1177
25072
  }
1178
1179
75216
  ~ExternalHeader() override {
1180
25072
    nghttp2_rcbuf_decref(buf_);
1181
25072
    buf_ = nullptr;
1182
50144
  }
1183
1184
50269
  const char* data() const override {
1185
50269
    return const_cast<const char*>(reinterpret_cast<char*>(vec_.base));
1186
  }
1187
1188
100288
  size_t length() const override {
1189
100288
    return vec_.len;
1190
  }
1191
1192
  static inline
1193
1813
  MaybeLocal<String> GetInternalizedString(Environment* env,
1194
                                           const nghttp2_vec& vec) {
1195
    return String::NewFromOneByte(env->isolate(),
1196
                                  vec.base,
1197
                                  v8::NewStringType::kInternalized,
1198
1813
                                  vec.len);
1199
  }
1200
1201
  template <bool may_internalize>
1202
143216
  static MaybeLocal<String> New(Http2Session* session, nghttp2_rcbuf* buf) {
1203
143216
    Environment* env = session->env();
1204

143216
    if (nghttp2_rcbuf_is_static(buf)) {
1205
118087
      auto& static_str_map = env->isolate_data()->http2_static_strs;
1206
118087
      v8::Eternal<v8::String>& eternal = static_str_map[buf];
1207

118087
      if (eternal.IsEmpty()) {
1208
        Local<String> str =
1209
3514
            GetInternalizedString(env, nghttp2_rcbuf_get_buf(buf))
1210
3514
                .ToLocalChecked();
1211
1757
        eternal.Set(env->isolate(), str);
1212
1757
        return str;
1213
      }
1214
232660
      return eternal.Get(env->isolate());
1215
    }
1216
1217
25129
    nghttp2_vec vec = nghttp2_rcbuf_get_buf(buf);
1218

25129
    if (vec.len == 0) {
1219
1
      nghttp2_rcbuf_decref(buf);
1220
2
      return String::Empty(env->isolate());
1221
    }
1222
1223
56
    if (may_internalize && vec.len < 64) {
1224
56
      nghttp2_rcbuf_decref(buf);
1225
      // This is a short header name, so there is a good chance V8 already has
1226
      // it internalized.
1227
56
      return GetInternalizedString(env, vec);
1228
    }
1229
1230
25072
    session->StopTrackingRcbuf(buf);
1231
25072
    ExternalHeader* h_str = new ExternalHeader(buf);
1232
25072
    MaybeLocal<String> str = String::NewExternalOneByte(env->isolate(), h_str);
1233

25072
    if (str.IsEmpty())
1234
      delete h_str;
1235
1236
25072
    return str;
1237
  }
1238
1239
 private:
1240
  nghttp2_rcbuf* buf_;
1241
  nghttp2_vec vec_;
1242
};
1243
1244
class Headers {
1245
 public:
1246
  Headers(Isolate* isolate, Local<Context> context, Local<Array> headers);
1247
23474
  ~Headers() = default;
1248
1249
23474
  nghttp2_nv* operator*() {
1250
23474
    return reinterpret_cast<nghttp2_nv*>(*buf_);
1251
  }
1252
1253
23508
  size_t length() const {
1254
23508
    return count_;
1255
  }
1256
1257
 private:
1258
  size_t count_;
1259
  MaybeStackBuffer<char, 3000> buf_;
1260
};
1261
1262
class Origins {
1263
 public:
1264
  Origins(Isolate* isolate,
1265
          Local<Context> context,
1266
          Local<v8::String> origin_string,
1267
          size_t origin_count);
1268
5
  ~Origins() = default;
1269
1270
5
  nghttp2_origin_entry* operator*() {
1271
5
    return reinterpret_cast<nghttp2_origin_entry*>(*buf_);
1272
  }
1273
1274
5
  size_t length() const {
1275
5
    return count_;
1276
  }
1277
1278
 private:
1279
  size_t count_;
1280
  MaybeStackBuffer<char, 512> buf_;
1281
};
1282
1283
}  // namespace http2
1284
}  // namespace node
1285
1286
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1287
1288
#endif  // SRC_NODE_HTTP2_H_