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: 424 449 94.4 %
Date: 2020-06-24 22:13:30 Branches: 196 264 74.2 %

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 kOnHeaders = 0;
73
const uint32_t kOnHeadersComplete = 1;
74
const uint32_t kOnBody = 2;
75
const uint32_t kOnMessageComplete = 3;
76
const uint32_t kOnExecute = 4;
77
const uint32_t kOnTimeout = 5;
78
// Any more fields than this will be flushed into JS
79
const size_t kMaxHeaderFieldsCount = 32;
80
81
14871
inline bool IsOWS(char c) {
82

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

13073
    if (!on_heap_ && size_ > 0) {
123
5260
      char* s = new char[size_];
124
5260
      memcpy(s, str_, size_);
125
5260
      str_ = s;
126
5260
      on_heap_ = true;
127
    }
128
13073
  }
129
130
131
468128
  void Reset() {
132
468128
    if (on_heap_) {
133
5230
      delete[] str_;
134
5230
      on_heap_ = false;
135
    }
136
137
468128
    str_ = nullptr;
138
468128
    size_ = 0;
139
468128
  }
140
141
142
46164
  void Update(const char* str, size_t size) {
143
46164
    if (str_ == nullptr) {
144
46101
      str_ = str;
145

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

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


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

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

64928
    if (head_response.IsEmpty() || !head_response.ToLocalChecked()
362
48692
                                        ->IntegerValue(env()->context())
363
16228
                                        .To(&val)) {
364
8
      got_exception_ = true;
365
8
      return -1;
366
    }
367
368
16228
    return val;
369
  }
370
371
372
10695
  int on_body(const char* at, size_t length) {
373
10695
    EscapableHandleScope scope(env()->isolate());
374
375
10695
    Local<Object> obj = object();
376
32085
    Local<Value> cb = obj->Get(env()->context(), kOnBody).ToLocalChecked();
377
378
10695
    if (!cb->IsFunction())
379
      return 0;
380
381
    // We came from consumed stream
382
21390
    if (current_buffer_.IsEmpty()) {
383
      // Make sure Buffer will be in parent HandleScope
384
1000
      current_buffer_ = scope.Escape(Buffer::Copy(
385
          env()->isolate(),
386
          current_buffer_data_,
387
1000
          current_buffer_len_).ToLocalChecked());
388
    }
389
390
    Local<Value> argv[3] = {
391
      current_buffer_,
392
10695
      Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_),
393
      Integer::NewFromUnsigned(env()->isolate(), length)
394
53475
    };
395
396
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
397
10695
                                       arraysize(argv),
398
21390
                                       argv);
399
400
10695
    if (r.IsEmpty()) {
401
      got_exception_ = true;
402
      llhttp_set_error_reason(&parser_, "HPE_JS_EXCEPTION:JS Exception");
403
      return HPE_USER;
404
    }
405
406
10695
    return 0;
407
  }
408
409
410
15037
  int on_message_complete() {
411
30074
    HandleScope scope(env()->isolate());
412
413
15037
    if (num_fields_)
414
4
      Flush();  // Flush trailing HTTP headers.
415
416
15037
    Local<Object> obj = object();
417
30074
    Local<Value> cb = obj->Get(env()->context(),
418
45111
                               kOnMessageComplete).ToLocalChecked();
419
420
15037
    if (!cb->IsFunction())
421
2
      return 0;
422
423
    MaybeLocal<Value> r;
424
    {
425
      InternalCallbackScope callback_scope(
426
30070
          this, InternalCallbackScope::kSkipTaskQueues);
427
60140
      r = cb.As<Function>()->Call(env()->context(), object(), 0, nullptr);
428
15035
      if (r.IsEmpty()) callback_scope.MarkAsFailed();
429
    }
430
431
15035
    if (r.IsEmpty()) {
432
      got_exception_ = true;
433
      return -1;
434
    }
435
436
15035
    return 0;
437
  }
438
439
  // Reset nread for the next chunk
440
10269
  int on_chunk_header() {
441
10269
    header_nread_ = 0;
442
10269
    return 0;
443
  }
444
445
446
  // Reset nread for the next chunk
447
10115
  int on_chunk_complete() {
448
10115
    header_nread_ = 0;
449
10115
    return 0;
450
  }
