shrpx_http2_session.cc 40.9 KB
Newer Older
1
/*
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
2
 * nghttp2 - HTTP/2.0 C Library
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * Copyright (c) 2012 Tatsuhiro Tsujikawa
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
25
#include "shrpx_http2_session.h"
26

27
#include <netinet/tcp.h>
28 29 30 31 32 33 34 35 36 37 38
#include <unistd.h>
#include <vector>

#include <openssl/err.h>

#include <event2/bufferevent_ssl.h>

#include "shrpx_upstream.h"
#include "shrpx_downstream.h"
#include "shrpx_config.h"
#include "shrpx_error.h"
39
#include "shrpx_http2_downstream_connection.h"
40
#include "shrpx_client_handler.h"
41
#include "shrpx_ssl.h"
42
#include "shrpx_http.h"
43
#include "http2.h"
44
#include "util.h"
45
#include "base64.h"
46

Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
47
using namespace nghttp2;
48 49 50

namespace shrpx {

51
Http2Session::Http2Session(event_base *evbase, SSL_CTX *ssl_ctx)
52 53
  : evbase_(evbase),
    ssl_ctx_(ssl_ctx),
54 55 56 57 58
    ssl_(nullptr),
    session_(nullptr),
    bev_(nullptr),
    wrbev_(nullptr),
    rdbev_(nullptr),
59 60 61 62 63
    settings_timerev_(nullptr),
    fd_(-1),
    state_(DISCONNECTED),
    notified_(false),
    flow_control_(false)
64 65
{}

66
Http2Session::~Http2Session()
67 68 69 70
{
  disconnect();
}

71
int Http2Session::disconnect()
72
{
73
  if(LOG_ENABLED(INFO)) {
74
    SSLOG(INFO, this) << "Disconnecting";
75
  }
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
76
  nghttp2_session_del(session_);
77
  session_ = nullptr;
78

79 80 81 82 83
  if(settings_timerev_) {
    event_free(settings_timerev_);
    settings_timerev_ = nullptr;
  }

84
  if(ssl_) {
85
    SSL_set_shutdown(ssl_, SSL_RECEIVED_SHUTDOWN);
86 87 88
    SSL_shutdown(ssl_);
  }
  if(bev_) {
89
    int fd = bufferevent_getfd(bev_);
90 91
    bufferevent_disable(bev_, EV_READ | EV_WRITE);
    bufferevent_free(bev_);
92
    bev_ = nullptr;
93 94 95 96 97 98 99 100 101
    if(fd != -1) {
      if(fd_ == -1) {
        fd_ = fd;
      } else if(fd != fd_) {
        SSLOG(WARNING, this) << "fd in bev_ != fd_";
        shutdown(fd, SHUT_WR);
        close(fd);
      }
    }
102 103 104 105
  }
  if(ssl_) {
    SSL_free(ssl_);
  }
106
  ssl_ = nullptr;
107

108
  if(fd_ != -1) {
109 110 111
    if(LOG_ENABLED(INFO)) {
      SSLOG(INFO, this) << "Closing fd=" << fd_;
    }
112 113 114 115 116 117
    shutdown(fd_, SHUT_WR);
    close(fd_);
    fd_ = -1;
  }

  if(proxy_htp_) {
118
    proxy_htp_.reset();
119 120 121 122 123 124
  }

  notified_ = false;
  state_ = DISCONNECTED;

  // Delete all client handler associated to Downstream. When deleting
125
  // Http2DownstreamConnection, it calls this object's
126
  // remove_downstream_connection(). The multiple
127
  // Http2DownstreamConnection objects belong to the same ClientHandler
128 129
  // object. So first dump ClientHandler objects and delete them once
  // and for all.
130
  std::vector<Http2DownstreamConnection*> vec(dconns_.begin(), dconns_.end());
131
  std::set<ClientHandler*> handlers;
132
  for(size_t i = 0; i < vec.size(); ++i) {
133
    handlers.insert(vec[i]->get_client_handler());
134
  }
135 136
  for(auto& h : handlers) {
    delete h;
137 138
  }

139
  dconns_.clear();
140 141
  for(auto& s : streams_) {
    delete s;
142 143 144 145 146 147 148 149 150
  }
  streams_.clear();
  return 0;
}

namespace {
void notify_readcb(bufferevent *bev, void *arg)
{
  int rv;
151
  auto http2session = static_cast<Http2Session*>(arg);
152 153 154 155
  http2session->clear_notify();
  switch(http2session->get_state()) {
  case Http2Session::DISCONNECTED:
    rv = http2session->initiate_connection();
156
    if(rv != 0) {
157
      SSLOG(FATAL, http2session)
158
        << "Could not initiate backend connection";
159
      http2session->disconnect();
160 161
    }
    break;
162 163
  case Http2Session::CONNECTED:
    rv = http2session->send();
164
    if(rv != 0) {
165
      http2session->disconnect();
166 167 168 169 170 171 172 173 174
    }
    break;
  }
}
} // namespace

namespace {
void notify_eventcb(bufferevent *bev, short events, void *arg)
{
175
  auto http2session = static_cast<Http2Session*>(arg);
176 177
  // TODO should DIE()?
  if(events & BEV_EVENT_EOF) {
178
    SSLOG(ERROR, http2session) << "Notification connection lost: EOF";
179 180
  }
  if(events & BEV_EVENT_TIMEOUT) {
181
    SSLOG(ERROR, http2session) << "Notification connection lost: timeout";
182 183
  }
  if(events & BEV_EVENT_ERROR) {
184
    SSLOG(ERROR, http2session) << "Notification connection lost: network error";
185 186 187 188
  }
}
} // namespace

189
int Http2Session::init_notification()
190 191 192 193 194
{
  int rv;
  int sockpair[2];
  rv = socketpair(AF_UNIX, SOCK_STREAM, 0, sockpair);
  if(rv == -1) {
195
    SSLOG(FATAL, this) << "socketpair() failed: errno=" << errno;
196 197 198 199 200 201
    return -1;
  }
  wrbev_ = bufferevent_socket_new(evbase_, sockpair[0],
                                  BEV_OPT_CLOSE_ON_FREE|
                                  BEV_OPT_DEFER_CALLBACKS);
  if(!wrbev_) {
202
    SSLOG(FATAL, this) << "bufferevent_socket_new() failed";
203 204 205 206 207 208 209 210 211
    for(int i = 0; i < 2; ++i) {
      close(sockpair[i]);
    }
    return -1;
  }
  rdbev_ = bufferevent_socket_new(evbase_, sockpair[1],
                                  BEV_OPT_CLOSE_ON_FREE|
                                  BEV_OPT_DEFER_CALLBACKS);
  if(!rdbev_) {
212
    SSLOG(FATAL, this) << "bufferevent_socket_new() failed";
213 214 215 216
    close(sockpair[1]);
    return -1;
  }
  bufferevent_enable(rdbev_, EV_READ);
217
  bufferevent_setcb(rdbev_, notify_readcb, nullptr, notify_eventcb, this);
218 219 220 221 222 223 224
  return 0;
}

namespace {
void readcb(bufferevent *bev, void *ptr)
{
  int rv;
225
  auto http2session = static_cast<Http2Session*>(ptr);
226
  rv = http2session->on_read();
227
  if(rv != 0) {
228
    http2session->disconnect();
229 230 231 232 233 234 235
  }
}
} // namespace

namespace {
void writecb(bufferevent *bev, void *ptr)
{
236 237 238
  if(evbuffer_get_length(bufferevent_get_output(bev)) > 0) {
    return;
  }
239
  int rv;
240
  auto http2session = static_cast<Http2Session*>(ptr);
241
  rv = http2session->on_write();
242
  if(rv != 0) {
243
    http2session->disconnect();
244 245 246 247 248 249 250
  }
}
} // namespace

namespace {
void eventcb(bufferevent *bev, short events, void *ptr)
{
251
  auto http2session = static_cast<Http2Session*>(ptr);
252
  if(events & BEV_EVENT_CONNECTED) {
253
    if(LOG_ENABLED(INFO)) {
254
      SSLOG(INFO, http2session) << "Connection established";
255
    }
256
    http2session->set_state(Http2Session::CONNECTED);
257
    if((!get_config()->downstream_no_tls &&
258 259 260
        !get_config()->insecure && http2session->check_cert() != 0) ||
       http2session->on_connect() != 0) {
      http2session->disconnect();
261 262
      return;
    }
263 264
    int fd = bufferevent_getfd(bev);
    int val = 1;
265 266
    if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
                  reinterpret_cast<char *>(&val), sizeof(val)) == -1) {
267 268
      SSLOG(WARNING, http2session)
        << "Setting option TCP_NODELAY failed: errno=" << errno;
269
    }
270
  } else if(events & BEV_EVENT_EOF) {
271
    if(LOG_ENABLED(INFO)) {
272
      SSLOG(INFO, http2session) << "EOF";
273
    }
274
    http2session->disconnect();
275
  } else if(events & (BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT)) {
276
    if(LOG_ENABLED(INFO)) {
277
      if(events & BEV_EVENT_ERROR) {
278
        SSLOG(INFO, http2session) << "Network error";
279
      } else {
280
        SSLOG(INFO, http2session) << "Timeout";
281
      }
282
    }
283
    http2session->disconnect();
284 285 286 287
  }
}
} // namespace

288 289 290
namespace {
void proxy_readcb(bufferevent *bev, void *ptr)
{
291
  auto http2session = static_cast<Http2Session*>(ptr);
292 293 294
  if(http2session->on_read_proxy() == 0) {
    switch(http2session->get_state()) {
    case Http2Session::PROXY_CONNECTED:
295
      // The current bufferevent is no longer necessary, so delete it
296
      // here. But we keep fd_ inside it.
297
      http2session->unwrap_free_bev();
298
      // Initiate SSL/TLS handshake through established tunnel.
299 300
      if(http2session->initiate_connection() != 0) {
        http2session->disconnect();
301
      }
302
      break;
303 304
    case Http2Session::PROXY_FAILED:
      http2session->disconnect();
305 306 307
      break;
    }
  } else {
308
    http2session->disconnect();
309 310 311 312 313 314 315
  }
}
} // namespace

namespace {
void proxy_eventcb(bufferevent *bev, short events, void *ptr)
{
316
  auto http2session = static_cast<Http2Session*>(ptr);
317 318
  if(events & BEV_EVENT_CONNECTED) {
    if(LOG_ENABLED(INFO)) {
319
      SSLOG(INFO, http2session) << "Connected to the proxy";
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    }
    std::string req = "CONNECT ";
    req += get_config()->downstream_hostport;
    req += " HTTP/1.1\r\nHost: ";
    req += get_config()->downstream_host;
    req += "\r\n";
    if(get_config()->downstream_http_proxy_userinfo) {
      req += "Proxy-Authorization: Basic ";
      size_t len = strlen(get_config()->downstream_http_proxy_userinfo);
      req += base64::encode(get_config()->downstream_http_proxy_userinfo,
                            get_config()->downstream_http_proxy_userinfo+len);
      req += "\r\n";
    }
    req += "\r\n";
    if(LOG_ENABLED(INFO)) {
335
      SSLOG(INFO, http2session) << "HTTP proxy request headers\n" << req;
336 337
    }
    if(bufferevent_write(bev, req.c_str(), req.size()) != 0) {
338 339
      SSLOG(ERROR, http2session) << "bufferevent_write() failed";
      http2session->disconnect();
340 341 342
    }
  } else if(events & BEV_EVENT_EOF) {
    if(LOG_ENABLED(INFO)) {
343
      SSLOG(INFO, http2session) << "Proxy EOF";
344
    }
345
    http2session->disconnect();
346 347 348
  } else if(events & (BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT)) {
    if(LOG_ENABLED(INFO)) {
      if(events & BEV_EVENT_ERROR) {
349
        SSLOG(INFO, http2session) << "Network error";
350
      } else {
351
        SSLOG(INFO, http2session) << "Timeout";
352 353
      }
    }
354
    http2session->disconnect();
355 356 357 358
  }
}
} // namespace

359
int Http2Session::check_cert()
360 361 362 363
{
  return ssl::check_cert(ssl_);
}

364
int Http2Session::initiate_connection()
365
{
366
  int rv = 0;
367 368 369 370 371 372 373
  if(get_config()->downstream_http_proxy_host && state_ == DISCONNECTED) {
    if(LOG_ENABLED(INFO)) {
      SSLOG(INFO, this) << "Connecting to the proxy "
                        << get_config()->downstream_http_proxy_host << ":"
                        << get_config()->downstream_http_proxy_port;
    }
    bev_ = bufferevent_socket_new(evbase_, -1, BEV_OPT_DEFER_CALLBACKS);
374 375 376 377
    if(!bev_) {
      SSLOG(ERROR, this) << "bufferevent_socket_new() failed";
      return SHRPX_ERR_NETWORK;
    }
378 379 380 381 382 383
    bufferevent_enable(bev_, EV_READ);
    bufferevent_set_timeouts(bev_, &get_config()->downstream_read_timeout,
                             &get_config()->downstream_write_timeout);

    // No need to set writecb because we write the request when
    // connected at once.
384
    bufferevent_setcb(bev_, proxy_readcb, nullptr, proxy_eventcb, this);
385 386 387 388 389 390 391 392 393 394
    rv = bufferevent_socket_connect
      (bev_,
       const_cast<sockaddr*>(&get_config()->downstream_http_proxy_addr.sa),
       get_config()->downstream_http_proxy_addrlen);
    if(rv != 0) {
      SSLOG(ERROR, this) << "Failed to connect to the proxy "
                         << get_config()->downstream_http_proxy_host << ":"
                         << get_config()->downstream_http_proxy_port;
      return SHRPX_ERR_NETWORK;
    }
395 396
    proxy_htp_ = util::make_unique<http_parser>();
    http_parser_init(proxy_htp_.get(), HTTP_RESPONSE);
397
    proxy_htp_->data = this;
398

399 400 401 402 403
    state_ = PROXY_CONNECTING;
  } else if(state_ == DISCONNECTED || state_ == PROXY_CONNECTED) {
    if(LOG_ENABLED(INFO)) {
      SSLOG(INFO, this) << "Connecting to downstream server";
    }
404 405 406 407 408 409 410 411
    if(ssl_ctx_) {
      // We are establishing TLS connection.
      ssl_ = SSL_new(ssl_ctx_);
      if(!ssl_) {
        SSLOG(ERROR, this) << "SSL_new() failed: "
                           << ERR_error_string(ERR_get_error(), NULL);
        return -1;
      }
412

413
      const char *sni_name = nullptr;
414 415 416 417 418 419 420 421
      if ( get_config()->backend_tls_sni_name ) {
        sni_name = get_config()->backend_tls_sni_name;
      }
      else {
        sni_name = get_config()->downstream_host;
      }

      if(!ssl::numeric_host(sni_name)) {
422 423 424
        // TLS extensions: SNI. There is no documentation about the return
        // code for this function (actually this is macro wrapping SSL_ctrl
        // at the time of this writing).
425
        SSL_set_tlsext_host_name(ssl_, sni_name);
426 427 428 429 430 431
      }
      // If state_ == PROXY_CONNECTED, we has connected to the proxy
      // using fd_ and tunnel has been established.
      bev_ = bufferevent_openssl_socket_new(evbase_, fd_, ssl_,
                                            BUFFEREVENT_SSL_CONNECTING,
                                            BEV_OPT_DEFER_CALLBACKS);
432 433 434 435
      if(!bev_) {
        SSLOG(ERROR, this) << "bufferevent_socket_new() failed";
        return SHRPX_ERR_NETWORK;
      }
436 437 438 439 440 441 442 443
      rv = bufferevent_socket_connect
        (bev_,
         // TODO maybe not thread-safe?
         const_cast<sockaddr*>(&get_config()->downstream_addr.sa),
         get_config()->downstream_addrlen);
    } else if(state_ == DISCONNECTED) {
      // Without TLS and proxy.
      bev_ = bufferevent_socket_new(evbase_, -1, BEV_OPT_DEFER_CALLBACKS);
444 445 446 447
      if(!bev_) {
        SSLOG(ERROR, this) << "bufferevent_socket_new() failed";
        return SHRPX_ERR_NETWORK;
      }
448 449 450 451 452 453 454 455
      rv = bufferevent_socket_connect
        (bev_,
         const_cast<sockaddr*>(&get_config()->downstream_addr.sa),
         get_config()->downstream_addrlen);
    } else {
      assert(state_ == PROXY_CONNECTED);
      // Without TLS but with proxy.
      bev_ = bufferevent_socket_new(evbase_, fd_, BEV_OPT_DEFER_CALLBACKS);
456 457 458 459
      if(!bev_) {
        SSLOG(ERROR, this) << "bufferevent_socket_new() failed";
        return SHRPX_ERR_NETWORK;
      }
460 461 462 463 464 465 466
      // Connection already established.
      eventcb(bev_, BEV_EVENT_CONNECTED, this);
      // eventcb() has no return value. Check state_ to whether it was
      // failed or not.
      if(state_ == DISCONNECTED) {
        return -1;
      }
467 468 469 470 471 472 473 474
    }
    if(rv != 0) {
      return SHRPX_ERR_NETWORK;
    }

    bufferevent_setwatermark(bev_, EV_READ, 0, SHRPX_READ_WARTER_MARK);
    bufferevent_enable(bev_, EV_READ);
    bufferevent_setcb(bev_, readcb, writecb, eventcb, this);
475
    // Set timeout for HTTP2 session
476 477
    bufferevent_set_timeouts(bev_, &get_config()->downstream_read_timeout,
                             &get_config()->downstream_write_timeout);
478

479 480 481 482
    // We have been already connected when no TLS and proxy is used.
    if(state_ != CONNECTED) {
      state_ = CONNECTING;
    }
483 484 485
  } else {
    // Unreachable
    DIE();
486
  }
487 488
  return 0;
}
489

490
void Http2Session::unwrap_free_bev()
491
{
492 493
  assert(fd_ == -1);
  fd_ = bufferevent_getfd(bev_);
494
  bufferevent_free(bev_);
495
  bev_ = nullptr;
496
}
497

498 499 500
namespace {
int htp_hdrs_completecb(http_parser *htp)
{
501
  auto http2session = static_cast<Http2Session*>(htp->data);
502 503 504
  // We just check status code here
  if(htp->status_code == 200) {
    if(LOG_ENABLED(INFO)) {
505
      SSLOG(INFO, http2session) << "Tunneling success";
506
    }
507
    http2session->set_state(Http2Session::PROXY_CONNECTED);
508
  } else {
509 510
    SSLOG(WARNING, http2session) << "Tunneling failed";
    http2session->set_state(Http2Session::PROXY_FAILED);
511
  }
512 513
  return 0;
}
514 515 516 517
} // namespace

namespace {
http_parser_settings htp_hooks = {
518 519 520 521 522
  nullptr, /*http_cb      on_message_begin;*/
  nullptr, /*http_data_cb on_url;*/
  nullptr, /*http_cb on_status_complete */
  nullptr, /*http_data_cb on_header_field;*/
  nullptr, /*http_data_cb on_header_value;*/
