GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_http_parser.cc Lines: 440 467 94.2 %
Date: 2021-02-11 04:11:15 Branches: 201 272 73.9 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node.h"
23
#include "node_buffer.h"
24
#include "util.h"
25
26
#include "async_wrap-inl.h"
27
#include "env-inl.h"
28
#include "memory_tracker-inl.h"
29
#include "stream_base-inl.h"
30
#include "v8.h"
31
#include "llhttp.h"
32
33
#include <cstdlib>  // free()
34
#include <cstring>  // strdup(), strchr()
35
36
37
// This is a binding to llhttp (https://github.com/nodejs/llhttp)
38
// The goal is to decouple sockets from parsing for more javascript-level
39
// agility. A Buffer is read from a socket and passed to parser.execute().
40
// The parser then issues callbacks with slices of the data
41
//     parser.onMessageBegin
42
//     parser.onPath
43
//     parser.onBody
44
//     ...
45
// No copying is performed when slicing the buffer, only small reference
46
// allocations.
47
48
49
namespace node {
50
namespace {  // NOLINT(build/namespaces)
51
52
using v8::Array;
53
using v8::Boolean;
54
using v8::Context;
55
using v8::EscapableHandleScope;
56
using v8::Exception;
57
using v8::Function;
58
using v8::FunctionCallbackInfo;
59
using v8::FunctionTemplate;
60
using v8::HandleScope;
61
using v8::Int32;
62
using v8::Integer;
63
using v8::Local;
64
using v8::MaybeLocal;
65
using v8::Number;
66
using v8::Object;
67
using v8::String;
68
using v8::Uint32;
69
using v8::Undefined;
70
using v8::Value;
71
72
const uint32_t kOnMessageBegin = 0;
73
const uint32_t kOnHeaders = 1;
74
const uint32_t kOnHeadersComplete = 2;
75
const uint32_t kOnBody = 3;
76
const uint32_t kOnMessageComplete = 4;
77
const uint32_t kOnExecute = 5;
78
const uint32_t kOnTimeout = 6;
79
// Any more fields than this will be flushed into JS
80
const size_t kMaxHeaderFieldsCount = 32;
81
82
17206
inline bool IsOWS(char c) {
83

17206
  return c == ' ' || c == '\t';
84
}
85
86
1452
class BindingData : public BaseObject {
87
 public:
88
753
  BindingData(Environment* env, Local<Object> obj)
89
753
      : BaseObject(env, obj) {}
90
91
  static constexpr FastStringKey type_name { "http_parser" };
92
93
  std::vector<char> parser_buffer;
94
  bool parser_buffer_in_use = false;
95
96
3
  void MemoryInfo(MemoryTracker* tracker) const override {
97
3
    tracker->TrackField("parser_buffer", parser_buffer);
98
3
  }
99
3
  SET_SELF_SIZE(BindingData)
100
3
  SET_MEMORY_INFO_NAME(BindingData)
101
};
102
103
// TODO(addaleax): Remove once we're on C++17.
104
constexpr FastStringKey BindingData::type_name;
105
106
// helper class for the Parser
107
struct StringPtr {
108
238458
  StringPtr() {
109
238458
    on_heap_ = false;
110
238458
    Reset();
111
238458
  }
112
113
114
472824
  ~StringPtr() {
115
236412
    Reset();
116
236412
  }
117
118
119
  // If str_ does not point to a heap string yet, this function makes it do
120
  // so. This is called at the end of each http_parser_execute() so as not
121
  // to leak references. See issue #2438 and test-http-parser-bad-ref.js.
122
14731
  void Save() {
123

14731
    if (!on_heap_ && size_ > 0) {
124
5968
      char* s = new char[size_];
125
5968
      memcpy(s, str_, size_);
126
5968
      str_ = s;
127
5968
      on_heap_ = true;
128
    }
129
14731
  }
130
131
132
555531
  void Reset() {
133
555531
    if (on_heap_) {
134
5935
      delete[] str_;
135
5935
      on_heap_ = false;
136
    }
137
138
555531
    str_ = nullptr;
139
555531
    size_ = 0;
140
555531
  }
141
142
143
51543
  void Update(const char* str, size_t size) {
144
51543
    if (str_ == nullptr) {
145
51480
      str_ = str;
146

63
    } else if (on_heap_ || str_ + size_ != str) {
147
      // Non-consecutive input, make a copy on the heap.
148
      // TODO(bnoordhuis) Use slab allocation, O(n) allocs is bad.
149
63
      char* s = new char[size_ + size];
150
63
      memcpy(s, str_, size_);
151
63
      memcpy(s + size_, str, size);
152
153
63
      if (on_heap_)
154
62
        delete[] str_;
155
      else
156
1
        on_heap_ = true;
157
158
63
      str_ = s;
159
    }
160
51543
    size_ += size;
161
51543
  }
162
163
164
51395
  Local<String> ToString(Environment* env) const {
165
51395
    if (size_ != 0)
166
51331
      return OneByteString(env->isolate(), str_, size_);
167
    else
168
128
      return String::Empty(env->isolate());
169
  }
170
171
172
  // Strip trailing OWS (SPC or HTAB) from string.
173
17208
  Local<String> ToTrimmedString(Environment* env) {
174

17219
    while (size_ > 0 && IsOWS(str_[size_ - 1])) {
175
11
      size_--;
176
    }
177
17197
    return ToString(env);
178
  }
179
180
181
  const char* str_;
182
  bool on_heap_;
183
  size_t size_;
184
};
185
186


7164
class Parser : public AsyncWrap, public StreamListener {
187
 public:
188
3613
  Parser(BindingData* binding_data, Local<Object> wrap)
189
3613
      : AsyncWrap(binding_data->env(), wrap),
190
        current_buffer_len_(0),
191
        current_buffer_data_(nullptr),
192

7226
        binding_data_(binding_data) {
193
3613
  }
194
195
196
  void MemoryInfo(MemoryTracker* tracker) const override {
197
    tracker->TrackField("current_buffer", current_buffer_);
198
  }
199
200
  SET_MEMORY_INFO_NAME(Parser)
201
  SET_SELF_SIZE(Parser)
202
203
16988
  int on_message_begin() {
204
16988
    num_fields_ = num_values_ = 0;
205
16988
    url_.Reset();
206
16988
    status_message_.Reset();
207
16988
    header_parsing_start_time_ = uv_hrtime();
208
209
50964
    Local<Value> cb = object()->Get(env()->context(), kOnMessageBegin)
210
16988
                              .ToLocalChecked();
211
16988
    if (cb->IsFunction()) {
212
      InternalCallbackScope callback_scope(
213
27668
        this, InternalCallbackScope::kSkipTaskQueues);
214
215
27668
      MaybeLocal<Value> r = cb.As<Function>()->Call(
216
55336
        env()->context(), object(), 0, nullptr);
217
218
13834
      if (r.IsEmpty()) callback_scope.MarkAsFailed();
219
    }
220
221
16988
    return 0;
222
  }
223
224
225
13909
  int on_url(const char* at, size_t length) {
226
13909
    int rv = TrackHeader(length);
227
13909
    if (rv != 0) {
228
      return rv;
229
    }
230
231
13909
    url_.Update(at, length);
232
13909
    return 0;
233
  }
234
235
236
3069
  int on_status(const char* at, size_t length) {
237
3069
    int rv = TrackHeader(length);
238
3069
    if (rv != 0) {
239
      return rv;
240
    }
241
242
3069
    status_message_.Update(at, length);
243
3069
    return 0;
244
  }
245
246
247
17295
  int on_header_field(const char* at, size_t length) {
248
17295
    int rv = TrackHeader(length);
249
17295
    if (rv != 0) {
250
      return rv;
251
    }
252
253
17295
    if (num_fields_ == num_values_) {
254
      // start of new field name
255
17266
      num_fields_++;
256
17266
      if (num_fields_ == kMaxHeaderFieldsCount) {
257
        // ran out of space - flush to javascript land
258
47
        Flush();
259
47
        num_fields_ = 1;
260
47
        num_values_ = 0;
261
      }
262
17266
      fields_[num_fields_ - 1].Reset();
263
    }
264
265
17295
    CHECK_LT(num_fields_, kMaxHeaderFieldsCount);
266
17295
    CHECK_EQ(num_fields_, num_values_ + 1);
267
268
17295
    fields_[num_fields_ - 1].Update(at, length);
269
270
17295
    return 0;
271
  }
272
273
274
17285
  int on_header_value(const char* at, size_t length) {
275
17285
    int rv = TrackHeader(length);
276
17285
    if (rv != 0) {
277
15
      return rv;
278
    }
279
280
17270
    if (num_values_ != num_fields_) {
281
      // start of new header value
282
17244
      num_values_++;
283
17244
      values_[num_values_ - 1].Reset();
284
    }
285
286
17270
    CHECK_LT(num_values_, arraysize(values_));
287
17270
    CHECK_EQ(num_values_, num_fields_);
288
289
17270
    values_[num_values_ - 1].Update(at, length);
290
291
17270
    return 0;
292
  }
293
294
295
16942
  int on_headers_complete() {
296
16942
    header_nread_ = 0;
297
16942
    header_parsing_start_time_ = 0;
298
299
    // Arguments for the on-headers-complete javascript callback. This
300
    // list needs to be kept in sync with the actual argument list for
301
    // `parserOnHeadersComplete` in lib/_http_common.js.
302
    enum on_headers_complete_arg_index {
303
      A_VERSION_MAJOR = 0,
304
      A_VERSION_MINOR,
305
      A_HEADERS,
306
      A_METHOD,
307
      A_URL,
308
      A_STATUS_CODE,
309
      A_STATUS_MESSAGE,
310
      A_UPGRADE,
311
      A_SHOULD_KEEP_ALIVE,
312
      A_MAX
313
    };
314
315
169420
    Local<Value> argv[A_MAX];
316
16942
    Local<Object> obj = object();
317
33884
    Local<Value> cb = obj->Get(env()->context(),
318
50826
                               kOnHeadersComplete).ToLocalChecked();
319
320
16942
    if (!cb->IsFunction())
321
      return 0;
322
323
16942
    Local<Value> undefined = Undefined(env()->isolate());
324
169420
    for (size_t i = 0; i < arraysize(argv); i++)
325
152478
      argv[i] = undefined;
326
327
16942
    if (have_flushed_) {
328
      // Slow case, flush remaining headers.
329
16
      Flush();
330
    } else {
331
      // Fast case, pass headers and URL to JS land.
332
33852
      argv[A_HEADERS] = CreateHeaders();
333
16926
      if (parser_.type == HTTP_REQUEST)
334
27744
        argv[A_URL] = url_.ToString(env());
335
    }
336
337
16942
    num_fields_ = 0;
338
16942
    num_values_ = 0;
339
340
    // METHOD
341
16942
    if (parser_.type == HTTP_REQUEST) {
342
13880
      argv[A_METHOD] =
343
27760
          Uint32::NewFromUnsigned(env()->isolate(), parser_.method);
344
    }
345
346
    // STATUS
347
16942
    if (parser_.type == HTTP_RESPONSE) {
348
3062
      argv[A_STATUS_CODE] =
349
6124
          Integer::New(env()->isolate(), parser_.status_code);
350
6124
      argv[A_STATUS_MESSAGE] = status_message_.ToString(env());
351
    }
352
353
    // VERSION
354
33884
    argv[A_VERSION_MAJOR] = Integer::New(env()->isolate(), parser_.http_major);
355
33884
    argv[A_VERSION_MINOR] = Integer::New(env()->isolate(), parser_.http_minor);
356
357
    bool should_keep_alive;
358
16942
    should_keep_alive = llhttp_should_keep_alive(&parser_);
359
360
16942
    argv[A_SHOULD_KEEP_ALIVE] =
361
33884
        Boolean::New(env()->isolate(), should_keep_alive);
362
363
33884
    argv[A_UPGRADE] = Boolean::New(env()->isolate(), parser_.upgrade);
364
365
    MaybeLocal<Value> head_response;
366
    {
367
      InternalCallbackScope callback_scope(
368
16940
          this, InternalCallbackScope::kSkipTaskQueues);
369
33882
      head_response = cb.As<Function>()->Call(
370
67766
          env()->context(), object(), arraysize(argv), argv);
371
16940
      if (head_response.IsEmpty()) callback_scope.MarkAsFailed();
372
    }
373
374
    int64_t val;
375
376

67744
    if (head_response.IsEmpty() || !head_response.ToLocalChecked()
377
50804
                                        ->IntegerValue(env()->context())
378
16932
                                        .To(&val)) {
379
8
      got_exception_ = true;
380
8
      return -1;
381
    }
382
383
16932
    return static_cast<int>(val);
384
  }
385
386
387
11133
  int on_body(const char* at, size_t length) {
388
11133
    EscapableHandleScope scope(env()->isolate());
389
390
11133
    Local<Object> obj = object();
391
33399
    Local<Value> cb = obj->Get(env()->context(), kOnBody).ToLocalChecked();
392
393
11133
    if (!cb->IsFunction())
394
      return 0;
395
396
    // We came from consumed stream
397
22266
    if (current_buffer_.IsEmpty()) {
398
      // Make sure Buffer will be in parent HandleScope
399
1064
      current_buffer_ = scope.Escape(Buffer::Copy(
400
          env()->isolate(),
401
          current_buffer_data_,
402
1064
          current_buffer_len_).ToLocalChecked());
403
    }
404
405
    Local<Value> argv[3] = {
406
        current_buffer_,
407
        Integer::NewFromUnsigned(
408
11133
            env()->isolate(), static_cast<uint32_t>(at - current_buffer_data_)),
409
55665
        Integer::NewFromUnsigned(env()->isolate(), length)};
410
411
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
412
11133
                                       arraysize(argv),
413
22266
                                       argv);
414
415
11133
    if (r.IsEmpty()) {
416
      got_exception_ = true;
417
      llhttp_set_error_reason(&parser_, "HPE_JS_EXCEPTION:JS Exception");
418
      return HPE_USER;
419
    }
420
421
11133
    return 0;
422
  }
423
424
425
15734
  int on_message_complete() {
426
31468
    HandleScope scope(env()->isolate());
427
428
15734
    if (num_fields_)
429
4
      Flush();  // Flush trailing HTTP headers.
430
431
15734
    Local<Object> obj = object();
432
31468
    Local<Value> cb = obj->Get(env()->context(),
433
47202
                               kOnMessageComplete).ToLocalChecked();
434
435
15734
    if (!cb->IsFunction())
436
2
      return 0;
437
438
    MaybeLocal<Value> r;
439
    {
440
      InternalCallbackScope callback_scope(
441
31464
          this, InternalCallbackScope::kSkipTaskQueues);
442
62928
      r = cb.As<Function>()->Call(env()->context(), object(), 0, nullptr);
443
15732
      if (r.IsEmpty()) callback_scope.MarkAsFailed();
444
    }
445
446
15732
    if (r.IsEmpty()) {
447
      got_exception_ = true;
448
      return -1;
449
    }
450
451
15732
    return 0;
452
  }
453
454
  // Reset nread for the next chunk
455
10926
  int on_chunk_header() {
456
10926
    header_nread_ = 0;
457
10926
    return 0;
458
  }
459
460
461
  // Reset nread for the next chunk
462
10772
  int on_chunk_complete() {
463
10772
    header_nread_ = 0;
464
10772
    return 0;
465
  }
466
467
3613
  static void New(const FunctionCallbackInfo<Value>& args) {
468
3613
    BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
469
3613
    new Parser(binding_data, args.This());
470
3613
  }
471
472
473
3
  static void Close(const FunctionCallbackInfo<Value>& args) {
474
    Parser* parser;
475
3
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
476
477
3
    delete parser;
478
  }
479
480
481
5858
  static void Free(const FunctionCallbackInfo<Value>& args) {
482
    Parser* parser;
483
5858
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
484
485
    // Since the Parser destructor isn't going to run the destroy() callbacks
486
    // it needs to be triggered manually.
487
5858
    parser->EmitTraceEventDestroy();
488
5858
    parser->EmitDestroy();
489
  }
490
491
492
7193
  void Save() {
493
7193
    url_.Save();
494
7193
    status_message_.Save();
495
496
7395
    for (size_t i = 0; i < num_fields_; i++) {
497
202
      fields_[i].Save();
498
    }
499
500
7336
    for (size_t i = 0; i < num_values_; i++) {
501
143
      values_[i].Save();
502
    }
503
7193
  }
504
505
506
  // var bytesParsed = parser->execute(buffer);
507
3228
  static void Execute(const FunctionCallbackInfo<Value>& args) {
508
    Parser* parser;
509
3228
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
510
6456
    CHECK(parser->current_buffer_.IsEmpty());
511
3228
    CHECK_EQ(parser->current_buffer_len_, 0);
512
3228
    CHECK_NULL(parser->current_buffer_data_);
513
514
3228
    ArrayBufferViewContents<char> buffer(args[0]);
515
516
    // This is a hack to get the current_buffer to the callbacks with the least
517
    // amount of overhead. Nothing else will run while http_parser_execute()
518
    // runs, therefore this pointer can be set and used for the execution.
519
9684
    parser->current_buffer_ = args[0].As<Object>();
520
521
3228
    Local<Value> ret = parser->Execute(buffer.data(), buffer.length());
522
523
3227
    if (!ret.IsEmpty())
524
6448
      args.GetReturnValue().Set(ret);
525
  }
526
527
528
929
  static void Finish(const FunctionCallbackInfo<Value>& args) {
529
    Parser* parser;
530
929
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
531
532
1858
    CHECK(parser->current_buffer_.IsEmpty());
533
929
    Local<Value> ret = parser->Execute(nullptr, 0);
534
535
929
    if (!ret.IsEmpty())
536
64
      args.GetReturnValue().Set(ret);
537
  }
538
539
540
6054
  static void Initialize(const FunctionCallbackInfo<Value>& args) {
541
6054
    Environment* env = Environment::GetCurrent(args);
542
12108
    bool lenient = args[3]->IsTrue();
543
544
6054
    uint64_t max_http_header_size = 0;
545
6054
    uint64_t headers_timeout = 0;
546
547
12108
    CHECK(args[0]->IsInt32());
548
12108
    CHECK(args[1]->IsObject());
549
550
6054
    if (args.Length() > 2) {
551
9768
      CHECK(args[2]->IsNumber());
552
4884
      max_http_header_size =
553
19536
          static_cast<uint64_t>(args[2].As<Number>()->Value());
554
    }
555
6054
    if (max_http_header_size == 0) {
556
6052
      max_http_header_size = env->options()->max_http_header_size;
557
    }
558
559
6054
    if (args.Length() > 4) {
560
9768
      CHECK(args[4]->IsInt32());
561
14652
      headers_timeout = args[4].As<Int32>()->Value();
562
    }
563
564
    llhttp_type_t type =
565
18162
        static_cast<llhttp_type_t>(args[0].As<Int32>()->Value());
566
567

6054
    CHECK(type == HTTP_REQUEST || type == HTTP_RESPONSE);
568
    Parser* parser;
569
6054
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
570
    // Should always be called from the same context.
571
6054
    CHECK_EQ(env, parser->env());
572
573
    AsyncWrap::ProviderType provider =
574
6054
        (type == HTTP_REQUEST ?
575
            AsyncWrap::PROVIDER_HTTPINCOMINGMESSAGE
576
6054
            : AsyncWrap::PROVIDER_HTTPCLIENTREQUEST);
577
578
6054
    parser->set_provider_type(provider);
579
12108
    parser->AsyncReset(args[1].As<Object>());
580
6054
    parser->Init(type, max_http_header_size, lenient, headers_timeout);
581
  }
582
583
  template <bool should_pause>
584
11
  static void Pause(const FunctionCallbackInfo<Value>& args) {
585
11
    Environment* env = Environment::GetCurrent(args);
586
    Parser* parser;
587

15
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
588
    // Should always be called from the same context.
589

11
    CHECK_EQ(env, parser->env());
590
591

11
    if (parser->execute_depth_) {
592
4
      parser->pending_pause_ = should_pause;
593
4
      return;
594
    }
595
596
    if (should_pause) {
597
4
      llhttp_pause(&parser->parser_);
598
    } else {
599
3
      llhttp_resume(&parser->parser_);
600
    }
601
  }
602
603
604
3228
  static void Consume(const FunctionCallbackInfo<Value>& args) {
605
    Parser* parser;
606
3228
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
607
6456
    CHECK(args[0]->IsObject());
608
6456
    StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
609
3228
    CHECK_NOT_NULL(stream);
610
3228
    stream->PushStreamListener(parser);
611
  }
612
613
614
3218
  static void Unconsume(const FunctionCallbackInfo<Value>& args) {
615
    Parser* parser;
616
3218
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
617
618
    // Already unconsumed
619
3218
    if (parser->stream_ == nullptr)
620
      return;
621
622
3218
    parser->stream_->RemoveStreamListener(parser);
623
  }
624
625
626
52
  static void GetCurrentBuffer(const FunctionCallbackInfo<Value>& args) {
627
    Parser* parser;
628
52
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
629
630
104
    Local<Object> ret = Buffer::Copy(
631
        parser->env(),
632
        parser->current_buffer_data_,
633
104
        parser->current_buffer_len_).ToLocalChecked();
634
635
104
    args.GetReturnValue().Set(ret);
636
  }
637
638
 protected:
639
  static const size_t kAllocBufferSize = 64 * 1024;
640
641
4198
  uv_buf_t OnStreamAlloc(size_t suggested_size) override {
642
    // For most types of streams, OnStreamRead will be immediately after
643
    // OnStreamAlloc, and will consume all data, so using a static buffer for
644
    // reading is more efficient. For other streams, just use Malloc() directly.
645
4198
    if (binding_data_->parser_buffer_in_use)
646
      return uv_buf_init(Malloc(suggested_size), suggested_size);
647
4198
    binding_data_->parser_buffer_in_use = true;
648
649
4198
    if (binding_data_->parser_buffer.empty())
650
333
      binding_data_->parser_buffer.resize(kAllocBufferSize);
651
652
4198
    return uv_buf_init(binding_data_->parser_buffer.data(), kAllocBufferSize);
653
  }
654
655
656
4219
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override {
657
7169
    HandleScope scope(env()->isolate());
658
    // Once we’re done here, either indicate that the HTTP parser buffer
659
    // is free for re-use, or free() the data if it didn’t come from there
660
    // in the first place.
661
4215
    auto on_scope_leave = OnScopeLeave([&]() {
662
4234
      if (buf.base == binding_data_->parser_buffer.data())
663
4196
        binding_data_->parser_buffer_in_use = false;
664
      else
665
19
        free(buf.base);
666
11384
    });
667
668
4219
    if (nread < 0) {
669
252
      PassReadErrorToPreviousListener(nread);
670
252
      return;
671
    }
672
673
    // Ignore, empty reads have special meaning in http parser
674
3967
    if (nread == 0)
675
      return;
676
677
3967
    current_buffer_.Clear();
678
3967
    Local<Value> ret = Execute(buf.base, nread);
679
680
    // Exception
681
3966
    if (ret.IsEmpty())
682
5
      return;
683
684
    // check header parsing time
685

3961
    if (header_parsing_start_time_ != 0 && headers_timeout_ != 0) {
686
42
      uint64_t now = uv_hrtime();
687
42
      uint64_t parsing_time = (now - header_parsing_start_time_) / 1000000;
688
689
42
      if (parsing_time > headers_timeout_) {
690
        Local<Value> cb =
691
18
            object()->Get(env()->context(), kOnTimeout).ToLocalChecked();
692
693
6
        if (!cb->IsFunction())
694
          return;
695
696
6
        MakeCallback(cb.As<Function>(), 0, nullptr);
697
698
6
        return;
699
      }
700
    }
701
702
    Local<Value> cb =
703
11865
        object()->Get(env()->context(), kOnExecute).ToLocalChecked();
704
705
3955
    if (!cb->IsFunction())
706
1002
      return;
707
708
    // Hooks for GetCurrentBuffer
709
2953
    current_buffer_len_ = nread;
710
2953
    current_buffer_data_ = buf.base;
711
712
2953
    MakeCallback(cb.As<Function>(), 1, &ret);
713
714
2950
    current_buffer_len_ = 0;
715
2950
    current_buffer_data_ = nullptr;
716
  }
717
718
719
8124
  Local<Value> Execute(const char* data, size_t len) {
720
8124
    EscapableHandleScope scope(env()->isolate());
721
722
8124
    current_buffer_len_ = len;
723
8124
    current_buffer_data_ = data;
724
8124
    got_exception_ = false;
725
726
    llhttp_errno_t err;
727
728
    // Do not allow re-entering `http_parser_execute()`
729
8124
    CHECK_EQ(execute_depth_, 0);
730
731
8124
    execute_depth_++;
732
8124
    if (data == nullptr) {
733
929
      err = llhttp_finish(&parser_);
734
    } else {
735
7195
      err = llhttp_execute(&parser_, data, len);
736
7193
      Save();
737
    }
738
8122
    execute_depth_--;
739
740
    // Calculate bytes read and resume after Upgrade/CONNECT pause
741
8122
    size_t nread = len;
742
8122
    if (err != HPE_OK) {
743
334
      nread = llhttp_get_error_pos(&parser_) - data;
744
745
      // This isn't a real pause, just a way to stop parsing early.
746
334
      if (err == HPE_PAUSED_UPGRADE) {
747
53
        err = HPE_OK;
748
53
        llhttp_resume_after_upgrade(&parser_);
749
      }
750
    }
751
752
    // Apply pending pause
753
8122
    if (pending_pause_) {
754
      pending_pause_ = false;
755
      llhttp_pause(&parser_);
756
    }
757
758
    // Unassign the 'buffer_' variable
759
8122
    current_buffer_.Clear();
760
8122
    current_buffer_len_ = 0;
761
8122
    current_buffer_data_ = nullptr;
762
763
    // If there was an exception in one of the callbacks
764
8122
    if (got_exception_)
765
8
      return scope.Escape(Local<Value>());
766
767
8114
    Local<Integer> nread_obj = Integer::New(env()->isolate(), nread);
768
769
    // If there was a parse error in one of the callbacks
770
    // TODO(bnoordhuis) What if there is an error on EOF?
771

8114
    if (!parser_.upgrade && err != HPE_OK) {
772
220
      Local<Value> e = Exception::Error(env()->parse_error_string());
773
660
      Local<Object> obj = e->ToObject(env()->isolate()->GetCurrentContext())
774
220
        .ToLocalChecked();
775
440
      obj->Set(env()->context(),
776
               env()->bytes_parsed_string(),
777
880
               nread_obj).Check();
778
220
      const char* errno_reason = llhttp_get_error_reason(&parser_);
779
780
      Local<String> code;
781
      Local<String> reason;
782
220
      if (err == HPE_USER) {
783
15
        const char* colon = strchr(errno_reason, ':');
784
15
        CHECK_NOT_NULL(colon);
785
        code = OneByteString(env()->isolate(),
786
                             errno_reason,
787
15
                             static_cast<int>(colon - errno_reason));
788
15
        reason = OneByteString(env()->isolate(), colon + 1);
789
      } else {
790
205
        code = OneByteString(env()->isolate(), llhttp_errno_name(err));
791
205
        reason = OneByteString(env()->isolate(), errno_reason);
792
      }
793
794
880
      obj->Set(env()->context(), env()->code_string(), code).Check();
795
880
      obj->Set(env()->context(), env()->reason_string(), reason).Check();
796
      return scope.Escape(e);
797
    }
798
799
    // No return value is needed for `Finish()`
800
7894
    if (data == nullptr) {
801
897
      return scope.Escape(Local<Value>());
802
    }
803
6997
    return scope.Escape(nread_obj);
804
  }
805
806
16993
  Local<Array> CreateHeaders() {
807
    // There could be extra entries but the max size should be fixed
808
1104545
    Local<Value> headers_v[kMaxHeaderFieldsCount * 2];
809
810
34190
    for (size_t i = 0; i < num_values_; ++i) {
811
34394
      headers_v[i * 2] = fields_[i].ToString(env());
812
34394
      headers_v[i * 2 + 1] = values_[i].ToTrimmedString(env());
813
    }
814
815
16993
    return Array::New(env()->isolate(), headers_v, num_values_ * 2);
816
  }
817
818
819
  // spill headers and request path to JS land
820
67
  void Flush() {
821
134
    HandleScope scope(env()->isolate());
822
823
67
    Local<Object> obj = object();
824
201
    Local<Value> cb = obj->Get(env()->context(), kOnHeaders).ToLocalChecked();
825
826
67
    if (!cb->IsFunction())
827
      return;
828
829
    Local<Value> argv[2] = {
830
      CreateHeaders(),
831
      url_.ToString(env())
832
201
    };
833
834
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
835
67
                                       arraysize(argv),
836
134
                                       argv);
837
838
67
    if (r.IsEmpty())
839
      got_exception_ = true;
840
841
67
    url_.Reset();
842
67
    have_flushed_ = true;
843
  }
844
845
846
6054
  void Init(llhttp_type_t type, uint64_t max_http_header_size,
847
            bool lenient, uint64_t headers_timeout) {
848
6054
    llhttp_init(&parser_, type, &settings);
849
6054
    llhttp_set_lenient(&parser_, lenient);
850
6054
    header_nread_ = 0;
851
6054
    url_.Reset();
852
6054
    status_message_.Reset();
853
6054
    num_fields_ = 0;
854
6054
    num_values_ = 0;
855
6054
    have_flushed_ = false;
856
6054
    got_exception_ = false;
857
6054
    max_http_header_size_ = max_http_header_size;
858
6054
    header_parsing_start_time_ = 0;
859
6054
    headers_timeout_ = headers_timeout;
860
6054
  }
861
862
863
51558
  int TrackHeader(size_t len) {
864
51558
    header_nread_ += len;
865
51558
    if (header_nread_ >= max_http_header_size_) {
866
15
      llhttp_set_error_reason(&parser_, "HPE_HEADER_OVERFLOW:Header overflow");
867
15
      return HPE_USER;
868
    }
869
51543
    return 0;
870
  }
871
872
873
133902
  int MaybePause() {
874
133902
    CHECK_NE(execute_depth_, 0);
875
876
133902
    if (!pending_pause_) {
877
133902
      return 0;
878
    }
879
880
    pending_pause_ = false;
881
    llhttp_set_error_reason(&parser_, "Paused in callback");
882
    return HPE_PAUSED;
883
  }
884
885
886
  bool IsNotIndicativeOfMemoryLeakAtExit() const override {
887
    // HTTP parsers are able to emit events without any GC root referring
888
    // to them, because they receive events directly from the underlying
889
    // libuv resource.
890
    return true;
891
  }
892
893
894
  llhttp_t parser_;
895
  StringPtr fields_[kMaxHeaderFieldsCount];  // header fields
896
  StringPtr values_[kMaxHeaderFieldsCount];  // header values
897
  StringPtr url_;
898
  StringPtr status_message_;
899
  size_t num_fields_;
900
  size_t num_values_;
901
  bool have_flushed_;
902
  bool got_exception_;
903
  Local<Object> current_buffer_;
904
  size_t current_buffer_len_;
905
  const char* current_buffer_data_;
906
  unsigned int execute_depth_ = 0;
907
  bool pending_pause_ = false;
908
  uint64_t header_nread_ = 0;
909
  uint64_t max_http_header_size_;
910
  uint64_t headers_timeout_;
911
  uint64_t header_parsing_start_time_ = 0;
912
913
  BaseObjectPtr<BindingData> binding_data_;
914
915
  // These are helper functions for filling `http_parser_settings`, which turn
916
  // a member function of Parser into a C-style HTTP parser callback.
917
  template <typename Parser, Parser> struct Proxy;
918
  template <typename Parser, typename ...Args, int (Parser::*Member)(Args...)>
919
  struct Proxy<int (Parser::*)(Args...), Member> {
920
134053
    static int Raw(llhttp_t* p, Args ... args) {
921
134053
      Parser* parser = ContainerOf(&Parser::parser_, p);
922
134053
      int rv = (parser->*Member)(std::forward<Args>(args)...);
923





134051
      if (rv == 0) {
924
133902
        rv = parser->MaybePause();
925
      }
926
134051
      return rv;
927
    }
928
  };
929
930
  typedef int (Parser::*Call)();
931
  typedef int (Parser::*DataCall)(const char* at, size_t length);
932
933
  static const llhttp_settings_t settings;
934
};
935
936
const llhttp_settings_t Parser::settings = {
937
  Proxy<Call, &Parser::on_message_begin>::Raw,
938
  Proxy<DataCall, &Parser::on_url>::Raw,
939
  Proxy<DataCall, &Parser::on_status>::Raw,
940
  Proxy<DataCall, &Parser::on_header_field>::Raw,
941
  Proxy<DataCall, &Parser::on_header_value>::Raw,
942
  Proxy<Call, &Parser::on_headers_complete>::Raw,
943
  Proxy<DataCall, &Parser::on_body>::Raw,
944
  Proxy<Call, &Parser::on_message_complete>::Raw,
945
  Proxy<Call, &Parser::on_chunk_header>::Raw,
946
  Proxy<Call, &Parser::on_chunk_complete>::Raw,
947
};
948
949
950
753
void InitializeHttpParser(Local<Object> target,
951
                          Local<Value> unused,
952
                          Local<Context> context,
953
                          void* priv) {
954
753
  Environment* env = Environment::GetCurrent(context);
955
  BindingData* const binding_data =
956
753
      env->AddBindingData<BindingData>(context, target);
957
753
  if (binding_data == nullptr) return;
958
959
753
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
960
1506
  t->InstanceTemplate()->SetInternalFieldCount(Parser::kInternalFieldCount);
961
962
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"),
963
753
         Integer::New(env->isolate(), HTTP_REQUEST));
