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: 369 392 94.1 %
Date: 2019-10-07 22:40:39 Branches: 174 238 73.1 %

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::Object;
66
using v8::String;
67
using v8::Uint32;
68
using v8::Undefined;
69
using v8::Value;
70
71
const uint32_t kOnHeaders = 0;
72
const uint32_t kOnHeadersComplete = 1;
73
const uint32_t kOnBody = 2;
74
const uint32_t kOnMessageComplete = 3;
75
const uint32_t kOnExecute = 4;
76
// Any more fields than this will be flushed into JS
77
const size_t kMaxHeaderFieldsCount = 32;
78
79
// helper class for the Parser
80
struct StringPtr {
81
199056
  StringPtr() {
82
199056
    on_heap_ = false;
83
199056
    Reset();
84
199056
  }
85
86
87
196350
  ~StringPtr() {
88
196350
    Reset();
89
196350
  }
90
91
92
  // If str_ does not point to a heap string yet, this function makes it do
93
  // so. This is called at the end of each http_parser_execute() so as not
94
  // to leak references. See issue #2438 and test-http-parser-bad-ref.js.
95
247830
  void Save() {
96

247830
    if (!on_heap_ && size_ > 0) {
97
116578
      char* s = new char[size_];
98
116578
      memcpy(s, str_, size_);
99
116578
      str_ = s;
100
116578
      on_heap_ = true;
101
    }
102
247830
  }
103
104
105
1110182
  void Reset() {
106
1110182
    if (on_heap_) {
107
116535
      delete[] str_;
108
116535
      on_heap_ = false;
109
    }
110
111
1110182
    str_ = nullptr;
112
1110182
    size_ = 0;
113
1110182
  }
114
115
116
500003
  void Update(const char* str, size_t size) {
117
500003
    if (str_ == nullptr) {
118
499775
      str_ = str;
119

228
    } else if (on_heap_ || str_ + size_ != str) {
120
      // Non-consecutive input, make a copy on the heap.
121
      // TODO(bnoordhuis) Use slab allocation, O(n) allocs is bad.
122
228
      char* s = new char[size_ + size];
123
228
      memcpy(s, str_, size_);
124
228
      memcpy(s + size_, str, size);
125
126
228
      if (on_heap_)
127
227
        delete[] str_;
128
      else
129
1
        on_heap_ = true;
130
131
228
      str_ = s;
132
    }
133
500003
    size_ += size;
134
500003
  }
135
136
137
499714
  Local<String> ToString(Environment* env) const {
138
499714
    if (str_)
139
499652
      return OneByteString(env->isolate(), str_, size_);
140
    else
141
124
      return String::Empty(env->isolate());
142
  }
143
144
145
  const char* str_;
146
  bool on_heap_;
147
  size_t size_;
148
};
149
150