523
  htp_hdrs_completecb, /*http_cb      on_headers_complete;*/
524 525
  nullptr, /*http_data_cb on_body;*/
  nullptr  /*http_cb      on_message_complete;*/
526 527
};
} // namespace
528

529
int Http2Session::on_read_proxy()
530
{
531 532
  auto input = bufferevent_get_input(bev_);
  auto mem = evbuffer_pullup(input, -1);
533

534
  size_t nread = http_parser_execute(proxy_htp_.get(), &htp_hooks,
535 536 537
                                     reinterpret_cast<const char*>(mem),
                                     evbuffer_get_length(input));

538 539 540 541
  if(evbuffer_drain(input, nread) != 0) {
    SSLOG(FATAL, this) << "evbuffer_drain() failed";
    return -1;
  }
542
  auto htperr = HTTP_PARSER_ERRNO(proxy_htp_.get());
543 544 545 546 547
  if(htperr == HPE_OK) {
    return 0;
  } else {
    return -1;
  }
548 549
}

550
void Http2Session::add_downstream_connection(Http2DownstreamConnection *dconn)
551 552 553 554
{
  dconns_.insert(dconn);
}

555 556
void Http2Session::remove_downstream_connection
(Http2DownstreamConnection *dconn)
557 558 559 560 561
{
  dconns_.erase(dconn);
  dconn->detach_stream_data();
}