451
452
3006
  static void New(const FunctionCallbackInfo<Value>& args) {
453
3006
    BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
454
3006
    new Parser(binding_data, args.This());
455
3006
  }
456
457
458
3
  static void Close(const FunctionCallbackInfo<Value>& args) {
459
    Parser* parser;
460
3
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
461
462
3
    delete parser;
463
  }
464
465
466
5163
  static void Free(const FunctionCallbackInfo<Value>& args) {
467
    Parser* parser;
468
5163
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
469
470
    // Since the Parser destructor isn't going to run the destroy() callbacks
471
    // it needs to be triggered manually.
472
5163
    parser->EmitTraceEventDestroy();
473
5163
    parser->EmitDestroy();
474
  }
475
476
477
6366
  void Save() {
478
6366
    url_.Save();
479
6366
    status_message_.Save();
480
481
6565
    for (size_t i = 0; i < num_fields_; i++) {
482
199
      fields_[i].Save();
483
    }
484
485
6508
    for (size_t i = 0; i < num_values_; i++) {
486
142
      values_[i].Save();
487
    }
488
6366
  }
489
490
491
  // var bytesParsed = parser->execute(buffer);
492
2790
  static void Execute(const FunctionCallbackInfo<Value>& args) {
493
    Parser* parser;
494
2790
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
495
5580
    CHECK(parser->current_buffer_.IsEmpty());
496
2790
    CHECK_EQ(parser->current_buffer_len_, 0);
497
2790
    CHECK_NULL(parser->current_buffer_data_);
498
499
2790
    ArrayBufferViewContents<char> buffer(args[0]);
500
501
    // This is a hack to get the current_buffer to the callbacks with the least
502
    // amount of overhead. Nothing else will run while http_parser_execute()
503
    // runs, therefore this pointer can be set and used for the execution.
504
8370
    parser->current_buffer_ = args[0].As<Object>();
505
506
2790
    Local<Value> ret = parser->Execute(buffer.data(), buffer.length());
507
508
2789
    if (!ret.IsEmpty())
509
5572
      args.GetReturnValue().Set(ret);
510
  }
511
512
513
912
  static void Finish(const FunctionCallbackInfo<Value>& args) {
514
    Parser* parser;
515
912
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
516
517
1824
    CHECK(parser->current_buffer_.IsEmpty());
518
912
    Local<Value> ret = parser->Execute(nullptr, 0);
519
520
912
    if (!ret.IsEmpty())
521
58
      args.GetReturnValue().Set(ret);
522
  }
523
524
525
5358
  static void Initialize(const FunctionCallbackInfo<Value>& args) {
526
5358
    Environment* env = Environment::GetCurrent(args);
527
10716
    bool lenient = args[3]->IsTrue();
528
529
5358
    uint64_t max_http_header_size = 0;
530
5358
    uint64_t headers_timeout = 0;
531
532
10716
    CHECK(args[0]->IsInt32());
533
10716
    CHECK(args[1]->IsObject());
534
535
5358
    if (args.Length() > 2) {
536
8376
      CHECK(args[2]->IsNumber());
537
12564
      max_http_header_size = args[2].As<Number>()->Value();
538
    }
539
5358
    if (max_http_header_size == 0) {
540
5356
      max_http_header_size = env->options()->max_http_header_size;
541
    }
542
543
5358
    if (args.Length() > 4) {
544
8376
      CHECK(args[4]->IsInt32());
545
12564
      headers_timeout = args[4].As<Number>()->Value();
546
    }
547
548
    llhttp_type_t type =
549
16074
        static_cast<llhttp_type_t>(args[0].As<Int32>()->Value());
550
551

5358
    CHECK(type == HTTP_REQUEST || type == HTTP_RESPONSE);
552
    Parser* parser;
553
5358
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
554
    // Should always be called from the same context.
555
5358
    CHECK_EQ(env, parser->env());
556
557
    AsyncWrap::ProviderType provider =
558
5358
        (type == HTTP_REQUEST ?
559
            AsyncWrap::PROVIDER_HTTPINCOMINGMESSAGE
560
5358
            : AsyncWrap::PROVIDER_HTTPCLIENTREQUEST);
561
562
5358
    parser->set_provider_type(provider);
563
10716
    parser->AsyncReset(args[1].As<Object>());
564
5358
    parser->Init(type, max_http_header_size, lenient, headers_timeout);
565
  }
