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

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

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

142184
    if (nghttp2_rcbuf_is_static(buf)) {
1202
117313
      auto& static_str_map = env->isolate_data()->http2_static_strs;
1203
117313
      v8::Eternal<v8::String>& eternal = static_str_map[buf];
1204

117313
      if (eternal.IsEmpty()) {
1205
        Local<String> str =
1206
3532
            GetInternalizedString(env, nghttp2_rcbuf_get_buf(buf))
1207
3532
                .ToLocalChecked();
1208
1766
        eternal.Set(env->isolate(), str);
1209
1766
        return str;
1210
      }
1211
231094
      return eternal.Get(env->isolate());
1212
    }
1213
1214
24871
    nghttp2_vec vec = nghttp2_rcbuf_get_buf(buf);
1215

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

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