562
void Http2Session::remove_stream_data(StreamData *sd)
563 564 565 566 567 568 569 570
{
  streams_.erase(sd);
  if(sd->dconn) {
    sd->dconn->detach_stream_data();
  }
  delete sd;
}

571
int Http2Session::submit_request(Http2DownstreamConnection *dconn,
572 573 574
                                 uint8_t pri,
                                 const nghttp2_nv *nva, size_t nvlen,
                                 const nghttp2_data_provider *data_prd)
575 576
{
  assert(state_ == CONNECTED);
577
  auto sd = util::make_unique<StreamData>();
578 579
  int rv = nghttp2_submit_request(session_, pri, nva, nvlen,
                                  data_prd, sd.get());
580
  if(rv == 0) {
581 582
    dconn->attach_stream_data(sd.get());
    streams_.insert(sd.release());
583
  } else {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
584 585
    SSLOG(FATAL, this) << "nghttp2_submit_request() failed: "
                       << nghttp2_strerror(rv);
586 587 588 589 590
    return -1;
  }
  return 0;
}

591
int Http2Session::submit_rst_stream(int32_t stream_id,
592
                                   nghttp2_error_code error_code)
593 594
{
  assert(state_ == CONNECTED);
595 596 597 598 599 600
  if(LOG_ENABLED(INFO)) {
    SSLOG(INFO, this) << "RST_STREAM stream_id="
                      << stream_id
                      << " with error_code="
                      << error_code;
  }
601 602
  int rv = nghttp2_submit_rst_stream(session_, NGHTTP2_FLAG_NONE,
                                     stream_id, error_code);
603
  if(rv != 0) {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
604 605
    SSLOG(FATAL, this) << "nghttp2_submit_rst_stream() failed: "
                       << nghttp2_strerror(rv);
606 607 608 609 610
    return -1;
  }
  return 0;
}

