GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — node/src/node_http2.cc at master · zmmbreeze/node Expand file tree/ Copy pathnode_http2.ccMore file actions 3002 lines (2592 loc) · 112 KB / Copy pathnode_http2.ccFile metadata and controls3002 lines (2592 loc) · 112 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #include "aliased_buffer.h" #include "debug_utils.h" #include "node.h" #include "node_buffer.h" #include "node_http2.h" #include "node_http2_state.h" #include "node_internals.h" #include "node_perf.h" #include <algorithm> namespace node { using v8::ArrayBuffer; using v8::Boolean; using v8::Context; using v8::Float64Array; using v8::Function; using v8::Integer; using v8::Number; using v8::ObjectTemplate; using v8::String; using v8::Uint32; using v8::Uint32Array; using v8::Undefined; using node::performance::PerformanceEntry; namespace http2 { namespace { const char zero_bytes_256[256] = {}; inline Http2Stream* GetStream(Http2Session* session, int32_t id, nghttp2_data_source* source) { Http2Stream* stream = static_cast<Http2Stream*>(source->ptr); if (stream == nullptr) stream = session->FindStream(id); CHECK_NOT_NULL(stream); CHECK_EQ(id, stream->id()); return stream; } } // anonymous namespace // These configure the callbacks required by nghttp2 itself. There are // two sets of callback functions, one that is used if a padding callback // is set, and other that does not include the padding callback. const Http2Session::Callbacks Http2Session::callback_struct_saved[2] = { Callbacks(false), Callbacks(true)}; // The Http2Scope object is used to queue a write to the i/o stream. It is // used whenever any action is take on the underlying nghttp2 API that may // push data into nghttp2 outbound data queue. // // For example: // // Http2Scope h2scope(session); // nghttp2_submit_ping(**session, ... ); // // When the Http2Scope passes out of scope and is deconstructed, it will // call Http2Session::MaybeScheduleWrite(). Http2Scope::Http2Scope(Http2Stream* stream) : Http2Scope(stream->session()) {} Http2Scope::Http2Scope(Http2Session* session) { if (session == nullptr) return; if (session->flags_ & (SESSION_STATE_HAS_SCOPE | SESSION_STATE_WRITE_SCHEDULED)) { // There is another scope further below on the stack, or it is already // known that a write is scheduled. In either case, there is nothing to do. return; } session->flags_ |= SESSION_STATE_HAS_SCOPE; session_ = session; // Always keep the session object alive for at least as long as // this scope is active. session_handle_ = session->object(); CHECK(!session_handle_.IsEmpty()); } Http2Scope::~Http2Scope() { if (session_ == nullptr) return; session_->flags_ &= ~SESSION_STATE_HAS_SCOPE; session_->MaybeScheduleWrite(); } // The Http2Options object is used during the construction of Http2Session // instances to configure an appropriate nghttp2_options struct. The class // uses a single TypedArray instance that is shared with the JavaScript side // to more efficiently pass values back and forth. Http2Options::Http2Options(Environment* env) { nghttp2_option_new(&options_); // We manually handle flow control within a session in order to // implement backpressure -- that is, we only send WINDOW_UPDATE // frames to the remote peer as data is actually consumed by user // code. This ensures that the flow of data over the connection // does not move too quickly and limits the amount of data we // are required to buffer. nghttp2_option_set_no_auto_window_update(options_, 1); // Enable built in support for ALTSVC frames. Once we add support for // other non-built in extension frames, this will need to be handled // a bit differently. For now, let's let nghttp2 take care of it. nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC); AliasedBuffer<uint32_t, Uint32Array>& buffer = env->http2_state()->options_buffer; uint32_t flags = buffer[IDX_OPTIONS_FLAGS]; if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) { nghttp2_option_set_max_deflate_dynamic_table_size( options_, buffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE]); } if (flags & (1 << IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS)) { nghttp2_option_set_max_reserved_remote_streams( options_, buffer[IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS]); } if (flags & (1 << IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH)) { nghttp2_option_set_max_send_header_block_length( options_, buffer[IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH]); } // Recommended default nghttp2_option_set_peer_max_concurrent_streams(options_, 100); if (flags & (1 << IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS)) { nghttp2_option_set_peer_max_concurrent_streams( options_, buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]); } // The padding strategy sets the mechanism by which we determine how much // additional frame padding to apply to DATA and HEADERS frames. Currently // this is set on a per-session basis, but eventually we may switch to // a per-stream setting, giving users greater control if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) { padding_strategy_type strategy = static_cast<padding_strategy_type>( buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY)); SetPaddingStrategy(strategy); } // The max header list pairs option controls the maximum number of // header pairs the session may accept. This is a hard limit.. that is, // if the remote peer sends more than this amount, the stream will be // automatically closed with an RST_STREAM. if (flags & (1 << IDX_OPTIONS_MAX_HEADER_LIST_PAIRS)) { SetMaxHeaderPairs(buffer[IDX_OPTIONS_MAX_HEADER_LIST_PAIRS]); } // The HTTP2 specification places no limits on the number of HTTP2 // PING frames that can be sent. In order to prevent PINGS from being // abused as an attack vector, however, we place a strict upper limit // on the number of unacknowledged PINGS that can be sent at any given // time. if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_PINGS)) { SetMaxOutstandingPings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_PINGS]); } // The HTTP2 specification places no limits on the number of HTTP2 // SETTINGS frames that can be sent. In order to prevent PINGS from being // abused as an attack vector, however, we place a strict upper limit // on the number of unacknowledged SETTINGS that can be sent at any given // time. if (flags & (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS)) { SetMaxOutstandingSettings(buffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS]); } // The HTTP2 specification places no limits on the amount of memory // that a session can consume. In order to prevent abuse, we place a // cap on the amount of memory a session can consume at any given time. // this is a credit based system. Existing streams may cause the limit // to be temporarily exceeded but once over the limit, new streams cannot // created. // Important: The maxSessionMemory option in javascript is expressed in // terms of MB increments (i.e. the value 1 == 1 MB) if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY)) { SetMaxSessionMemory(buffer[IDX_OPTIONS_MAX_SESSION_MEMORY] * 1e6); } } void Http2Session::Http2Settings::Init() { AliasedBuffer<uint32_t, Uint32Array>& buffer = env()->http2_state()->settings_buffer; uint32_t flags = buffer[IDX_SETTINGS_COUNT]; size_t n = 0; #define GRABSETTING(N, trace) \ if (flags & (1 << IDX_SETTINGS_##N)) { \ uint32_t val = buffer[IDX_SETTINGS_##N]; \ if (session_ != nullptr) \ Debug(session_, "setting " trace ": %d\n", val); \ entries_[n++] = \ nghttp2_settings_entry {NGHTTP2_SETTINGS_##N, val}; \ } GRABSETTING(HEADER_TABLE_SIZE, "header table size"); GRABSETTING(MAX_CONCURRENT_STREAMS, "max concurrent streams"); GRABSETTING(MAX_FRAME_SIZE, "max frame size"); GRABSETTING(INITIAL_WINDOW_SIZE, "initial window size"); GRABSETTING(MAX_HEADER_LIST_SIZE, "max header list size"); GRABSETTING(ENABLE_PUSH, "enable push"); #undef GRABSETTING count_ = n; } Http2Session::Http2Settings::Http2Settings( Environment* env) : AsyncWrap(env, env->http2settings_constructor_template() ->NewInstance(env->context()) .ToLocalChecked(), AsyncWrap::PROVIDER_HTTP2SETTINGS), session_(nullptr), startTime_(0) { Init(); } // The Http2Settings class is used to configure a SETTINGS frame that is // to be sent to the connected peer. The settings are set using a TypedArray // that is shared with the JavaScript side. Http2Session::Http2Settings::Http2Settings( Http2Session* session) : AsyncWrap(session->env(), session->env()->http2settings_constructor_template() ->NewInstance(session->env()->context()) .ToLocalChecked(), AsyncWrap::PROVIDER_HTTP2SETTINGS), session_(session), startTime_(uv_hrtime()) { Init(); } // Generates a Buffer that contains the serialized payload of a SETTINGS // frame. This can be used, for instance, to create the Base64-encoded // content of an Http2-Settings header field. Local<Value> Http2Session::Http2Settings::Pack() { const size_t len = count_ * 6; Local<Value> buf = Buffer::New(env(), len).ToLocalChecked(); ssize_t ret = nghttp2_pack_settings_payload( reinterpret_cast<uint8_t*>(Buffer::Data(buf)), len, &entries_[0], count_); if (ret >= 0) return buf; else return Undefined(env()->isolate()); } // Updates the shared TypedArray with the current remote or local settings for // the session. void Http2Session::Http2Settings::Update(Environment* env, Http2Session* session, get_setting fn) { AliasedBuffer<uint32_t, Uint32Array>& buffer = env->http2_state()->settings_buffer; buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = fn(**session, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE); buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] = fn(**session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] = fn(**session, NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE); buffer[IDX_SETTINGS_MAX_FRAME_SIZE] = fn(**session, NGHTTP2_SETTINGS_MAX_FRAME_SIZE); buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] = fn(**session, NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE); buffer[IDX_SETTINGS_ENABLE_PUSH] = fn(**session, NGHTTP2_SETTINGS_ENABLE_PUSH); } // Initializes the shared TypedArray with the default settings values. void Http2Session::Http2Settings::RefreshDefaults(Environment* env) { AliasedBuffer<uint32_t, Uint32Array>& buffer = env->http2_state()->settings_buffer; buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = DEFAULT_SETTINGS_HEADER_TABLE_SIZE; buffer[IDX_SETTINGS_ENABLE_PUSH] = DEFAULT_SETTINGS_ENABLE_PUSH; buffer[IDX_SETTINGS_INITIAL_WINDOW_SIZE] = DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; buffer[IDX_SETTINGS_MAX_FRAME_SIZE] = DEFAULT_SETTINGS_MAX_FRAME_SIZE; buffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] = DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE; buffer[IDX_SETTINGS_COUNT] = (1 << IDX_SETTINGS_HEADER_TABLE_SIZE) | (1 << IDX_SETTINGS_ENABLE_PUSH) | (1 << IDX_SETTINGS_INITIAL_WINDOW_SIZE) | (1 << IDX_SETTINGS_MAX_FRAME_SIZE) | (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE); } void Http2Session::Http2Settings::Send() { Http2Scope h2scope(session_); CHECK_EQ(nghttp2_submit_settings(**session_, NGHTTP2_FLAG_NONE, &entries_[0], count_), 0); } void Http2Session::Http2Settings::Done(bool ack) { uint64_t end = uv_hrtime(); double duration = (end - startTime_) / 1e6; Local<Value> argv[2] = { Boolean::New(env()->isolate(), ack), Number::New(env()->isolate(), duration) }; MakeCallback(env()->ondone_string(), arraysize(argv), argv); delete this; } // The Http2Priority class initializes an appropriate nghttp2_priority_spec // struct used when either creating a stream or updating its priority // settings. Http2Priority::Http2Priority(Environment* env, Local<Value> parent, Local<Value> weight, Local<Value> exclusive) { Local<Context> context = env->context(); int32_t parent_ = parent->Int32Value(context).ToChecked(); int32_t weight_ = weight->Int32Value(context).ToChecked(); bool exclusive_ = exclusive->BooleanValue(context).ToChecked(); Debug(env, DebugCategory::HTTP2STREAM, "Http2Priority: parent: %d, weight: %d, exclusive: %d\n", parent_, weight_, exclusive_); nghttp2_priority_spec_init(&spec, parent_, weight_, exclusive_ ? 1 : 0); } const char* Http2Session::TypeName() const { switch (session_type_) { case NGHTTP2_SESSION_SERVER: return "server"; case NGHTTP2_SESSION_CLIENT: return "client"; default: // This should never happen ABORT(); } } // The Headers class initializes a proper array of nghttp2_nv structs // containing the header name value pairs. Headers::Headers(Isolate* isolate, Local<Context> context, Local<Array> headers) { Local<Value> header_string = headers->Get(context, 0).ToLocalChecked(); Local<Value> header_count = headers->Get(context, 1).ToLocalChecked(); count_ = header_count.As<Uint32>()->Value(); int header_string_len = header_string.As<String>()->Length(); if (count_ == 0) { CHECK_EQ(header_string_len, 0); return; } // Allocate a single buffer with count_ nghttp2_nv structs, followed // by the raw header data as passed from JS. This looks like: // | possible padding | nghttp2_nv | nghttp2_nv | ... | header contents | buf_.AllocateSufficientStorage((alignof(nghttp2_nv) - 1) + count_ * sizeof(nghttp2_nv) + header_string_len); // Make sure the start address is aligned appropriately for an nghttp2_nv*. char* start = reinterpret_cast<char*>( ROUND_UP(reinterpret_cast<uintptr_t>(*buf_), alignof(nghttp2_nv))); char* header_contents = start + (count_ * sizeof(nghttp2_nv)); nghttp2_nv* const nva = reinterpret_cast<nghttp2_nv*>(start); CHECK_LE(header_contents + header_string_len, *buf_ + buf_.length()); CHECK_EQ(header_string.As<String>() ->WriteOneByte(reinterpret_cast<uint8_t*>(header_contents), 0, header_string_len, String::NO_NULL_TERMINATION), header_string_len); size_t n = 0; char* p; for (p = header_contents; p < header_contents + header_string_len; n++) { if (n >= count_) { // This can happen if a passed header contained a null byte. In that // case, just provide nghttp2 with an invalid header to make it reject // the headers list. static uint8_t zero = '\0'; nva[0].name = nva[0].value = &zero; nva[0].namelen = nva[0].valuelen = 1; count_ = 1; return; } nva[n].flags = NGHTTP2_NV_FLAG_NONE; nva[n].name = reinterpret_cast<uint8_t*>(p); nva[n].namelen = strlen(p); p += nva[n].namelen + 1; nva[n].value = reinterpret_cast<uint8_t*>(p); nva[n].valuelen = strlen(p); p += nva[n].valuelen + 1; } } // Sets the various callback functions that nghttp2 will use to notify us // about significant events while processing http2 stuff. Http2Session::Callbacks::Callbacks(bool kHasGetPaddingCallback) { CHECK_EQ(nghttp2_session_callbacks_new(&callbacks), 0); nghttp2_session_callbacks_set_on_begin_headers_callback( callbacks, OnBeginHeadersCallback); nghttp2_session_callbacks_set_on_header_callback2( callbacks, OnHeaderCallback); nghttp2_session_callbacks_set_on_frame_recv_callback( callbacks, OnFrameReceive); nghttp2_session_callbacks_set_on_stream_close_callback( callbacks, OnStreamClose); nghttp2_session_callbacks_set_on_data_chunk_recv_callback( callbacks, OnDataChunkReceived); nghttp2_session_callbacks_set_on_frame_not_send_callback( callbacks, OnFrameNotSent); nghttp2_session_callbacks_set_on_invalid_header_callback2( callbacks, OnInvalidHeader); nghttp2_session_callbacks_set_error_callback( callbacks, OnNghttpError); nghttp2_session_callbacks_set_send_data_callback( callbacks, OnSendData); nghttp2_session_callbacks_set_on_invalid_frame_recv_callback( callbacks, OnInvalidFrame); nghttp2_session_callbacks_set_on_frame_send_callback( callbacks, OnFrameSent); if (kHasGetPaddingCallback) { nghttp2_session_callbacks_set_select_padding_callback( callbacks, OnSelectPadding); } } Http2Session::Callbacks::~Callbacks() { nghttp2_session_callbacks_del(callbacks); } // Track memory allocated by nghttp2 using a custom allocator. class Http2Session::MemoryAllocatorInfo { public: explicit MemoryAllocatorInfo(Http2Session* session) : info({ session, H2Malloc, H2Free, H2Calloc, H2Realloc }) {} static void* H2Malloc(size_t size, void* user_data) { return H2Realloc(nullptr, size, user_data); } static void* H2Calloc(size_t nmemb, size_t size, void* user_data) { size_t real_size = MultiplyWithOverflowCheck(nmemb, size); void* mem = H2Malloc(real_size, user_data); if (mem != nullptr) memset(mem, 0, real_size); return mem; } static void H2Free(void* ptr, void* user_data) { if (ptr == nullptr) return; // free(null); happens quite often. void* result = H2Realloc(ptr, 0, user_data); CHECK_EQ(result, nullptr); } static void* H2Realloc(void* ptr, size_t size, void* user_data) { Http2Session* session = static_cast<Http2Session*>(user_data); size_t previous_size = 0; char* original_ptr = nullptr; // We prepend each allocated buffer with a size_t containing the full // size of the allocation. if (size > 0) size += sizeof(size_t); if (ptr != nullptr) { // We are free()ing or re-allocating. original_ptr = static_cast<char*>(ptr) - sizeof(size_t); previous_size = *reinterpret_cast<size_t*>(original_ptr); // This means we called StopTracking() on this pointer before. if (previous_size == 0) { // Fall back to the standard Realloc() function. char* ret = UncheckedRealloc(original_ptr, size); if (ret != nullptr) ret += sizeof(size_t); return ret; } } CHECK_GE(session->current_nghttp2_memory_, previous_size); // TODO(addaleax): Add the following, and handle NGHTTP2_ERR_NOMEM properly // everywhere: // // if (size > previous_size && // !session->IsAvailableSessionMemory(size - previous_size)) { // return nullptr; //} char* mem = UncheckedRealloc(original_ptr, size); if (mem != nullptr) { // Adjust the memory info counter. session->current_nghttp2_memory_ += size - previous_size; *reinterpret_cast<size_t*>(mem) = size; mem += sizeof(size_t); } else if (size == 0) { session->current_nghttp2_memory_ -= previous_size; } return mem; } static void StopTracking(Http2Session* session, void* ptr) { size_t* original_ptr = reinterpret_cast<size_t*>( static_cast<char*>(ptr) - sizeof(size_t)); session->current_nghttp2_memory_ -= *original_ptr; *original_ptr = 0; } inline nghttp2_mem* operator*() { return &info; } nghttp2_mem info; }; void Http2Session::StopTrackingRcbuf(nghttp2_rcbuf* buf) { MemoryAllocatorInfo::StopTracking(this, buf); } Http2Session::Http2Session(Environment* env, Local<Object> wrap, nghttp2_session_type type) : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION), session_type_(type) { MakeWeak(); statistics_.start_time = uv_hrtime(); // Capture the configuration options for this session Http2Options opts(env); max_session_memory_ = opts.GetMaxSessionMemory(); uint32_t maxHeaderPairs = opts.GetMaxHeaderPairs(); max_header_pairs_ = type == NGHTTP2_SESSION_SERVER ? std::max(maxHeaderPairs, 4U) // minimum # of request headers : std::max(maxHeaderPairs, 1U); // minimum # of response headers max_outstanding_pings_ = opts.GetMaxOutstandingPings(); max_outstanding_settings_ = opts.GetMaxOutstandingSettings(); padding_strategy_ = opts.GetPaddingStrategy(); bool hasGetPaddingCallback = padding_strategy_ != PADDING_STRATEGY_NONE; nghttp2_session_callbacks* callbacks = callback_struct_saved[hasGetPaddingCallback ? 1 : 0].callbacks; auto fn = type == NGHTTP2_SESSION_SERVER ? nghttp2_session_server_new3 : nghttp2_session_client_new3; MemoryAllocatorInfo allocator_info(this); // This should fail only if the system is out of memory, which // is going to cause lots of other problems anyway, or if any // of the options are out of acceptable range, which we should // be catching before it gets this far. Either way, crash if this // fails. CHECK_EQ(fn(&session_, callbacks, this, *opts, *allocator_info), 0); outgoing_storage_.reserve(4096); outgoing_buffers_.reserve(32); } Http2Session::~Http2Session() { CHECK_EQ(flags_ & SESSION_STATE_HAS_SCOPE, 0); Debug(this, "freeing nghttp2 session"); for (const auto& iter : streams_) iter.second->session_ = nullptr; nghttp2_session_del(session_); CHECK_EQ(current_nghttp2_memory_, 0); } std::string Http2Session::diagnostic_name() const { return std::string("Http2Session ") + TypeName() + " (" + std::to_string(static_cast<int64_t>(get_async_id())) + ")"; } inline bool HasHttp2Observer(Environment* env) { AliasedBuffer<uint32_t, Uint32Array>& observers = env->performance_state()->observers; return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0; } void Http2Stream::EmitStatistics() { if (!HasHttp2Observer(env())) return; Http2StreamPerformanceEntry* entry = new Http2StreamPerformanceEntry(env(), id_, statistics_); env()->SetImmediate([](Environment* env, void* data) { // This takes ownership, the entry is destroyed at the end of this scope. std::unique_ptr<Http2StreamPerformanceEntry> entry { static_cast<Http2StreamPerformanceEntry*>(data) }; if (!HasHttp2Observer(env)) return; HandleScope handle_scope(env->isolate()); AliasedBuffer<double, Float64Array>& buffer = env->http2_state()->stream_stats_buffer; buffer[IDX_STREAM_STATS_ID] = entry->id(); if (entry->first_byte() != 0) { buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = (entry->first_byte() - entry->startTimeNano()) / 1e6; } else { buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTE] = 0; } if (entry->first_header() != 0) { buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = (entry->first_header() - entry->startTimeNano()) / 1e6; } else { buffer[IDX_STREAM_STATS_TIMETOFIRSTHEADER] = 0; } if (entry->first_byte_sent() != 0) { buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = (entry->first_byte_sent() - entry->startTimeNano()) / 1e6; } else { buffer[IDX_STREAM_STATS_TIMETOFIRSTBYTESENT] = 0; } buffer[IDX_STREAM_STATS_SENTBYTES] = entry->sent_bytes(); buffer[IDX_STREAM_STATS_RECEIVEDBYTES] = entry->received_bytes(); entry->Notify(entry->ToObject()); }, static_cast<void*>(entry)); } void Http2Session::EmitStatistics() { if (!HasHttp2Observer(env())) return; Http2SessionPerformanceEntry* entry = new Http2SessionPerformanceEntry(env(), statistics_, session_type_); env()->SetImmediate([](Environment* env, void* data) { // This takes ownership, the entr is destroyed at the end of this scope. std::unique_ptr<Http2SessionPerformanceEntry> entry { static_cast<Http2SessionPerformanceEntry*>(data) }; if (!HasHttp2Observer(env)) return; HandleScope handle_scope(env->isolate()); AliasedBuffer<double, Float64Array>& buffer = env->http2_state()->session_stats_buffer; buffer[IDX_SESSION_STATS_TYPE] = entry->type(); buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6; buffer[IDX_SESSION_STATS_FRAMESRECEIVED] = entry->frame_count(); buffer[IDX_SESSION_STATS_FRAMESSENT] = entry->frame_sent(); buffer[IDX_SESSION_STATS_STREAMCOUNT] = entry->stream_count(); buffer[IDX_SESSION_STATS_STREAMAVERAGEDURATION] = entry->stream_average_duration(); buffer[IDX_SESSION_STATS_DATA_SENT] = entry->data_sent(); buffer[IDX_SESSION_STATS_DATA_RECEIVED] = entry->data_received(); buffer[IDX_SESSION_STATS_MAX_CONCURRENT_STREAMS] = entry->max_concurrent_streams(); entry->Notify(entry->ToObject()); }, static_cast<void*>(entry)); } // Closes the session and frees the associated resources void Http2Session::Close(uint32_t code, bool socket_closed) { Debug(this, "closing session"); if (flags_ & SESSION_STATE_CLOSING) return; flags_ |= SESSION_STATE_CLOSING; // Stop reading on the i/o stream if (stream_ != nullptr) stream_->ReadStop(); // If the socket is not closed, then attempt to send a closing GOAWAY // frame. There is no guarantee that this GOAWAY will be received by // the peer but the HTTP/2 spec recommends sending it anyway. We'll // make a best effort. if (!socket_closed) { Debug(this, "terminating session with code %d", code); CHECK_EQ(nghttp2_session_terminate_session(session_, code), 0); SendPendingData(); } else if (stream_ != nullptr) { stream_->RemoveStreamListener(this); } flags_ |= SESSION_STATE_CLOSED; // If there are outstanding pings, those will need to be canceled, do // so on the next iteration of the event loop to avoid calling out into // javascript since this may be called during garbage collection. while (!outstanding_pings_.empty()) { Http2Session::Http2Ping* ping = PopPing(); env()->SetImmediate([](Environment* env, void* data) { static_cast<Http2Session::Http2Ping*>(data)->Done(false); }, static_cast<void*>(ping)); } statistics_.end_time = uv_hrtime(); EmitStatistics(); } // Locates an existing known stream by ID. nghttp2 has a similar method // but this is faster and does not fail if the stream is not found. inline Http2Stream* Http2Session::FindStream(int32_t id) { auto s = streams_.find(id); return s != streams_.end() ? s->second : nullptr; } inline bool Http2Session::CanAddStream() { uint32_t maxConcurrentStreams = nghttp2_session_get_local_settings( session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); size_t maxSize = std::min(streams_.max_size(), static_cast<size_t>(maxConcurrentStreams)); // We can add a new stream so long as we are less than the current // maximum on concurrent streams and there's enough available memory return streams_.size() < maxSize && IsAvailableSessionMemory(sizeof(Http2Stream)); } inline void Http2Session::AddStream(Http2Stream* stream) { CHECK_GE(++statistics_.stream_count, 0); streams_[stream->id()] = stream; size_t size = streams_.size(); if (size > statistics_.max_concurrent_streams) statistics_.max_concurrent_streams = size; IncrementCurrentSessionMemory(sizeof(*stream)); } inline void Http2Session::RemoveStream(Http2Stream* stream) { if (streams_.empty() || stream == nullptr) return; // Nothing to remove, item was never added? streams_.erase(stream->id()); DecrementCurrentSessionMemory(sizeof(*stream)); } // Used as one of the Padding Strategy functions. Will attempt to ensure // that the total frame size, including header bytes, are 8-byte aligned. // If maxPayloadLen is smaller than the number of bytes necessary to align, // will return maxPayloadLen instead. ssize_t Http2Session::OnDWordAlignedPadding(size_t frameLen, size_t maxPayloadLen) { size_t r = (frameLen + 9) % 8; if (r == 0) return frameLen; // If already a multiple of 8, return. size_t pad = frameLen + (8 - r); // If maxPayloadLen happens to be less than the calculated pad length, // use the max instead, even tho this means the frame will not be // aligned. pad = std::min(maxPayloadLen, pad); Debug(this, "using frame size padding: %d", pad); return pad; } // Used as one of the Padding Strategy functions. Uses the maximum amount // of padding allowed for the current frame. ssize_t Http2Session::OnMaxFrameSizePadding(size_t frameLen, size_t maxPayloadLen) { Debug(this, "using max frame size padding: %d", maxPayloadLen); return maxPayloadLen; } // Used as one of the Padding Strategy functions. Uses a callback to JS land // to determine the amount of padding for the current frame. This option is // rather more expensive because of the JS boundary cross. It generally should // not be the preferred option. ssize_t Http2Session::OnCallbackPadding(size_t frameLen, size_t maxPayloadLen) { if (frameLen == 0) return 0; Debug(this, "using callback to determine padding"); Isolate* isolate = env()->isolate(); HandleScope handle_scope(isolate); Local<Context> context = env()->context(); Context::Scope context_scope(context); AliasedBuffer<uint32_t, Uint32Array>& buffer = env()->http2_state()->padding_buffer; buffer[PADDING_BUF_FRAME_LENGTH] = frameLen; buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen; buffer[PADDING_BUF_RETURN_VALUE] = frameLen; MakeCallback(env()->ongetpadding_string(), 0, nullptr); uint32_t retval = buffer[PADDING_BUF_RETURN_VALUE]; retval = std::min(retval, static_cast<uint32_t>(maxPayloadLen)); retval = std::max(retval, static_cast<uint32_t>(frameLen)); Debug(this, "using padding size %d", retval); return retval; } // Write data received from the i/o stream to the underlying nghttp2_session. // On each call to nghttp2_session_mem_recv, nghttp2 will begin calling the // various callback functions. Each of these will typically result in a call // out to JavaScript so this particular function is rather hot and can be // quite expensive. This is a potential performance optimization target later. ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) { size_t total = 0; // Note that nghttp2_session_mem_recv is a synchronous operation that // will trigger a number of other callbacks. Those will, in turn have // multiple side effects. for (size_t n = 0; n < nbufs; n++) { Debug(this, "receiving %d bytes [wants data? %d]", bufs[n].len, nghttp2_session_want_read(session_)); ssize_t ret = nghttp2_session_mem_recv(session_, reinterpret_cast<uint8_t*>(bufs[n].base), bufs[n].len); CHECK_NE(ret, NGHTTP2_ERR_NOMEM); if (ret < 0) return ret; total += ret; } // Send any data that was queued up while processing the received data. if (!IsDestroyed()) { SendPendingData(); } return total; } inline int32_t GetFrameID(const nghttp2_frame* frame) { // If this is a push promise, we want to grab the id of the promised stream return (frame->hd.type == NGHTTP2_PUSH_PROMISE) ? frame->push_promise.promised_stream_id : frame->hd.stream_id; } // Called by nghttp2 at the start of receiving a HEADERS frame. We use this // callback to determine if a new stream is being created or if we are simply // adding a new block of headers to an existing stream. The header pairs // themselves are set in the OnHeaderCallback int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle, const nghttp2_frame* frame, void* user_data) { Http2Session* session = static_cast<Http2Session*>(user_data); int32_t id = GetFrameID(frame); Debug(session, "beginning headers for stream %d", id); Http2Stream* stream = session->FindStream(id); if (stream == nullptr) { if (!session->CanAddStream()) { // Too many concurrent streams being opened nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id, NGHTTP2_ENHANCE_YOUR_CALM); return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; } new Http2Stream(session, id, frame->headers.cat); } else if (!stream->IsDestroyed()) { stream->StartHeaders(frame->headers.cat); } return 0; } // Called by nghttp2 for each header name/value pair in a HEADERS block. // This had to have been preceded by a call to OnBeginHeadersCallback so // the Http2Stream is guaranteed to already exist. int Http2Session::OnHeaderCallback(nghttp2_session* handle, const nghttp2_frame* frame, nghttp2_rcbuf* name, nghttp2_rcbuf* value, uint8_t flags, void* user_data) { Http2Session* session = static_cast<Http2Session*>(user_data); int32_t id = GetFrameID(frame); Http2Stream* stream = session->FindStream(id); // If stream is null at this point, either something odd has happened // or the stream was closed locally while header processing was occurring. // either way, do not proceed and close the stream. if (stream == nullptr) return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; // If the stream has already been destroyed, ignore. if (!stream->IsDestroyed() && !stream->AddHeader(name, value, flags)) { // This will only happen if the connected peer sends us more // than the allowed number of header items at any given time stream->SubmitRstStream(NGHTTP2_ENHANCE_YOUR_CALM); return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; } return 0; } // Called by nghttp2 when a complete HTTP2 frame has been received. There are // only a handful of frame types tha we care about handling here. int Http2Session::OnFrameReceive(nghttp2_session* handle, const nghttp2_frame* frame, void* user_data) { Http2Session* session = static_cast<Http2Session*>(user_data); session->statistics_.frame_count++; Debug(session, "complete frame received: type: %d", frame->hd.type); switch (frame->hd.type) { case NGHTTP2_DATA: session->HandleDataFrame(frame); break; case NGHTTP2_PUSH_PROMISE: // Intentional fall-through, handled just like headers frames case NGHTTP2_HEADERS: session->HandleHeadersFrame(frame); break; case NGHTTP2_SETTINGS: session->HandleSettingsFrame(frame); break; case NGHTTP2_PRIORITY: session->HandlePriorityFrame(frame); break; case NGHTTP2_GOAWAY: session->HandleGoawayFrame(frame); break; case NGHTTP2_PING: session->HandlePingFrame(frame); break; case NGHTTP2_ALTSVC: session->HandleAltSvcFrame(frame); break; default: break; } return 0; } int Http2Session::OnInvalidFrame(nghttp2_session* handle, const nghttp2_frame* frame, int lib_error_code, void* user_data) { Http2Session* session = static_cast<Http2Session*>(user_data); Debug(session, "invalid frame received, code: %d", lib_error_code); // If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error if (nghttp2_is_fatal(lib_error_code) || lib_error_code == NGHTTP2_ERR_STREAM_CLOSED) { Environment* env = session->env(); Isolate* isolate = env->isolate(); HandleScope scope(isolate); Local<Context> context = env->context(); Context::Scope context_scope(context); Local<Value> arg = Integer::New(isolate, lib_error_code); session->MakeCallback(env->error_string(), 1, &arg); } return 0; } // If nghttp2 is unable to send a queued up frame, it will call this callback // to let us know. If the failure occurred because we are in the process of // closing down the session or stream, we go ahead and ignore it. We don't // really care about those and there's nothing we can reasonably do about it // anyway. Other types of failures are reported up to JavaScript. This should // be exceedingly rare. int Http2Session::OnFrameNotSent(nghttp2_session* handle, const nghttp2_frame* frame, int error_code, void* user_data) { Http2Session* session = static_cast<Http2Session*>(user_data); Environment* env = session->env(); Debug(session, "frame type %d was not sent, code: %d", frame->hd.type, error_code); // Do not report if the frame was not sent due to the session closing if (error_code != NGHTTP2_ERR_SESSION_CLOSING && error_code != NGHTTP2_ERR_STREAM_CLOSED && error_code != NGHTTP2_ERR_STREAM_CLOSING) { Isolate* isolate = env->isolate(); HandleScope scope(isolate); Local<Context> context = env->context(); Context::Scope context_scope(context); Local<Value> argv[3] = { Integer::New(isolate, frame->hd.stream_id), Integer::New(isolate, frame->hd.type), Integer::New(isolate, error_code) }; session->MakeCallback(env->onframeerror_string(), arraysize(argv), argv); } return 0; } int Http2Session::OnFrameSent(nghttp2_session* handle, const nghttp2_frame* frame, void* user_data) { Http2Session* session = static_cast<Http2Session*>(user_data); session->statistics_.frame_sent += 1; return 0; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |