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-06 22:30:00 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
198528
  StringPtr() {
82
198528
    on_heap_ = false;
83
198528
    Reset();
84
198528
  }
85
86
87
195690
  ~StringPtr() {
88
195690
    Reset();
89
195690
  }
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
252502
  void Save() {
96

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

242
    } 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
242
      char* s = new char[size_ + size];
123
242
      memcpy(s, str_, size_);
124
242
      memcpy(s + size_, str, size);
125
126
242
      if (on_heap_)
127
241
        delete[] str_;
128
      else
129
1
        on_heap_ = true;
130
131
242
      str_ = s;
132
    }
133
507082
    size_ += size;
134
507082
  }
135
136
137
506779
  Local<String> ToString(Environment* env) const {
138
506779
    if (str_)
139
506717
      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


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

6016
        current_buffer_data_(nullptr) {
156
3008
  }
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
129858
  int on_message_begin() {
167
129858
    num_fields_ = num_values_ = 0;
168
129858
    url_.Reset();
169
129858
    status_message_.Reset();
170
129858
    return 0;
171
  }
172
173
174
117068
  int on_url(const char* at, size_t length) {
175
117068
    int rv = TrackHeader(length);
176
117068
    if (rv != 0) {
177
      return rv;
178
    }
179
180
117068
    url_.Update(at, length);
181
117068
    return 0;
182
  }
183
184
185
12781
  int on_status(const char* at, size_t length) {
186
12781
    int rv = TrackHeader(length);
187
12781
    if (rv != 0) {
188
      return rv;
189
    }
190
191
12781
    status_message_.Update(at, length);
192
12781
    return 0;
193
  }
194
195
196
188537
  int on_header_field(const char* at, size_t length) {
197
188537
    int rv = TrackHeader(length);
198
188537
    if (rv != 0) {
199
      return rv;
200
    }
201
202
188537
    if (num_fields_ == num_values_) {
203
      // start of new field name
204
188508
      num_fields_++;
205
188508
      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
188508
      fields_[num_fields_ - 1].Reset();
212
    }
213
214
188537
    CHECK_LT(num_fields_, kMaxHeaderFieldsCount);
215
188537
    CHECK_EQ(num_fields_, num_values_ + 1);
216
217
188537
    fields_[num_fields_ - 1].Update(at, length);
218
219
188537
    return 0;
220
  }
221
222
223
188709
  int on_header_value(const char* at, size_t length) {
224
188709
    int rv = TrackHeader(length);
225
188709
    if (rv != 0) {
226
13
      return rv;
227
    }
228
229
188696
    if (num_values_ != num_fields_) {
230
      // start of new header value
231
188491
      num_values_++;
232
188491
      values_[num_values_ - 1].Reset();
233
    }
234
235
188696
    CHECK_LT(num_values_, arraysize(values_));
236
188696
    CHECK_EQ(num_values_, num_fields_);
237
238
188696
    values_[num_values_ - 1].Update(at, length);
239
240
188696
    return 0;
241
  }
242
243
244
129820
  int on_headers_complete() {
245
129820
    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
1298200
    Local<Value> argv[A_MAX];
264
129820
    Local<Object> obj = object();
265
    Local<Value> cb = obj->Get(env()->context(),
266
389460
                               kOnHeadersComplete).ToLocalChecked();
267
268
129820
    if (!cb->IsFunction())
269
      return 0;
270
271
129820
    Local<Value> undefined = Undefined(env()->isolate());
272
1298200
    for (size_t i = 0; i < arraysize(argv); i++)
273
1168380
      argv[i] = undefined;
274
275
129820
    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
259608
      argv[A_HEADERS] = CreateHeaders();
281
129804
      if (parser_.type == HTTP_REQUEST)
282
234072
        argv[A_URL] = url_.ToString(env());
283
    }
284
285
129820
    num_fields_ = 0;
286
129820
    num_values_ = 0;
287
288
    // METHOD
289
129820
    if (parser_.type == HTTP_REQUEST) {
290
      argv[A_METHOD] =
291
234088
          Uint32::NewFromUnsigned(env()->isolate(), parser_.method);
292
    }
293
294
    // STATUS
295
129820
    if (parser_.type == HTTP_RESPONSE) {
296
      argv[A_STATUS_CODE] =
297
25552
          Integer::New(env()->isolate(), parser_.status_code);
298
25552
      argv[A_STATUS_MESSAGE] = status_message_.ToString(env());
299
    }
300
301
    // VERSION
302
259640
    argv[A_VERSION_MAJOR] = Integer::New(env()->isolate(), parser_.http_major);
303
259640
    argv[A_VERSION_MINOR] = Integer::New(env()->isolate(), parser_.http_minor);
304
305
    bool should_keep_alive;
306
129820
    should_keep_alive = llhttp_should_keep_alive(&parser_);
307
308
    argv[A_SHOULD_KEEP_ALIVE] =
309
259640
        Boolean::New(env()->isolate(), should_keep_alive);
310
311
259640
    argv[A_UPGRADE] = Boolean::New(env()->isolate(), parser_.upgrade);
312
313
129820
    AsyncCallbackScope callback_scope(env());
314
315
    MaybeLocal<Value> head_response =
316
259640
        MakeCallback(cb.As<Function>(), arraysize(argv), argv);
317
318
    int64_t val;
319
320

649083
    if (head_response.IsEmpty() || !head_response.ToLocalChecked()
321
649062
                                        ->IntegerValue(env()->context())
322
519251
                                        .To(&val)) {
323
7
      got_exception_ = true;
324
7
      return -1;
325
    }
326
327
129811
    return val;
328
  }
329
330
331
22880
  int on_body(const char* at, size_t length) {
332
22880
    EscapableHandleScope scope(env()->isolate());
333
334
22880
    Local<Object> obj = object();
335
68640
    Local<Value> cb = obj->Get(env()->context(), kOnBody).ToLocalChecked();
336
337
22880
    if (!cb->IsFunction())
338
      return 0;
339
340
    // We came from consumed stream
341
45760
    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
5318
          current_buffer_len_).ToLocalChecked());
347
    }
348
349
    Local<Value> argv[3] = {
350
      current_buffer_,
351
22880
      Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_),
352
      Integer::NewFromUnsigned(env()->isolate(), length)
353
114400
    };
354
355
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
356
22880
                                       arraysize(argv),
357
45760
                                       argv);
358
359
22880
    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
22880
    return 0;
366
  }
367
368
369
128624
  int on_message_complete() {
370
128624
    HandleScope scope(env()->isolate());
371
372
128624
    if (num_fields_)
373
4
      Flush();  // Flush trailing HTTP headers.
374
375
128624
    Local<Object> obj = object();
376
    Local<Value> cb = obj->Get(env()->context(),
377
385872
                               kOnMessageComplete).ToLocalChecked();
378
379
128624
    if (!cb->IsFunction())
380
2
      return 0;
381
382
257244
    AsyncCallbackScope callback_scope(env());
383
384
128622
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(), 0, nullptr);
385
386
128622
    if (r.IsEmpty()) {
387
      got_exception_ = true;
388
      return -1;
389
    }
390
391
257246
    return 0;
392
  }
393
394
  // Reset nread for the next chunk
395
27248
  int on_chunk_header() {
396
27248
    header_nread_ = 0;
397
27248
    return 0;
398
  }
399
400
401
  // Reset nread for the next chunk
402
27093
  int on_chunk_complete() {
403
27093
    header_nread_ = 0;
404
27093
    return 0;
405
  }
406
407
3008
  static void New(const FunctionCallbackInfo<Value>& args) {
408
3008
    Environment* env = Environment::GetCurrent(args);
409
3008
    new Parser(env, args.This());
410
3008
  }
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
43616
  static void Free(const FunctionCallbackInfo<Value>& args) {
422
    Parser* parser;
423
87232
    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
43616
    parser->EmitTraceEventDestroy();
428
43616
    parser->EmitDestroy();
429
  }
430
431
432
125499
  void Save() {
433
125499
    url_.Save();
434
125499
    status_message_.Save();
435
436
126277
    for (size_t i = 0; i < num_fields_; i++) {
437
778
      fields_[i].Save();
438
    }
439
440
126225
    for (size_t i = 0; i < num_values_; i++) {
441
726
      values_[i].Save();
442
    }
443
125499
  }
444
445
446
  // var bytesParsed = parser->execute(buffer);
447
16149
  static void Execute(const FunctionCallbackInfo<Value>& args) {
448
    Parser* parser;
449
32297
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
450
32298
    CHECK(parser->current_buffer_.IsEmpty());
451
16149
    CHECK_EQ(parser->current_buffer_len_, 0);
452
16149
    CHECK_NULL(parser->current_buffer_data_);
453
454
16149
    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
48447
    parser->current_buffer_ = args[0].As<Object>();
460
461
16149
    Local<Value> ret = parser->Execute(buffer.data(), buffer.length());
462
463
16148
    if (!ret.IsEmpty())
464
32292
      args.GetReturnValue().Set(ret);
465
  }
466
467
468
29132
  static void Finish(const FunctionCallbackInfo<Value>& args) {
469
    Parser* parser;
470
58264
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
471
472
58264
    CHECK(parser->current_buffer_.IsEmpty());
473
29132
    Local<Value> ret = parser->Execute(nullptr, 0);
474
475
29132
    if (!ret.IsEmpty())
476
48
      args.GetReturnValue().Set(ret);
477
  }
