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-07-19 22:14:24 Branches: 198 268 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 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
126014
inline bool IsOWS(char c) {
82

126014
  return c == ' ' || c == '\t';
83
}
84
85
1426
class BindingData : public BaseObject {
86
 public:
87
745
  BindingData(Environment* env, Local<Object> obj)
88
745
      : 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
204072
  StringPtr() {
108
204072
    on_heap_ = false;
109
204072
    Reset();
110
204072
  }
111
112
113
404316
  ~StringPtr() {
114
202158
    Reset();
115
202158
  }
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
132431
  void Save() {
122

132431
    if (!on_heap_ && size_ > 0) {
123
64911
      char* s = new char[size_];
124
64911
      memcpy(s, str_, size_);
125
64911
      str_ = s;
126
64911
      on_heap_ = true;
127
    }
128
132431
  }
129
130
131
821276
  void Reset() {
132
821276
    if (on_heap_) {
133
64881
      delete[] str_;
134
64881
      on_heap_ = false;
135
    }
136
137
821276
    str_ = nullptr;
138
821276
    size_ = 0;
139
821276
  }
140
141
142
328101
  void Update(const char* str, size_t size) {
143
328101
    if (str_ == nullptr) {
144
328038
      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
328101
    size_ += size;
160
328101
  }
161
162
163
327958
  Local<String> ToString(Environment* env) const {
164
327958
    if (size_ != 0)
165
327894
      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
126016
  Local<String> ToTrimmedString(Environment* env) {
173

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


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

6184
        binding_data_(binding_data) {
192
3092
  }
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
75933
  int on_message_begin() {
203
75933
    num_fields_ = num_values_ = 0;
204
75933
    url_.Reset();
205
75933
    status_message_.Reset();
206
75933
    header_parsing_start_time_ = uv_hrtime();
207
75933
    return 0;
208
  }
209
210
211
73139
  int on_url(const char* at, size_t length) {
212
73139
    int rv = TrackHeader(length);
213
73139
    if (rv != 0) {
214
      return rv;
215
    }
216
217
73139
    url_.Update(at, length);
218
73139
    return 0;
219
  }
220
221
222
2784
  int on_status(const char* at, size_t length) {
223
2784
    int rv = TrackHeader(length);
224
2784
    if (rv != 0) {
225
      return rv;
226
    }
227
228
2784
    status_message_.Update(at, length);
229
2784
    return 0;
230
  }
231
232
233
126101
  int on_header_field(const char* at, size_t length) {
234
126101
    int rv = TrackHeader(length);
235
126101
    if (rv != 0) {
236
      return rv;
237
    }
238
239
126101
    if (num_fields_ == num_values_) {
240
      // start of new field name
241
126072
      num_fields_++;
242
126072
      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
126072
      fields_[num_fields_ - 1].Reset();
249
    }
250
251
126101
    CHECK_LT(num_fields_, kMaxHeaderFieldsCount);
252
126101
    CHECK_EQ(num_fields_, num_values_ + 1);
253
254
126101
    fields_[num_fields_ - 1].Update(at, length);
255
256
126101
    return 0;
257
  }
258
259
260
126092
  int on_header_value(const char* at, size_t length) {
261
126092
    int rv = TrackHeader(length);
262
126092
    if (rv != 0) {
263
15
      return rv;
264
    }
265
266
126077
    if (num_values_ != num_fields_) {
267
      // start of new header value
268
126051
      num_values_++;
269
126051
      values_[num_values_ - 1].Reset();
270
    }
271
272
126077
    CHECK_LT(num_values_, arraysize(values_));
273
126077
    CHECK_EQ(num_values_, num_fields_);
274
275
126077
    values_[num_values_ - 1].Update(at, length);
276
277
126077
    return 0;
278
  }
279
280
281
75889
  int on_headers_complete() {
282
75889
    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
758890
    Local<Value> argv[A_MAX];
301
75889
    Local<Object> obj = object();
302
151778
    Local<Value> cb = obj->Get(env()->context(),
303
227667
                               kOnHeadersComplete).ToLocalChecked();
304
305
75889
    if (!cb->IsFunction())
306
      return 0;
307
308
75889
    Local<Value> undefined = Undefined(env()->isolate());
309
758890
    for (size_t i = 0; i < arraysize(argv); i++)
310
683001
      argv[i] = undefined;
311
312
75889
    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
151746
      argv[A_HEADERS] = CreateHeaders();
318
75873
      if (parser_.type == HTTP_REQUEST)
319
146208
        argv[A_URL] = url_.ToString(env());
320
    }
321
322
75889
    num_fields_ = 0;
323
75889
    num_values_ = 0;
324
325
    // METHOD
326
75889
    if (parser_.type == HTTP_REQUEST) {
327
73112
      argv[A_METHOD] =
328
146224
          Uint32::NewFromUnsigned(env()->isolate(), parser_.method);
329
    }
330
331
    // STATUS
332
75889
    if (parser_.type == HTTP_RESPONSE) {
333
2777
      argv[A_STATUS_CODE] =
334
5554
          Integer::New(env()->isolate(), parser_.status_code);
335
5554
      argv[A_STATUS_MESSAGE] = status_message_.ToString(env());
336
    }
337
338
    // VERSION
339
151778
    argv[A_VERSION_MAJOR] = Integer::New(env()->isolate(), parser_.http_major);
340
151778
    argv[A_VERSION_MINOR] = Integer::New(env()->isolate(), parser_.http_minor);
341
342
    bool should_keep_alive;
343
75889
    should_keep_alive = llhttp_should_keep_alive(&parser_);
344
345
75889
    argv[A_SHOULD_KEEP_ALIVE] =
346
151778
        Boolean::New(env()->isolate(), should_keep_alive);
347
348
151778
    argv[A_UPGRADE] = Boolean::New(env()->isolate(), parser_.upgrade);
349
350
    MaybeLocal<Value> head_response;
351
    {
352
      InternalCallbackScope callback_scope(
353
151776
          this, InternalCallbackScope::kSkipTaskQueues);
354
151776
      head_response = cb.As<Function>()->Call(
355
303554
          env()->context(), object(), arraysize(argv), argv);
356
75887
      if (head_response.IsEmpty()) callback_scope.MarkAsFailed();
357
    }
358
359
    int64_t val;
360
361

303532
    if (head_response.IsEmpty() || !head_response.ToLocalChecked()
362
227645
                                        ->IntegerValue(env()->context())
363
75879
                                        .To(&val)) {
364
8
      got_exception_ = true;
365
8
      return -1;
366
    }
367
368
75879
    return val;
369
  }
370
371
372
10796
  int on_body(const char* at, size_t length) {
373
10796
    EscapableHandleScope scope(env()->isolate());
374
375
10796
    Local<Object> obj = object();
376
32388
    Local<Value> cb = obj->Get(env()->context(), kOnBody).ToLocalChecked();
377
378
10796
    if (!cb->IsFunction())
379
      return 0;
380
381
    // We came from consumed stream
382
21592
    if (current_buffer_.IsEmpty()) {
383
      // Make sure Buffer will be in parent HandleScope
384
1098
      current_buffer_ = scope.Escape(Buffer::Copy(
385
          env()->isolate(),
386
          current_buffer_data_,
387
1098
          current_buffer_len_).ToLocalChecked());
388
    }
389
390
    Local<Value> argv[3] = {
391
      current_buffer_,
392
10796
      Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_),
393
      Integer::NewFromUnsigned(env()->isolate(), length)
394
53980
    };
395
396
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
397
10796
                                       arraysize(argv),
398
21592
                                       argv);
399
400
10796
    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
10796
    return 0;
407
  }
408
409
410
74688
  int on_message_complete() {
411
149376
    HandleScope scope(env()->isolate());
412
413
74688
    if (num_fields_)
414
4
      Flush();  // Flush trailing HTTP headers.
415
416
74688
    Local<Object> obj = object();
417
149376
    Local<Value> cb = obj->Get(env()->context(),
418
224064
                               kOnMessageComplete).ToLocalChecked();
419
420
74688
    if (!cb->IsFunction())
421
2
      return 0;
422
423
    MaybeLocal<Value> r;
424
    {
425
      InternalCallbackScope callback_scope(
426
149372
          this, InternalCallbackScope::kSkipTaskQueues);
427
298744
      r = cb.As<Function>()->Call(env()->context(), object(), 0, nullptr);
428
74686
      if (r.IsEmpty()) callback_scope.MarkAsFailed();
429
    }
430
431
74686
    if (r.IsEmpty()) {
432
      got_exception_ = true;
433
      return -1;
434
    }
435
436
74686
    return 0;
437
  }
438
439
  // Reset nread for the next chunk
440
10389
  int on_chunk_header() {
441
10389
    header_nread_ = 0;
442
10389
    return 0;
443
  }
444
445
446
  // Reset nread for the next chunk
447
10235
  int on_chunk_complete() {
448
10235
    header_nread_ = 0;
449
10235
    return 0;
450
  }
451
452
3092
  static void New(const FunctionCallbackInfo<Value>& args) {
453
3092
    BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
454
3092
    new Parser(binding_data, args.This());
455
3092
  }
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
5296
  static void Free(const FunctionCallbackInfo<Value>& args) {
467
    Parser* parser;
468
5296
    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
5296
    parser->EmitTraceEventDestroy();
473
5296
    parser->EmitDestroy();
474
  }
475
476
477
66045
  void Save() {
478
66045
    url_.Save();
479
66045
    status_message_.Save();
480
481
66244
    for (size_t i = 0; i < num_fields_; i++) {
482
199
      fields_[i].Save();
483
    }
484
485
66187
    for (size_t i = 0; i < num_values_; i++) {
486
142
      values_[i].Save();
487
    }
488
66045
  }
489
490
491
  // var bytesParsed = parser->execute(buffer);
492
2888
  static void Execute(const FunctionCallbackInfo<Value>& args) {
493
    Parser* parser;
494
2888
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
495
5776
    CHECK(parser->current_buffer_.IsEmpty());
496
2888
    CHECK_EQ(parser->current_buffer_len_, 0);
497
2888
    CHECK_NULL(parser->current_buffer_data_);
498
499
2888
    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
8664
    parser->current_buffer_ = args[0].As<Object>();
505
506
2888
    Local<Value> ret = parser->Execute(buffer.data(), buffer.length());
507
508
2887
    if (!ret.IsEmpty())
509
5768
      args.GetReturnValue().Set(ret);
510
  }
511
512
513
945
  static void Finish(const FunctionCallbackInfo<Value>& args) {
514
    Parser* parser;
515
945
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
516
517
1890
    CHECK(parser->current_buffer_.IsEmpty());
518
945
    Local<Value> ret = parser->Execute(nullptr, 0);
519
520
945
    if (!ret.IsEmpty())
521
58
      args.GetReturnValue().Set(ret);
522
  }
523
524
525
5495
  static void Initialize(const FunctionCallbackInfo<Value>& args) {
526
5495
    Environment* env = Environment::GetCurrent(args);
527
10990
    bool lenient = args[3]->IsTrue();
528
529
5495
    uint64_t max_http_header_size = 0;
530
5495
    uint64_t headers_timeout = 0;
531
532
10990
    CHECK(args[0]->IsInt32());
533
10990
    CHECK(args[1]->IsObject());
534
535
5495
    if (args.Length() > 2) {
536
8646
      CHECK(args[2]->IsNumber());
537
12969
      max_http_header_size = args[2].As<Number>()->Value();
538
    }
539
5495
    if (max_http_header_size == 0) {
540
5492
      max_http_header_size = env->options()->max_http_header_size;
541
    }
542
543
5495
    if (args.Length() > 4) {
544
8646
      CHECK(args[4]->IsInt32());
545
12969
      headers_timeout = args[4].As<Number>()->Value();
546
    }
547
548
    llhttp_type_t type =
549
16485
        static_cast<llhttp_type_t>(args[0].As<Int32>()->Value());
550
551

5495
    CHECK(type == HTTP_REQUEST || type == HTTP_RESPONSE);
552
    Parser* parser;
553
5495
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
554
    // Should always be called from the same context.
555
5495
    CHECK_EQ(env, parser->env());
556
557
    AsyncWrap::ProviderType provider =
558
5495
        (type == HTTP_REQUEST ?
559
            AsyncWrap::PROVIDER_HTTPINCOMINGMESSAGE
560
5495
            : AsyncWrap::PROVIDER_HTTPCLIENTREQUEST);
561
562
5495
    parser->set_provider_type(provider);
563
10990
    parser->AsyncReset(args[1].As<Object>());
564
5495
    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
2952
  static void Consume(const FunctionCallbackInfo<Value>& args) {
589
    Parser* parser;
590
2952
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
591
5904
    CHECK(args[0]->IsObject());
592
5904
    StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
593
2952
    CHECK_NOT_NULL(stream);
594
2952
    stream->PushStreamListener(parser);
595
  }
596
597
598
2942
  static void Unconsume(const FunctionCallbackInfo<Value>& args) {
599
    Parser* parser;
600
2942
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
601
602
    // Already unconsumed
603
2942
    if (parser->stream_ == nullptr)
604
      return;
605
606
2942
    parser->stream_->RemoveStreamListener(parser);
607
  }
608
609
610
50
  static void GetCurrentBuffer(const FunctionCallbackInfo<Value>& args) {
611
    Parser* parser;
612
50
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
613
614
100
    Local<Object> ret = Buffer::Copy(
615
        parser->env(),
616
        parser->current_buffer_data_,
617
100
        parser->current_buffer_len_).ToLocalChecked();
618
619
100
    args.GetReturnValue().Set(ret);
620
  }
621
622
 protected:
623
  static const size_t kAllocBufferSize = 64 * 1024;
624
625
63451
  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
63451
    if (binding_data_->parser_buffer_in_use)
630
      return uv_buf_init(Malloc(suggested_size), suggested_size);
631
63451
    binding_data_->parser_buffer_in_use = true;
632
633
63451
    if (binding_data_->parser_buffer.empty())
634
320
      binding_data_->parser_buffer.resize(kAllocBufferSize);
635
636
63451
    return uv_buf_init(binding_data_->parser_buffer.data(), kAllocBufferSize);
637
  }
638
639
640
63471
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override {
641
125614
    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
63467
    auto on_scope_leave = OnScopeLeave([&]() {
646
63485
      if (buf.base == binding_data_->parser_buffer.data())
647
63449
        binding_data_->parser_buffer_in_use = false;
648
      else
649
18
        free(buf.base);
650
189081
    });
651
652
63471
    if (nread < 0) {
653
312
      PassReadErrorToPreviousListener(nread);
654
312
      return;
655
    }
656
657
    // Ignore, empty reads have special meaning in http parser
658
63159
    if (nread == 0)
659
      return;
660
661
63159
    current_buffer_.Clear();
662
63159
    Local<Value> ret = Execute(buf.base, nread);
663
664
    // Exception
665
63158
    if (ret.IsEmpty())
666
5
      return;
667
668
    // check header parsing time
669

63153
    if (header_parsing_start_time_ != 0 && headers_timeout_ != 0) {
670
62150
      uint64_t now = uv_hrtime();
671
62150
      uint64_t parsing_time = (now - header_parsing_start_time_) / 1e6;
672
673
62150
      if (parsing_time > headers_timeout_) {
674
        Local<Value> cb =
675
15
            object()->Get(env()->context(), kOnTimeout).ToLocalChecked();
676
677
5
        if (!cb->IsFunction())
678
          return;
679
680
5
        MakeCallback(cb.As<Function>(), 0, nullptr);
681
682
5
        return;
683
      }
684
    }
685
686
    Local<Value> cb =
687
189444
        object()->Get(env()->context(), kOnExecute).ToLocalChecked();
688
689
63148
    if (!cb->IsFunction())
690
1002
      return;
691
692
    // Hooks for GetCurrentBuffer
693
62146
    current_buffer_len_ = nread;
694
62146
    current_buffer_data_ = buf.base;
695
696
62146
    MakeCallback(cb.As<Function>(), 1, &ret);
697
698
62143
    current_buffer_len_ = 0;
699
62143
    current_buffer_data_ = nullptr;
700
  }
701
702
703
66992
  Local<Value> Execute(const char* data, size_t len) {
704
66992
    EscapableHandleScope scope(env()->isolate());
705
706
66992
    current_buffer_len_ = len;
707
66992
    current_buffer_data_ = data;
708
66992
    got_exception_ = false;
709
710
    llhttp_errno_t err;
711
712
    // Do not allow re-entering `http_parser_execute()`
713
66992
    CHECK_EQ(execute_depth_, 0);
714
715
66992
    execute_depth_++;
716
66992
    if (data == nullptr) {
717
945
      err = llhttp_finish(&parser_);
718
    } else {
719
66047
      err = llhttp_execute(&parser_, data, len);
720
66045
      Save();
721
    }
722
66990
    execute_depth_--;
723
724
    // Calculate bytes read and resume after Upgrade/CONNECT pause
725
66990
    size_t nread = len;
726
66990
    if (err != HPE_OK) {
727
330
      nread = llhttp_get_error_pos(&parser_) - data;
728
729
      // This isn't a real pause, just a way to stop parsing early.
730
330
      if (err == HPE_PAUSED_UPGRADE) {
731
53
        err = HPE_OK;
732
53
        llhttp_resume_after_upgrade(&parser_);
733
      }
734
    }
735
736
    // Apply pending pause
737
66990
    if (pending_pause_) {
738
      pending_pause_ = false;
739
      llhttp_pause(&parser_);
740
    }
741
742
    // Unassign the 'buffer_' variable
743
66990
    current_buffer_.Clear();
744
66990
    current_buffer_len_ = 0;
745
66990
    current_buffer_data_ = nullptr;
746
747
    // If there was an exception in one of the callbacks
748
66990
    if (got_exception_)
749
8
      return scope.Escape(Local<Value>());
750
751
66982
    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

66982
    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
66766
    if (data == nullptr) {
784
916
      return scope.Escape(Local<Value>());
785
    }
786
65850
    return scope.Escape(nread_obj);
787
  }
788
789
75940
  Local<Array> CreateHeaders() {
790
    // There could be extra entries but the max size should be fixed
791
4936100
    Local<Value> headers_v[kMaxHeaderFieldsCount * 2];
792
793
201945
    for (size_t i = 0; i < num_values_; ++i) {
794
252010
      headers_v[i * 2] = fields_[i].ToString(env());
795
252010
      headers_v[i * 2 + 1] = values_[i].ToTrimmedString(env());
796
    }
797
798
75940
    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
5495
  void Init(llhttp_type_t type, uint64_t max_http_header_size,
830
            bool lenient, uint64_t headers_timeout) {
831
5495
    llhttp_init(&parser_, type, &settings);
832
5495
    llhttp_set_lenient(&parser_, lenient);
833
5495
    header_nread_ = 0;
834
5495
    url_.Reset();
835
5495
    status_message_.Reset();
836
5495
    num_fields_ = 0;
837
5495
    num_values_ = 0;
838
5495
    have_flushed_ = false;
839
5495
    got_exception_ = false;
840
5495
    max_http_header_size_ = max_http_header_size;
841
5495
    header_parsing_start_time_ = 0;
842
5495
    headers_timeout_ = headers_timeout;
843
5495
  }
844
845
846
328116
  int TrackHeader(size_t len) {
847
328116
    header_nread_ += len;
848
328116
    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
328101
    return 0;
853
  }
854
855
856
585959
  int MaybePause() {
857
585959
    CHECK_NE(execute_depth_, 0);
858
859
585959
    if (!pending_pause_) {
860
585959
      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
586046
    static int Raw(llhttp_t* p, Args ... args) {
895
586046
      Parser* parser = ContainerOf(&Parser::parser_, p);
896
586046
      int rv = (parser->*Member)(std::forward<Args>(args)...);
897





586044
      if (rv == 0) {
898
585959
        rv = parser->MaybePause();
899
      }
900
586044
      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
745
void InitializeHttpParser(Local<Object> target,
925
                          Local<Value> unused,
926
                          Local<Context> context,
927
                          void* priv) {
928
745
  Environment* env = Environment::GetCurrent(context);
929
  BindingData* const binding_data =
930
745
      env->AddBindingData<BindingData>(context, target);
931
745
  if (binding_data == nullptr) return;
932
933
745
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
934
1490
  t->InstanceTemplate()->SetInternalFieldCount(Parser::kInternalFieldCount);
935
1490
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"));
936
937
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"),
938
745
         Integer::New(env->isolate(), HTTP_REQUEST));
939
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "RESPONSE"),
940
745
         Integer::New(env->isolate(), HTTP_RESPONSE));
941
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeaders"),
942
745
         Integer::NewFromUnsigned(env->isolate(), kOnHeaders));
943
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeadersComplete"),
944
745
         Integer::NewFromUnsigned(env->isolate(), kOnHeadersComplete));
945
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnBody"),
946
745
         Integer::NewFromUnsigned(env->isolate(), kOnBody));