964
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "RESPONSE"),
965
753
         Integer::New(env->isolate(), HTTP_RESPONSE));
966
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageBegin"),
967
753
         Integer::NewFromUnsigned(env->isolate(), kOnMessageBegin));
968
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeaders"),
969
753
         Integer::NewFromUnsigned(env->isolate(), kOnHeaders));
970
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeadersComplete"),
971
753
         Integer::NewFromUnsigned(env->isolate(), kOnHeadersComplete));
972
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnBody"),
973
753
         Integer::NewFromUnsigned(env->isolate(), kOnBody));
974
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageComplete"),
975
753
         Integer::NewFromUnsigned(env->isolate(), kOnMessageComplete));
976
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnExecute"),
977
753
         Integer::NewFromUnsigned(env->isolate(), kOnExecute));
978
3012
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnTimeout"),
979
753
         Integer::NewFromUnsigned(env->isolate(), kOnTimeout));
980
981
753
  Local<Array> methods = Array::New(env->isolate());
982
#define V(num, name, string)                                                  \
983
    methods->Set(env->context(),                                              \
984
        num, FIXED_ONE_BYTE_STRING(env->isolate(), #string)).Check();
985
13554
  HTTP_METHOD_MAP(V)
986
#undef V
987
1506
  target->Set(env->context(),
988
              FIXED_ONE_BYTE_STRING(env->isolate(), "methods"),
989
9036
              methods).Check();
990
3765
991
6024
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
992
5271
  env->SetProtoMethod(t, "close", Parser::Close);
993
5271
  env->SetProtoMethod(t, "free", Parser::Free);
994
5271
  env->SetProtoMethod(t, "execute", Parser::Execute);
995
4518
  env->SetProtoMethod(t, "finish", Parser::Finish);
996
6024
  env->SetProtoMethod(t, "initialize", Parser::Initialize);
997
5271
  env->SetProtoMethod(t, "pause", Parser::Pause<true>);
998
5271
  env->SetProtoMethod(t, "resume", Parser::Pause<false>);
999
5271
  env->SetProtoMethod(t, "consume", Parser::Consume);
1000
4518
  env->SetProtoMethod(t, "unconsume", Parser::Unconsume);
1001
6024
  env->SetProtoMethod(t, "getCurrentBuffer", Parser::GetCurrentBuffer);
1002
4518
1003
4518
  env->SetConstructorFunction(target, "HTTPParser", t);
1004
6024
}
1005
3765
1006
4518
}  // anonymous namespace
1007
4518
}  // namespace node
1008
3765
1009

23306
NODE_MODULE_CONTEXT_AWARE_INTERNAL(http_parser, node::InitializeHttpParser)