5950
class Parser : public AsyncWrap, public StreamListener {
151
 public:
152
3016
  Parser(Environment* env, Local<Object> wrap)
153
      : AsyncWrap(env, wrap),
154
        current_buffer_len_(0),
155

6032
        current_buffer_data_(nullptr) {
156
3016
  }
157
158
159
  void MemoryInfo(MemoryTracker* tracker) const override {
160
    tracker->TrackField("current_buffer", current_buffer_);
161
  }
162
163
  SET_MEMORY_INFO_NAME(Parser)
164
  SET_SELF_SIZE(Parser)
165
166
127619
  int on_message_begin() {
167
127619
    num_fields_ = num_values_ = 0;
168
127619
    url_.Reset();
169
127619
    status_message_.Reset();
170
127619
    return 0;
171
  }
172
173
174
114838
  int on_url(const char* at, size_t length) {
175
114838
    int rv = TrackHeader(length);
176
114838
    if (rv != 0) {
177
      return rv;
178
    }
179
180
114838
    url_.Update(at, length);
181
114838
    return 0;
182
  }
183
184
185
12772
  int on_status(const char* at, size_t length) {
186
12772
    int rv = TrackHeader(length);
187
12772
    if (rv != 0) {
188
      return rv;
189
    }
190
191
12772
    status_message_.Update(at, length);
192
12772
    return 0;
193
  }
194
195
196
186124
  int on_header_field(const char* at, size_t length) {
197
186124
    int rv = TrackHeader(length);
198
186124
    if (rv != 0) {
199
      return rv;
200
    }
201
202
186124
    if (num_fields_ == num_values_) {
203
      // start of new field name
204
186095
      num_fields_++;
205
186095
      if (num_fields_ == kMaxHeaderFieldsCount) {
206
        // ran out of space - flush to javascript land
207
47
        Flush();
208
47
        num_fields_ = 1;
209
47
        num_values_ = 0;
210
      }
211
186095
      fields_[num_fields_ - 1].Reset();
212
    }
213
214
186124
    CHECK_LT(num_fields_, kMaxHeaderFieldsCount);
215
186124
    CHECK_EQ(num_fields_, num_values_ + 1);
216
217
186124
    fields_[num_fields_ - 1].Update(at, length);
218
219
186124
    return 0;
220
  }
221
222
223
186282
  int on_header_value(const char* at, size_t length) {
224
186282
    int rv = TrackHeader(length);
225
186282
    if (rv != 0) {
226
13
      return rv;
227
    }
228
229
186269
    if (num_values_ != num_fields_) {
230
      // start of new header value
231
186078
      num_values_++;
232
186078
      values_[num_values_ - 1].Reset();
233
    }
234
235
186269
    CHECK_LT(num_values_, arraysize(values_));
236
186269
    CHECK_EQ(num_values_, num_fields_);
237
238
186269
    values_[num_values_ - 1].Update(at, length);
239
240
186269
    return 0;
241
  }
242
243
244
127581
  int on_headers_complete() {
245
127581
    header_nread_ = 0;
246
247
    // Arguments for the on-headers-complete javascript callback. This
248
    // list needs to be kept in sync with the actual argument list for
249
    // `parserOnHeadersComplete` in lib/_http_common.js.
250
    enum on_headers_complete_arg_index {
251
      A_VERSION_MAJOR = 0,
252
      A_VERSION_MINOR,
253
      A_HEADERS,
254
      A_METHOD,
255
      A_URL,
256
      A_STATUS_CODE,
257
      A_STATUS_MESSAGE,
258
      A_UPGRADE,
259
      A_SHOULD_KEEP_ALIVE,
260
      A_MAX
261
    };
262
263
1275810
    Local<Value> argv[A_MAX];
264
127581
    Local<Object> obj = object();
265
    Local<Value> cb = obj->Get(env()->context(),
266
382743
                               kOnHeadersComplete).ToLocalChecked();
267
268
127581
    if (!cb->IsFunction())
269
      return 0;
270
271
127581
    Local<Value> undefined = Undefined(env()->isolate());
272
1275810
    for (size_t i = 0; i < arraysize(argv); i++)
273
1148229
      argv[i] = undefined;
274
275
127581
    if (have_flushed_) {
276
      // Slow case, flush remaining headers.
277
16
      Flush();
278
    } else {
279
      // Fast case, pass headers and URL to JS land.
280
255130
      argv[A_HEADERS] = CreateHeaders();
281
127565
      if (parser_.type == HTTP_REQUEST)
282
229612
        argv[A_URL] = url_.ToString(env());
283
    }
284
285
127581
    num_fields_ = 0;
286
127581
    num_values_ = 0;
287
288
    // METHOD
289
127581
    if (parser_.type == HTTP_REQUEST) {
290
      argv[A_METHOD] =
291
229628
          Uint32::NewFromUnsigned(env()->isolate(), parser_.method);
292
    }
293
294
    // STATUS
295
127581
    if (parser_.type == HTTP_RESPONSE) {
296
      argv[A_STATUS_CODE] =
297
25534
          Integer::New(env()->isolate(), parser_.status_code);
298
25534
      argv[A_STATUS_MESSAGE] = status_message_.ToString(env());
299
    }
300
301
    // VERSION
302
255162
    argv[A_VERSION_MAJOR] = Integer::New(env()->isolate(), parser_.http_major);
303
255162
    argv[A_VERSION_MINOR] = Integer::New(env()->isolate(), parser_.http_minor);
304
305
    bool should_keep_alive;
306
127581
    should_keep_alive = llhttp_should_keep_alive(&parser_);
307
308
    argv[A_SHOULD_KEEP_ALIVE] =
309
255162
        Boolean::New(env()->isolate(), should_keep_alive);
310
311
255162
    argv[A_UPGRADE] = Boolean::New(env()->isolate(), parser_.upgrade);
312
313
127581
    AsyncCallbackScope callback_scope(env());
314
315
    MaybeLocal<Value> head_response =
316
255162
        MakeCallback(cb.As<Function>(), arraysize(argv), argv);
317
318
    int64_t val;
319
320

637888
    if (head_response.IsEmpty() || !head_response.ToLocalChecked()
321
637867
                                        ->IntegerValue(env()->context())
322
510295
                                        .To(&val)) {
323
7
      got_exception_ = true;
324
7
      return -1;
325
    }
326
327
127572
    return val;
328
  }
329
330
331
22824
  int on_body(const char* at, size_t length) {
332
22824
    EscapableHandleScope scope(env()->isolate());
333
334
22824
    Local<Object> obj = object();
335
68472
    Local<Value> cb = obj->Get(env()->context(), kOnBody).ToLocalChecked();
336
337
22824
    if (!cb->IsFunction())
338
      return 0;
339
340
    // We came from consumed stream
341
45648
    if (current_buffer_.IsEmpty()) {
342
      // Make sure Buffer will be in parent HandleScope
343
      current_buffer_ = scope.Escape(Buffer::Copy(
344
          env()->isolate(),
345
          current_buffer_data_,
346
5282
          current_buffer_len_).ToLocalChecked());
347
    }
348
349
    Local<Value> argv[3] = {
350
      current_buffer_,
351
22824
      Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_),
352
      Integer::NewFromUnsigned(env()->isolate(), length)
353
114120
    };
354
355
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
356
22824
                                       arraysize(argv),
357
45648
                                       argv);
