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: 0 178 0.0 %
Date: 2019-02-01 22:03:38 Branches: 0 50 0.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
struct nghttp2_stream_write : public MemoryRetainer {
90
  WriteWrap* req_wrap = nullptr;
91
  uv_buf_t buf;
92
93
  inline explicit nghttp2_stream_write(uv_buf_t buf_) : buf(buf_) {}
94
  inline nghttp2_stream_write(WriteWrap* req, uv_buf_t buf_) :
95
      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
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
  ~Http2Options() {
375
    nghttp2_option_del(options_);
376
  }
377
378
  nghttp2_option* operator*() const {
379
    return options_;
380
  }
381
382
  void SetMaxHeaderPairs(uint32_t max) {
383
    max_header_pairs_ = max;
384
  }
385
386
  uint32_t GetMaxHeaderPairs() const {
387
    return max_header_pairs_;
388
  }
389
390
  void SetPaddingStrategy(padding_strategy_type val) {
391
    padding_strategy_ = static_cast<padding_strategy_type>(val);
392
  }
393
394
  padding_strategy_type GetPaddingStrategy() const {
395
    return padding_strategy_;
396
  }
397
398
  void SetMaxOutstandingPings(size_t max) {
399
    max_outstanding_pings_ = max;
400
  }
401
402
  size_t GetMaxOutstandingPings() {
403
    return max_outstanding_pings_;
404
  }
405
406
  void SetMaxOutstandingSettings(size_t max) {
407
    max_outstanding_settings_ = max;
408
  }
409
410
  size_t GetMaxOutstandingSettings() {
411
    return max_outstanding_settings_;
412
  }
413
414
  void SetMaxSessionMemory(uint64_t max) {
415
    max_session_memory_ = max;
416
  }
417
418
  uint64_t GetMaxSessionMemory() {
419
    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
  nghttp2_priority_spec* operator*() {
439
    return &spec;
440
  }
441
 private:
442
  nghttp2_priority_spec spec;
443
};
444
445
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
  Http2Stream(Http2Session* session,
455
              int32_t id,
456
              nghttp2_headers_category category = NGHTTP2_HCAT_HEADERS,
457
              int options = 0);
458
  ~Http2Stream() override;
459
460
  nghttp2_stream* operator*();
461
462
  Http2Session* session() { return session_; }
463
  const Http2Session* session() const { return session_; }
464
465
  void EmitStatistics();
466
467
  // Process a Data Chunk
468
  void OnDataChunk(uv_buf_t* chunk);
469
470
471
  // Required for StreamBase
472
  int ReadStart() override;
473
474
  // Required for StreamBase
475
  int ReadStop() override;
476
477
  // Required for StreamBase
478
  int DoShutdown(ShutdownWrap* req_wrap) override;
479
480
  bool HasWantsWrite() const override { return true; }
481
482
  // Initiate a response on this stream.
483
  int SubmitResponse(nghttp2_nv* nva, size_t len, int options);
484
485
  // Submit informational headers for this stream
486
  int SubmitInfo(nghttp2_nv* nva, size_t len);
487
488
  // Submit trailing headers for this stream
489
  int SubmitTrailers(nghttp2_nv* nva, size_t len);
490
  void OnTrailers();
491
492
  // Submit a PRIORITY frame for this stream
493
  int SubmitPriority(nghttp2_priority_spec* prispec, bool silent = false);
494
495
  // Submits an RST_STREAM frame using the given code
496
  void SubmitRstStream(const uint32_t code);
497
498
  void FlushRstStream();
499
500
  // Submits a PUSH_PROMISE frame with this stream as the parent.
501
  Http2Stream* SubmitPushPromise(
502
      nghttp2_nv* nva,
503
      size_t len,
504
      int32_t* ret,
505
      int options = 0);
506
507
508
  void Close(int32_t code);
509
510
  // Destroy this stream instance and free all held memory.
511
  void Destroy();
512
513
  inline bool IsDestroyed() const {
514
    return flags_ & NGHTTP2_STREAM_FLAG_DESTROYED;
515
  }
516
517
  inline bool IsWritable() const {
518
    return !(flags_ & NGHTTP2_STREAM_FLAG_SHUT);
519
  }
520
521
  inline bool IsPaused() const {
522
    return flags_ & NGHTTP2_STREAM_FLAG_READ_PAUSED;
523
  }
524
525
  inline bool IsClosed() const {
526
    return flags_ & NGHTTP2_STREAM_FLAG_CLOSED;
527
  }
528
529
  inline bool HasTrailers() const {
530
    return flags_ & NGHTTP2_STREAM_FLAG_TRAILERS;
531
  }
532
533
  // Returns true if this stream is in the reading state, which occurs when
534
  // the NGHTTP2_STREAM_FLAG_READ_START flag has been set and the
535
  // NGHTTP2_STREAM_FLAG_READ_PAUSED flag is *not* set.
536
  inline bool IsReading() const {
537
    return flags_ & NGHTTP2_STREAM_FLAG_READ_START &&
538
           !(flags_ & NGHTTP2_STREAM_FLAG_READ_PAUSED);
539
  }
540
541
  // Returns the RST_STREAM code used to close this stream
542
  inline int32_t code() const { return code_; }
543
544
  // Returns the stream identifier for this stream
545
  inline int32_t id() const { return id_; }
546
547
  inline void IncrementAvailableOutboundLength(size_t amount);
548
  inline void DecrementAvailableOutboundLength(size_t amount);
549
550
  bool AddHeader(nghttp2_rcbuf* name, nghttp2_rcbuf* value, uint8_t flags);
551
552
  inline std::vector<nghttp2_header> move_headers() {
553
    return std::move(current_headers_);
554
  }
555
556
  inline nghttp2_headers_category headers_category() const {
557
    return current_headers_category_;
558
  }
559
560
  void StartHeaders(nghttp2_headers_category category);
561
562
  // Required for StreamBase
563
  bool IsAlive() override {
564
    return true;
565
  }
566
567
  // Required for StreamBase
568
  bool IsClosing() override {
569
    return false;
570
  }
571
572
  AsyncWrap* GetAsyncWrap() override { return this; }
573
574
  int DoWrite(WriteWrap* w, uv_buf_t* bufs, size_t count,
575
              uv_stream_t* send_handle) override;
576
577
  void MemoryInfo(MemoryTracker* tracker) const override {
578
    tracker->TrackField("current_headers", current_headers_);
579
    tracker->TrackField("queue", queue_);
580
  }
581
582
  SET_MEMORY_INFO_NAME(Http2Stream)
583
  SET_SELF_SIZE(Http2Stream)
584
585
  std::string diagnostic_name() const override;
586
587
  // JavaScript API
588
  static void GetID(const FunctionCallbackInfo<Value>& args);
589
  static void Destroy(const FunctionCallbackInfo<Value>& args);
590
  static void FlushData(const FunctionCallbackInfo<Value>& args);
591
  static void Priority(const FunctionCallbackInfo<Value>& args);
592
  static void PushPromise(const FunctionCallbackInfo<Value>& args);
593
  static void RefreshState(const FunctionCallbackInfo<Value>& args);
594
  static void Info(const FunctionCallbackInfo<Value>& args);
595
  static void Trailers(const FunctionCallbackInfo<Value>& args);
596
  static void Respond(const FunctionCallbackInfo<Value>& args);
597
  static void RstStream(const FunctionCallbackInfo<Value>& args);
598
599
  class Provider;
600
601
  struct Statistics {
602
    uint64_t start_time;
603
    uint64_t end_time;
604
    uint64_t first_header;     // Time first header was received
605
    uint64_t first_byte;       // Time first DATA frame byte was received
606
    uint64_t first_byte_sent;  // Time first DATA frame byte was sent
607
    uint64_t sent_bytes;
608
    uint64_t received_bytes;
609
  };
610
611
  Statistics statistics_ = {};
612
613
 private:
614
  Http2Session* session_ = nullptr;             // The Parent HTTP/2 Session
615
  int32_t id_ = 0;                              // The Stream Identifier
616
  int32_t code_ = NGHTTP2_NO_ERROR;             // The RST_STREAM code (if any)
617
  int flags_ = NGHTTP2_STREAM_FLAG_NONE;        // Internal state flags
618
619
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
620
  uint32_t max_header_length_ = DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE;
621
622
  // The Current Headers block... As headers are received for this stream,
623
  // they are temporarily stored here until the OnFrameReceived is called
624
  // signalling the end of the HEADERS frame
625
  nghttp2_headers_category current_headers_category_ = NGHTTP2_HCAT_HEADERS;
626
  uint32_t current_headers_length_ = 0;  // total number of octets
627
  std::vector<nghttp2_header> current_headers_;
628
629
  // This keeps track of the amount of data read from the socket while the
630
  // socket was in paused mode. When `ReadStart()` is called (and not before
631
  // then), we tell nghttp2 that we consumed that data to get proper
632
  // backpressure handling.
633
  size_t inbound_consumed_data_while_paused_ = 0;
634
635
  // Outbound Data... This is the data written by the JS layer that is
636
  // waiting to be written out to the socket.
637
  std::queue<nghttp2_stream_write> queue_;
638
  size_t available_outbound_length_ = 0;
639
640
  Http2StreamListener stream_listener_;
641
642
  friend class Http2Session;
643
};
644
645
class Http2Stream::Provider {
646
 public:
647
  Provider(Http2Stream* stream, int options);
648
  explicit Provider(int options);
649
  virtual ~Provider();
650
651
  nghttp2_data_provider* operator*() {
652
    return !empty_ ? &provider_ : nullptr;
653
  }
654
655
  class FD;
656
  class Stream;
657
 protected:
658
  nghttp2_data_provider provider_;
659
660
 private:
661
  bool empty_ = false;
662
};
663
664
class Http2Stream::Provider::Stream : public Http2Stream::Provider {
665
 public:
666
  Stream(Http2Stream* stream, int options);
667
  explicit Stream(int options);
668
669
  static ssize_t OnRead(nghttp2_session* session,
670
                        int32_t id,
671
                        uint8_t* buf,
672
                        size_t length,
673
                        uint32_t* flags,
674
                        nghttp2_data_source* source,
675
                        void* user_data);
676
};
677
678
679
class Http2Session : public AsyncWrap, public StreamListener {
680
 public:
681
  Http2Session(Environment* env,
682
               Local<Object> wrap,
683
               nghttp2_session_type type = NGHTTP2_SESSION_SERVER);
684
  ~Http2Session() override;
685
686
  class Http2Ping;
687
  class Http2Settings;
688
  class MemoryAllocatorInfo;
689
690
  void EmitStatistics();
691
692
  inline StreamBase* underlying_stream() {
693
    return static_cast<StreamBase*>(stream_);
694
  }
695
696
  void Start();
697
  void Stop();
698
  void Close(uint32_t code = NGHTTP2_NO_ERROR,
699
             bool socket_closed = false);
700
  void Consume(Local<External> external);
701
  void Unconsume();
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
711
  bool Ping(v8::Local<v8::Function> function);
712
713
  uint8_t SendPendingData();
714
715
  // Submits a new request. If the request is a success, assigned
716
  // will be a pointer to the Http2Stream instance assigned.
717
  // This only works if the session is a client session.
718
  Http2Stream* SubmitRequest(
719
      nghttp2_priority_spec* prispec,
720
      nghttp2_nv* nva,
721
      size_t len,
722
      int32_t* ret,
723
      int options = 0);
724
725
  inline nghttp2_session_type type() const { return session_type_; }
726
727
  inline nghttp2_session* session() const { return session_; }
728
729
  inline nghttp2_session* operator*() { return session_; }
730
731
  inline uint32_t GetMaxHeaderPairs() const { return max_header_pairs_; }
732
733
  inline const char* TypeName() const;
734
735
  inline bool IsDestroyed() {
736
    return (flags_ & SESSION_STATE_CLOSED) || session_ == nullptr;
737
  }
738
739
  // Schedule a write if nghttp2 indicates it wants to write to the socket.
740
  void MaybeScheduleWrite();
741
742
  // Stop reading if nghttp2 doesn't want to anymore.
743
  void MaybeStopReading();
744
745
  // Returns pointer to the stream, or nullptr if stream does not exist
746
  inline Http2Stream* FindStream(int32_t id);
747
748
  inline bool CanAddStream();
749
750
  // Adds a stream instance to this session
751
  inline void AddStream(Http2Stream* stream);
752
753
  // Removes a stream instance from this session
754
  inline void RemoveStream(Http2Stream* stream);
755
756
  // Indicates whether there currently exist outgoing buffers for this stream.
757
  bool HasWritesOnSocketForStream(Http2Stream* stream);
758
759
  // Write data to the session
760
  ssize_t Write(const uv_buf_t* bufs, size_t nbufs);
761
762
  void MemoryInfo(MemoryTracker* tracker) const override {
763
    tracker->TrackField("streams", streams_);
764
    tracker->TrackField("outstanding_pings", outstanding_pings_);
765
    tracker->TrackField("outstanding_settings", outstanding_settings_);
766
    tracker->TrackField("outgoing_buffers", outgoing_buffers_);
767
    tracker->TrackFieldWithSize("outgoing_storage", outgoing_storage_.size());
768
    tracker->TrackFieldWithSize("pending_rst_streams",
769
                                pending_rst_streams_.size() * sizeof(int32_t));
770
  }
771
772
  SET_MEMORY_INFO_NAME(Http2Session)
773
  SET_SELF_SIZE(Http2Session)
774
775
  std::string diagnostic_name() const override;
776
777
  // Schedule an RstStream for after the current write finishes.
778
  inline void AddPendingRstStream(int32_t stream_id) {
779
    pending_rst_streams_.emplace_back(stream_id);
780
  }
781
782
  inline bool HasPendingRstStream(int32_t stream_id) {
783
    return pending_rst_streams_.end() != std::find(pending_rst_streams_.begin(),
784
                                                   pending_rst_streams_.end(),
785
                                                   stream_id);
786
  }
787
788
  // Handle reads/writes from the underlying network transport.
789
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
790
  void OnStreamAfterWrite(WriteWrap* w, int status) override;
791
792
  // The JavaScript API
793
  static void New(const FunctionCallbackInfo<Value>& args);
794
  static void Consume(const FunctionCallbackInfo<Value>& args);
795
  static void Unconsume(const FunctionCallbackInfo<Value>& args);
796
  static void Destroying(const FunctionCallbackInfo<Value>& args);
797
  static void Destroy(const FunctionCallbackInfo<Value>& args);
798
  static void Settings(const FunctionCallbackInfo<Value>& args);
799
  static void Request(const FunctionCallbackInfo<Value>& args);
800
  static void SetNextStreamID(const FunctionCallbackInfo<Value>& args);
801
  static void Goaway(const FunctionCallbackInfo<Value>& args);
802
  static void UpdateChunksSent(const FunctionCallbackInfo<Value>& args);
803
  static void RefreshState(const FunctionCallbackInfo<Value>& args);
804
  static void Ping(const FunctionCallbackInfo<Value>& args);
805
  static void AltSvc(const FunctionCallbackInfo<Value>& args);
806
  static void Origin(const FunctionCallbackInfo<Value>& args);
807
808
  template <get_setting fn>
809
  static void RefreshSettings(const FunctionCallbackInfo<Value>& args);
810
811
  template <get_setting fn>
812
  static void GetSettings(const FunctionCallbackInfo<Value>& args);
813
814
  uv_loop_t* event_loop() const {
815
    return env()->event_loop();
816
  }
817
818
  Http2Ping* PopPing();
819
  bool AddPing(Http2Ping* ping);
820
821
  Http2Settings* PopSettings();
822
  bool AddSettings(Http2Settings* settings);
823
824
  void IncrementCurrentSessionMemory(uint64_t amount) {
825
    current_session_memory_ += amount;
826
  }
827
828
  void DecrementCurrentSessionMemory(uint64_t amount) {
829
    current_session_memory_ -= amount;
830
  }
831
832
  // Tell our custom memory allocator that this rcbuf is independent of
833
  // this session now, and may outlive it.
834
  void StopTrackingRcbuf(nghttp2_rcbuf* buf);
835
836
  // Returns the current session memory including memory allocated by nghttp2,
837
  // the current outbound storage queue, and pending writes.
838
  uint64_t GetCurrentSessionMemory() {
839
    uint64_t total = current_session_memory_ + sizeof(Http2Session);
840
    total += current_nghttp2_memory_;
841
    total += outgoing_storage_.size();
842
    return total;
843
  }
844
845
  // Return true if current_session_memory + amount is less than the max
846
  bool IsAvailableSessionMemory(uint64_t amount) {
847
    return GetCurrentSessionMemory() + amount <= max_session_memory_;
848
  }
849
850
  struct Statistics {
851
    uint64_t start_time;
852
    uint64_t end_time;
853
    uint64_t ping_rtt;
854
    uint64_t data_sent;
855
    uint64_t data_received;
856
    uint32_t frame_count;
857
    uint32_t frame_sent;
858
    int32_t stream_count;
859
    size_t max_concurrent_streams;
860
    double stream_average_duration;
861
  };
862
863
  Statistics statistics_ = {};
864
865
 private:
866
  // Frame Padding Strategies
867
  ssize_t OnDWordAlignedPadding(size_t frameLength,
868
                                size_t maxPayloadLen);
869
  ssize_t OnMaxFrameSizePadding(size_t frameLength,
870
                                size_t maxPayloadLen);
871
  ssize_t OnCallbackPadding(size_t frameLength,
872
                            size_t maxPayloadLen);
873
874
  // Frame Handler
875
  void HandleDataFrame(const nghttp2_frame* frame);
876
  void HandleGoawayFrame(const nghttp2_frame* frame);
877
  void HandleHeadersFrame(const nghttp2_frame* frame);
878
  void HandlePriorityFrame(const nghttp2_frame* frame);
879
  void HandleSettingsFrame(const nghttp2_frame* frame);
880
  void HandlePingFrame(const nghttp2_frame* frame);
881
  void HandleAltSvcFrame(const nghttp2_frame* frame);
882
  void HandleOriginFrame(const nghttp2_frame* frame);
883
884
  // nghttp2 callbacks
885
  static int OnBeginHeadersCallback(
886
      nghttp2_session* session,
887
      const nghttp2_frame* frame,
888
      void* user_data);
889
  static int OnHeaderCallback(
890
      nghttp2_session* session,
891
      const nghttp2_frame* frame,
892
      nghttp2_rcbuf* name,
893
      nghttp2_rcbuf* value,
894
      uint8_t flags,
895
      void* user_data);
896
  static int OnFrameReceive(
897
      nghttp2_session* session,
898
      const nghttp2_frame* frame,
899
      void* user_data);
900
  static int OnFrameNotSent(
901
      nghttp2_session* session,
902
      const nghttp2_frame* frame,
903
      int error_code,
904
      void* user_data);
905
  static int OnFrameSent(
906
      nghttp2_session* session,
907
      const nghttp2_frame* frame,
908
      void* user_data);
909
  static int OnStreamClose(
910
      nghttp2_session* session,
911
      int32_t id,
912
      uint32_t code,
913
      void* user_data);
914
  static int OnInvalidHeader(
915
      nghttp2_session* session,
916
      const nghttp2_frame* frame,
917
      nghttp2_rcbuf* name,
918
      nghttp2_rcbuf* value,
919
      uint8_t flags,
920
      void* user_data);
921
  static int OnDataChunkReceived(
922
      nghttp2_session* session,
923
      uint8_t flags,
924
      int32_t id,
925
      const uint8_t* data,
926
      size_t len,
927
      void* user_data);
928
  static ssize_t OnSelectPadding(
929
      nghttp2_session* session,
930
      const nghttp2_frame* frame,
931
      size_t maxPayloadLen,
932
      void* user_data);
933
  static int OnNghttpError(
934
      nghttp2_session* session,
935
      const char* message,
936
      size_t len,
937
      void* user_data);
938
  static int OnSendData(
939
      nghttp2_session* session,
940
      nghttp2_frame* frame,
941
      const uint8_t* framehd,
942
      size_t length,
943
      nghttp2_data_source* source,
944
      void* user_data);
945
  static int OnInvalidFrame(
946
      nghttp2_session* session,
947
      const nghttp2_frame* frame,
948
      int lib_error_code,
949
      void* user_data);
950
951
  struct Callbacks {
952
    inline explicit Callbacks(bool kHasGetPaddingCallback);
953
    inline ~Callbacks();
954
955
    nghttp2_session_callbacks* callbacks;
956
  };
957
958
  /* Use callback_struct_saved[kHasGetPaddingCallback ? 1 : 0] */
959
  static const Callbacks callback_struct_saved[2];
960
961
  // The underlying nghttp2_session handle
962
  nghttp2_session* session_;
963
964
  // The session type: client or server
965
  nghttp2_session_type session_type_;
966
967
  // The maximum number of header pairs permitted for streams on this session
968
  uint32_t max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
969
970
  // The maximum amount of memory allocated for this session
971
  uint64_t max_session_memory_ = DEFAULT_MAX_SESSION_MEMORY;
972
  uint64_t current_session_memory_ = 0;
973
  // The amount of memory allocated by nghttp2 internals
974
  uint64_t current_nghttp2_memory_ = 0;
975
976
  // The collection of active Http2Streams associated with this session
977
  std::unordered_map<int32_t, Http2Stream*> streams_;
978
979
  int flags_ = SESSION_STATE_NONE;
980
981
  // The StreamBase instance being used for i/o
982
  padding_strategy_type padding_strategy_ = PADDING_STRATEGY_NONE;
983
984
  // use this to allow timeout tracking during long-lasting writes
985
  uint32_t chunks_sent_since_last_write_ = 0;
986
987
  uv_buf_t stream_buf_ = uv_buf_init(nullptr, 0);
988
  v8::Local<v8::ArrayBuffer> stream_buf_ab_;
989
990
  size_t max_outstanding_pings_ = DEFAULT_MAX_PINGS;
991
  std::queue<Http2Ping*> outstanding_pings_;
992
993
  size_t max_outstanding_settings_ = DEFAULT_MAX_SETTINGS;
994
  std::queue<Http2Settings*> outstanding_settings_;
995
996
  std::vector<nghttp2_stream_write> outgoing_buffers_;
997
  std::vector<uint8_t> outgoing_storage_;
998
  std::vector<int32_t> pending_rst_streams_;
999
1000
  void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length);
