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-05 22:32:21 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
195294
  StringPtr() {
82
195294
    on_heap_ = false;
83
195294
    Reset();
84
195294
  }
85
86
87
192654
  ~StringPtr() {
88
192654
    Reset();
89
192654
  }
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
247597
  void Save() {
96

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

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


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

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

637648
    if (head_response.IsEmpty() || !head_response.ToLocalChecked()
321
637627
                                        ->IntegerValue(env()->context())
322
510103
                                        .To(&val)) {
323
7
      got_exception_ = true;
324
7
      return -1;
325
    }
326
327
127524
    return val;
328
  }
329
330
331
22779
  int on_body(const char* at, size_t length) {
332
22779
    EscapableHandleScope scope(env()->isolate());
333
334
22779
    Local<Object> obj = object();
335
68337
    Local<Value> cb = obj->Get(env()->context(), kOnBody).ToLocalChecked();
336
337
22779
    if (!cb->IsFunction())
338
      return 0;
339
340
    // We came from consumed stream
341
45558
    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
5304
          current_buffer_len_).ToLocalChecked());
347
    }
348
349
    Local<Value> argv[3] = {
350
      current_buffer_,
351
22779
      Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_),
352
      Integer::NewFromUnsigned(env()->isolate(), length)
353
113895
    };
354
355
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(),
356
22779
                                       arraysize(argv),
357
45558
                                       argv);
358
359
22779
    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
22779
    return 0;
366
  }
367
368
369
126337
  int on_message_complete() {
370
126337
    HandleScope scope(env()->isolate());
371
372
126337
    if (num_fields_)
373
4
      Flush();  // Flush trailing HTTP headers.
374
375
126337
    Local<Object> obj = object();
376
    Local<Value> cb = obj->Get(env()->context(),
377
379011
                               kOnMessageComplete).ToLocalChecked();
378
379
126337
    if (!cb->IsFunction())
380
2
      return 0;
381
382
252670
    AsyncCallbackScope callback_scope(env());
383
384
126335
    MaybeLocal<Value> r = MakeCallback(cb.As<Function>(), 0, nullptr);
385
386
126335
    if (r.IsEmpty()) {
387
      got_exception_ = true;
388
      return -1;
389
    }
390
391
252672
    return 0;
392
  }
393
394
  // Reset nread for the next chunk
395
27247
  int on_chunk_header() {
396
27247
    header_nread_ = 0;
397
27247
    return 0;
398
  }
399
400
401
  // Reset nread for the next chunk
402
27092
  int on_chunk_complete() {
403
27092
    header_nread_ = 0;
404
27092
    return 0;
405
  }
406
407
2959
  static void New(const FunctionCallbackInfo<Value>& args) {
408
2959
    Environment* env = Environment::GetCurrent(args);
409
2959
    new Parser(env, args.This());
410
2959
  }
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
43609
  static void Free(const FunctionCallbackInfo<Value>& args) {
422
    Parser* parser;
423
87218
    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
43609
    parser->EmitTraceEventDestroy();
428
43609
    parser->EmitDestroy();
429
  }
430
431
432
123089
  void Save() {
433
123089
    url_.Save();
434
123089
    status_message_.Save();
435
436
123825
    for (size_t i = 0; i < num_fields_; i++) {
437
736
      fields_[i].Save();
438
    }
439
440
123772
    for (size_t i = 0; i < num_values_; i++) {
441
683
      values_[i].Save();
442
    }
443
123089
  }
444
445
446
  // var bytesParsed = parser->execute(buffer);
447
16057
  static void Execute(const FunctionCallbackInfo<Value>& args) {
448
    Parser* parser;
449
32113
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
450
32114
    CHECK(parser->current_buffer_.IsEmpty());
451
16057
    CHECK_EQ(parser->current_buffer_len_, 0);
452
16057
    CHECK_NULL(parser->current_buffer_data_);
453
454
16057
    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
48171
    parser->current_buffer_ = args[0].As<Object>();
460
461
16057
    Local<Value> ret = parser->Execute(buffer.data(), buffer.length());
462
463
16056
    if (!ret.IsEmpty())
464
32108
      args.GetReturnValue().Set(ret);
465
  }
466
467
468
29134
  static void Finish(const FunctionCallbackInfo<Value>& args) {
469
    Parser* parser;
470
58268
    ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder());
471
472
58268
    CHECK(parser->current_buffer_.IsEmpty());
473
29134
    Local<Value> ret = parser->Execute(nullptr, 0);
474
475
29134
    if (!ret.IsEmpty())
476
48
      args.GetReturnValue().Set(ret);
477
  }
478
479
480
43815
  static void Initialize(const FunctionCallbackInfo<Value>& args) {
481
43815
    Environment* env = Environment::GetCurrent(args);
482
483
87630
    CHECK(args[0]->IsInt32());
484
87630
    CHECK(args[1]->IsObject());
485
486
    llhttp_type_t type =
487
131445
        static_cast<llhttp_type_t>(args[0].As<Int32>()->Value());
488
489

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

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





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