358
359
22824
    if (r.IsEmpty()) {
360
      got_exception_ = true;
361
      llhttp_set_error_reason(&parser_, "HPE_JS_EXCEPTION:JS Exception");
362
      return HPE_USER;
363
    }
364
365
22824
    return 0;
366
  }
367
368
369
126385
  int on_message_complete() {
370
126385
    HandleScope scope(env()->isolate());
371
372
126385
    if (num_fields_)
373
4
      Flush();  // Flush trailing HTTP headers.
374
375
126385
    Local<Object> obj = object();
376
    Local<Value> cb = obj->Get(env()->context(),
377
379155
                               kOnMessageComplete).ToLocalChecked();
378
379
126385
    if (!cb->IsFunction())
380
2
      return 0;
381
382
252766
    AsyncCallbackScope callback_scope(env());
383
384
126383
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(), 0, nullptr);
385
386
126383
    if (r.IsEmpty()) {
387
      got_exception_ = true;
388
      return -1;
389
    }
390
391
252768
    return 0;
392
  }
393
394
  // Reset nread for the next chunk
395
27213
  int on_chunk_header() {
396
27213
    header_nread_ = 0;
397
27213
    return 0;
398
  }
399
400
401
  // Reset nread for the next chunk
402
27058
  int on_chunk_complete() {
403
27058
    header_nread_ = 0;
404
27058
    return 0;
405
  }
406
407
3016
  static void New(const FunctionCallbackInfo<Value>& args) {
408
3016
    Environment* env = Environment::GetCurrent(args);
409
3016
    new Parser(env, args.This());
410
3016
  }
411
412
413
3
  static void Close(const FunctionCallbackInfo<Value>& args) {
414
    Parser* parser;
415
6
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
416
417
3
    delete parser;
418
  }
419
420
421
43443
  static void Free(const FunctionCallbackInfo<Value>& args) {
422
    Parser* parser;
423
86886
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
424
425
    // Since the Parser destructor isn't going to run the destroy() callbacks
426
    // it needs to be triggered manually.
427
43443
    parser->EmitTraceEventDestroy();
428
43443
    parser->EmitDestroy();
429
  }
430
431
432
123201
  void Save() {
433
123201
    url_.Save();
434
123201
    status_message_.Save();
435
436
123941
    for (size_t i = 0; i < num_fields_; i++) {
437
740
      fields_[i].Save();
438
    }
439
440
123889
    for (size_t i = 0; i < num_values_; i++) {
441
688
      values_[i].Save();
442
    }
443
123201
  }
444
445
446
  // var bytesParsed = parser->execute(buffer);