478
479
480
43822
  static void Initialize(const FunctionCallbackInfo<Value>& args) {
481
43822
    Environment* env = Environment::GetCurrent(args);
482
483
87644
    CHECK(args[0]->IsInt32());
484
87644
    CHECK(args[1]->IsObject());
485
486
    llhttp_type_t type =
487
131466
        static_cast<llhttp_type_t>(args[0].As<Int32>()->Value());
488
489

43822
    CHECK(type == HTTP_REQUEST || type == HTTP_RESPONSE);
490
    Parser* parser;
491
87644
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
492
    // Should always be called from the same context.
493
43822
    CHECK_EQ(env, parser->env());
494
495
    AsyncWrap::ProviderType provider =
496
        (type == HTTP_REQUEST ?
497
            AsyncWrap::PROVIDER_HTTPINCOMINGMESSAGE
498
43822
            : AsyncWrap::PROVIDER_HTTPCLIENTREQUEST);
499
500
43822
    parser->set_provider_type(provider);
501
87644
    parser->AsyncReset(args[1].As<Object>());
502
43822
    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
31290
  static void Consume(const FunctionCallbackInfo<Value>& args) {
527
    Parser* parser;
528
62580
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
529
62580
    CHECK(args[0]->IsObject());
530
62580
    StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
531
31290
    CHECK_NOT_NULL(stream);
532
31290
    stream->PushStreamListener(parser);
533
  }
534
535
536
31273
  static void Unconsume(const FunctionCallbackInfo<Value>& args) {
537
    Parser* parser;
538
31273
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
539
540
    // Already unconsumed
541
31273
    if (parser->stream_ == nullptr)
542
      return;
543
544
31273
    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
137816
  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
137816
    if (env()->http_parser_buffer_in_use())
568
      return uv_buf_init(Malloc(suggested_size), suggested_size);
569
137816
    env()->set_http_parser_buffer_in_use(true);
570
571
137816
    if (env()->http_parser_buffer() == nullptr)
572
294
      env()->set_http_parser_buffer(new char[kAllocBufferSize]);
573
574
137816
    return uv_buf_init(env()->http_parser_buffer(), kAllocBufferSize);
575
  }
576
577
578
137833
  void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override {
579
137833
    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
137829
    OnScopeLeave on_scope_leave([&]() {
584
137829
      if (buf.base == env()->http_parser_buffer())
585
137812
        env()->set_http_parser_buffer_in_use(false);
586
      else
587
17
        free(buf.base);
588
384003
    });
589
590
137833
    if (nread < 0) {
591
28481
      PassReadErrorToPreviousListener(nread);
592
28481
      return;
593
    }
594
595
    // Ignore, empty reads have special meaning in http parser
596
109352
    if (nread == 0)
597
      return;
598
599
109352
    current_buffer_.Clear();
600
109352
    Local<Value> ret = Execute(buf.base, nread);
601
602
    // Exception
603
109351
    if (ret.IsEmpty())
604
5
      return;
605
606
    Local<Value> cb =
607
328038
        object()->Get(env()->context(), kOnExecute).ToLocalChecked();
608
609
109346
    if (!cb->IsFunction())
610
1002
      return;
611
612
    // Hooks for GetCurrentBuffer
613
108344
    current_buffer_len_ = nread;
614
108344
    current_buffer_data_ = buf.base;
615
616
108344
    MakeCallback(cb.As<Function>(), 1, &ret);
617
618
108341
    current_buffer_len_ = 0;
619
216682
    current_buffer_data_ = nullptr;
620
  }
621
622
623
154633
  Local<Value> Execute(const char* data, size_t len) {
624
154633
    EscapableHandleScope scope(env()->isolate());
625
626
154633
    current_buffer_len_ = len;
627
154633
    current_buffer_data_ = data;
628
154633
    got_exception_ = false;
629
630
    llhttp_errno_t err;
631
632
    // Do not allow re-entering `http_parser_execute()`
633
154633
    CHECK_EQ(execute_depth_, 0);
634
635
154633
    execute_depth_++;
636
154633
    if (data == nullptr) {
637
29132
      err = llhttp_finish(&parser_);
638
    } else {
639
125501
      err = llhttp_execute(&parser_, data, len);
640
125499
      Save();
641
    }
642
154631
    execute_depth_--;
643
644
    // Calculate bytes read and resume after Upgrade/CONNECT pause
645
154631
    size_t nread = len;
646
154631
    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
154631
    if (pending_pause_) {
658
      pending_pause_ = false;
659
      llhttp_pause(&parser_);
660
    }
661
662
    // Unassign the 'buffer_' variable
663
154631
    current_buffer_.Clear();
664
154631
    current_buffer_len_ = 0;
665
154631
    current_buffer_data_ = nullptr;
666
667
    // If there was an exception in one of the callbacks
668
154631
    if (got_exception_)
669
7
      return scope.Escape(Local<Value>());
670
671
154624
    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

154624
    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
154419
    if (data == nullptr) {
704
29108
      return scope.Escape(Local<Value>());
705
    }
706
125311
    return scope.Escape(nread_obj);
707
  }
708
709
129871
  Local<Array> CreateHeaders() {
710
    // There could be extra entries but the max size should be fixed
711
8441615
    Local<Value> headers_v[kMaxHeaderFieldsCount * 2];
712
713
318321
    for (size_t i = 0; i < num_values_; ++i) {
714
376900
      headers_v[i * 2] = fields_[i].ToString(env());
715
376900
      headers_v[i * 2 + 1] = values_[i].ToString(env());
716
    }
717
718
129871
    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
43822
  void Init(llhttp_type_t type) {
750
43822
    llhttp_init(&parser_, type, &settings);
751
43822
    header_nread_ = 0;
752
43822
    url_.Reset();
753
43822
    status_message_.Reset();
754
43822
    num_fields_ = 0;
755
43822
    num_values_ = 0;
756
43822
    have_flushed_ = false;
757
43822
    got_exception_ = false;
758
43822
  }
759
760
761
507095
  int TrackHeader(size_t len) {
762
507095
    header_nread_ += len;
763
507095
    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
507082
    return 0;
768
  }
769
770
771
972537
  int MaybePause() {
772
972537
    CHECK_NE(execute_depth_, 0);
773
774
972537
    if (!pending_pause_) {
775
972537
      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
972618
    static int Raw(llhttp_t* p, Args ... args) {
805
972618
      Parser* parser = ContainerOf(&Parser::parser_, p);
806
972618
      int rv = (parser->*Member)(std::forward<Args>(args)...);
807





972616
      if (rv == 0) {
808
972537
        rv = parser->MaybePause();
809
      }
810
972616
      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
754
void InitializeHttpParser(Local<Object> target,
835
                          Local<Value> unused,
836
                          Local<Context> context,
837
                          void* priv) {
838
754
  Environment* env = Environment::GetCurrent(context);
839
754
  Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
840
1508
  t->InstanceTemplate()->SetInternalFieldCount(1);
841
1508
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"));
842
843
754
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"),
844
2262
         Integer::New(env->isolate(), HTTP_REQUEST));
845
754
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "RESPONSE"),
846
2262
         Integer::New(env->isolate(), HTTP_RESPONSE));
847
754
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeaders"),
848
2262
         Integer::NewFromUnsigned(env->isolate(), kOnHeaders));
849
754
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeadersComplete"),
850
2262
         Integer::NewFromUnsigned(env->isolate(), kOnHeadersComplete));
851
754
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnBody"),
852
2262
         Integer::NewFromUnsigned(env->isolate(), kOnBody));