1001
  void ClearOutgoing(int status);
1002
1003
  friend class Http2Scope;
1004
  friend class Http2StreamListener;
1005
};
1006
1007
class Http2SessionPerformanceEntry : public PerformanceEntry {
1008
 public:
1009
  Http2SessionPerformanceEntry(
1010
      Environment* env,
1011
      const Http2Session::Statistics& stats,
1012
      nghttp2_session_type type) :
1013
          PerformanceEntry(env, "Http2Session", "http2",
1014
                           stats.start_time,
1015
                           stats.end_time),
1016
          ping_rtt_(stats.ping_rtt),
1017
          data_sent_(stats.data_sent),
1018
          data_received_(stats.data_received),
1019
          frame_count_(stats.frame_count),
1020
          frame_sent_(stats.frame_sent),
1021
          stream_count_(stats.stream_count),
1022
          max_concurrent_streams_(stats.max_concurrent_streams),
1023
          stream_average_duration_(stats.stream_average_duration),
1024
          session_type_(type) { }
1025
1026
  uint64_t ping_rtt() const { return ping_rtt_; }
1027
  uint64_t data_sent() const { return data_sent_; }
1028
  uint64_t data_received() const { return data_received_; }
1029
  uint32_t frame_count() const { return frame_count_; }
1030
  uint32_t frame_sent() const { return frame_sent_; }
1031
  int32_t stream_count() const { return stream_count_; }
1032
  size_t max_concurrent_streams() const { return max_concurrent_streams_; }
1033
  double stream_average_duration() const { return stream_average_duration_; }
1034
  nghttp2_session_type type() const { return session_type_; }
1035
1036
  void Notify(Local<Value> obj) {
1037
    PerformanceEntry::Notify(env(), kind(), obj);
1038
  }
1039
1040
 private:
1041
  uint64_t ping_rtt_;
1042
  uint64_t data_sent_;
1043
  uint64_t data_received_;
1044
  uint32_t frame_count_;
1045
  uint32_t frame_sent_;
1046
  int32_t stream_count_;
1047
  size_t max_concurrent_streams_;
1048
  double stream_average_duration_;
1049
  nghttp2_session_type session_type_;
1050
};
1051
1052
class Http2StreamPerformanceEntry : public PerformanceEntry {
1053
 public:
1054
  Http2StreamPerformanceEntry(
1055
      Environment* env,
1056
      int32_t id,
1057
      const Http2Stream::Statistics& stats) :
1058
          PerformanceEntry(env, "Http2Stream", "http2",
1059
                           stats.start_time,
1060
                           stats.end_time),
1061
          id_(id),
1062
          first_header_(stats.first_header),
1063
          first_byte_(stats.first_byte),
1064
          first_byte_sent_(stats.first_byte_sent),
1065
          sent_bytes_(stats.sent_bytes),
1066
          received_bytes_(stats.received_bytes) { }
1067
1068
  int32_t id() const { return id_; }
1069
  uint64_t first_header() const { return first_header_; }
1070
  uint64_t first_byte() const { return first_byte_; }
1071
  uint64_t first_byte_sent() const { return first_byte_sent_; }
1072
  uint64_t sent_bytes() const { return sent_bytes_; }
1073
  uint64_t received_bytes() const { return received_bytes_; }
1074
1075
  void Notify(Local<Value> obj) {
1076
    PerformanceEntry::Notify(env(), kind(), obj);
1077
  }
1078
1079
 private:
1080
  int32_t id_;
1081
  uint64_t first_header_;
1082
  uint64_t first_byte_;
1083
  uint64_t first_byte_sent_;
1084
  uint64_t sent_bytes_;
1085
  uint64_t received_bytes_;
1086
};
1087
1088
class Http2Session::Http2Ping : public AsyncWrap {
1089
 public:
1090
  explicit Http2Ping(Http2Session* session);
1091
1092
  void MemoryInfo(MemoryTracker* tracker) const override {
1093
    tracker->TrackField("session", session_);
1094
  }
1095
1096
  SET_MEMORY_INFO_NAME(Http2Ping)
1097
  SET_SELF_SIZE(Http2Ping)
1098
1099
  void Send(uint8_t* payload);
1100
  void Done(bool ack, const uint8_t* payload = nullptr);
1101
1102
 private:
1103
  Http2Session* session_;
1104
  uint64_t startTime_;
1105
1106
  friend class Http2Session;
1107
};
1108
1109
// The Http2Settings class is used to parse the settings passed in for
1110
// an Http2Session, converting those into an array of nghttp2_settings_entry
1111
// structs.
1112
class Http2Session::Http2Settings : public AsyncWrap {
1113
 public:
1114
  explicit Http2Settings(Environment* env);
1115
  explicit Http2Settings(Http2Session* session);
1116
1117
  void MemoryInfo(MemoryTracker* tracker) const override {
1118
    tracker->TrackField("session", session_);
1119
  }
1120
1121
  SET_MEMORY_INFO_NAME(Http2Settings)
1122
  SET_SELF_SIZE(Http2Settings)
1123
1124
  void Send();
1125
  void Done(bool ack);
1126
1127
  // Returns a Buffer instance with the serialized SETTINGS payload
1128
  Local<Value> Pack();
1129
1130
  // Resets the default values in the settings buffer
1131
  static void RefreshDefaults(Environment* env);
1132
1133
  // Update the local or remote settings for the given session
1134
  static void Update(Environment* env,
1135
                     Http2Session* session,
1136
                     get_setting fn);
1137
1138
 private:
1139
  Http2Settings(Environment* env, Http2Session* session, uint64_t start_time);
1140
  void Init();
1141
  Http2Session* session_;
1142
  uint64_t startTime_;
1143
  size_t count_ = 0;
1144
  nghttp2_settings_entry entries_[IDX_SETTINGS_COUNT];
1145
};
1146
1147
class ExternalHeader :
1148
    public String::ExternalOneByteStringResource {
1149
 public:
1150
  explicit ExternalHeader(nghttp2_rcbuf* buf)
1151
     : buf_(buf), vec_(nghttp2_rcbuf_get_buf(buf)) {
1152
  }
1153
1154
  ~ExternalHeader() override {
1155
    nghttp2_rcbuf_decref(buf_);
1156
    buf_ = nullptr;
1157
  }
1158
1159
  const char* data() const override {
1160
    return const_cast<const char*>(reinterpret_cast<char*>(vec_.base));
1161
  }
1162
1163
  size_t length() const override {
1164
    return vec_.len;
1165
  }
1166
1167
  static inline
1168
  MaybeLocal<String> GetInternalizedString(Environment* env,
1169
                                           const nghttp2_vec& vec) {
1170
    return String::NewFromOneByte(env->isolate(),
1171
                                  vec.base,
1172
                                  v8::NewStringType::kInternalized,
1173
                                  vec.len);
1174
  }
1175
1176
  template <bool may_internalize>
1177
  static MaybeLocal<String> New(Http2Session* session, nghttp2_rcbuf* buf) {
1178
    Environment* env = session->env();
1179
    if (nghttp2_rcbuf_is_static(buf)) {
1180
      auto& static_str_map = env->isolate_data()->http2_static_strs;
1181
      v8::Eternal<v8::String>& eternal = static_str_map[buf];
1182
      if (eternal.IsEmpty()) {
1183
        Local<String> str =
1184
            GetInternalizedString(env, nghttp2_rcbuf_get_buf(buf))
1185
                .ToLocalChecked();
1186
        eternal.Set(env->isolate(), str);
1187
        return str;
1188
      }
1189
      return eternal.Get(env->isolate());
1190
    }
1191
1192
    nghttp2_vec vec = nghttp2_rcbuf_get_buf(buf);
1193
    if (vec.len == 0) {
1194
      nghttp2_rcbuf_decref(buf);
1195
      return String::Empty(env->isolate());
1196
    }
1197
1198
    if (may_internalize && vec.len < 64) {
1199
      nghttp2_rcbuf_decref(buf);
1200
      // This is a short header name, so there is a good chance V8 already has
1201
      // it internalized.
1202
      return GetInternalizedString(env, vec);
1203
    }
1204
1205
    session->StopTrackingRcbuf(buf);
1206
    ExternalHeader* h_str = new ExternalHeader(buf);
1207
    MaybeLocal<String> str = String::NewExternalOneByte(env->isolate(), h_str);
1208
    if (str.IsEmpty())
1209
      delete h_str;
1210
1211
    return str;
1212
  }
1213
1214
 private:
1215
  nghttp2_rcbuf* buf_;
1216
  nghttp2_vec vec_;
1217
};
1218
1219
class Headers {
1220
 public:
1221
  Headers(Isolate* isolate, Local<Context> context, Local<Array> headers);
1222
  ~Headers() {}
1223
1224
  nghttp2_nv* operator*() {
1225
    return reinterpret_cast<nghttp2_nv*>(*buf_);
1226
  }
1227
1228
  size_t length() const {
1229
    return count_;
1230
  }
1231
1232
 private:
1233
  size_t count_;
1234
  MaybeStackBuffer<char, 3000> buf_;
1235
};
1236
1237
class Origins {
1238
 public:
1239
  Origins(Isolate* isolate,
1240
          Local<Context> context,
1241
          Local<v8::String> origin_string,
1242
          size_t origin_count);
1243
  ~Origins() {}
1244
1245
  nghttp2_origin_entry* operator*() {
1246
    return reinterpret_cast<nghttp2_origin_entry*>(*buf_);
1247
  }
1248
1249
  size_t length() const {
1250
    return count_;
1251
  }
1252
1253
 private:
1254
  size_t count_;
1255
  MaybeStackBuffer<char, 512> buf_;
1256
};
1257
1258
}  // namespace http2
1259
}  // namespace node
1260
1261
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1262
1263
#endif  // SRC_NODE_HTTP2_H_