447
16102
  static void Execute(const FunctionCallbackInfo<Value>& args) {
448
    Parser* parser;
449
32203
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
450
32204
    CHECK(parser->current_buffer_.IsEmpty());
451
16102
    CHECK_EQ(parser->current_buffer_len_, 0);
452
16102
    CHECK_NULL(parser->current_buffer_data_);
453
454
16102
    ArrayBufferViewContents<char> buffer(args[0]);
455
456
    // This is a hack to get the current_buffer to the callbacks with the least
457
    // amount of overhead. Nothing else will run while http_parser_execute()
458
    // runs, therefore this pointer can be set and used for the execution.
459
48306
    parser->current_buffer_ = args[0].As<Object>();
460
461
16102
    Local<Value> ret = parser->Execute(buffer.data(), buffer.length());
462
463
16101
    if (!ret.IsEmpty())
464
32198
      args.GetReturnValue().Set(ret);
465
  }
466
467
468
29133
  static void Finish(const FunctionCallbackInfo<Value>& args) {
469
    Parser* parser;
470
58266
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
471
472
58266
    CHECK(parser->current_buffer_.IsEmpty());
473
29133
    Local<Value> ret = parser->Execute(nullptr, 0);
474
475
29133
    if (!ret.IsEmpty())
476
48
      args.GetReturnValue().Set(ret);
477
  }
478
479
480
43649
  static void Initialize(const FunctionCallbackInfo<Value>& args) {
481
43649
    Environment* env = Environment::GetCurrent(args);
482
483
87298
    CHECK(args[0]->IsInt32());
484
87298
    CHECK(args[1]->IsObject());
485
486
    llhttp_type_t type =
487
130947
        static_cast<llhttp_type_t>(args[0].As<Int32>()->Value());
488
489

43649
    CHECK(type == HTTP_REQUEST || type == HTTP_RESPONSE);
490
    Parser* parser;
491
87298
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
492
    // Should always be called from the same context.
493
43649
    CHECK_EQ(env, parser->env());
494
495
    AsyncWrap::ProviderType provider =
496
        (type == HTTP_REQUEST ?
497
            AsyncWrap::PROVIDER_HTTPINCOMINGMESSAGE
498
43649
            : AsyncWrap::PROVIDER_HTTPCLIENTREQUEST);
499
500
43649
    parser->set_provider_type(provider);
501
87298
    parser->AsyncReset(args[1].As<Object>());
502
43649
    parser->Init(type);
503
  }
504
505
  template <bool should_pause>
506
11
  static void Pause(const FunctionCallbackInfo<Value>& args) {
507
11
    Environment* env = Environment::GetCurrent(args);
508
    Parser* parser;
509

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

11
    CHECK_EQ(env, parser->env());
512
513

11
    if (parser->execute_depth_) {
514
4
      parser->pending_pause_ = should_pause;
515
4
      return;
516
    }
517
518
    if (should_pause) {
519
4
      llhttp_pause(&parser->parser_);
520
    } else {
521
3
      llhttp_resume(&parser->parser_);
522
    }
523
  }
524
525
526
31126
  static void Consume(const FunctionCallbackInfo<Value>& args) {
527
    Parser* parser;
528
62252
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
529
62252
    CHECK(args[0]->IsObject());
530
62252
    StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
531
31126
    CHECK_NOT_NULL(stream);
532
31126
    stream->PushStreamListener(parser);
533
  }
534
535
536
31109
  static void Unconsume(const FunctionCallbackInfo<Value>& args) {
537
    Parser* parser;
538
31109
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
539
540
    // Already unconsumed
541
31109
    if (parser->stream_ == nullptr)
542
      return;
543
544
31109
    parser->stream_->RemoveStreamListener(parser);
545
  }
546
547
548
48
  static void GetCurrentBuffer(const FunctionCallbackInfo<Value>& args) {
549
    Parser* parser;
550
96
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
551
552
    Local<Object> ret = Buffer::Copy(
553
        parser->env(),
554
        parser->current_buffer_data_,
555
96
        parser->current_buffer_len_).ToLocalChecked();
556
557
96
    args.GetReturnValue().Set(ret);
558
  }
559
560
 protected:
561
  static const size_t kAllocBufferSize = 64 * 1024;
562
563
135565
  uv_buf_t OnStreamAlloc(size_t suggested_size) override {
564
    // For most types of streams, OnStreamRead will be immediately after
565
    // OnStreamAlloc, and will consume all data, so using a static buffer for
566
    // reading is more efficient. For other streams, just use Malloc() directly.
567
135565
    if (env()->http_parser_buffer_in_use())
568
      return uv_buf_init(Malloc(suggested_size), suggested_size);
569
135565
    env()->set_http_parser_buffer_in_use(true);
570
571
135565
    if (env()->http_parser_buffer() == nullptr)
572
294
      env()->set_http_parser_buffer(new char[kAllocBufferSize]);
573
574
135565
    return uv_buf_init(env()->http_parser_buffer(), kAllocBufferSize);
575
  }