853
754
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageComplete"),
854
2262
         Integer::NewFromUnsigned(env->isolate(), kOnMessageComplete));
855
754
  t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnExecute"),
856
2262
         Integer::NewFromUnsigned(env->isolate(), kOnExecute));
857
858
754
  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
77662
  HTTP_METHOD_MAP(V)
863
#undef V
864
  target->Set(env->context(),
865
              FIXED_ONE_BYTE_STRING(env->isolate(), "methods"),
866
3016
              methods).Check();
867
868
1508
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
869
754
  env->SetProtoMethod(t, "close", Parser::Close);
870
754
  env->SetProtoMethod(t, "free", Parser::Free);
871
754
  env->SetProtoMethod(t, "execute", Parser::Execute);
872
754
  env->SetProtoMethod(t, "finish", Parser::Finish);
873
754
  env->SetProtoMethod(t, "initialize", Parser::Initialize);
874
754
  env->SetProtoMethod(t, "pause", Parser::Pause<true>);
875
754
  env->SetProtoMethod(t, "resume", Parser::Pause<false>);
876
754
  env->SetProtoMethod(t, "consume", Parser::Consume);
877
754
  env->SetProtoMethod(t, "unconsume", Parser::Unconsume);
878
754
  env->SetProtoMethod(t, "getCurrentBuffer", Parser::GetCurrentBuffer);
879
880
  target->Set(env->context(),
881
              FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"),
882
4524
              t->GetFunction(env->context()).ToLocalChecked()).Check();
883
754
}
884
885
}  // anonymous namespace
886
}  // namespace node
887
888
5058
NODE_MODULE_CONTEXT_AWARE_INTERNAL(http_parser, node::InitializeHttpParser)