566
567
  template <bool should_pause>
568
11
  static void Pause(const FunctionCallbackInfo<Value>& args) {
569
11
    Environment* env = Environment::GetCurrent(args);
570
    Parser* parser;
571

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

11
    CHECK_EQ(env, parser->env());
574
575

11
    if (parser->execute_depth_) {
576
4
      parser->pending_pause_ = should_pause;
577
4
      return;
578
    }
579
580
    if (should_pause) {
581
4
      llhttp_pause(&parser->parser_);
582
    } else {
583
3
      llhttp_resume(&parser->parser_);
584
    }
585
  }
586
587
588
2878
  static void Consume(const FunctionCallbackInfo<Value>& args) {
589
    Parser* parser;
590
2878
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
591
5756
    CHECK(args[0]->IsObject());
592
5756
    StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
593
2878
    CHECK_NOT_NULL(stream);
594
2878
    stream->PushStreamListener(parser);
595
  }
596
597
598
2869
  static void Unconsume(const FunctionCallbackInfo<Value>& args) {
599
    Parser* parser;
600
2869
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
601
602
    // Already unconsumed
603
2869
    if (parser->stream_ == nullptr)
604
      return;
605
606
2869
    parser->stream_->RemoveStreamListener(parser);
607
  }
608
609
610
49
  static void GetCurrentBuffer(const FunctionCallbackInfo<Value>& args) {
611
    Parser* parser;
612
49
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
613
614
98
    Local<Object> ret = Buffer::Copy(
615
        parser->env(),
616
        parser->current_buffer_data_,
617
98
        parser->current_buffer_len_).ToLocalChecked();
618
619
98
    args.GetReturnValue().Set(ret);
620
  }
621
622
 protected:
623
  static const size_t kAllocBufferSize = 64 * 1024;
624
625
3799
  uv_buf_t OnStreamAlloc(size_t suggested_size) override {
626
    // For most types of streams, OnStreamRead will be immediately after
627
    // OnStreamAlloc, and will consume all data, so using a static buffer for
628
    // reading is more efficient. For other streams, just use Malloc() directly.
629
3799
    if (binding_data_->parser_buffer_in_use)
630
      return uv_buf_init(Malloc(suggested_size), suggested_size);
631
3799
    binding_data_->parser_buffer_in_use = true;
632
633
3799
    if (binding_data_->parser_buffer.empty())
634
308
      binding_data_->parser_buffer.resize(kAllocBufferSize);
635
636
3799
    return uv_buf_init(binding_data_->parser_buffer.data(), kAllocBufferSize);
637
  }
638
639
640
3819
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override {
641
6380
    HandleScope scope(env()->isolate());
642
    // Once we’re done here, either indicate that the HTTP parser buffer
643
    // is free for re-use, or free() the data if it didn’t come from there
644
    // in the first place.
645
3815
    auto on_scope_leave = OnScopeLeave([&]() {
646
3833
      if (buf.base == binding_data_->parser_buffer.data())
647
3797
        binding_data_->parser_buffer_in_use = false;
648
      else
649
18
        free(buf.base);
650
10195
    });
651
652
3819
    if (nread < 0) {
653
241
      PassReadErrorToPreviousListener(nread);
654
241
      return;
655
    }
656
657
    // Ignore, empty reads have special meaning in http parser
658
3578
    if (nread == 0)
659
      return;
660
661
3578
    current_buffer_.Clear();
662
3578
    Local<Value> ret = Execute(buf.base, nread);
663
664
    // Exception
665
3577
    if (ret.IsEmpty())
666
5
      return;
667
668
    // check header parsing time
669

3572
    if (header_parsing_start_time_ != 0 && headers_timeout_ != 0) {
670
2569
      uint64_t now = uv_hrtime();
671
2569
      uint64_t parsing_time = (now - header_parsing_start_time_) / 1e6;
672
673
2569
      if (parsing_time > headers_timeout_) {
674
        Local<Value> cb =
675
18
            object()->Get(env()->context(), kOnTimeout).ToLocalChecked();
676
677
6
        if (!cb->IsFunction())
678
          return;
679
680
6
        MakeCallback(cb.As<Function>(), 0, nullptr);
681
682
6
        return;
683
      }
684
    }
685
686
    Local<Value> cb =
687
10698
        object()->Get(env()->context(), kOnExecute).ToLocalChecked();
688
689
3566
    if (!cb->IsFunction())
690
1002
      return;
691
692
    // Hooks for GetCurrentBuffer
693
2564
    current_buffer_len_ = nread;
694
2564
    current_buffer_data_ = buf.base;
695
696
2564
    MakeCallback(cb.As<Function>(), 1, &ret);
697
698
2561
    current_buffer_len_ = 0;
699
2561
    current_buffer_data_ = nullptr;
700
  }
