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

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

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

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

105584
      if (eternal.IsEmpty()) {
1177
        Local<String> str =
1178
3388
            GetInternalizedString(env, nghttp2_rcbuf_get_buf(buf))
1179
3388
                .ToLocalChecked();
1180
1694
        eternal.Set(env->isolate(), str);
1181
1694
        return str;
1182
      }
1183
207780
      return eternal.Get(env->isolate());
1184
    }
1185
1186
21710
    nghttp2_vec vec = nghttp2_rcbuf_get_buf(buf);
1187

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

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