576
577
578
135582
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override {
579
135582
    HandleScope scope(env()->isolate());
580
    // Once we’re done here, either indicate that the HTTP parser buffer
581
    // is free for re-use, or free() the data if it didn’t come from there
582
    // in the first place.
583
135578
    OnScopeLeave on_scope_leave([&]() {
584
135578
      if (buf.base == env()->http_parser_buffer())
585
135561
        env()->set_http_parser_buffer_in_use(false);
586
      else
587
17
        free(buf.base);
588
377250
    });
589
590
135582
    if (nread < 0) {
591
28481
      PassReadErrorToPreviousListener(nread);
592
28481
      return;
593
    }
594
595
    // Ignore, empty reads have special meaning in http parser
596
107101
    if (nread == 0)
597
      return;
598
599
107101
    current_buffer_.Clear();
600
107101
    Local<Value> ret = Execute(buf.base, nread);
601
602
    // Exception
603
107100
    if (ret.IsEmpty())
604
5
      return;
605
606
    Local<Value> cb =
607
321285
        object()->Get(env()->context(), kOnExecute).ToLocalChecked();
608
609
107095
    if (!cb->IsFunction())
610
1002
      return;
611
612
    // Hooks for GetCurrentBuffer
613
106093
    current_buffer_len_ = nread;
614
106093
    current_buffer_data_ = buf.base;
615
616
106093
    MakeCallback(cb.As<Function>(), 1, &ret);
617
618
106090
    current_buffer_len_ = 0;
619
212180
    current_buffer_data_ = nullptr;
620
  }
621
622
623
152336
  Local<Value> Execute(const char* data, size_t len) {
624
152336
    EscapableHandleScope scope(env()->isolate());
625
626
152336
    current_buffer_len_ = len;
627
152336
    current_buffer_data_ = data;
628
152336
    got_exception_ = false;
629
630
    llhttp_errno_t err;
631
632
    // Do not allow re-entering `http_parser_execute()`
633
152336
    CHECK_EQ(execute_depth_, 0);
634
635
152336
    execute_depth_++;
636
152336
    if (data == nullptr) {
637
29133
      err = llhttp_finish(&parser_);
638
    } else {
639
123203
      err = llhttp_execute(&parser_, data, len);
640
123201
      Save();
641
    }
642
152334
    execute_depth_--;
643
644
    // Calculate bytes read and resume after Upgrade/CONNECT pause
645
152334
    size_t nread = len;
646
152334
    if (err != HPE_OK) {
647
314
      nread = llhttp_get_error_pos(&parser_) - data;
648
649
      // This isn't a real pause, just a way to stop parsing early.
650
314
      if (err == HPE_PAUSED_UPGRADE) {
651
51
        err = HPE_OK;
652
51
        llhttp_resume_after_upgrade(&parser_);
653
      }
654
    }
655
656
    // Apply pending pause
657
152334
    if (pending_pause_) {
658
      pending_pause_ = false;
659
      llhttp_pause(&parser_);
660
    }
661
662
    // Unassign the 'buffer_' variable
663
152334
    current_buffer_.Clear();
664
152334
    current_buffer_len_ = 0;
665
152334
    current_buffer_data_ = nullptr;
666
667
    // If there was an exception in one of the callbacks
668
152334
    if (got_exception_)
669
7
      return scope.Escape(Local<Value>());
670
671
152327
    Local<Integer> nread_obj = Integer::New(env()->isolate(), nread);
672
673
    // If there was a parse error in one of the callbacks
674
    // TODO(bnoordhuis) What if there is an error on EOF?
675

152327
    if (!parser_.upgrade && err != HPE_OK) {
676
205
      Local<Value> e = Exception::Error(env()->parse_error_string());
677
410
      Local<Object> obj = e->ToObject(env()->isolate()->GetCurrentContext())
678
410
        .ToLocalChecked();
679
      obj->Set(env()->context(),
680
               env()->bytes_parsed_string(),
681
820
               nread_obj).Check();
682
205
      const char* errno_reason = llhttp_get_error_reason(&parser_);
683
684
      Local<String> code;
685
      Local<String> reason;
686
205
      if (err == HPE_USER) {
687
13
        const char* colon = strchr(errno_reason, ':');
688
13
        CHECK_NOT_NULL(colon);
689
        code = OneByteString(env()->isolate(), errno_reason,
690
13
                             colon - errno_reason);
691
13
        reason = OneByteString(env()->isolate(), colon + 1);
692
      } else {
693
192
        code = OneByteString(env()->isolate(), llhttp_errno_name(err));
694
192
        reason = OneByteString(env()->isolate(), errno_reason);
695
      }
696
697
820
      obj->Set(env()->context(), env()->code_string(), code).Check();
698
820
      obj->Set(env()->context(), env()->reason_string(), reason).Check();
699
      return scope.Escape(e);
700
    }
701
702
    // No return value is needed for `Finish()`
703
152122
    if (data == nullptr) {
704
29109
      return scope.Escape(Local<Value>());
705
    }
706
123013
    return scope.Escape(nread_obj);
707
  }