701
702
703
7280
  Local<Value> Execute(const char* data, size_t len) {
704
7280
    EscapableHandleScope scope(env()->isolate());
705
706
7280
    current_buffer_len_ = len;
707
7280
    current_buffer_data_ = data;
708
7280
    got_exception_ = false;
709
710
    llhttp_errno_t err;
711
712
    // Do not allow re-entering `http_parser_execute()`
713
7280
    CHECK_EQ(execute_depth_, 0);
714
715
7280
    execute_depth_++;
716
7280
    if (data == nullptr) {
717
912
      err = llhttp_finish(&parser_);
718
    } else {
719
6368
      err = llhttp_execute(&parser_, data, len);
720
6366
      Save();
721
    }
722
7278
    execute_depth_--;
723
724
    // Calculate bytes read and resume after Upgrade/CONNECT pause
725
7278
    size_t nread = len;
726
7278
    if (err != HPE_OK) {
727
328
      nread = llhttp_get_error_pos(&parser_) - data;
728
729
      // This isn't a real pause, just a way to stop parsing early.
730
328
      if (err == HPE_PAUSED_UPGRADE) {
731
52
        err = HPE_OK;
732
52
        llhttp_resume_after_upgrade(&parser_);
733
      }
734
    }
735
736
    // Apply pending pause
737
7278
    if (pending_pause_) {
738
      pending_pause_ = false;
739
      llhttp_pause(&parser_);
740
    }
741
742
    // Unassign the 'buffer_' variable
743
7278
    current_buffer_.Clear();
744
7278
    current_buffer_len_ = 0;
745
7278
    current_buffer_data_ = nullptr;
746
747
    // If there was an exception in one of the callbacks
748
7278
    if (got_exception_)
749
8
      return scope.Escape(Local<Value>());
750
751
7270
    Local<Integer> nread_obj = Integer::New(env()->isolate(), nread);
752
753
    // If there was a parse error in one of the callbacks
754
    // TODO(bnoordhuis) What if there is an error on EOF?
755

7270
    if (!parser_.upgrade && err != HPE_OK) {
756
216
      Local<Value> e = Exception::Error(env()->parse_error_string());
757
648
      Local<Object> obj = e->ToObject(env()->isolate()->GetCurrentContext())
758
216
        .ToLocalChecked();
759
432
      obj->Set(env()->context(),
760
               env()->bytes_parsed_string(),
761
864
               nread_obj).Check();
762
216
      const char* errno_reason = llhttp_get_error_reason(&parser_);
763
764
      Local<String> code;
765
      Local<String> reason;
766
216
      if (err == HPE_USER) {
767
15
        const char* colon = strchr(errno_reason, ':');
768
15
        CHECK_NOT_NULL(colon);
769
        code = OneByteString(env()->isolate(), errno_reason,
770
15
                             colon - errno_reason);
771
15
        reason = OneByteString(env()->isolate(), colon + 1);
772
      } else {
773
201
        code = OneByteString(env()->isolate(), llhttp_errno_name(err));
774
201
        reason = OneByteString(env()->isolate(), errno_reason);
775
      }
776
777
864
      obj->Set(env()->context(), env()->code_string(), code).Check();
778
864
      obj->Set(env()->context(), env()->reason_string(), reason).Check();
779
      return scope.Escape(e);
780
    }
781
782
    // No return value is needed for `Finish()`
783
7054
    if (data == nullptr) {
784
883
      return scope.Escape(Local<Value>());
785
    }
786
6171
    return scope.Escape(nread_obj);
787
  }
