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

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

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

127428
    if (nghttp2_rcbuf_is_static(buf)) {
1173
105685
      auto& static_str_map = env->isolate_data()->http2_static_strs;
1174
105685
      v8::Eternal<v8::String>& eternal = static_str_map[buf];
1175

105685
      if (eternal.IsEmpty()) {
1176
        Local<String> str =
1177
3410
            GetInternalizedString(env, nghttp2_rcbuf_get_buf(buf))
1178
3410
                .ToLocalChecked();
1179
1705
        eternal.Set(env->isolate(), str);
1180
1705
        return str;
1181
      }
1182
207960
      return eternal.Get(env->isolate());
1183
    }
1184
1185
21743
    nghttp2_vec vec = nghttp2_rcbuf_get_buf(buf);
1186

21743
    if (vec.len == 0) {
1187
      nghttp2_rcbuf_decref(buf);
1188
      return String::Empty(env->isolate());
1189
    }
1190
1191
55
    if (may_internalize && vec.len < 64) {
1192
55
      nghttp2_rcbuf_decref(buf);
1193
      // This is a short header name, so there is a good chance V8 already has
1194
      // it internalized.
1195
55
      return GetInternalizedString(env, vec);
1196
    }
1197
1198
21688
    session->StopTrackingRcbuf(buf);
1199
21688
    ExternalHeader* h_str = new ExternalHeader(buf);
1200
21688
    MaybeLocal<String> str = String::NewExternalOneByte(env->isolate(), h_str);
1201

21688
    if (str.IsEmpty())
1202
      delete h_str;
1203
1204
21688
    return str;
1205
  }
1206
1207
 private:
1208
  nghttp2_rcbuf* buf_;
1209
  nghttp2_vec vec_;
1210
};
1211
1212
class Headers {
1213
 public:
1214
  Headers(Isolate* isolate, Local<Context> context, Local<Array> headers);
1215
21212
  ~Headers() {}
1216
1217
21212
  nghttp2_nv* operator*() {
1218
21212
    return reinterpret_cast<nghttp2_nv*>(*buf_);
1219
  }
1220
1221
21246
  size_t length() const {
1222
21246
    return count_;
1223
  }
1224
1225
 private:
1226
  size_t count_;
1227
  MaybeStackBuffer<char, 3000> buf_;
1228
};
1229
1230
class Origins {
1231
 public:
1232
  Origins(Isolate* isolate,
1233
          Local<Context> context,
1234
          Local<v8::String> origin_string,
1235
          size_t origin_count);
1236
5
  ~Origins() {}
1237
1238
5
  nghttp2_origin_entry* operator*() {
1239
5
    return reinterpret_cast<nghttp2_origin_entry*>(*buf_);
1240
  }
1241
1242
5
  size_t length() const {
1243
5
    return count_;
1244
  }
1245
1246
 private:
1247
  size_t count_;
1248
  MaybeStackBuffer<char, 512> buf_;
1249
};
1250
1251
}  // namespace http2
1252
}  // namespace node
1253
1254
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1255
1256
#endif  // SRC_NODE_HTTP2_H_