708
709
127632
  Local<Array> CreateHeaders() {
710
    // There could be extra entries but the max size should be fixed
711
8296080
    Local<Value> headers_v[kMaxHeaderFieldsCount * 2];
712
713
313669
    for (size_t i = 0; i < num_values_; ++i) {
714
372074
      headers_v[i * 2] = fields_[i].ToString(env());
715
372074
      headers_v[i * 2 + 1] = values_[i].ToString(env());
716
    }
717
718
127632
    return Array::New(env()->isolate(), headers_v, num_values_ * 2);
719
  }
720
721
722
  // spill headers and request path to JS land
723
67
  void Flush() {
724
67
    HandleScope scope(env()->isolate());
725
726
67
    Local<Object> obj = object();
727
201
    Local<Value> cb = obj->Get(env()->context(), kOnHeaders).ToLocalChecked();
728
729
67
    if (!cb->IsFunction())
730
67
      return;
731
732
    Local<Value> argv[2] = {
733
      CreateHeaders(),
734
      url_.ToString(env())
735
201
    };
736
737
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
738
67
                                       arraysize(argv),
739
134
                                       argv);
740
741
67
    if (r.IsEmpty())
742
      got_exception_ = true;
743
744
67
    url_.Reset();
745
67
    have_flushed_ = true;
746
  }
747
748
749
43649
  void Init(llhttp_type_t type) {
750
43649
    llhttp_init(&parser_, type, &settings);
751
43649
    header_nread_ = 0;
752
43649
    url_.Reset();
753
43649
    status_message_.Reset();
754
43649
    num_fields_ = 0;
755
43649
    num_values_ = 0;
756
43649
    have_flushed_ = false;
757
43649
    got_exception_ = false;
758
43649
  }
759
760
761
500016
  int TrackHeader(size_t len) {
762
500016
    header_nread_ += len;
763
500016
    if (header_nread_ >= per_process::cli_options->max_http_header_size) {
764
13
      llhttp_set_error_reason(&parser_, "HPE_HEADER_OVERFLOW:Header overflow");
765
13
      return HPE_USER;
766
    }
767
500003
    return 0;
768
  }
769
770
771
958615
  int MaybePause() {
772
958615
    CHECK_NE(execute_depth_, 0);
773
774
958615
    if (!pending_pause_) {
775
958615
      return 0;
776
    }
777
778
    pending_pause_ = false;
779
    llhttp_set_error_reason(&parser_, "Paused in callback");
780
    return HPE_PAUSED;
781
  }
782
783
  llhttp_t parser_;
784
  StringPtr fields_[kMaxHeaderFieldsCount];  // header fields
785
  StringPtr values_[kMaxHeaderFieldsCount];  // header values
786
  StringPtr url_;
787
  StringPtr status_message_;
788
  size_t num_fields_;
789
  size_t num_values_;
790
  bool have_flushed_;
791
  bool got_exception_;
792
  Local<Object> current_buffer_;
793
  size_t current_buffer_len_;
794
  const char* current_buffer_data_;
795
  unsigned int execute_depth_ = 0;
796
  bool pending_pause_ = false;
797
  uint64_t header_nread_ = 0;
798
799
  // These are helper functions for filling `http_parser_settings`, which turn
800
  // a member function of Parser into a C-style HTTP parser callback.
801
  template <typename Parser, Parser> struct Proxy;