611
int Http2Session::submit_window_update(Http2DownstreamConnection *dconn,
612 613 614 615
                                      int32_t amount)
{
  assert(state_ == CONNECTED);
  int rv;
616 617 618 619 620 621
  int32_t stream_id;
  if(dconn) {
    stream_id = dconn->get_downstream()->get_downstream_stream_id();
  } else {
    stream_id = 0;
  }
622 623
  rv = nghttp2_submit_window_update(session_, NGHTTP2_FLAG_NONE,
                                    stream_id, amount);
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
624 625 626
  if(rv < NGHTTP2_ERR_FATAL) {
    SSLOG(FATAL, this) << "nghttp2_submit_window_update() failed: "
                       << nghttp2_strerror(rv);
627 628 629 630 631
    return -1;
  }
  return 0;
}

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
int Http2Session::submit_priority(Http2DownstreamConnection *dconn,
                                  int32_t pri)
{
  assert(state_ == CONNECTED);
  if(!dconn) {
    return 0;
  }
  int rv;
  rv = nghttp2_submit_priority(session_, NGHTTP2_FLAG_NONE,
                               dconn->get_downstream()->
                               get_downstream_stream_id(), pri);
  if(rv < NGHTTP2_ERR_FATAL) {
    SSLOG(FATAL, this) << "nghttp2_submit_priority() failed: "
                       << nghttp2_strerror(rv);
    return -1;
  }
  return 0;
}

651
nghttp2_session* Http2Session::get_session() const
652
{
653
  return session_;
654 655
}

656
bool Http2Session::get_flow_control() const
657 658 659 660
{
  return flow_control_;
}

661
int Http2Session::resume_data(Http2DownstreamConnection *dconn)
662 663
{
  assert(state_ == CONNECTED);
664
  auto downstream = dconn->get_downstream();
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
665
  int rv = nghttp2_session_resume_data(session_,
666 667 668
                                       downstream->get_downstream_stream_id());
  switch(rv) {
  case 0:
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
669
  case NGHTTP2_ERR_INVALID_ARGUMENT:
670 671
    return 0;
  default:
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
672 673
    SSLOG(FATAL, this) << "nghttp2_resume_session() failed: "
                       << nghttp2_strerror(rv);
674 675 676 677 678
    return -1;
  }
}

namespace {
679
void call_downstream_readcb(Http2Session *http2session, Downstream *downstream)
680
{
681
  auto upstream = downstream->get_upstream();
682 683
  if(upstream) {
    (upstream->get_downstream_readcb())
684
      (http2session->get_bev(),
685 686 687 688 689 690
       downstream->get_downstream_connection());
  }
}
} // namespace

namespace {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
691
ssize_t send_callback(nghttp2_session *session,
692 693 694 695
                      const uint8_t *data, size_t len, int flags,
                      void *user_data)
{
  int rv;
696
  auto http2session = static_cast<Http2Session*>(user_data);
697
  auto bev = http2session->get_bev();
698
  auto output = bufferevent_get_output(bev);
699
  // Check buffer length and return WOULDBLOCK if it is large enough.
700
  if(evbuffer_get_length(output) > Http2Session::OUTBUF_MAX_THRES) {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
701
    return NGHTTP2_ERR_WOULDBLOCK;
702 703 704 705
  }

  rv = evbuffer_add(output, data, len);
  if(rv == -1) {
706
    SSLOG(FATAL, http2session) << "evbuffer_add() failed";
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
707
    return NGHTTP2_ERR_CALLBACK_FAILURE;
708 709 710 711 712 713 714
  } else {
    return len;
  }
}
} // namespace

