2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2012 Tatsuhiro Tsujikawa
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 #include "shrpx_http2_session.h"
27 #include <netinet/tcp.h>
30 #endif // HAVE_UNISTD_H
34 #include <openssl/err.h>
36 #include "shrpx_upstream.h"
37 #include "shrpx_downstream.h"
38 #include "shrpx_config.h"
39 #include "shrpx_error.h"
40 #include "shrpx_http2_downstream_connection.h"
41 #include "shrpx_client_handler.h"
42 #include "shrpx_tls.h"
43 #include "shrpx_http.h"
44 #include "shrpx_worker.h"
45 #include "shrpx_connect_blocker.h"
46 #include "shrpx_log.h"
52 using namespace nghttp2;
57 constexpr ev_tstamp CONNCHK_TIMEOUT = 5.;
58 constexpr ev_tstamp CONNCHK_PING_TIMEOUT = 1.;
62 constexpr size_t MAX_BUFFER_SIZE = 32_k;
66 void connchk_timeout_cb(struct ev_loop *loop, ev_timer *w, int revents) {
67 auto http2session = static_cast<Http2Session *>(w->data);
69 ev_timer_stop(loop, w);
71 switch (http2session->get_connection_check_state()) {
72 case ConnectionCheck::STARTED:
73 // ping timeout; disconnect
74 if (LOG_ENABLED(INFO)) {
75 SSLOG(INFO, http2session) << "ping timeout";
82 if (LOG_ENABLED(INFO)) {
83 SSLOG(INFO, http2session) << "connection check required";
85 http2session->set_connection_check_state(ConnectionCheck::REQUIRED);
91 void settings_timeout_cb(struct ev_loop *loop, ev_timer *w, int revents) {
92 auto http2session = static_cast<Http2Session *>(w->data);
94 if (LOG_ENABLED(INFO)) {
95 SSLOG(INFO, http2session) << "SETTINGS timeout";
98 downstream_failure(http2session->get_addr(), http2session->get_raddr());
100 if (http2session->terminate_session(NGHTTP2_SETTINGS_TIMEOUT) != 0) {
105 http2session->signal_write();
110 void timeoutcb(struct ev_loop *loop, ev_timer *w, int revents) {
111 auto conn = static_cast<Connection *>(w->data);
112 auto http2session = static_cast<Http2Session *>(conn->data);
114 if (w == &conn->rt && !conn->expired_rt()) {
118 if (LOG_ENABLED(INFO)) {
119 SSLOG(INFO, http2session) << "Timeout";
122 http2session->on_timeout();
129 void readcb(struct ev_loop *loop, ev_io *w, int revents) {
131 auto conn = static_cast<Connection *>(w->data);
132 auto http2session = static_cast<Http2Session *>(conn->data);
133 rv = http2session->do_read();
139 http2session->connection_alive();
144 void writecb(struct ev_loop *loop, ev_io *w, int revents) {
146 auto conn = static_cast<Connection *>(w->data);
147 auto http2session = static_cast<Http2Session *>(conn->data);
148 rv = http2session->do_write();
154 http2session->reset_connection_check_timer_if_not_checking();
159 void initiate_connection_cb(struct ev_loop *loop, ev_timer *w, int revents) {
160 auto http2session = static_cast<Http2Session *>(w->data);
161 ev_timer_stop(loop, w);
162 if (http2session->initiate_connection() != 0) {
163 if (LOG_ENABLED(INFO)) {
164 SSLOG(INFO, http2session) << "Could not initiate backend connection";
175 void prepare_cb(struct ev_loop *loop, ev_prepare *w, int revents) {
176 auto http2session = static_cast<Http2Session *>(w->data);
177 http2session->check_retire();
181 Http2Session::Http2Session(struct ev_loop *loop, SSL_CTX *ssl_ctx,
183 const std::shared_ptr<DownstreamAddrGroup> &group,
184 DownstreamAddr *addr)
187 conn_(loop, -1, nullptr, worker->get_mcpool(),
188 group->shared_addr->timeout.write, group->shared_addr->timeout.read,
189 {}, {}, writecb, readcb, timeoutcb, this,
190 get_config()->tls.dyn_rec.warmup_threshold,
191 get_config()->tls.dyn_rec.idle_timeout, Proto::HTTP2),
192 wb_(worker->get_mcpool()),
199 state_(Http2SessionState::DISCONNECTED),
200 connection_check_state_(ConnectionCheck::NONE),
201 freelist_zone_(FreelistZone::NONE),
202 settings_recved_(false),
203 allow_connect_proto_(false) {
204 read_ = write_ = &Http2Session::noop;
206 on_read_ = &Http2Session::read_noop;
207 on_write_ = &Http2Session::write_noop;
209 // We will resuse this many times, so use repeat timeout value. The
210 // timeout value is set later.
211 ev_timer_init(&connchk_timer_, connchk_timeout_cb, 0., 0.);
213 connchk_timer_.data = this;
215 // SETTINGS ACK timeout is 10 seconds for now. We will resuse this
216 // many times, so use repeat timeout value.
217 ev_timer_init(&settings_timer_, settings_timeout_cb, 0., 0.);
219 settings_timer_.data = this;
221 ev_timer_init(&initiate_connection_timer_, initiate_connection_cb, 0., 0.);
222 initiate_connection_timer_.data = this;
224 ev_prepare_init(&prep_, prepare_cb);
226 ev_prepare_start(loop, &prep_);
229 Http2Session::~Http2Session() {
230 exclude_from_scheduling();
231 disconnect(should_hard_fail());
234 int Http2Session::disconnect(bool hard) {
235 if (LOG_ENABLED(INFO)) {
236 SSLOG(INFO, this) << "Disconnecting";
238 nghttp2_session_del(session_);
244 auto dns_tracker = worker_->get_dns_tracker();
245 dns_tracker->cancel(dns_query_.get());
248 conn_.rlimit.stopw();
249 conn_.wlimit.stopw();
251 ev_prepare_stop(conn_.loop, &prep_);
253 ev_timer_stop(conn_.loop, &initiate_connection_timer_);
254 ev_timer_stop(conn_.loop, &settings_timer_);
255 ev_timer_stop(conn_.loop, &connchk_timer_);
257 read_ = write_ = &Http2Session::noop;
259 on_read_ = &Http2Session::read_noop;
260 on_write_ = &Http2Session::write_noop;
268 connection_check_state_ = ConnectionCheck::NONE;
269 state_ = Http2SessionState::DISCONNECTED;
271 // When deleting Http2DownstreamConnection, it calls this object's
272 // remove_downstream_connection(). The multiple
273 // Http2DownstreamConnection objects belong to the same
274 // ClientHandler object if upstream is h2. So be careful when you
275 // delete ClientHandler here.
277 // We allow creating new pending Http2DownstreamConnection with this
278 // object. Upstream::on_downstream_reset() may add
279 // Http2DownstreamConnection to another Http2Session.
281 for (auto dc = dconns_.head; dc;) {
282 auto next = dc->dlnext;
283 auto downstream = dc->get_downstream();
284 auto upstream = downstream->get_upstream();
286 // Failure is allowed only for HTTP/1 upstream where upstream is
287 // not shared by multiple Downstreams.
288 if (upstream->on_downstream_reset(downstream, hard) != 0) {
289 delete upstream->get_client_handler();
296 auto streams = std::move(streams_);
297 for (auto s = streams.head; s;) {
298 auto next = s->dlnext;
306 int Http2Session::resolve_name() {
307 auto dns_query = std::make_unique<DNSQuery>(
308 addr_->host, [this](DNSResolverStatus status, const Address *result) {
311 if (status == DNSResolverStatus::OK) {
312 *resolved_addr_ = *result;
313 util::set_port(*this->resolved_addr_, this->addr_->port);
316 rv = this->initiate_connection();
321 resolved_addr_ = std::make_unique<Address>();
322 auto dns_tracker = worker_->get_dns_tracker();
323 switch (dns_tracker->resolve(resolved_addr_.get(), dns_query.get())) {
324 case DNSResolverStatus::ERROR:
326 case DNSResolverStatus::RUNNING:
327 dns_query_ = std::move(dns_query);
328 state_ = Http2SessionState::RESOLVING_NAME;
330 case DNSResolverStatus::OK:
331 util::set_port(*resolved_addr_, addr_->port);
340 int htp_hdrs_completecb(llhttp_t *htp);
344 constexpr llhttp_settings_t htp_hooks = {
345 nullptr, // llhttp_cb on_message_begin;
346 nullptr, // llhttp_data_cb on_url;
347 nullptr, // llhttp_data_cb on_status;
348 nullptr, // llhttp_data_cb on_header_field;
349 nullptr, // llhttp_data_cb on_header_value;
350 htp_hdrs_completecb, // llhttp_cb on_headers_complete;
351 nullptr, // llhttp_data_cb on_body;
352 nullptr, // llhttp_cb on_message_complete;
353 nullptr, // llhttp_cb on_chunk_header
354 nullptr, // llhttp_cb on_chunk_complete
358 int Http2Session::initiate_connection() {
361 auto worker_blocker = worker_->get_connect_blocker();
363 if (state_ == Http2SessionState::DISCONNECTED ||
364 state_ == Http2SessionState::RESOLVING_NAME) {
365 if (worker_blocker->blocked()) {
366 if (LOG_ENABLED(INFO)) {
368 << "Worker wide backend connection was blocked temporarily";
374 auto &downstreamconf = *get_config()->conn.downstream;
376 const auto &proxy = get_config()->downstream_http_proxy;
377 if (!proxy.host.empty() && state_ == Http2SessionState::DISCONNECTED) {
378 if (LOG_ENABLED(INFO)) {
379 SSLOG(INFO, this) << "Connecting to the proxy " << proxy.host << ":"
383 conn_.fd = util::create_nonblock_socket(proxy.addr.su.storage.ss_family);
385 if (conn_.fd == -1) {
387 SSLOG(WARN, this) << "Backend proxy socket() failed; addr="
388 << util::to_numeric_addr(&proxy.addr)
389 << ", errno=" << error;
391 worker_blocker->on_failure();
395 rv = connect(conn_.fd, &proxy.addr.su.sa, proxy.addr.len);
396 if (rv != 0 && errno != EINPROGRESS) {
398 SSLOG(WARN, this) << "Backend proxy connect() failed; addr="
399 << util::to_numeric_addr(&proxy.addr)
400 << ", errno=" << error;
402 worker_blocker->on_failure();
407 raddr_ = &proxy.addr;
409 worker_blocker->on_success();
411 ev_io_set(&conn_.rev, conn_.fd, EV_READ);
412 ev_io_set(&conn_.wev, conn_.fd, EV_WRITE);
414 conn_.wlimit.startw();
416 conn_.wt.repeat = downstreamconf.timeout.connect;
417 ev_timer_again(conn_.loop, &conn_.wt);
419 write_ = &Http2Session::connected;
421 on_read_ = &Http2Session::downstream_read_proxy;
422 on_write_ = &Http2Session::downstream_connect_proxy;
424 proxy_htp_ = std::make_unique<llhttp_t>();
425 llhttp_init(proxy_htp_.get(), HTTP_RESPONSE, &htp_hooks);
426 proxy_htp_->data = this;
428 state_ = Http2SessionState::PROXY_CONNECTING;
433 if (state_ == Http2SessionState::DISCONNECTED ||
434 state_ == Http2SessionState::PROXY_CONNECTED ||
435 state_ == Http2SessionState::RESOLVING_NAME) {
436 if (LOG_ENABLED(INFO)) {
437 if (state_ != Http2SessionState::RESOLVING_NAME) {
438 SSLOG(INFO, this) << "Connecting to downstream server";
444 if (state_ != Http2SessionState::RESOLVING_NAME) {
445 auto ssl = tls::create_ssl(ssl_ctx_);
450 tls::setup_downstream_http2_alpn(ssl);
453 conn_.tls.client_session_cache = &addr_->tls_session_cache;
456 addr_->sni.empty() ? StringRef{addr_->host} : StringRef{addr_->sni};
458 if (!util::numeric_host(sni_name.c_str())) {
459 // TLS extensions: SNI. There is no documentation about the return
460 // code for this function (actually this is macro wrapping SSL_ctrl
461 // at the time of this writing).
462 SSL_set_tlsext_host_name(conn_.tls.ssl, sni_name.c_str());
465 auto tls_session = tls::reuse_tls_session(addr_->tls_session_cache);
467 SSL_set_session(conn_.tls.ssl, tls_session);
468 SSL_SESSION_free(tls_session);
472 if (state_ == Http2SessionState::DISCONNECTED) {
476 downstream_failure(addr_, nullptr);
479 if (state_ == Http2SessionState::RESOLVING_NAME) {
482 raddr_ = resolved_addr_.get();
484 raddr_ = &addr_->addr;
488 if (state_ == Http2SessionState::RESOLVING_NAME) {
489 if (dns_query_->status == DNSResolverStatus::ERROR) {
490 downstream_failure(addr_, nullptr);
493 assert(dns_query_->status == DNSResolverStatus::OK);
494 state_ = Http2SessionState::DISCONNECTED;
496 raddr_ = resolved_addr_.get();
499 // If state_ == Http2SessionState::PROXY_CONNECTED, we have
500 // connected to the proxy using conn_.fd and tunnel has been
502 if (state_ == Http2SessionState::DISCONNECTED) {
503 assert(conn_.fd == -1);
505 conn_.fd = util::create_nonblock_socket(raddr_->su.storage.ss_family);
506 if (conn_.fd == -1) {
509 << "socket() failed; addr=" << util::to_numeric_addr(raddr_)
510 << ", errno=" << error;
512 worker_blocker->on_failure();
516 worker_blocker->on_success();
518 rv = connect(conn_.fd,
519 // TODO maybe not thread-safe?
520 const_cast<sockaddr *>(&raddr_->su.sa), raddr_->len);
521 if (rv != 0 && errno != EINPROGRESS) {
524 << "connect() failed; addr=" << util::to_numeric_addr(raddr_)
525 << ", errno=" << error;
527 downstream_failure(addr_, raddr_);
531 ev_io_set(&conn_.rev, conn_.fd, EV_READ);
532 ev_io_set(&conn_.wev, conn_.fd, EV_WRITE);
535 conn_.prepare_client_handshake();
537 if (state_ == Http2SessionState::DISCONNECTED) {
538 // Without TLS and proxy.
542 downstream_failure(addr_, nullptr);
545 if (state_ == Http2SessionState::RESOLVING_NAME) {
548 raddr_ = resolved_addr_.get();
550 raddr_ = &addr_->addr;
554 if (state_ == Http2SessionState::RESOLVING_NAME) {
555 if (dns_query_->status == DNSResolverStatus::ERROR) {
556 downstream_failure(addr_, nullptr);
559 assert(dns_query_->status == DNSResolverStatus::OK);
560 state_ = Http2SessionState::DISCONNECTED;
562 raddr_ = resolved_addr_.get();
565 if (state_ == Http2SessionState::DISCONNECTED) {
566 // Without TLS and proxy.
567 assert(conn_.fd == -1);
569 conn_.fd = util::create_nonblock_socket(raddr_->su.storage.ss_family);
571 if (conn_.fd == -1) {
574 << "socket() failed; addr=" << util::to_numeric_addr(raddr_)
575 << ", errno=" << error;
577 worker_blocker->on_failure();
581 worker_blocker->on_success();
583 rv = connect(conn_.fd, const_cast<sockaddr *>(&raddr_->su.sa),
585 if (rv != 0 && errno != EINPROGRESS) {
588 << "connect() failed; addr=" << util::to_numeric_addr(raddr_)
589 << ", errno=" << error;
591 downstream_failure(addr_, raddr_);
595 ev_io_set(&conn_.rev, conn_.fd, EV_READ);
596 ev_io_set(&conn_.wev, conn_.fd, EV_WRITE);
600 // We have been already connected when no TLS and proxy is used.
601 if (state_ == Http2SessionState::PROXY_CONNECTED) {
602 on_read_ = &Http2Session::read_noop;
603 on_write_ = &Http2Session::write_noop;
608 write_ = &Http2Session::connected;
610 state_ = Http2SessionState::CONNECTING;
611 conn_.wlimit.startw();
613 conn_.wt.repeat = downstreamconf.timeout.connect;
614 ev_timer_again(conn_.loop, &conn_.wt);
626 int htp_hdrs_completecb(llhttp_t *htp) {
627 auto http2session = static_cast<Http2Session *>(htp->data);
629 // We only read HTTP header part. If tunneling succeeds, response
630 // body is a different protocol (HTTP/2 in this case), we don't read
633 // We just check status code here
634 if (htp->status_code / 100 == 2) {
635 if (LOG_ENABLED(INFO)) {
636 SSLOG(INFO, http2session) << "Tunneling success";
638 http2session->set_state(Http2SessionState::PROXY_CONNECTED);
643 SSLOG(WARN, http2session) << "Tunneling failed: " << htp->status_code;
644 http2session->set_state(Http2SessionState::PROXY_FAILED);
650 int Http2Session::downstream_read_proxy(const uint8_t *data, size_t datalen) {
651 auto htperr = llhttp_execute(proxy_htp_.get(),
652 reinterpret_cast<const char *>(data), datalen);
653 if (htperr == HPE_PAUSED) {
655 case Http2SessionState::PROXY_CONNECTED:
656 // Initiate SSL/TLS handshake through established tunnel.
657 if (initiate_connection() != 0) {
661 case Http2SessionState::PROXY_FAILED:
666 // should not be here
670 if (htperr != HPE_OK) {
677 int Http2Session::downstream_connect_proxy() {
678 if (LOG_ENABLED(INFO)) {
679 SSLOG(INFO, this) << "Connected to the proxy";
682 std::string req = "CONNECT ";
683 req.append(addr_->hostport.c_str(), addr_->hostport.size());
684 if (addr_->port == 80 || addr_->port == 443) {
686 req += util::utos(addr_->port);
688 req += " HTTP/1.1\r\nHost: ";
691 const auto &proxy = get_config()->downstream_http_proxy;
692 if (!proxy.userinfo.empty()) {
693 req += "Proxy-Authorization: Basic ";
694 req += base64::encode(std::begin(proxy.userinfo), std::end(proxy.userinfo));
698 if (LOG_ENABLED(INFO)) {
699 SSLOG(INFO, this) << "HTTP proxy request headers\n" << req;
703 on_write_ = &Http2Session::write_noop;
709 void Http2Session::add_downstream_connection(Http2DownstreamConnection *dconn) {
710 dconns_.append(dconn);
714 void Http2Session::remove_downstream_connection(
715 Http2DownstreamConnection *dconn) {
717 dconns_.remove(dconn);
718 dconn->detach_stream_data();
720 if (LOG_ENABLED(INFO)) {
721 SSLOG(INFO, this) << "Remove downstream";
724 if (freelist_zone_ == FreelistZone::NONE && !max_concurrency_reached()) {
725 if (LOG_ENABLED(INFO)) {
726 SSLOG(INFO, this) << "Append to http2_extra_freelist, addr=" << addr_
727 << ", freelist.size="
728 << addr_->http2_extra_freelist.size();
731 add_to_extra_freelist();
735 void Http2Session::remove_stream_data(StreamData *sd) {
738 sd->dconn->detach_stream_data();
743 int Http2Session::submit_request(Http2DownstreamConnection *dconn,
744 const nghttp2_nv *nva, size_t nvlen,
745 const nghttp2_data_provider *data_prd) {
746 assert(state_ == Http2SessionState::CONNECTED);
747 auto sd = std::make_unique<StreamData>();
748 sd->dlnext = sd->dlprev = nullptr;
749 // TODO Specify nullptr to pri_spec for now
751 nghttp2_submit_request(session_, nullptr, nva, nvlen, data_prd, sd.get());
753 SSLOG(FATAL, this) << "nghttp2_submit_request() failed: "
754 << nghttp2_strerror(stream_id);
758 dconn->attach_stream_data(sd.get());
759 dconn->get_downstream()->set_downstream_stream_id(stream_id);
760 streams_.append(sd.release());
765 int Http2Session::submit_rst_stream(int32_t stream_id, uint32_t error_code) {
766 assert(state_ == Http2SessionState::CONNECTED);
767 if (LOG_ENABLED(INFO)) {
768 SSLOG(INFO, this) << "RST_STREAM stream_id=" << stream_id
769 << " with error_code=" << error_code;
771 int rv = nghttp2_submit_rst_stream(session_, NGHTTP2_FLAG_NONE, stream_id,
774 SSLOG(FATAL, this) << "nghttp2_submit_rst_stream() failed: "
775 << nghttp2_strerror(rv);
781 nghttp2_session *Http2Session::get_session() const { return session_; }
783 int Http2Session::resume_data(Http2DownstreamConnection *dconn) {
784 assert(state_ == Http2SessionState::CONNECTED);
785 auto downstream = dconn->get_downstream();
786 int rv = nghttp2_session_resume_data(session_,
787 downstream->get_downstream_stream_id());
790 case NGHTTP2_ERR_INVALID_ARGUMENT:
793 SSLOG(FATAL, this) << "nghttp2_resume_session() failed: "
794 << nghttp2_strerror(rv);
800 void call_downstream_readcb(Http2Session *http2session,
801 Downstream *downstream) {
802 auto upstream = downstream->get_upstream();
806 if (upstream->downstream_read(downstream->get_downstream_connection()) != 0) {
807 delete upstream->get_client_handler();
813 int on_stream_close_callback(nghttp2_session *session, int32_t stream_id,
814 uint32_t error_code, void *user_data) {
815 auto http2session = static_cast<Http2Session *>(user_data);
816 if (LOG_ENABLED(INFO)) {
817 SSLOG(INFO, http2session)
818 << "Stream stream_id=" << stream_id
819 << " is being closed with error code " << error_code;
821 auto sd = static_cast<StreamData *>(
822 nghttp2_session_get_stream_user_data(session, stream_id));
824 // We might get this close callback when pushed streams are
828 auto dconn = sd->dconn;
830 auto downstream = dconn->get_downstream();
831 auto upstream = downstream->get_upstream();
833 if (downstream->get_downstream_stream_id() % 2 == 0 &&
834 downstream->get_request_state() == DownstreamState::INITIAL) {
835 // Downstream is canceled in backend before it is submitted in
838 // This will avoid to send RST_STREAM to backend
839 downstream->set_response_state(DownstreamState::MSG_RESET);
840 upstream->cancel_premature_downstream(downstream);
842 if (downstream->get_upgraded() && downstream->get_response_state() ==
843 DownstreamState::HEADER_COMPLETE) {
844 // For tunneled connection, we have to submit RST_STREAM to
845 // upstream *after* whole response body is sent. We just set
846 // MSG_COMPLETE here. Upstream will take care of that.
847 downstream->get_upstream()->on_downstream_body_complete(downstream);
848 downstream->set_response_state(DownstreamState::MSG_COMPLETE);
849 } else if (error_code == NGHTTP2_NO_ERROR) {
850 switch (downstream->get_response_state()) {
851 case DownstreamState::MSG_COMPLETE:
852 case DownstreamState::MSG_BAD_HEADER:
855 downstream->set_response_state(DownstreamState::MSG_RESET);
857 } else if (downstream->get_response_state() !=
858 DownstreamState::MSG_BAD_HEADER) {
859 downstream->set_response_state(DownstreamState::MSG_RESET);
861 if (downstream->get_response_state() == DownstreamState::MSG_RESET &&
862 downstream->get_response_rst_stream_error_code() ==
864 downstream->set_response_rst_stream_error_code(error_code);
866 call_downstream_readcb(http2session, downstream);
868 // dconn may be deleted
870 // The life time of StreamData ends here
871 http2session->remove_stream_data(sd);
876 void Http2Session::start_settings_timer() {
877 auto &downstreamconf = get_config()->http2.downstream;
879 ev_timer_set(&settings_timer_, downstreamconf.timeout.settings, 0.);
880 ev_timer_start(conn_.loop, &settings_timer_);
883 void Http2Session::stop_settings_timer() {
884 ev_timer_stop(conn_.loop, &settings_timer_);
888 int on_header_callback2(nghttp2_session *session, const nghttp2_frame *frame,
889 nghttp2_rcbuf *name, nghttp2_rcbuf *value,
890 uint8_t flags, void *user_data) {
891 auto http2session = static_cast<Http2Session *>(user_data);
892 auto sd = static_cast<StreamData *>(
893 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
894 if (!sd || !sd->dconn) {
897 auto downstream = sd->dconn->get_downstream();
899 auto namebuf = nghttp2_rcbuf_get_buf(name);
900 auto valuebuf = nghttp2_rcbuf_get_buf(value);
902 auto &resp = downstream->response();
903 auto &httpconf = get_config()->http;
905 switch (frame->hd.type) {
906 case NGHTTP2_HEADERS: {
907 auto trailer = frame->headers.cat == NGHTTP2_HCAT_HEADERS &&
908 !downstream->get_expect_final_response();
910 if (resp.fs.buffer_size() + namebuf.len + valuebuf.len >
911 httpconf.response_header_field_buffer ||
912 resp.fs.num_fields() >= httpconf.max_response_header_fields) {
913 if (LOG_ENABLED(INFO)) {
914 DLOG(INFO, downstream)
915 << "Too large or many header field size="
916 << resp.fs.buffer_size() + namebuf.len + valuebuf.len
917 << ", num=" << resp.fs.num_fields() + 1;
921 // We don't care trailer part exceeds header size limit; just
926 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
929 auto token = http2::lookup_token(namebuf.base, namebuf.len);
930 auto no_index = flags & NGHTTP2_NV_FLAG_NO_INDEX;
932 downstream->add_rcbuf(name);
933 downstream->add_rcbuf(value);
936 // just store header fields for trailer part
937 resp.fs.add_trailer_token(StringRef{namebuf.base, namebuf.len},
938 StringRef{valuebuf.base, valuebuf.len},
943 resp.fs.add_header_token(StringRef{namebuf.base, namebuf.len},
944 StringRef{valuebuf.base, valuebuf.len}, no_index,
948 case NGHTTP2_PUSH_PROMISE: {
949 auto promised_stream_id = frame->push_promise.promised_stream_id;
950 auto promised_sd = static_cast<StreamData *>(
951 nghttp2_session_get_stream_user_data(session, promised_stream_id));
952 if (!promised_sd || !promised_sd->dconn) {
953 http2session->submit_rst_stream(promised_stream_id, NGHTTP2_CANCEL);
954 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
957 auto promised_downstream = promised_sd->dconn->get_downstream();
959 auto namebuf = nghttp2_rcbuf_get_buf(name);
960 auto valuebuf = nghttp2_rcbuf_get_buf(value);
962 assert(promised_downstream);
964 auto &promised_req = promised_downstream->request();
966 // We use request header limit for PUSH_PROMISE
967 if (promised_req.fs.buffer_size() + namebuf.len + valuebuf.len >
968 httpconf.request_header_field_buffer ||
969 promised_req.fs.num_fields() >= httpconf.max_request_header_fields) {
970 if (LOG_ENABLED(INFO)) {
971 DLOG(INFO, downstream)
972 << "Too large or many header field size="
973 << promised_req.fs.buffer_size() + namebuf.len + valuebuf.len
974 << ", num=" << promised_req.fs.num_fields() + 1;
977 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
980 promised_downstream->add_rcbuf(name);
981 promised_downstream->add_rcbuf(value);
983 auto token = http2::lookup_token(namebuf.base, namebuf.len);
984 promised_req.fs.add_header_token(StringRef{namebuf.base, namebuf.len},
985 StringRef{valuebuf.base, valuebuf.len},
986 flags & NGHTTP2_NV_FLAG_NO_INDEX, token);
997 int on_invalid_header_callback2(nghttp2_session *session,
998 const nghttp2_frame *frame, nghttp2_rcbuf *name,
999 nghttp2_rcbuf *value, uint8_t flags,
1001 auto http2session = static_cast<Http2Session *>(user_data);
1002 auto sd = static_cast<StreamData *>(
1003 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1004 if (!sd || !sd->dconn) {
1010 if (frame->hd.type == NGHTTP2_PUSH_PROMISE) {
1011 stream_id = frame->push_promise.promised_stream_id;
1013 stream_id = frame->hd.stream_id;
1016 if (LOG_ENABLED(INFO)) {
1017 auto namebuf = nghttp2_rcbuf_get_buf(name);
1018 auto valuebuf = nghttp2_rcbuf_get_buf(value);
1020 SSLOG(INFO, http2session)
1021 << "Invalid header field for stream_id=" << stream_id
1022 << " in frame type=" << static_cast<uint32_t>(frame->hd.type)
1023 << ": name=[" << StringRef{namebuf.base, namebuf.len} << "], value=["
1024 << StringRef{valuebuf.base, valuebuf.len} << "]";
1027 http2session->submit_rst_stream(stream_id, NGHTTP2_PROTOCOL_ERROR);
1029 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
1034 int on_begin_headers_callback(nghttp2_session *session,
1035 const nghttp2_frame *frame, void *user_data) {
1036 auto http2session = static_cast<Http2Session *>(user_data);
1038 switch (frame->hd.type) {
1039 case NGHTTP2_HEADERS: {
1040 if (frame->headers.cat != NGHTTP2_HCAT_RESPONSE &&
1041 frame->headers.cat != NGHTTP2_HCAT_PUSH_RESPONSE) {
1044 auto sd = static_cast<StreamData *>(
1045 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1046 if (!sd || !sd->dconn) {
1047 http2session->submit_rst_stream(frame->hd.stream_id,
1048 NGHTTP2_INTERNAL_ERROR);
1053 case NGHTTP2_PUSH_PROMISE: {
1054 auto promised_stream_id = frame->push_promise.promised_stream_id;
1055 auto sd = static_cast<StreamData *>(
1056 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1057 if (!sd || !sd->dconn) {
1058 http2session->submit_rst_stream(promised_stream_id, NGHTTP2_CANCEL);
1059 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
1062 auto downstream = sd->dconn->get_downstream();
1065 assert(downstream->get_downstream_stream_id() == frame->hd.stream_id);
1067 if (http2session->handle_downstream_push_promise(downstream,
1068 promised_stream_id) != 0) {
1069 http2session->submit_rst_stream(promised_stream_id, NGHTTP2_CANCEL);
1070 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
1082 int on_response_headers(Http2Session *http2session, Downstream *downstream,
1083 nghttp2_session *session, const nghttp2_frame *frame) {
1086 auto upstream = downstream->get_upstream();
1087 auto handler = upstream->get_client_handler();
1088 const auto &req = downstream->request();
1089 auto &resp = downstream->response();
1091 auto &nva = resp.fs.headers();
1093 auto config = get_config();
1094 auto &loggingconf = config->logging;
1096 downstream->set_expect_final_response(false);
1098 auto status = resp.fs.header(http2::HD__STATUS);
1099 // libnghttp2 guarantees this exists and can be parsed
1101 auto status_code = http2::parse_http_status_code(status->value);
1103 resp.http_status = status_code;
1104 resp.http_major = 2;
1105 resp.http_minor = 0;
1107 downstream->set_downstream_addr_group(
1108 http2session->get_downstream_addr_group());
1109 downstream->set_addr(http2session->get_addr());
1111 if (LOG_ENABLED(INFO)) {
1112 std::stringstream ss;
1113 for (auto &nv : nva) {
1114 ss << TTY_HTTP_HD << nv.name << TTY_RST << ": " << nv.value << "\n";
1116 SSLOG(INFO, http2session)
1117 << "HTTP response headers. stream_id=" << frame->hd.stream_id << "\n"
1121 if (downstream->get_non_final_response()) {
1123 if (LOG_ENABLED(INFO)) {
1124 SSLOG(INFO, http2session) << "This is non-final response.";
1127 downstream->set_expect_final_response(true);
1128 rv = upstream->on_downstream_header_complete(downstream);
1130 // Now Dowstream's response headers are erased.
1133 http2session->submit_rst_stream(frame->hd.stream_id,
1134 NGHTTP2_PROTOCOL_ERROR);
1135 downstream->set_response_state(DownstreamState::MSG_RESET);
1141 downstream->set_response_state(DownstreamState::HEADER_COMPLETE);
1142 downstream->check_upgrade_fulfilled_http2();
1144 if (downstream->get_upgraded()) {
1145 resp.connection_close = true;
1146 // On upgrade success, both ends can send data
1147 if (upstream->resume_read(SHRPX_NO_BUFFER, downstream, 0) != 0) {
1148 // If resume_read fails, just drop connection. Not ideal.
1152 downstream->set_request_state(DownstreamState::HEADER_COMPLETE);
1153 if (LOG_ENABLED(INFO)) {
1154 SSLOG(INFO, http2session)
1155 << "HTTP upgrade success. stream_id=" << frame->hd.stream_id;
1158 auto content_length = resp.fs.header(http2::HD_CONTENT_LENGTH);
1159 if (content_length) {
1160 // libnghttp2 guarantees this can be parsed
1161 resp.fs.content_length = util::parse_uint(content_length->value);
1164 if (resp.fs.content_length == -1 && downstream->expect_response_body()) {
1165 // Here we have response body but Content-Length is not known in
1167 if (req.http_major <= 0 || (req.http_major == 1 && req.http_minor == 0)) {
1168 // We simply close connection for pre-HTTP/1.1 in this case.
1169 resp.connection_close = true;
1171 // Otherwise, use chunked encoding to keep upstream connection
1172 // open. In HTTP2, we are supposed not to receive
1173 // transfer-encoding.
1174 resp.fs.add_header_token(StringRef::from_lit("transfer-encoding"),
1175 StringRef::from_lit("chunked"), false,
1176 http2::HD_TRANSFER_ENCODING);
1177 downstream->set_chunked_response(true);
1182 if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1183 resp.headers_only = true;
1186 if (loggingconf.access.write_early && downstream->accesslog_ready()) {
1187 handler->write_accesslog(downstream);
1188 downstream->set_accesslog_written(true);
1191 rv = upstream->on_downstream_header_complete(downstream);
1193 // Handling early return (in other words, response was hijacked by
1194 // mruby scripting).
1195 if (downstream->get_response_state() == DownstreamState::MSG_COMPLETE) {
1196 http2session->submit_rst_stream(frame->hd.stream_id, NGHTTP2_CANCEL);
1198 http2session->submit_rst_stream(frame->hd.stream_id,
1199 NGHTTP2_INTERNAL_ERROR);
1200 downstream->set_response_state(DownstreamState::MSG_RESET);
1209 int on_frame_recv_callback(nghttp2_session *session, const nghttp2_frame *frame,
1212 auto http2session = static_cast<Http2Session *>(user_data);
1214 switch (frame->hd.type) {
1215 case NGHTTP2_DATA: {
1216 auto sd = static_cast<StreamData *>(
1217 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1218 if (!sd || !sd->dconn) {
1221 auto downstream = sd->dconn->get_downstream();
1222 auto upstream = downstream->get_upstream();
1223 rv = upstream->on_downstream_body(downstream, nullptr, 0, true);
1225 http2session->submit_rst_stream(frame->hd.stream_id,
1226 NGHTTP2_INTERNAL_ERROR);
1227 downstream->set_response_state(DownstreamState::MSG_RESET);
1229 } else if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1231 downstream->disable_downstream_rtimer();
1233 if (downstream->get_response_state() ==
1234 DownstreamState::HEADER_COMPLETE) {
1236 downstream->set_response_state(DownstreamState::MSG_COMPLETE);
1238 rv = upstream->on_downstream_body_complete(downstream);
1241 downstream->set_response_state(DownstreamState::MSG_RESET);
1246 call_downstream_readcb(http2session, downstream);
1249 case NGHTTP2_HEADERS: {
1250 auto sd = static_cast<StreamData *>(
1251 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1252 if (!sd || !sd->dconn) {
1255 auto downstream = sd->dconn->get_downstream();
1257 if (frame->headers.cat == NGHTTP2_HCAT_RESPONSE ||
1258 frame->headers.cat == NGHTTP2_HCAT_PUSH_RESPONSE) {
1259 rv = on_response_headers(http2session, downstream, session, frame);
1264 } else if (frame->headers.cat == NGHTTP2_HCAT_HEADERS) {
1265 if (downstream->get_expect_final_response()) {
1266 rv = on_response_headers(http2session, downstream, session, frame);
1274 if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1275 downstream->disable_downstream_rtimer();
1277 if (downstream->get_response_state() ==
1278 DownstreamState::HEADER_COMPLETE) {
1279 downstream->set_response_state(DownstreamState::MSG_COMPLETE);
1281 auto upstream = downstream->get_upstream();
1283 rv = upstream->on_downstream_body_complete(downstream);
1286 downstream->set_response_state(DownstreamState::MSG_RESET);
1290 downstream->reset_downstream_rtimer();
1293 // This may delete downstream
1294 call_downstream_readcb(http2session, downstream);
1298 case NGHTTP2_RST_STREAM: {
1299 auto sd = static_cast<StreamData *>(
1300 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1301 if (sd && sd->dconn) {
1302 auto downstream = sd->dconn->get_downstream();
1303 downstream->set_response_rst_stream_error_code(
1304 frame->rst_stream.error_code);
1305 call_downstream_readcb(http2session, downstream);
1309 case NGHTTP2_SETTINGS: {
1310 if ((frame->hd.flags & NGHTTP2_FLAG_ACK) == 0) {
1311 http2session->on_settings_received(frame);
1315 http2session->stop_settings_timer();
1317 auto addr = http2session->get_addr();
1318 auto &connect_blocker = addr->connect_blocker;
1320 connect_blocker->on_success();
1325 if (frame->hd.flags & NGHTTP2_FLAG_ACK) {
1326 if (LOG_ENABLED(INFO)) {
1327 LOG(INFO) << "PING ACK received";
1329 http2session->connection_alive();
1332 case NGHTTP2_PUSH_PROMISE: {
1333 auto promised_stream_id = frame->push_promise.promised_stream_id;
1335 if (LOG_ENABLED(INFO)) {
1336 SSLOG(INFO, http2session)
1337 << "Received downstream PUSH_PROMISE stream_id="
1338 << frame->hd.stream_id
1339 << ", promised_stream_id=" << promised_stream_id;
1342 auto sd = static_cast<StreamData *>(
1343 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1344 if (!sd || !sd->dconn) {
1345 http2session->submit_rst_stream(promised_stream_id, NGHTTP2_CANCEL);
1349 auto downstream = sd->dconn->get_downstream();
1352 assert(downstream->get_downstream_stream_id() == frame->hd.stream_id);
1354 auto promised_sd = static_cast<StreamData *>(
1355 nghttp2_session_get_stream_user_data(session, promised_stream_id));
1356 if (!promised_sd || !promised_sd->dconn) {
1357 http2session->submit_rst_stream(promised_stream_id, NGHTTP2_CANCEL);
1361 auto promised_downstream = promised_sd->dconn->get_downstream();
1363 assert(promised_downstream);
1365 if (http2session->handle_downstream_push_promise_complete(
1366 downstream, promised_downstream) != 0) {
1367 http2session->submit_rst_stream(promised_stream_id, NGHTTP2_CANCEL);
1373 case NGHTTP2_GOAWAY:
1374 if (LOG_ENABLED(INFO)) {
1375 auto debug_data = util::ascii_dump(frame->goaway.opaque_data,
1376 frame->goaway.opaque_data_len);
1378 SSLOG(INFO, http2session)
1379 << "GOAWAY received: last-stream-id=" << frame->goaway.last_stream_id
1380 << ", error_code=" << frame->goaway.error_code
1381 << ", debug_data=" << debug_data;
1391 int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags,
1392 int32_t stream_id, const uint8_t *data,
1393 size_t len, void *user_data) {
1395 auto http2session = static_cast<Http2Session *>(user_data);
1396 auto sd = static_cast<StreamData *>(
1397 nghttp2_session_get_stream_user_data(session, stream_id));
1398 if (!sd || !sd->dconn) {
1399 http2session->submit_rst_stream(stream_id, NGHTTP2_INTERNAL_ERROR);
1401 if (http2session->consume(stream_id, len) != 0) {
1402 return NGHTTP2_ERR_CALLBACK_FAILURE;
1407 auto downstream = sd->dconn->get_downstream();
1408 if (!downstream->expect_response_body()) {
1409 http2session->submit_rst_stream(stream_id, NGHTTP2_INTERNAL_ERROR);
1411 if (http2session->consume(stream_id, len) != 0) {
1412 return NGHTTP2_ERR_CALLBACK_FAILURE;
1418 // We don't want DATA after non-final response, which is illegal in
1420 if (downstream->get_non_final_response()) {
1421 http2session->submit_rst_stream(stream_id, NGHTTP2_PROTOCOL_ERROR);
1423 if (http2session->consume(stream_id, len) != 0) {
1424 return NGHTTP2_ERR_CALLBACK_FAILURE;
1430 downstream->reset_downstream_rtimer();
1432 auto &resp = downstream->response();
1434 resp.recv_body_length += len;
1435 resp.unconsumed_body_length += len;
1437 auto upstream = downstream->get_upstream();
1438 rv = upstream->on_downstream_body(downstream, data, len, false);
1440 http2session->submit_rst_stream(stream_id, NGHTTP2_INTERNAL_ERROR);
1442 if (http2session->consume(stream_id, len) != 0) {
1443 return NGHTTP2_ERR_CALLBACK_FAILURE;
1446 downstream->set_response_state(DownstreamState::MSG_RESET);
1449 call_downstream_readcb(http2session, downstream);
1455 int on_frame_send_callback(nghttp2_session *session, const nghttp2_frame *frame,
1457 auto http2session = static_cast<Http2Session *>(user_data);
1459 if (frame->hd.type == NGHTTP2_DATA || frame->hd.type == NGHTTP2_HEADERS) {
1460 auto sd = static_cast<StreamData *>(
1461 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1463 if (!sd || !sd->dconn) {
1467 auto downstream = sd->dconn->get_downstream();
1469 if (frame->hd.type == NGHTTP2_HEADERS &&
1470 frame->headers.cat == NGHTTP2_HCAT_REQUEST) {
1471 downstream->set_request_header_sent(true);
1472 auto src = downstream->get_blocked_request_buf();
1474 auto dest = downstream->get_request_buf();
1476 if (http2session->resume_data(sd->dconn) != 0) {
1477 return NGHTTP2_ERR_CALLBACK_FAILURE;
1479 downstream->ensure_downstream_wtimer();
1483 if ((frame->hd.flags & NGHTTP2_FLAG_END_STREAM) == 0) {
1487 downstream->reset_downstream_rtimer();
1492 if (frame->hd.type == NGHTTP2_SETTINGS &&
1493 (frame->hd.flags & NGHTTP2_FLAG_ACK) == 0) {
1494 http2session->start_settings_timer();
1501 int on_frame_not_send_callback(nghttp2_session *session,
1502 const nghttp2_frame *frame, int lib_error_code,
1504 auto http2session = static_cast<Http2Session *>(user_data);
1505 if (LOG_ENABLED(INFO)) {
1506 SSLOG(INFO, http2session) << "Failed to send control frame type="
1507 << static_cast<uint32_t>(frame->hd.type)
1508 << ", lib_error_code=" << lib_error_code << ": "
1509 << nghttp2_strerror(lib_error_code);
1511 if (frame->hd.type != NGHTTP2_HEADERS ||
1512 lib_error_code == NGHTTP2_ERR_STREAM_CLOSED ||
1513 lib_error_code == NGHTTP2_ERR_STREAM_CLOSING) {
1517 auto sd = static_cast<StreamData *>(
1518 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1525 auto downstream = sd->dconn->get_downstream();
1527 if (lib_error_code == NGHTTP2_ERR_START_STREAM_NOT_ALLOWED) {
1528 // Migrate to another downstream connection.
1529 auto upstream = downstream->get_upstream();
1531 if (upstream->on_downstream_reset(downstream, false)) {
1532 // This should be done for h1 upstream only. Deleting
1533 // ClientHandler for h2 upstream may lead to crash.
1534 delete upstream->get_client_handler();
1540 // To avoid stream hanging around, flag DownstreamState::MSG_RESET.
1541 downstream->set_response_state(DownstreamState::MSG_RESET);
1542 call_downstream_readcb(http2session, downstream);
1549 constexpr auto PADDING = std::array<uint8_t, 256>{};
1553 int send_data_callback(nghttp2_session *session, nghttp2_frame *frame,
1554 const uint8_t *framehd, size_t length,
1555 nghttp2_data_source *source, void *user_data) {
1556 auto http2session = static_cast<Http2Session *>(user_data);
1557 auto sd = static_cast<StreamData *>(
1558 nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1560 if (sd == nullptr) {
1561 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
1564 auto dconn = sd->dconn;
1565 auto downstream = dconn->get_downstream();
1566 auto input = downstream->get_request_buf();
1567 auto wb = http2session->get_request_buf();
1571 wb->append(framehd, 9);
1572 if (frame->data.padlen > 0) {
1573 padlen = frame->data.padlen - 1;
1574 wb->append(static_cast<uint8_t>(padlen));
1577 input->remove(*wb, length);
1579 wb->append(PADDING.data(), padlen);
1581 if (input->rleft() == 0) {
1582 downstream->disable_downstream_wtimer();
1584 downstream->reset_downstream_wtimer();
1588 // This is important because it will handle flow control
1590 if (downstream->get_upstream()->resume_read(SHRPX_NO_BUFFER, downstream,
1592 // In this case, downstream may be deleted.
1593 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
1596 // Here sd->dconn could be nullptr, because
1597 // Upstream::resume_read() may delete downstream which will delete
1598 // dconn. Is this still really true?
1605 nghttp2_session_callbacks *create_http2_downstream_callbacks() {
1607 nghttp2_session_callbacks *callbacks;
1609 rv = nghttp2_session_callbacks_new(&callbacks);
1615 nghttp2_session_callbacks_set_on_stream_close_callback(
1616 callbacks, on_stream_close_callback);
1618 nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks,
1619 on_frame_recv_callback);
1621 nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
1622 callbacks, on_data_chunk_recv_callback);
1624 nghttp2_session_callbacks_set_on_frame_send_callback(callbacks,
1625 on_frame_send_callback);
1627 nghttp2_session_callbacks_set_on_frame_not_send_callback(
1628 callbacks, on_frame_not_send_callback);
1630 nghttp2_session_callbacks_set_on_header_callback2(callbacks,
1631 on_header_callback2);
1633 nghttp2_session_callbacks_set_on_invalid_header_callback2(
1634 callbacks, on_invalid_header_callback2);
1636 nghttp2_session_callbacks_set_on_begin_headers_callback(
1637 callbacks, on_begin_headers_callback);
1639 nghttp2_session_callbacks_set_send_data_callback(callbacks,
1640 send_data_callback);
1642 if (get_config()->padding) {
1643 nghttp2_session_callbacks_set_select_padding_callback(
1644 callbacks, http::select_padding_callback);
1650 int Http2Session::connection_made() {
1653 state_ = Http2SessionState::CONNECTED;
1655 on_write_ = &Http2Session::downstream_write;
1656 on_read_ = &Http2Session::downstream_read;
1659 const unsigned char *next_proto = nullptr;
1660 unsigned int next_proto_len = 0;
1662 #ifndef OPENSSL_NO_NEXTPROTONEG
1663 SSL_get0_next_proto_negotiated(conn_.tls.ssl, &next_proto, &next_proto_len);
1664 #endif // !OPENSSL_NO_NEXTPROTONEG
1665 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1667 SSL_get0_alpn_selected(conn_.tls.ssl, &next_proto, &next_proto_len);
1669 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
1672 downstream_failure(addr_, raddr_);
1676 auto proto = StringRef{next_proto, next_proto_len};
1677 if (LOG_ENABLED(INFO)) {
1678 SSLOG(INFO, this) << "Negotiated next protocol: " << proto;
1680 if (!util::check_h2_is_selected(proto)) {
1681 downstream_failure(addr_, raddr_);
1686 auto config = get_config();
1687 auto &http2conf = config->http2;
1689 rv = nghttp2_session_client_new2(&session_, http2conf.downstream.callbacks,
1690 this, http2conf.downstream.option);
1696 std::array<nghttp2_settings_entry, 4> entry;
1698 entry[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
1699 entry[0].value = http2conf.downstream.max_concurrent_streams;
1701 entry[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
1702 entry[1].value = http2conf.downstream.window_size;
1704 if (http2conf.no_server_push || config->http2_proxy) {
1705 entry[nentry].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH;
1706 entry[nentry].value = 0;
1710 if (http2conf.downstream.decoder_dynamic_table_size !=
1711 NGHTTP2_DEFAULT_HEADER_TABLE_SIZE) {
1712 entry[nentry].settings_id = NGHTTP2_SETTINGS_HEADER_TABLE_SIZE;
1713 entry[nentry].value = http2conf.downstream.decoder_dynamic_table_size;
1717 rv = nghttp2_submit_settings(session_, NGHTTP2_FLAG_NONE, entry.data(),
1723 rv = nghttp2_session_set_local_window_size(
1724 session_, NGHTTP2_FLAG_NONE, 0,
1725 http2conf.downstream.connection_window_size);
1730 reset_connection_check_timer(CONNCHK_TIMEOUT);
1732 submit_pending_requests();
1738 int Http2Session::do_read() { return read_(*this); }
1739 int Http2Session::do_write() { return write_(*this); }
1741 int Http2Session::on_read(const uint8_t *data, size_t datalen) {
1742 return on_read_(*this, data, datalen);
1745 int Http2Session::on_write() { return on_write_(*this); }
1747 int Http2Session::downstream_read(const uint8_t *data, size_t datalen) {
1750 rv = nghttp2_session_mem_recv(session_, data, datalen);
1752 SSLOG(ERROR, this) << "nghttp2_session_mem_recv() returned error: "
1753 << nghttp2_strerror(rv);
1757 if (nghttp2_session_want_read(session_) == 0 &&
1758 nghttp2_session_want_write(session_) == 0 && wb_.rleft() == 0) {
1759 if (LOG_ENABLED(INFO)) {
1760 SSLOG(INFO, this) << "No more read/write for this HTTP2 session";
1769 int Http2Session::downstream_write() {
1771 const uint8_t *data;
1772 auto datalen = nghttp2_session_mem_send(session_, &data);
1774 SSLOG(ERROR, this) << "nghttp2_session_mem_send() returned error: "
1775 << nghttp2_strerror(datalen);
1781 wb_.append(data, datalen);
1783 if (wb_.rleft() >= MAX_BUFFER_SIZE) {
1788 if (nghttp2_session_want_read(session_) == 0 &&
1789 nghttp2_session_want_write(session_) == 0 && wb_.rleft() == 0) {
1790 if (LOG_ENABLED(INFO)) {
1791 SSLOG(INFO, this) << "No more read/write for this session";
1799 void Http2Session::signal_write() {
1801 case Http2SessionState::DISCONNECTED:
1802 if (!ev_is_active(&initiate_connection_timer_)) {
1803 if (LOG_ENABLED(INFO)) {
1804 LOG(INFO) << "Start connecting to backend server";
1806 // Since the timer is set to 0., these will feed 2 events. We
1807 // will stop the timer in the initiate_connection_timer_ to void
1809 ev_timer_start(conn_.loop, &initiate_connection_timer_);
1810 ev_feed_event(conn_.loop, &initiate_connection_timer_, 0);
1813 case Http2SessionState::CONNECTED:
1814 conn_.wlimit.startw();
1821 struct ev_loop *Http2Session::get_loop() const {
1825 ev_io *Http2Session::get_wev() { return &conn_.wev; }
1827 Http2SessionState Http2Session::get_state() const { return state_; }
1829 void Http2Session::set_state(Http2SessionState state) { state_ = state; }
1831 int Http2Session::terminate_session(uint32_t error_code) {
1833 rv = nghttp2_session_terminate_session(session_, error_code);
1840 SSL *Http2Session::get_ssl() const { return conn_.tls.ssl; }
1842 int Http2Session::consume(int32_t stream_id, size_t len) {
1849 rv = nghttp2_session_consume(session_, stream_id, len);
1852 SSLOG(WARN, this) << "nghttp2_session_consume() returned error: "
1853 << nghttp2_strerror(rv);
1861 bool Http2Session::can_push_request(const Downstream *downstream) const {
1862 auto &req = downstream->request();
1863 return state_ == Http2SessionState::CONNECTED &&
1864 connection_check_state_ == ConnectionCheck::NONE &&
1865 (req.connect_proto == ConnectProto::NONE || settings_recved_);
1868 void Http2Session::start_checking_connection() {
1869 if (state_ != Http2SessionState::CONNECTED ||
1870 connection_check_state_ != ConnectionCheck::REQUIRED) {
1873 connection_check_state_ = ConnectionCheck::STARTED;
1875 SSLOG(INFO, this) << "Start checking connection";
1876 // If connection is down, we may get error when writing data. Issue
1877 // ping frame to see whether connection is alive.
1878 nghttp2_submit_ping(session_, NGHTTP2_FLAG_NONE, NULL);
1880 // set ping timeout and start timer again
1881 reset_connection_check_timer(CONNCHK_PING_TIMEOUT);
1886 void Http2Session::reset_connection_check_timer(ev_tstamp t) {
1887 connchk_timer_.repeat = t;
1888 ev_timer_again(conn_.loop, &connchk_timer_);
1891 void Http2Session::reset_connection_check_timer_if_not_checking() {
1892 if (connection_check_state_ != ConnectionCheck::NONE) {
1896 reset_connection_check_timer(CONNCHK_TIMEOUT);
1899 void Http2Session::connection_alive() {
1900 reset_connection_check_timer(CONNCHK_TIMEOUT);
1902 if (connection_check_state_ == ConnectionCheck::NONE) {
1906 if (LOG_ENABLED(INFO)) {
1907 SSLOG(INFO, this) << "Connection alive";
1910 connection_check_state_ = ConnectionCheck::NONE;
1912 submit_pending_requests();
1915 void Http2Session::submit_pending_requests() {
1916 for (auto dconn = dconns_.head; dconn; dconn = dconn->dlnext) {
1917 auto downstream = dconn->get_downstream();
1919 if (!downstream->get_request_pending() ||
1920 !downstream->request_submission_ready()) {
1924 auto &req = downstream->request();
1925 if (req.connect_proto != ConnectProto::NONE && !settings_recved_) {
1929 auto upstream = downstream->get_upstream();
1931 if (dconn->push_request_headers() != 0) {
1932 if (LOG_ENABLED(INFO)) {
1933 SSLOG(INFO, this) << "backend request failed";
1936 upstream->on_downstream_abort_request(downstream, 400);
1941 upstream->resume_read(SHRPX_NO_BUFFER, downstream, 0);
1945 void Http2Session::set_connection_check_state(ConnectionCheck state) {
1946 connection_check_state_ = state;
1949 ConnectionCheck Http2Session::get_connection_check_state() const {
1950 return connection_check_state_;
1953 int Http2Session::noop() { return 0; }
1955 int Http2Session::read_noop(const uint8_t *data, size_t datalen) { return 0; }
1957 int Http2Session::write_noop() { return 0; }
1959 int Http2Session::connected() {
1960 auto sock_error = util::get_socket_error(conn_.fd);
1961 if (sock_error != 0) {
1962 SSLOG(WARN, this) << "Backend connect failed; addr="
1963 << util::to_numeric_addr(raddr_)
1964 << ": errno=" << sock_error;
1966 downstream_failure(addr_, raddr_);
1971 if (LOG_ENABLED(INFO)) {
1972 SSLOG(INFO, this) << "Connection established";
1975 // Reset timeout for write. Previously, we set timeout for connect.
1976 conn_.wt.repeat = group_->shared_addr->timeout.write;
1977 ev_timer_again(conn_.loop, &conn_.wt);
1979 conn_.rlimit.startw();
1982 read_ = &Http2Session::read_clear;
1983 write_ = &Http2Session::write_clear;
1985 if (state_ == Http2SessionState::PROXY_CONNECTING) {
1989 if (conn_.tls.ssl) {
1990 read_ = &Http2Session::tls_handshake;
1991 write_ = &Http2Session::tls_handshake;
1996 if (connection_made() != 0) {
1997 state_ = Http2SessionState::CONNECT_FAILING;
2004 int Http2Session::read_clear() {
2005 conn_.last_read = ev_now(conn_.loop);
2007 std::array<uint8_t, 16_k> buf;
2010 auto nread = conn_.read_clear(buf.data(), buf.size());
2013 return write_clear();
2020 if (on_read(buf.data(), nread) != 0) {
2026 int Http2Session::write_clear() {
2027 conn_.last_read = ev_now(conn_.loop);
2029 std::array<struct iovec, MAX_WR_IOVCNT> iov;
2032 if (wb_.rleft() > 0) {
2033 auto iovcnt = wb_.riovec(iov.data(), iov.size());
2034 auto nwrite = conn_.writev_clear(iov.data(), iovcnt);
2041 // We may have pending data in receive buffer which may
2042 // contain part of response body. So keep reading. Invoke
2043 // read event to get read(2) error just in case.
2044 ev_feed_event(conn_.loop, &conn_.rev, EV_READ);
2045 write_ = &Http2Session::write_void;
2053 if (on_write() != 0) {
2056 if (wb_.rleft() == 0) {
2061 conn_.wlimit.stopw();
2062 ev_timer_stop(conn_.loop, &conn_.wt);
2067 int Http2Session::tls_handshake() {
2068 conn_.last_read = ev_now(conn_.loop);
2072 auto rv = conn_.tls_handshake();
2074 if (rv == SHRPX_ERR_INPROGRESS) {
2079 downstream_failure(addr_, raddr_);
2084 if (LOG_ENABLED(INFO)) {
2085 SSLOG(INFO, this) << "SSL/TLS handshake completed";
2088 if (!get_config()->tls.insecure &&
2089 tls::check_cert(conn_.tls.ssl, addr_, raddr_) != 0) {
2090 downstream_failure(addr_, raddr_);
2095 read_ = &Http2Session::read_tls;
2096 write_ = &Http2Session::write_tls;
2098 if (connection_made() != 0) {
2099 state_ = Http2SessionState::CONNECT_FAILING;
2106 int Http2Session::read_tls() {
2107 conn_.last_read = ev_now(conn_.loop);
2109 std::array<uint8_t, 16_k> buf;
2114 auto nread = conn_.read_tls(buf.data(), buf.size());
2124 if (on_read(buf.data(), nread) != 0) {
2130 int Http2Session::write_tls() {
2131 conn_.last_read = ev_now(conn_.loop);
2138 if (wb_.rleft() > 0) {
2139 auto iovcnt = wb_.riovec(&iov, 1);
2144 auto nwrite = conn_.write_tls(iov.iov_base, iov.iov_len);
2151 // We may have pending data in receive buffer which may
2152 // contain part of response body. So keep reading. Invoke
2153 // read event to get read(2) error just in case.
2154 ev_feed_event(conn_.loop, &conn_.rev, EV_READ);
2155 write_ = &Http2Session::write_void;
2164 if (on_write() != 0) {
2167 if (wb_.rleft() == 0) {
2168 conn_.start_tls_write_idle();
2173 conn_.wlimit.stopw();
2174 ev_timer_stop(conn_.loop, &conn_.wt);
2179 int Http2Session::write_void() {
2180 conn_.wlimit.stopw();
2184 bool Http2Session::should_hard_fail() const {
2186 case Http2SessionState::PROXY_CONNECTING:
2187 case Http2SessionState::PROXY_FAILED:
2189 case Http2SessionState::DISCONNECTED: {
2190 const auto &proxy = get_config()->downstream_http_proxy;
2191 return !proxy.host.empty();
2198 DownstreamAddr *Http2Session::get_addr() const { return addr_; }
2200 int Http2Session::handle_downstream_push_promise(Downstream *downstream,
2201 int32_t promised_stream_id) {
2202 auto upstream = downstream->get_upstream();
2203 if (!upstream->push_enabled()) {
2207 auto promised_downstream =
2208 upstream->on_downstream_push_promise(downstream, promised_stream_id);
2209 if (!promised_downstream) {
2213 // Now we have Downstream object for pushed stream.
2214 // promised_downstream->get_stream() still returns 0.
2216 auto handler = upstream->get_client_handler();
2218 auto promised_dconn = std::make_unique<Http2DownstreamConnection>(this);
2219 promised_dconn->set_client_handler(handler);
2221 auto ptr = promised_dconn.get();
2223 if (promised_downstream->attach_downstream_connection(
2224 std::move(promised_dconn)) != 0) {
2228 auto promised_sd = std::make_unique<StreamData>();
2230 nghttp2_session_set_stream_user_data(session_, promised_stream_id,
2233 ptr->attach_stream_data(promised_sd.get());
2234 streams_.append(promised_sd.release());
2239 int Http2Session::handle_downstream_push_promise_complete(
2240 Downstream *downstream, Downstream *promised_downstream) {
2241 auto &promised_req = promised_downstream->request();
2243 auto &promised_balloc = promised_downstream->get_block_allocator();
2245 auto authority = promised_req.fs.header(http2::HD__AUTHORITY);
2246 auto path = promised_req.fs.header(http2::HD__PATH);
2247 auto method = promised_req.fs.header(http2::HD__METHOD);
2248 auto scheme = promised_req.fs.header(http2::HD__SCHEME);
2251 authority = promised_req.fs.header(http2::HD_HOST);
2254 auto method_token = http2::lookup_method_token(method->value);
2255 if (method_token == -1) {
2256 if (LOG_ENABLED(INFO)) {
2257 SSLOG(INFO, this) << "Unrecognized method: " << method->value;
2263 // TODO Rewrite authority if we enabled rewrite host. But we
2264 // really don't know how to rewrite host. Should we use the same
2265 // host in associated stream?
2267 promised_req.authority = authority->value;
2269 promised_req.method = method_token;
2270 // libnghttp2 ensures that we don't have CONNECT method in
2271 // PUSH_PROMISE, and guarantees that :scheme exists.
2273 promised_req.scheme = scheme->value;
2276 // For server-wide OPTIONS request, path is empty.
2277 if (method_token != HTTP_OPTIONS || path->value != "*") {
2278 promised_req.path = http2::rewrite_clean_path(promised_balloc, path->value);
2281 promised_downstream->inspect_http2_request();
2283 auto upstream = promised_downstream->get_upstream();
2285 promised_downstream->set_request_state(DownstreamState::MSG_COMPLETE);
2286 promised_downstream->set_request_header_sent(true);
2288 if (upstream->on_downstream_push_promise_complete(downstream,
2289 promised_downstream) != 0) {
2296 size_t Http2Session::get_num_dconns() const { return dconns_.size(); }
2298 bool Http2Session::max_concurrency_reached(size_t extra) const {
2300 return dconns_.size() + extra >= 100;
2303 // If session does not allow further requests, it effectively means
2304 // that maximum concurrency is reached.
2305 return !nghttp2_session_check_request_allowed(session_) ||
2306 dconns_.size() + extra >=
2307 nghttp2_session_get_remote_settings(
2308 session_, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
2311 const std::shared_ptr<DownstreamAddrGroup> &
2312 Http2Session::get_downstream_addr_group() const {
2316 void Http2Session::add_to_extra_freelist() {
2317 if (freelist_zone_ != FreelistZone::NONE) {
2321 if (LOG_ENABLED(INFO)) {
2322 SSLOG(INFO, this) << "Append to http2_extra_freelist, addr=" << addr_
2323 << ", freelist.size="
2324 << addr_->http2_extra_freelist.size();
2327 freelist_zone_ = FreelistZone::EXTRA;
2328 addr_->http2_extra_freelist.append(this);
2331 void Http2Session::remove_from_freelist() {
2332 switch (freelist_zone_) {
2333 case FreelistZone::NONE:
2335 case FreelistZone::EXTRA:
2336 if (LOG_ENABLED(INFO)) {
2337 SSLOG(INFO, this) << "Remove from http2_extra_freelist, addr=" << addr_
2338 << ", freelist.size="
2339 << addr_->http2_extra_freelist.size();
2341 addr_->http2_extra_freelist.remove(this);
2343 case FreelistZone::GONE:
2347 freelist_zone_ = FreelistZone::NONE;
2350 void Http2Session::exclude_from_scheduling() {
2351 remove_from_freelist();
2352 freelist_zone_ = FreelistZone::GONE;
2355 DefaultMemchunks *Http2Session::get_request_buf() { return &wb_; }
2357 void Http2Session::on_timeout() {
2359 case Http2SessionState::PROXY_CONNECTING: {
2360 auto worker_blocker = worker_->get_connect_blocker();
2361 worker_blocker->on_failure();
2364 case Http2SessionState::CONNECTING:
2365 SSLOG(WARN, this) << "Connect time out; addr="
2366 << util::to_numeric_addr(raddr_);
2368 downstream_failure(addr_, raddr_);
2375 void Http2Session::check_retire() {
2376 if (!group_->retired) {
2380 ev_prepare_stop(conn_.loop, &prep_);
2382 auto last_stream_id = nghttp2_session_get_last_proc_stream_id(session_);
2383 nghttp2_submit_goaway(session_, NGHTTP2_FLAG_NONE, last_stream_id,
2384 NGHTTP2_NO_ERROR, nullptr, 0);
2389 const Address *Http2Session::get_raddr() const { return raddr_; }
2391 void Http2Session::on_settings_received(const nghttp2_frame *frame) {
2392 // TODO This effectively disallows nghttpx to change its behaviour
2393 // based on the 2nd SETTINGS.
2394 if (settings_recved_) {
2398 settings_recved_ = true;
2400 for (size_t i = 0; i < frame->settings.niv; ++i) {
2401 auto &ent = frame->settings.iv[i];
2402 if (ent.settings_id == NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL) {
2403 allow_connect_proto_ = true;
2408 submit_pending_requests();
2411 bool Http2Session::get_allow_connect_proto() const {
2412 return allow_connect_proto_;
2415 } // namespace shrpx