802
  template <typename Parser, typename ...Args, int (Parser::*Member)(Args...)>
803
  struct Proxy<int (Parser::*)(Args...), Member> {
804
958696
    static int Raw(llhttp_t* p, Args ... args) {
805
958696
      Parser* parser = ContainerOf(&Parser::parser_, p);
806
958696
      int rv = (parser->*Member)(std::forward<Args>(args)...);
807





958694
      if (rv == 0) {
808
958615
        rv = parser->MaybePause();
809
      }
810
958694
      return rv;
811
    }
812
  };
813
814
  typedef int (Parser::*Call)();
815
  typedef int (Parser::*DataCall)(const char* at, size_t length);
816
817
  static const llhttp_settings_t settings;
818
};
819
820
const llhttp_settings_t Parser::settings = {
821
  Proxy<Call, &Parser::on_message_begin>::Raw,
822
  Proxy<DataCall, &Parser::on_url>::Raw,
823
  Proxy<DataCall, &Parser::on_status>::Raw,
824
  Proxy<DataCall, &Parser::on_header_field>::Raw,
825
  Proxy<DataCall, &Parser::on_header_value>::Raw,
826
  Proxy<Call, &Parser::on_headers_complete>::Raw,
827
  Proxy<DataCall, &Parser::on_body>::Raw,
828
  Proxy<Call, &Parser::on_message_complete>::Raw,
829
  Proxy<Call, &Parser::on_chunk_header>::Raw,
830
  Proxy<Call, &Parser::on_chunk_complete>::Raw,
831
};
832
833
834
753
void InitializeHttpParser(Local<Object> target,
835
                          Local<Value> unused,
836
                          Local<Context> context,
837
                          void* priv) {
838
753
  Environment* env = Environment::GetCurrent(context);
839
753
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
840
1506
  t->InstanceTemplate()->SetInternalFieldCount(1);
841
1506
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"));
842
843
753
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"),
844
2259
         Integer::New(env->isolate(), HTTP_REQUEST));
845
753
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "RESPONSE"),
846
2259
         Integer::New(env->isolate(), HTTP_RESPONSE));
847
753
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeaders"),
848
2259
         Integer::NewFromUnsigned(env->isolate(), kOnHeaders));
849
753
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeadersComplete"),
850
2259
         Integer::NewFromUnsigned(env->isolate(), kOnHeadersComplete));
851
753
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnBody"),
852
2259
         Integer::NewFromUnsigned(env->isolate(), kOnBody));
853
753
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageComplete"),
854
2259
         Integer::NewFromUnsigned(env->isolate(), kOnMessageComplete));
855
753
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnExecute"),
856
2259
         Integer::NewFromUnsigned(env->isolate(), kOnExecute));
857
858
753
  Local<Array> methods = Array::New(env->isolate());
859
#define V(num, name, string)                                                  \
860
    methods->Set(env->context(),                                              \
861
        num, FIXED_ONE_BYTE_STRING(env->isolate(), #string)).Check();
862
77559
  HTTP_METHOD_MAP(V)
863
#undef V
864
  target->Set(env->context(),
865
              FIXED_ONE_BYTE_STRING(env->isolate(), "methods"),
866
3012
              methods).Check();
867
868
1506
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
869
753
  env->SetProtoMethod(t, "close", Parser::Close);
870
753
  env->SetProtoMethod(t, "free", Parser::Free);
871
753
  env->SetProtoMethod(t, "execute", Parser::Execute);
872
753
  env->SetProtoMethod(t, "finish", Parser::Finish);
873
753
  env->SetProtoMethod(t, "initialize", Parser::Initialize);
874
753
  env->SetProtoMethod(t, "pause", Parser::Pause<true>);
875
753
  env->SetProtoMethod(t, "resume", Parser::Pause<false>);
876
753
  env->SetProtoMethod(t, "consume", Parser::Consume);
877
753
  env->SetProtoMethod(t, "unconsume", Parser::Unconsume);
878
753
  env->SetProtoMethod(t, "getCurrentBuffer", Parser::GetCurrentBuffer);
879
880
  target->Set(env->context(),
881
              FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"),
882
4518
              t->GetFunction(env->context()).ToLocalChecked()).Check();
883
753
}
884
885
}  // anonymous namespace
886
}  // namespace node
887
888
4948
NODE_MODULE_CONTEXT_AWARE_INTERNAL(http_parser, node::InitializeHttpParser)