namespace {
715
int on_stream_close_callback
716
(nghttp2_session *session, int32_t stream_id, nghttp2_error_code error_code,
717 718 719
 void *user_data)
{
  int rv;
720
  auto http2session = static_cast<Http2Session*>(user_data);
721
  if(LOG_ENABLED(INFO)) {
722 723
    SSLOG(INFO, http2session) << "Stream stream_id=" << stream_id
                              << " is being closed";
724
  }
725
  auto sd = static_cast<StreamData*>
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
726
    (nghttp2_session_get_stream_user_data(session, stream_id));
727 728 729
  if(sd == 0) {
    // We might get this close callback when pushed streams are
    // closed.
730
    return 0;
731
  }
732
  auto dconn = sd->dconn;
733
  if(dconn) {
734
    auto downstream = dconn->get_downstream();
735
    if(downstream && downstream->get_downstream_stream_id() == stream_id) {
736 737
      auto upstream = downstream->get_upstream();
      if(error_code == NGHTTP2_NO_ERROR) {
738 739 740 741 742 743 744 745
        downstream->set_response_state(Downstream::MSG_COMPLETE);
        rv = upstream->on_downstream_body_complete(downstream);
        if(rv != 0) {
          downstream->set_response_state(Downstream::MSG_RESET);
        }
      } else {
        downstream->set_response_state(Downstream::MSG_RESET);
      }
746
      call_downstream_readcb(http2session, downstream);
747 748 749 750
      // dconn may be deleted
    }
  }
  // The life time of StreamData ends here
751
  http2session->remove_stream_data(sd);
752
  return 0;
753 754 755
}
} // namespace

756 757 758
namespace {
void settings_timeout_cb(evutil_socket_t fd, short what, void *arg)
{
759
  auto http2session = static_cast<Http2Session*>(arg);
760
  SSLOG(INFO, http2session) << "SETTINGS timeout";
761
  if(http2session->terminate_session(NGHTTP2_SETTINGS_TIMEOUT) != 0) {
762
    http2session->disconnect();
763 764
    return;
  }
765 766
  if(http2session->send() != 0) {
    http2session->disconnect();
767 768 769 770
  }
}
} // namespace

771
int Http2Session::start_settings_timer()
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
{
  int rv;
  // We submit SETTINGS only once
  if(settings_timerev_) {
    return 0;
  }
  settings_timerev_ = evtimer_new(evbase_, settings_timeout_cb, this);
  if(settings_timerev_ == nullptr) {
    return -1;
  }
  // SETTINGS ACK timeout is 10 seconds for now
  timeval settings_timeout = { 10, 0 };
  rv = evtimer_add(settings_timerev_, &settings_timeout);
  if(rv == -1) {
    return -1;
  }
  return 0;
}

791
void Http2Session::stop_settings_timer()
792 793 794 795 796 797 798 799
{
  if(settings_timerev_ == nullptr) {
    return;
  }
  event_free(settings_timerev_);
  settings_timerev_ = nullptr;
}