788
789
16289
  Local<Array> CreateHeaders() {
790
    // There could be extra entries but the max size should be fixed
791
1058785
    Local<Value> headers_v[kMaxHeaderFieldsCount * 2];
792
793
31151
    for (size_t i = 0; i < num_values_; ++i) {
794
29724
      headers_v[i * 2] = fields_[i].ToString(env());
795
29724
      headers_v[i * 2 + 1] = values_[i].ToTrimmedString(env());
796
    }
797
798
16289
    return Array::New(env()->isolate(), headers_v, num_values_ * 2);
799
  }
800
801
802
  // spill headers and request path to JS land
803
67
  void Flush() {
804
134
    HandleScope scope(env()->isolate());
805
806
67
    Local<Object> obj = object();
807
201
    Local<Value> cb = obj->Get(env()->context(), kOnHeaders).ToLocalChecked();
808
809
67
    if (!cb->IsFunction())
810
      return;
811
812
    Local<Value> argv[2] = {
813
      CreateHeaders(),
814
      url_.ToString(env())
815
201
    };
816
817
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
818
67
                                       arraysize(argv),
819
134
                                       argv);
820
821
67
    if (r.IsEmpty())
822
      got_exception_ = true;
823
824
67
    url_.Reset();
825
67
    have_flushed_ = true;
826
  }
827
828
829
5358
  void Init(llhttp_type_t type, uint64_t max_http_header_size,
830
            bool lenient, uint64_t headers_timeout) {
831
5358
    llhttp_init(&parser_, type, &settings);
832
5358
    llhttp_set_lenient(&parser_, lenient);
833
5358
    header_nread_ = 0;
834
5358
    url_.Reset();
835
5358
    status_message_.Reset();
836
5358
    num_fields_ = 0;
837
5358
    num_values_ = 0;
838
5358
    have_flushed_ = false;
839
5358
    got_exception_ = false;
840
5358
    max_http_header_size_ = max_http_header_size;
841
5358
    header_parsing_start_time_ = 0;
842
5358
    headers_timeout_ = headers_timeout;
843
5358
  }
844
845
846
46179
  int TrackHeader(size_t len) {
847
46179
    header_nread_ += len;
848
46179
    if (header_nread_ >= max_http_header_size_) {
849
15
      llhttp_set_error_reason(&parser_, "HPE_HEADER_OVERFLOW:Header overflow");
850
15
      return HPE_USER;
851
    }
852
46164
    return 0;
853
  }
854
855
856
124730
  int MaybePause() {
857
124730
    CHECK_NE(execute_depth_, 0);
858
859
124730
    if (!pending_pause_) {
860
124730
      return 0;
861
    }
862
863
    pending_pause_ = false;
864
    llhttp_set_error_reason(&parser_, "Paused in callback");
865
    return HPE_PAUSED;
866
  }
867
868
  llhttp_t parser_;
869
  StringPtr fields_[kMaxHeaderFieldsCount];  // header fields
870
  StringPtr values_[kMaxHeaderFieldsCount];  // header values
871
  StringPtr url_;
872
  StringPtr status_message_;
873
  size_t num_fields_;
874
  size_t num_values_;
875
  bool have_flushed_;
876
  bool got_exception_;
877
  Local<Object> current_buffer_;
878
  size_t current_buffer_len_;
879
  const char* current_buffer_data_;
880
  unsigned int execute_depth_ = 0;
881
  bool pending_pause_ = false;
882
  uint64_t header_nread_ = 0;
883
  uint64_t max_http_header_size_;
884
  uint64_t headers_timeout_;
885
  uint64_t header_parsing_start_time_ = 0;
886
887
  BaseObjectPtr<BindingData> binding_data_;
888
889
  // These are helper functions for filling `http_parser_settings`, which turn
890
  // a member function of Parser into a C-style HTTP parser callback.
891
  template <typename Parser, Parser> struct Proxy;
892
  template <typename Parser, typename ...Args, int (Parser::*Member)(Args...)>
893
  struct Proxy<int (Parser::*)(Args...), Member> {
894
124815
    static int Raw(llhttp_t* p, Args ... args) {
895
124815
      Parser* parser = ContainerOf(&Parser::parser_, p);
896
124815
      int rv = (parser->*Member)(std::forward<Args>(args)...);
897





124813
      if (rv == 0) {
898
124730
        rv = parser->MaybePause();
899
      }
900
124813
      return rv;
901
    }
902
  };
903
904
  typedef int (Parser::*Call)();
905
  typedef int (Parser::*DataCall)(const char* at, size_t length);
906
907
  static const llhttp_settings_t settings;
908
};
909
910
const llhttp_settings_t Parser::settings = {
911
  Proxy<Call, &Parser::on_message_begin>::Raw,
912
  Proxy<DataCall, &Parser::on_url>::Raw,
913
  Proxy<DataCall, &Parser::on_status>::Raw,
914
  Proxy<DataCall, &Parser::on_header_field>::Raw,
915
  Proxy<DataCall, &Parser::on_header_value>::Raw,
916
  Proxy<Call, &Parser::on_headers_complete>::Raw,
917
  Proxy<DataCall, &Parser::on_body>::Raw,
918
  Proxy<Call, &Parser::on_message_complete>::Raw,
919
  Proxy<Call, &Parser::on_chunk_header>::Raw,
920
  Proxy<Call, &Parser::on_chunk_complete>::Raw,
921
};
922
923
924
706
void InitializeHttpParser(Local<Object> target,
925
                          Local<Value> unused,
926
                          Local<Context> context,
927
                          void* priv) {
928
706
  Environment* env = Environment::GetCurrent(context);
929
  BindingData* const binding_data =
930
706
      env->AddBindingData<BindingData>(context, target);
931
706
  if (binding_data == nullptr) return;
932
933
706
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
934
1412
  t->InstanceTemplate()->SetInternalFieldCount(Parser::kInternalFieldCount);
935
1412
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"));
936
937
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"),
938
706
         Integer::New(env->isolate(), HTTP_REQUEST));
939
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "RESPONSE"),
940
706
         Integer::New(env->isolate(), HTTP_RESPONSE));
941
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeaders"),
942
706
         Integer::NewFromUnsigned(env->isolate(), kOnHeaders));
943
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeadersComplete"),
944
706
         Integer::NewFromUnsigned(env->isolate(), kOnHeadersComplete));
945
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnBody"),
946
706
         Integer::NewFromUnsigned(env->isolate(), kOnBody));
947
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageComplete"),
948
706
         Integer::NewFromUnsigned(env->isolate(), kOnMessageComplete));
949
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnExecute"),
950
706
         Integer::NewFromUnsigned(env->isolate(), kOnExecute));
951
2824
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnTimeout"),
952
706
         Integer::NewFromUnsigned(env->isolate(), kOnTimeout));
953
954
706
  Local<Array> methods = Array::New(env->isolate());
955
#define V(num, name, string)                                                  \
956
    methods->Set(env->context(),                                              \
957
        num, FIXED_ONE_BYTE_STRING(env->isolate(), #string)).Check();
958
72718
  HTTP_METHOD_MAP(V)
959
#undef V
960
1412
  target->Set(env->context(),
961
              FIXED_ONE_BYTE_STRING(env->isolate(), "methods"),
962
2824
              methods).Check();
963
964
1412
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
965
706
  env->SetProtoMethod(t, "close", Parser::Close);
966
706
  env->SetProtoMethod(t, "free", Parser::Free);
967
706
  env->SetProtoMethod(t, "execute", Parser::Execute);
968
706
  env->SetProtoMethod(t, "finish", Parser::Finish);
969
706
  env->SetProtoMethod(t, "initialize", Parser::Initialize);
970
706
  env->SetProtoMethod(t, "pause", Parser::Pause<true>);
971
706
  env->SetProtoMethod(t, "resume", Parser::Pause<false>);
972
706
  env->SetProtoMethod(t, "consume", Parser::Consume);
973
706
  env->SetProtoMethod(t, "unconsume", Parser::Unconsume);
974
706
  env->SetProtoMethod(t, "getCurrentBuffer", Parser::GetCurrentBuffer);
975
976
1412
  target->Set(env->context(),
977
              FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"),
978
4236
              t->GetFunction(env->context()).ToLocalChecked()).Check();
979
}
980
981
}  // anonymous namespace
982
}  // namespace node
983
984
4398
NODE_MODULE_CONTEXT_AWARE_INTERNAL(http_parser, node::InitializeHttpParser)