947
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageComplete"),
948
745
         Integer::NewFromUnsigned(env->isolate(), kOnMessageComplete));
949
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnExecute"),
950
745
         Integer::NewFromUnsigned(env->isolate(), kOnExecute));
951
2980
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnTimeout"),
952
745
         Integer::NewFromUnsigned(env->isolate(), kOnTimeout));
953
954
745
  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
76735
  HTTP_METHOD_MAP(V)
959
#undef V
960
1490
  target->Set(env->context(),
961
              FIXED_ONE_BYTE_STRING(env->isolate(), "methods"),
962
2980
              methods).Check();
963
964
1490
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
965
745
  env->SetProtoMethod(t, "close", Parser::Close);
966
745
  env->SetProtoMethod(t, "free", Parser::Free);
967
745
  env->SetProtoMethod(t, "execute", Parser::Execute);
968
745
  env->SetProtoMethod(t, "finish", Parser::Finish);
969
745
  env->SetProtoMethod(t, "initialize", Parser::Initialize);
970
745
  env->SetProtoMethod(t, "pause", Parser::Pause<true>);
971
745
  env->SetProtoMethod(t, "resume", Parser::Pause<false>);
972
745
  env->SetProtoMethod(t, "consume", Parser::Consume);
973
745
  env->SetProtoMethod(t, "unconsume", Parser::Unconsume);
974
745
  env->SetProtoMethod(t, "getCurrentBuffer", Parser::GetCurrentBuffer);
975
976
1490
  target->Set(env->context(),
977
              FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"),
978
4470
              t->GetFunction(env->context()).ToLocalChecked()).Check();
979
}
980
981
}  // anonymous namespace
982
}  // namespace node
983
984

19959
NODE_MODULE_CONTEXT_AWARE_INTERNAL(http_parser, node::InitializeHttpParser)