800 801 802 803 804 805 806 807 808 809 810
namespace {
int on_header_callback(nghttp2_session *session,
                       const nghttp2_frame *frame,
                       const uint8_t *name, size_t namelen,
                       const uint8_t *value, size_t valuelen,
                       void *user_data)
{
  if(frame->hd.type != NGHTTP2_HEADERS ||
     frame->headers.cat != NGHTTP2_HCAT_RESPONSE) {
    return 0;
  }
811
  auto sd = static_cast<StreamData*>
812 813 814 815 816 817 818 819
    (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
  if(!sd || !sd->dconn) {
    return 0;
  }
  auto downstream = sd->dconn->get_downstream();
  if(!downstream) {
    return 0;
  }
820 821 822 823
  if(downstream->get_response_headers_sum() > Downstream::MAX_HEADERS_SUM) {
    if(LOG_ENABLED(INFO)) {
      DLOG(INFO, downstream) << "Too large header block size="
                             << downstream->get_response_headers_sum();
824
    }
825
    return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
826
  }
827 828 829
  if(!http2::check_nv(name, namelen, value, valuelen)) {
    return 0;
  }
830 831 832 833 834 835
  downstream->split_add_response_header(name, namelen, value, valuelen);
  return 0;
}
} // namespace

namespace {
836 837 838
int on_begin_headers_callback(nghttp2_session *session,
                              const nghttp2_frame *frame,
                              void *user_data)
839
{
840 841 842 843 844
  auto http2session = static_cast<Http2Session*>(user_data);
  if(frame->headers.cat == NGHTTP2_HCAT_REQUEST) {
    // server sends request HEADERS
    http2session->submit_rst_stream(frame->hd.stream_id,
                                    NGHTTP2_REFUSED_STREAM);
845 846
    return 0;
  }
847 848 849 850 851 852 853 854
  if(frame->headers.cat != NGHTTP2_HCAT_RESPONSE) {
    return 0;
  }
  auto sd = static_cast<StreamData*>
    (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
  if(!sd || !sd->dconn) {
    http2session->submit_rst_stream(frame->hd.stream_id,
                                    NGHTTP2_INTERNAL_ERROR);
855 856
    return 0;
  }
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
  auto downstream = sd->dconn->get_downstream();
  if(!downstream ||
     downstream->get_downstream_stream_id() != frame->hd.stream_id) {
    http2session->submit_rst_stream(frame->hd.stream_id,
                                    NGHTTP2_INTERNAL_ERROR);
    return 0;
  }
  return 0;
}
} // namespace

namespace {
int on_response_headers(Http2Session *http2session,
                        nghttp2_session *session,
                        const nghttp2_frame *frame)
{
873
  int rv;
874
  auto sd = static_cast<StreamData*>
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
    (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
  if(!sd || !sd->dconn) {
    return 0;
  }
  auto downstream = sd->dconn->get_downstream();
  if(!downstream) {
    return 0;
  }
  downstream->normalize_response_headers();
  auto& nva = downstream->get_response_headers();

  if(!http2::check_http2_headers(nva)) {
    http2session->submit_rst_stream(frame->hd.stream_id,
                                    NGHTTP2_PROTOCOL_ERROR);
    downstream->set_response_state(Downstream::MSG_RESET);
    call_downstream_readcb(http2session, downstream);
    return 0;
  }

  auto status = http2::get_unique_header(nva, ":status");
  if(!status || http2::value_lws(status)) {
    http2session->submit_rst_stream(frame->hd.stream_id,
                                    NGHTTP2_PROTOCOL_ERROR);
    downstream->set_response_state(Downstream::MSG_RESET);
    call_downstream_readcb(http2session, downstream);
    return 0;
  }
  downstream->set_response_http_status(strtoul(status->second.c_str(),
                                               nullptr, 10));
  // Just assume it is HTTP/1.1. But we really consider to say 2.0
  // here.
  downstream->set_response_major(1);
  downstream->set_response_minor(1);

  auto content_length = http2::get_header(nva, "content-length");
  if(!content_length && downstream->get_request_method() != "HEAD" &&
     downstream->get_request_method() != "CONNECT") {
    unsigned int status;
    status = downstream->get_response_http_status();
    if(!((100 <= status && status <= 199) || status == 204 ||
         status == 304)) {
      // Here we have response body but Content-Length is not known
      // in advance.
      if(downstream->get_request_major() <= 0 ||
         downstream->get_request_minor() <= 0) {
        // We simply close connection for pre-HTTP/1.1 in this case.
        downstream->set_response_connection_close(true);
      } else {
        // Otherwise, use chunked encoding to keep upstream
        // connection open.  In HTTP2, we are supporsed not to
        // receive transfer-encoding.
        downstream->add_response_header("transfer-encoding", "chunked");
      }
    }
  }

  if(LOG_ENABLED(INFO)) {
    std::stringstream ss;
    for(auto& nv : nva) {
      ss << TTY_HTTP_HD << nv.first << TTY_RST << ": " << nv.second << "\n";
    }
    SSLOG(INFO, http2session) << "HTTP response headers. stream_id="
                              << frame->hd.stream_id
                              << "\n" << ss.str();
  }

  auto upstream = downstream->get_upstream();
  downstream->set_response_state(Downstream::HEADER_COMPLETE);
  downstream->check_upgrade_fulfilled();
  if(downstream->get_upgraded()) {
    downstream->set_response_connection_close(true);
    // On upgrade sucess, both ends can send data
    if(upstream->resume_read(SHRPX_MSG_BLOCK, downstream) != 0) {
      // If resume_read fails, just drop connection. Not ideal.
      delete upstream->get_client_handler();
      return 0;
    }
    downstream->set_request_state(Downstream::HEADER_COMPLETE);
    if(LOG_ENABLED(INFO)) {
      SSLOG(INFO, http2session) << "HTTP upgrade success. stream_id="
                                << frame->hd.stream_id;
    }
  } else if(downstream->get_request_method() == "CONNECT") {
    // If request is CONNECT, terminate request body to avoid for
    // stream to stall.
    downstream->end_upload_data();
  }
  rv = upstream->on_downstream_header_complete(downstream);
  if(rv != 0) {
    http2session->submit_rst_stream(frame->hd.stream_id,
                                    NGHTTP2_PROTOCOL_ERROR);
    downstream->set_response_state(Downstream::MSG_RESET);
  }
  call_downstream_readcb(http2session, downstream);
  return 0;
}
} // namespace

973
namespace {
974
int on_frame_recv_callback
975
(nghttp2_session *session, const nghttp2_frame *frame, void *user_data)
976
{
977
  auto http2session = static_cast<Http2Session*>(user_data);
978
  switch(frame->hd.type) {
979 980
  case NGHTTP2_HEADERS:
    return on_response_headers(http2session, session, frame);
981
  case NGHTTP2_RST_STREAM: {
982
    auto sd = static_cast<StreamData*>
983 984 985 986 987
      (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
    if(sd && sd->dconn) {
      auto downstream = sd->dconn->get_downstream();
      if(downstream &&
         downstream->get_downstream_stream_id() == frame->hd.stream_id) {
988
        if(downstream->get_upgraded() &&
989 990 991 992 993
           downstream->get_response_state() == Downstream::HEADER_COMPLETE) {
          // For tunneled connection, we has to submit RST_STREAM to
          // upstream *after* whole response body is sent. We just set
          // MSG_COMPLETE here. Upstream will take care of that.
          if(LOG_ENABLED(INFO)) {
994 995 996
            SSLOG(INFO, http2session) << "RST_STREAM against tunneled stream "
                                      << "stream_id="
                                      << frame->hd.stream_id;
997 998 999 1000 1001 1002 1003 1004 1005 1006
          }
          downstream->get_upstream()->on_downstream_body_complete(downstream);
          downstream->set_response_state(Downstream::MSG_COMPLETE);
        } else {
          // If we got RST_STREAM, just flag MSG_RESET to indicate
          // upstream connection must be terminated.
          downstream->set_response_state(Downstream::MSG_RESET);
        }
        downstream->set_response_rst_stream_error_code
          (frame->rst_stream.error_code);
1007
        call_downstream_readcb(http2session, downstream);
1008 1009 1010 1011
      }
    }
    break;
  }
1012 1013 1014 1015
  case NGHTTP2_SETTINGS:
    if((frame->hd.flags & NGHTTP2_FLAG_ACK) == 0) {
      break;
    }
1016
    http2session->stop_settings_timer();
1017
    break;
1018 1019
  case NGHTTP2_PUSH_PROMISE:
    if(LOG_ENABLED(INFO)) {
1020
      SSLOG(INFO, http2session)
1021 1022
        << "Received downstream PUSH_PROMISE stream_id=" << frame->hd.stream_id
        << ", promised_stream_id=" << frame->push_promise.promised_stream_id;
1023 1024
    }
    // We just respond with RST_STREAM.
1025
    http2session->submit_rst_stream(frame->push_promise.promised_stream_id,
1026
                                    NGHTTP2_REFUSED_STREAM);
1027
    break;
1028 1029 1030
  default:
    break;
  }
1031
  return 0;
1032 1033 1034 1035
}
} // namespace

namespace {
1036 1037 1038 1039
int on_data_chunk_recv_callback(nghttp2_session *session,
                                uint8_t flags, int32_t stream_id,
                                const uint8_t *data, size_t len,
                                void *user_data)
1040 1041
{
  int rv;
1042 1043
  auto http2session = static_cast<Http2Session*>(user_data);
  auto sd = static_cast<StreamData*>
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1044
    (nghttp2_session_get_stream_user_data(session, stream_id));
1045
  if(!sd || !sd->dconn) {
1046
    http2session->submit_rst_stream(stream_id, NGHTTP2_INTERNAL_ERROR);
1047
    return 0;
1048
  }
1049
  auto downstream = sd->dconn->get_downstream();
1050
  if(!downstream || downstream->get_downstream_stream_id() != stream_id) {
1051
    http2session->submit_rst_stream(stream_id, NGHTTP2_INTERNAL_ERROR);
1052
    return 0;
1053
  }
1054

1055
  auto upstream = downstream->get_upstream();
1056 1057
  rv = upstream->on_downstream_body(downstream, data, len);
  if(rv != 0) {
1058
    http2session->submit_rst_stream(stream_id, NGHTTP2_INTERNAL_ERROR);
1059 1060
    downstream->set_response_state(Downstream::MSG_RESET);
  }
1061
  call_downstream_readcb(http2session, downstream);
1062
  return 0;
1063 1064 1065 1066
}
} // namespace

namespace {
1067
int before_frame_send_callback(nghttp2_session *session,
1068
                               const nghttp2_frame *frame,
1069
                               void *user_data)
1070
{
1071
  auto http2session = static_cast<Http2Session*>(user_data);
1072 1073
  if(frame->hd.type == NGHTTP2_HEADERS &&
     frame->headers.cat == NGHTTP2_HCAT_REQUEST) {
1074
    auto sd = static_cast<StreamData*>
1075
      (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1076
    if(!sd || !sd->dconn) {
1077
      http2session->submit_rst_stream(frame->hd.stream_id, NGHTTP2_CANCEL);
1078
      return 0;
1079
    }
1080
    auto downstream = sd->dconn->get_downstream();
1081
    if(downstream) {
1082
      downstream->set_downstream_stream_id(frame->hd.stream_id);
1083
    } else {
1084
      http2session->submit_rst_stream(frame->hd.stream_id, NGHTTP2_CANCEL);
1085 1086
    }
  }
1087
  return 0;
1088 1089 1090
}
} // namespace

1091 1092 1093 1094
namespace {
int on_frame_send_callback(nghttp2_session* session,
                           const nghttp2_frame *frame, void *user_data)
{
1095
  auto http2session = static_cast<Http2Session*>(user_data);
1096 1097
  if(frame->hd.type == NGHTTP2_SETTINGS &&
     (frame->hd.flags & NGHTTP2_FLAG_ACK) == 0) {
1098
    if(http2session->start_settings_timer() != 0) {
1099 1100 1101 1102 1103 1104 1105
      return NGHTTP2_ERR_CALLBACK_FAILURE;
    }
  }
  return 0;
}
} // namespace

1106
namespace {
1107
int on_frame_not_send_callback(nghttp2_session *session,
1108 1109
                               const nghttp2_frame *frame,
                               int lib_error_code, void *user_data)
1110
{
1111
  auto http2session = static_cast<Http2Session*>(user_data);
1112 1113 1114 1115
  SSLOG(WARNING, http2session) << "Failed to send control frame type="
                               << frame->hd.type << ", "
                               << "lib_error_code=" << lib_error_code << ":"
                               << nghttp2_strerror(lib_error_code);
1116 1117
  if(frame->hd.type == NGHTTP2_HEADERS &&
     frame->headers.cat == NGHTTP2_HCAT_REQUEST) {
1118 1119
    // To avoid stream hanging around, flag Downstream::MSG_RESET and
    // terminate the upstream and downstream connections.
1120
    auto sd = static_cast<StreamData*>
1121
      (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id));
1122
    if(!sd) {
1123
      return 0;
1124 1125
    }
    if(sd->dconn) {
1126
      auto downstream = sd->dconn->get_downstream();
1127
      if(!downstream ||
1128
         downstream->get_downstream_stream_id() != frame->hd.stream_id) {
1129
        return 0;
1130 1131
      }
      downstream->set_response_state(Downstream::MSG_RESET);
1132
      call_downstream_readcb(http2session, downstream);
1133
    }
1134
    http2session->remove_stream_data(sd);
1135
  }
1136
  return 0;
1137 1138 1139 1140
}
} // namespace

namespace {
1141 1142 1143 1144
int on_unknown_frame_recv_callback(nghttp2_session *session,
                                   const uint8_t *head, size_t headlen,
                                   const uint8_t *payload, size_t payloadlen,
                                   void *user_data)
1145
{
1146
  auto http2session = static_cast<Http2Session*>(user_data);
1147
  if(LOG_ENABLED(INFO)) {
1148
    SSLOG(INFO, http2session) << "Received unknown control frame";
1149
  }
1150
  return 0;
1151 1152 1153
}
} // namespace

1154
int Http2Session::on_connect()
1155 1156
{
  int rv;
1157
  if(ssl_ctx_) {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1158 1159
    const unsigned char *next_proto = nullptr;
    unsigned int next_proto_len;
1160
    SSL_get0_next_proto_negotiated(ssl_, &next_proto, &next_proto_len);
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    for(int i = 0; i < 2; ++i) {
      if(next_proto) {
        if(LOG_ENABLED(INFO)) {
          std::string proto(next_proto, next_proto+next_proto_len);
          SSLOG(INFO, this) << "Negotiated next protocol: " << proto;
        }
        if(next_proto_len != NGHTTP2_PROTO_VERSION_ID_LEN ||
           memcmp(NGHTTP2_PROTO_VERSION_ID, next_proto,
                  NGHTTP2_PROTO_VERSION_ID_LEN) != 0) {
          return -1;
        }
        break;
      }
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
      SSL_get0_alpn_selected(ssl_, &next_proto, &next_proto_len);
#else // OPENSSL_VERSION_NUMBER < 0x10002000L
      break;
#endif // OPENSSL_VERSION_NUMBER < 0x10002000L
1179
    }
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1180
    if(!next_proto) {
1181 1182
      return -1;
    }
1183
  }
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1184
  nghttp2_session_callbacks callbacks;
1185 1186 1187
  memset(&callbacks, 0, sizeof(callbacks));
  callbacks.send_callback = send_callback;
  callbacks.on_stream_close_callback = on_stream_close_callback;
1188
  callbacks.on_frame_recv_callback = on_frame_recv_callback;
1189
  callbacks.on_data_chunk_recv_callback = on_data_chunk_recv_callback;
1190
  callbacks.before_frame_send_callback = before_frame_send_callback;
1191
  callbacks.on_frame_send_callback = on_frame_send_callback;
1192 1193
  callbacks.on_frame_not_send_callback = on_frame_not_send_callback;
  callbacks.on_unknown_frame_recv_callback = on_unknown_frame_recv_callback;
1194
  callbacks.on_header_callback = on_header_callback;
1195
  callbacks.on_begin_headers_callback = on_begin_headers_callback;
1196 1197 1198
  if(get_config()->padding) {
    callbacks.select_padding_callback = http::select_padding_callback;
  }
1199

1200 1201 1202 1203 1204 1205 1206 1207
  nghttp2_opt_set opt_set;
  opt_set.no_auto_stream_window_update = 1;
  opt_set.no_auto_connection_window_update = 1;
  uint32_t opt_set_mask =
    NGHTTP2_OPT_NO_AUTO_STREAM_WINDOW_UPDATE |
    NGHTTP2_OPT_NO_AUTO_CONNECTION_WINDOW_UPDATE;
  rv = nghttp2_session_client_new2(&session_, &callbacks, this,
                                   opt_set_mask, &opt_set);
1208 1209 1210 1211
  if(rv != 0) {
    return -1;
  }

1212
  flow_control_ = true;
1213

1214 1215 1216 1217
  nghttp2_settings_entry entry[3];
  entry[0].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH;
  entry[0].value = 0;
  entry[1].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
1218
  entry[1].value = get_config()->http2_max_concurrent_streams;
1219 1220

  entry[2].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
1221
  entry[2].value = (1 << get_config()->http2_downstream_window_bits) - 1;
1222

1223 1224
  rv = nghttp2_submit_settings(session_, NGHTTP2_FLAG_NONE, entry,
                               sizeof(entry)/sizeof(nghttp2_settings_entry));
1225 1226 1227
  if(rv != 0) {
    return -1;
  }
1228

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  if(get_config()->http2_downstream_connection_window_bits > 16) {
    int32_t delta =
      (1 << get_config()->http2_downstream_connection_window_bits) - 1
      - NGHTTP2_INITIAL_CONNECTION_WINDOW_SIZE;
    rv = nghttp2_submit_window_update(session_, NGHTTP2_FLAG_NONE, 0, delta);
    if(rv != 0) {
      return -1;
    }
  }

1239 1240 1241 1242 1243 1244
  rv = bufferevent_write(bev_, NGHTTP2_CLIENT_CONNECTION_HEADER,
                         NGHTTP2_CLIENT_CONNECTION_HEADER_LEN);
  if(rv != 0) {
    SSLOG(FATAL, this) << "bufferevent_write() failed";
    return -1;
  }
1245

1246 1247 1248 1249 1250 1251
  rv = send();
  if(rv != 0) {
    return -1;
  }

  // submit pending request
1252 1253
  for(auto dconn : dconns_) {
    if(dconn->push_request_headers() != 0) {
1254 1255 1256 1257 1258 1259
      return -1;
    }
  }
  return 0;
}

1260
int Http2Session::on_read()
1261
{
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
  ssize_t rv = 0;
  auto input = bufferevent_get_input(bev_);
  auto inputlen = evbuffer_get_length(input);
  auto mem = evbuffer_pullup(input, -1);

  rv = nghttp2_session_mem_recv(session_, mem, inputlen);
  if(rv < 0) {
    SSLOG(ERROR, this) << "nghttp2_session_recv() returned error: "
                       << nghttp2_strerror(rv);
    return -1;
  }
  evbuffer_drain(input, rv);
  rv = nghttp2_session_send(session_);
  if(rv < 0) {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1276 1277
    SSLOG(ERROR, this) << "nghttp2_session_send() returned error: "
                       << nghttp2_strerror(rv);
1278
    return -1;
1279
  }
1280 1281 1282 1283 1284
  if(nghttp2_session_want_read(session_) == 0 &&
     nghttp2_session_want_write(session_) == 0 &&
     evbuffer_get_length(bufferevent_get_output(bev_)) == 0) {
    if(LOG_ENABLED(INFO)) {
      SSLOG(INFO, this) << "No more read/write for this session";
1285
    }
1286
    return -1;
1287
  }
1288
  return 0;
1289 1290
}

1291
int Http2Session::on_write()
1292 1293 1294 1295
{
  return send();
}

1296
int Http2Session::send()
1297 1298
{
  int rv = 0;
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1299 1300 1301
  if((rv = nghttp2_session_send(session_)) < 0) {
    SSLOG(ERROR, this) << "nghttp2_session_send() returned error: "
                       << nghttp2_strerror(rv);
1302
  }
1303
  if(rv == 0) {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
1304
    if(nghttp2_session_want_read(session_) == 0 &&
1305 1306
       nghttp2_session_want_write(session_) == 0 &&
       evbuffer_get_length(bufferevent_get_output(bev_)) == 0) {
1307
      if(LOG_ENABLED(INFO)) {
1308 1309 1310 1311 1312
        SSLOG(INFO, this) << "No more read/write for this session";
      }
      rv = -1;
    }
  }
1313 1314 1315
  return rv;
}

1316
void Http2Session::clear_notify()
1317
{
1318
  auto input = bufferevent_get_output(rdbev_);
1319 1320 1321
  if(evbuffer_drain(input, evbuffer_get_length(input)) != 0) {
    SSLOG(FATAL, this) << "evbuffer_drain() failed";
  }
1322 1323 1324
  notified_ = false;
}

1325
void Http2Session::notify()
1326 1327
{
  if(!notified_) {
1328 1329 1330
    if(bufferevent_write(wrbev_, "1", 1) != 0) {
      SSLOG(FATAL, this) << "bufferevent_write failed";
    }
1331 1332 1333 1334
    notified_ = true;
  }
}

1335
bufferevent* Http2Session::get_bev() const
1336 1337 1338 1339
{
  return bev_;
}

1340
int Http2Session::get_state() const
1341 1342 1343 1344
{
  return state_;
}

1345
void Http2Session::set_state(int state)
1346 1347 1348 1349
{
  state_ = state;
}

1350
int Http2Session::terminate_session(nghttp2_error_code error_code)
1351 1352
{
  int rv;
1353
  rv = nghttp2_session_terminate_session(session_, error_code);
1354 1355 1356 1357 1358 1359
  if(rv != 0) {
    return -1;
  }
  return 0;
}

1360 1361 1362 1363 1364 1365 1366 1367 1368
size_t Http2Session::get_outbuf_length() const
{
  if(bev_) {
    return evbuffer_get_length(bufferevent_get_output(bev_));
  } else {
    return OUTBUF_MAX_THRES;
  }
}

1369
} // namespace shrpx