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: 178 193 92.2 %
Date: 2019-02-13 22:28:58 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
433606
struct nghttp2_stream_write : public MemoryRetainer {
90
  WriteWrap* req_wrap = nullptr;
91
  uv_buf_t buf;
92
93
66036
  inline explicit nghttp2_stream_write(uv_buf_t buf_) : buf(buf_) {}
94
19788
  inline nghttp2_stream_write(WriteWrap* req, uv_buf_t buf_) :
95
19788
      req_wrap(req), buf(buf_) {}
96
97
  void MemoryInfo(MemoryTracker* tracker) const override;
98
2
  SET_MEMORY_INFO_NAME(nghttp2_stream_write)
99
2
  SET_SELF_SIZE(nghttp2_stream_write)
100
};
101
102
191244
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
553
  ~Http2Options() {
375
553
    nghttp2_option_del(options_);
376
553
  }
377
378
553
  nghttp2_option* operator*() const {
379
553
    return options_;
380
  }
381
382
3
  void SetMaxHeaderPairs(uint32_t max) {
383
3
    max_header_pairs_ = max;
384
3
  }
385
386
553
  uint32_t GetMaxHeaderPairs() const {
387
553
    return max_header_pairs_;
388
  }
389
390
4
  void SetPaddingStrategy(padding_strategy_type val) {
391
4
    padding_strategy_ = val;
392
4
  }
393
394
553
  padding_strategy_type GetPaddingStrategy() const {
395
553
    return padding_strategy_;
396
  }
397
398
2
  void SetMaxOutstandingPings(size_t max) {
399
2
    max_outstanding_pings_ = max;
400
2
  }
401
402
553
  size_t GetMaxOutstandingPings() {
403
553
    return max_outstanding_pings_;
404
  }
405
406
2
  void SetMaxOutstandingSettings(size_t max) {
407
2
    max_outstanding_settings_ = max;
408
2
  }
409
410
553
  size_t GetMaxOutstandingSettings() {
411
553
    return max_outstanding_settings_;
412
  }
413
414
2
  void SetMaxSessionMemory(uint64_t max) {
415
2
    max_session_memory_ = max;
416
2
  }
417
418
553
  uint64_t GetMaxSessionMemory() {
419
553
    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
10610
  nghttp2_priority_spec* operator*() {
439
10610
    return &spec;
440
  }
441
 private:
442
  nghttp2_priority_spec spec;
443
};
444
445
42440
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
118808
  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
330589
  inline bool IsDestroyed() const {
511
330589
    return flags_ & NGHTTP2_STREAM_FLAG_DESTROYED;
512
  }
513
514
39411
  inline bool IsWritable() const {
515
39411
    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
10339
  inline bool IsReading() const {
534

20642
    return flags_ & NGHTTP2_STREAM_FLAG_READ_START &&
535
20642
           !(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
120617
  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
21108
  inline std::vector<nghttp2_header> move_headers() {
550
21108
    return std::move(current_headers_);
551
  }
552
553
21108
  inline nghttp2_headers_category headers_category() const {
554
21108
    return current_headers_category_;
555
  }
556
557
  void StartHeaders(nghttp2_headers_category category);
558
559
  // Required for StreamBase
560
44421
  bool IsAlive() override {
561
44421
    return true;
562
  }
563
564
  // Required for StreamBase
565
  bool IsClosing() override {
566
    return false;
567
  }
568
569
47263
  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
21162
  nghttp2_data_provider* operator*() {
655
21162
    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
21162
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
27700
  inline StreamBase* underlying_stream() {
696
27700
    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
21220
  inline nghttp2_session* session() const { return session_; }
725
726
184016
  inline nghttp2_session* operator*() { return session_; }
727
728
21220
  inline uint32_t GetMaxHeaderPairs() const { return max_header_pairs_; }
729
730
  inline const char* TypeName() const;
731
732
57270
  inline bool IsDestroyed() {
733

57270
    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
21214
  inline bool HasPendingRstStream(int32_t stream_id) {
780
42428
    return pending_rst_streams_.end() != std::find(pending_rst_streams_.begin(),
781
                                                   pending_rst_streams_.end(),
782
63642
                                                   stream_id);
783
  }
784
785
  // Handle reads/writes from the underlying network transport.
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
69319
  void IncrementCurrentSessionMemory(uint64_t amount) {
817
69319
    current_session_memory_ += amount;
818
69319
  }
819
820
59642
  void DecrementCurrentSessionMemory(uint64_t amount) {
821
59642
    current_session_memory_ -= amount;
822
59642
  }
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
74338
  uint64_t GetCurrentSessionMemory() {
831
74338
    uint64_t total = current_session_memory_ + sizeof(Http2Session);
832
74338
    total += current_nghttp2_memory_;
833
74338
    total += outgoing_storage_.size();
834
74338
    return total;
835
  }
836
837
  // Return true if current_session_memory + amount is less than the max
838
74338
  bool IsAvailableSessionMemory(uint64_t amount) {
839
74338
    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(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
1137
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
21640
  explicit ExternalHeader(nghttp2_rcbuf* buf)
1144
21640
     : buf_(buf), vec_(nghttp2_rcbuf_get_buf(buf)) {
1145
21640
  }
1146
1147
64920
  ~ExternalHeader() override {
1148
21640
    nghttp2_rcbuf_decref(buf_);
1149
21640
    buf_ = nullptr;
1150
43280
  }
1151
1152
43405
  const char* data() const override {
1153
43405
    return const_cast<const char*>(reinterpret_cast<char*>(vec_.base));
1154
  }
1155
1156
86560
  size_t length() const override {
1157
86560
    return vec_.len;
1158
  }
1159
1160
  static inline
1161
1749
  MaybeLocal<String> GetInternalizedString(Environment* env,
1162
                                           const nghttp2_vec& vec) {
1163
    return String::NewFromOneByte(env->isolate(),
1164
                                  vec.base,
1165
                                  v8::NewStringType::kInternalized,
1166
1749
                                  vec.len);
1167
  }
1168
1169
  template <bool may_internalize>
1170
127234
  static MaybeLocal<String> New(Http2Session* session, nghttp2_rcbuf* buf) {
1171
127234
    Environment* env = session->env();
1172

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

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

21695
    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
21640
    session->StopTrackingRcbuf(buf);
1199
21640
    ExternalHeader* h_str = new ExternalHeader(buf);
1200
21640
    MaybeLocal<String> str = String::NewExternalOneByte(env->isolate(), h_str);
1201

21640
    if (str.IsEmpty())
1202
      delete h_str;
1203
1204
21640
    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
21180
  ~Headers() {}
1216
1217
21180
  nghttp2_nv* operator*() {
1218
21180
    return reinterpret_cast<nghttp2_nv*>(*buf_);
1219
  }
1220
1221
21214
  size_t length() const {
1222
21214
    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_