2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2015 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_connection.h"
29 #endif // HAVE_UNISTD_H
30 #include <netinet/tcp.h>
34 #include <openssl/err.h>
36 #include "shrpx_tls.h"
37 #include "shrpx_memcached_request.h"
38 #include "shrpx_log.h"
41 #include "ssl_compat.h"
43 using namespace nghttp2;
47 #if !LIBRESSL_2_7_API && !OPENSSL_1_1_API
49 void *BIO_get_data(BIO *bio) { return bio->ptr; }
50 void BIO_set_data(BIO *bio, void *ptr) { bio->ptr = ptr; }
51 void BIO_set_init(BIO *bio, int init) { bio->init = init; }
53 #endif // !LIBRESSL_2_7_API && !OPENSSL_1_1_API
55 Connection::Connection(struct ev_loop *loop, int fd, SSL *ssl,
56 MemchunkPool *mcpool, ev_tstamp write_timeout,
57 ev_tstamp read_timeout,
58 const RateLimitConfig &write_limit,
59 const RateLimitConfig &read_limit, IOCb writecb,
60 IOCb readcb, TimerCb timeoutcb, void *data,
61 size_t tls_dyn_rec_warmup_threshold,
62 ev_tstamp tls_dyn_rec_idle_timeout, Proto proto)
63 : tls{DefaultMemchunks(mcpool), DefaultPeekMemchunks(mcpool),
64 DefaultMemchunks(mcpool)},
65 wlimit(loop, &wev, write_limit.rate, write_limit.burst),
66 rlimit(loop, &rev, read_limit.rate, read_limit.burst, this),
70 tls_dyn_rec_warmup_threshold(tls_dyn_rec_warmup_threshold),
71 tls_dyn_rec_idle_timeout(tls_dyn_rec_idle_timeout),
74 read_timeout(read_timeout) {
76 ev_io_init(&wev, writecb, fd, EV_WRITE);
77 ev_io_init(&rev, readcb, proto == Proto::HTTP3 ? 0 : fd, EV_READ);
82 ev_timer_init(&wt, timeoutcb, 0., write_timeout);
83 ev_timer_init(&rt, timeoutcb, 0., read_timeout);
88 // set 0. to double field explicitly just in case
89 tls.last_write_idle = 0.;
96 Connection::~Connection() { disconnect(); }
98 void Connection::disconnect() {
100 SSL_set_shutdown(tls.ssl,
101 SSL_get_shutdown(tls.ssl) | SSL_RECEIVED_SHUTDOWN);
104 if (tls.cached_session) {
105 SSL_SESSION_free(tls.cached_session);
106 tls.cached_session = nullptr;
109 if (tls.cached_session_lookup_req) {
110 tls.cached_session_lookup_req->canceled = true;
111 tls.cached_session_lookup_req = nullptr;
114 SSL_shutdown(tls.ssl);
120 tls.last_write_idle = 0.;
121 tls.warmup_writelen = 0;
122 tls.last_writelen = 0;
123 tls.last_readlen = 0;
124 tls.handshake_state = TLSHandshakeState::NORMAL;
125 tls.initial_handshake_done = false;
126 tls.reneg_started = false;
127 tls.sct_requested = false;
128 tls.early_data_finish = false;
131 if (proto != Proto::HTTP3 && fd != -1) {
132 shutdown(fd, SHUT_WR);
137 // Stop watchers here because they could be activated in
139 ev_timer_stop(loop, &rt);
140 ev_timer_stop(loop, &wt);
146 void Connection::prepare_client_handshake() {
147 SSL_set_connect_state(tls.ssl);
148 // This prevents SSL_read_early_data from being called.
149 tls.early_data_finish = true;
152 void Connection::prepare_server_handshake() {
153 SSL_set_accept_state(tls.ssl);
154 tls.server_handshake = true;
157 // BIO implementation is inspired by openldap implementation:
158 // http://www.openldap.org/devel/cvsweb.cgi/~checkout~/libraries/libldap/tls_o.c
160 int shrpx_bio_write(BIO *b, const char *buf, int len) {
161 if (buf == nullptr || len <= 0) {
165 auto conn = static_cast<Connection *>(BIO_get_data(b));
166 auto &wbuf = conn->tls.wbuf;
168 BIO_clear_retry_flags(b);
170 if (conn->tls.initial_handshake_done) {
171 // After handshake finished, send |buf| of length |len| to the
174 // Only when TLS session was prematurely ended before server sent
175 // all handshake message, this condition is true. This could be
176 // alert from SSL_shutdown(). Since connection is already down,
177 // just return error.
181 auto nwrite = conn->write_clear(buf, len);
187 BIO_set_retry_write(b);
194 wbuf.append(buf, len);
201 int shrpx_bio_read(BIO *b, char *buf, int len) {
202 if (buf == nullptr || len <= 0) {
206 auto conn = static_cast<Connection *>(BIO_get_data(b));
207 auto &rbuf = conn->tls.rbuf;
209 BIO_clear_retry_flags(b);
211 if (conn->tls.initial_handshake_done && rbuf.rleft() == 0) {
212 auto nread = conn->read_clear(buf, len);
217 BIO_set_retry_read(b);
223 if (rbuf.rleft() == 0) {
224 BIO_set_retry_read(b);
228 return rbuf.remove(buf, len);
233 int shrpx_bio_puts(BIO *b, const char *str) {
234 return shrpx_bio_write(b, str, strlen(str));
239 int shrpx_bio_gets(BIO *b, char *buf, int len) { return -1; }
243 long shrpx_bio_ctrl(BIO *b, int cmd, long num, void *ptr) {
254 int shrpx_bio_create(BIO *b) {
257 #else // !OPENSSL_1_1_API
262 #endif // !OPENSSL_1_1_API
268 int shrpx_bio_destroy(BIO *b) {
277 #endif // !OPENSSL_1_1_API
285 BIO_METHOD *create_bio_method() {
286 auto meth = BIO_meth_new(BIO_TYPE_FD, "nghttpx-bio");
287 BIO_meth_set_write(meth, shrpx_bio_write);
288 BIO_meth_set_read(meth, shrpx_bio_read);
289 BIO_meth_set_puts(meth, shrpx_bio_puts);
290 BIO_meth_set_gets(meth, shrpx_bio_gets);
291 BIO_meth_set_ctrl(meth, shrpx_bio_ctrl);
292 BIO_meth_set_create(meth, shrpx_bio_create);
293 BIO_meth_set_destroy(meth, shrpx_bio_destroy);
298 #else // !OPENSSL_1_1_API
300 BIO_METHOD *create_bio_method() {
301 static auto meth = new BIO_METHOD{
302 BIO_TYPE_FD, "nghttpx-bio", shrpx_bio_write,
303 shrpx_bio_read, shrpx_bio_puts, shrpx_bio_gets,
304 shrpx_bio_ctrl, shrpx_bio_create, shrpx_bio_destroy,
310 #endif // !OPENSSL_1_1_API
312 void Connection::set_ssl(SSL *ssl) {
315 if (proto != Proto::HTTP3) {
316 auto &tlsconf = get_config()->tls;
317 auto bio = BIO_new(tlsconf.bio_method);
318 BIO_set_data(bio, this);
319 SSL_set_bio(tls.ssl, bio, bio);
322 SSL_set_app_data(tls.ssl, this);
326 // We should buffer at least full encrypted TLS record here.
327 // Theoretically, peer can send client hello in several TLS records,
328 // which could exceed this limit, but it is not portable, and we don't
329 // have to handle such exotic behaviour.
330 bool read_buffer_full(DefaultPeekMemchunks &rbuf) {
331 return rbuf.rleft_buffered() >= 20_k;
335 int Connection::tls_handshake() {
337 ev_timer_stop(loop, &wt);
339 std::array<uint8_t, 16_k> buf;
341 if (ev_is_active(&rev)) {
342 auto nread = read_clear(buf.data(), buf.size());
344 if (LOG_ENABLED(INFO)) {
345 LOG(INFO) << "tls: handshake read error";
349 tls.rbuf.append(buf.data(), nread);
350 if (read_buffer_full(tls.rbuf)) {
355 if (tls.initial_handshake_done) {
356 return write_tls_pending_handshake();
359 switch (tls.handshake_state) {
360 case TLSHandshakeState::WAIT_FOR_SESSION_CACHE:
361 return SHRPX_ERR_INPROGRESS;
362 case TLSHandshakeState::GOT_SESSION_CACHE: {
363 // Use the same trick invented by @kazuho in h2o project.
365 // Discard all outgoing data.
367 // Rewind buffered incoming data to replay client hello.
368 tls.rbuf.disable_peek(false);
370 auto ssl_ctx = SSL_get_SSL_CTX(tls.ssl);
371 auto ssl_opts = SSL_get_options(tls.ssl);
374 auto ssl = tls::create_ssl(ssl_ctx);
378 if (ssl_opts & SSL_OP_NO_TICKET) {
379 SSL_set_options(ssl, SSL_OP_NO_TICKET);
384 SSL_set_accept_state(tls.ssl);
386 tls.handshake_state = TLSHandshakeState::NORMAL;
389 case TLSHandshakeState::CANCEL_SESSION_CACHE:
390 tls.handshake_state = TLSHandshakeState::NORMAL;
400 #if OPENSSL_1_1_1_API || defined(OPENSSL_IS_BORINGSSL)
401 auto &tlsconf = get_config()->tls;
402 #endif // OPENSSL_1_1_1_API || defined(OPENSSL_IS_BORINGSSL)
404 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
405 if (!tls.server_handshake || tls.early_data_finish) {
406 rv = SSL_do_handshake(tls.ssl);
411 rv = SSL_read_early_data(tls.ssl, buf.data(), buf.size(), &nread);
412 if (rv == SSL_READ_EARLY_DATA_ERROR) {
413 // If we have early data, and server sends ServerHello, assume
414 // that handshake is completed in server side, and start
415 // processing request. If we don't exit handshake code here,
416 // server waits for EndOfEarlyData and Finished message from
417 // client, which voids the purpose of 0-RTT data. The left
418 // over of handshake is done through write_tls or read_tls.
419 if (tlsconf.no_postpone_early_data &&
420 (tls.handshake_state == TLSHandshakeState::WRITE_STARTED ||
422 tls.earlybuf.rleft()) {
429 if (LOG_ENABLED(INFO)) {
430 LOG(INFO) << "tls: read early data " << nread << " bytes";
433 tls.earlybuf.append(buf.data(), nread);
435 if (rv == SSL_READ_EARLY_DATA_FINISH) {
436 if (LOG_ENABLED(INFO)) {
437 LOG(INFO) << "tls: read all early data; total "
438 << tls.earlybuf.rleft() << " bytes";
440 tls.early_data_finish = true;
441 // The same reason stated above.
442 if (tlsconf.no_postpone_early_data &&
443 (tls.handshake_state == TLSHandshakeState::WRITE_STARTED ||
445 tls.earlybuf.rleft()) {
449 rv = SSL_do_handshake(tls.ssl);
455 #else // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
456 rv = SSL_do_handshake(tls.ssl);
457 #endif // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
460 auto err = SSL_get_error(tls.ssl, rv);
462 case SSL_ERROR_WANT_READ:
463 if (read_buffer_full(tls.rbuf)) {
464 if (LOG_ENABLED(INFO)) {
465 LOG(INFO) << "tls: handshake message is too large";
470 case SSL_ERROR_WANT_WRITE:
472 case SSL_ERROR_SSL: {
473 if (LOG_ENABLED(INFO)) {
474 LOG(INFO) << "tls: handshake libssl error: "
475 << ERR_error_string(ERR_get_error(), nullptr);
479 auto iovcnt = tls.wbuf.riovec(iov, 1);
480 auto nwrite = writev_clear(iov, iovcnt);
482 tls.wbuf.drain(nwrite);
485 return SHRPX_ERR_NETWORK;
488 if (LOG_ENABLED(INFO)) {
489 LOG(INFO) << "tls: handshake libssl error " << err;
491 return SHRPX_ERR_NETWORK;
495 if (tls.handshake_state == TLSHandshakeState::WAIT_FOR_SESSION_CACHE) {
496 if (LOG_ENABLED(INFO)) {
497 LOG(INFO) << "tls: handshake is still in progress";
499 return SHRPX_ERR_INPROGRESS;
502 // Don't send handshake data if handshake was completed in OpenSSL
503 // routine. We have to check HTTP/2 requirement if HTTP/2 was
504 // negotiated before sending finished message to the peer.
506 #ifdef OPENSSL_IS_BORINGSSL
507 || SSL_in_init(tls.ssl)
508 #endif // OPENSSL_IS_BORINGSSL
511 // First write indicates that resumption stuff has done.
512 if (tls.handshake_state != TLSHandshakeState::WRITE_STARTED) {
513 tls.handshake_state = TLSHandshakeState::WRITE_STARTED;
514 // If peek has already disabled, this is noop.
515 tls.rbuf.disable_peek(true);
517 std::array<struct iovec, 4> iov;
518 auto iovcnt = tls.wbuf.riovec(iov.data(), iov.size());
519 auto nwrite = writev_clear(iov.data(), iovcnt);
521 if (LOG_ENABLED(INFO)) {
522 LOG(INFO) << "tls: handshake write error";
526 tls.wbuf.drain(nwrite);
528 if (tls.wbuf.rleft()) {
530 ev_timer_again(loop, &wt);
534 if (!read_buffer_full(tls.rbuf)) {
535 // We may have stopped reading
540 if (LOG_ENABLED(INFO)) {
541 LOG(INFO) << "tls: handshake is still in progress";
543 return SHRPX_ERR_INPROGRESS;
546 #ifdef OPENSSL_IS_BORINGSSL
547 if (!tlsconf.no_postpone_early_data && SSL_in_early_data(tls.ssl) &&
548 SSL_in_init(tls.ssl)) {
549 auto nread = SSL_read(tls.ssl, buf.data(), buf.size());
551 auto err = SSL_get_error(tls.ssl, nread);
553 case SSL_ERROR_WANT_READ:
554 case SSL_ERROR_WANT_WRITE:
556 case SSL_ERROR_ZERO_RETURN:
557 return SHRPX_ERR_EOF;
559 if (LOG_ENABLED(INFO)) {
560 LOG(INFO) << "SSL_read: "
561 << ERR_error_string(ERR_get_error(), nullptr);
563 return SHRPX_ERR_NETWORK;
565 if (LOG_ENABLED(INFO)) {
566 LOG(INFO) << "SSL_read: SSL_get_error returned " << err;
568 return SHRPX_ERR_NETWORK;
571 tls.earlybuf.append(buf.data(), nread);
574 if (SSL_in_init(tls.ssl)) {
575 return SHRPX_ERR_INPROGRESS;
578 #endif // OPENSSL_IS_BORINGSSL
580 // Handshake was done
582 rv = check_http2_requirement();
588 tls.rbuf.disable_peek(true);
590 tls.initial_handshake_done = true;
592 return write_tls_pending_handshake();
595 int Connection::write_tls_pending_handshake() {
596 // Send handshake data left in the buffer
597 while (tls.wbuf.rleft()) {
598 std::array<struct iovec, 4> iov;
599 auto iovcnt = tls.wbuf.riovec(iov.data(), iov.size());
600 auto nwrite = writev_clear(iov.data(), iovcnt);
602 if (LOG_ENABLED(INFO)) {
603 LOG(INFO) << "tls: handshake write error";
609 ev_timer_again(loop, &wt);
611 return SHRPX_ERR_INPROGRESS;
613 tls.wbuf.drain(nwrite);
616 #ifdef OPENSSL_IS_BORINGSSL
617 if (!SSL_in_init(tls.ssl)) {
618 // This will send a session ticket.
619 auto nwrite = SSL_write(tls.ssl, "", 0);
621 auto err = SSL_get_error(tls.ssl, nwrite);
623 case SSL_ERROR_WANT_READ:
624 if (LOG_ENABLED(INFO)) {
625 LOG(INFO) << "Close connection due to TLS renegotiation";
627 return SHRPX_ERR_NETWORK;
628 case SSL_ERROR_WANT_WRITE:
631 if (LOG_ENABLED(INFO)) {
632 LOG(INFO) << "SSL_write: "
633 << ERR_error_string(ERR_get_error(), nullptr);
635 return SHRPX_ERR_NETWORK;
637 if (LOG_ENABLED(INFO)) {
638 LOG(INFO) << "SSL_write: SSL_get_error returned " << err;
640 return SHRPX_ERR_NETWORK;
644 #endif // OPENSSL_IS_BORINGSSL
646 // We have to start read watcher, since later stage of code expects
650 // We may have whole request in tls.rbuf. This means that we don't
651 // get notified further read event. This is especially true for
653 handle_tls_pending_read();
655 if (LOG_ENABLED(INFO)) {
656 LOG(INFO) << "SSL/TLS handshake completed";
657 nghttp2::tls::TLSSessionInfo tls_info{};
658 if (nghttp2::tls::get_tls_session_info(&tls_info, tls.ssl)) {
659 LOG(INFO) << "cipher=" << tls_info.cipher
660 << " protocol=" << tls_info.protocol
661 << " resumption=" << (tls_info.session_reused ? "yes" : "no")
663 << util::format_hex(tls_info.session_id,
664 tls_info.session_id_length);
671 int Connection::check_http2_requirement() {
672 const unsigned char *next_proto = nullptr;
673 unsigned int next_proto_len;
675 #ifndef OPENSSL_NO_NEXTPROTONEG
676 SSL_get0_next_proto_negotiated(tls.ssl, &next_proto, &next_proto_len);
677 #endif // !OPENSSL_NO_NEXTPROTONEG
678 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
679 if (next_proto == nullptr) {
680 SSL_get0_alpn_selected(tls.ssl, &next_proto, &next_proto_len);
682 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
683 if (next_proto == nullptr ||
684 !util::check_h2_is_selected(StringRef{next_proto, next_proto_len})) {
687 if (!nghttp2::tls::check_http2_tls_version(tls.ssl)) {
688 if (LOG_ENABLED(INFO)) {
689 LOG(INFO) << "TLSv1.2 was not negotiated. HTTP/2 must not be used.";
694 auto check_block_list = false;
695 if (tls.server_handshake) {
696 check_block_list = !get_config()->tls.no_http2_cipher_block_list;
698 check_block_list = !get_config()->tls.client.no_http2_cipher_block_list;
701 if (check_block_list &&
702 nghttp2::tls::check_http2_cipher_block_list(tls.ssl)) {
703 if (LOG_ENABLED(INFO)) {
704 LOG(INFO) << "The negotiated cipher suite is in HTTP/2 cipher suite "
705 "block list. HTTP/2 must not be used.";
714 constexpr size_t SHRPX_SMALL_WRITE_LIMIT = 1300;
717 size_t Connection::get_tls_write_limit() {
719 if (tls_dyn_rec_warmup_threshold == 0) {
720 return std::numeric_limits<ssize_t>::max();
723 auto t = ev_now(loop);
725 if (tls.last_write_idle >= 0. &&
726 t - tls.last_write_idle > tls_dyn_rec_idle_timeout) {
727 // Time out, use small record size
728 tls.warmup_writelen = 0;
729 return SHRPX_SMALL_WRITE_LIMIT;
732 if (tls.warmup_writelen >= tls_dyn_rec_warmup_threshold) {
733 return std::numeric_limits<ssize_t>::max();
736 return SHRPX_SMALL_WRITE_LIMIT;
739 void Connection::update_tls_warmup_writelen(size_t n) {
740 if (tls.warmup_writelen < tls_dyn_rec_warmup_threshold) {
741 tls.warmup_writelen += n;
745 void Connection::start_tls_write_idle() {
746 if (tls.last_write_idle < 0.) {
747 tls.last_write_idle = ev_now(loop);
751 ssize_t Connection::write_tls(const void *data, size_t len) {
752 // SSL_write requires the same arguments (buf pointer and its
753 // length) on SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE.
754 // get_write_limit() may return smaller length than previously
755 // passed to SSL_write, which violates OpenSSL assumption. To avoid
756 // this, we keep last legnth passed to SSL_write to
757 // tls.last_writelen if SSL_write indicated I/O blocking.
758 if (tls.last_writelen == 0) {
759 len = std::min(len, wlimit.avail());
760 len = std::min(len, get_tls_write_limit());
765 len = tls.last_writelen;
766 tls.last_writelen = 0;
769 tls.last_write_idle = -1.;
773 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
775 if (SSL_is_init_finished(tls.ssl)) {
776 rv = SSL_write(tls.ssl, data, len);
779 rv = SSL_write_early_data(tls.ssl, data, len, &nwrite);
780 // Use the same semantics with SSL_write.
785 #else // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
786 auto rv = SSL_write(tls.ssl, data, len);
787 #endif // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
790 auto err = SSL_get_error(tls.ssl, rv);
792 case SSL_ERROR_WANT_READ:
793 if (LOG_ENABLED(INFO)) {
794 LOG(INFO) << "Close connection due to TLS renegotiation";
796 return SHRPX_ERR_NETWORK;
797 case SSL_ERROR_WANT_WRITE:
798 tls.last_writelen = len;
799 // starting write watcher and timer is done in write_clear via
803 if (LOG_ENABLED(INFO)) {
804 LOG(INFO) << "SSL_write: "
805 << ERR_error_string(ERR_get_error(), nullptr);
807 return SHRPX_ERR_NETWORK;
809 if (LOG_ENABLED(INFO)) {
810 LOG(INFO) << "SSL_write: SSL_get_error returned " << err;
812 return SHRPX_ERR_NETWORK;
816 update_tls_warmup_writelen(rv);
821 ssize_t Connection::read_tls(void *data, size_t len) {
824 #if OPENSSL_1_1_1_API
825 if (tls.earlybuf.rleft()) {
826 return tls.earlybuf.remove(data, len);
828 #endif // OPENSSL_1_1_1_API
830 // SSL_read requires the same arguments (buf pointer and its
831 // length) on SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE.
832 // rlimit_.avail() or rlimit_.avail() may return different length
833 // than the length previously passed to SSL_read, which violates
834 // OpenSSL assumption. To avoid this, we keep last legnth passed
835 // to SSL_read to tls_last_readlen_ if SSL_read indicated I/O
837 if (tls.last_readlen == 0) {
838 len = std::min(len, rlimit.avail());
843 len = tls.last_readlen;
844 tls.last_readlen = 0;
847 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
848 if (!tls.early_data_finish) {
849 // TLSv1.3 handshake is still going on.
851 auto rv = SSL_read_early_data(tls.ssl, data, len, &nread);
852 if (rv == SSL_READ_EARLY_DATA_ERROR) {
853 auto err = SSL_get_error(tls.ssl, rv);
855 case SSL_ERROR_WANT_READ:
856 tls.last_readlen = len;
859 if (LOG_ENABLED(INFO)) {
860 LOG(INFO) << "SSL_read: "
861 << ERR_error_string(ERR_get_error(), nullptr);
863 return SHRPX_ERR_NETWORK;
865 if (LOG_ENABLED(INFO)) {
866 LOG(INFO) << "SSL_read: SSL_get_error returned " << err;
868 return SHRPX_ERR_NETWORK;
872 if (LOG_ENABLED(INFO)) {
873 LOG(INFO) << "tls: read early data " << nread << " bytes";
876 if (rv == SSL_READ_EARLY_DATA_FINISH) {
877 if (LOG_ENABLED(INFO)) {
878 LOG(INFO) << "tls: read all early data";
880 tls.early_data_finish = true;
881 // We may have stopped write watcher in write_tls.
886 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
888 auto rv = SSL_read(tls.ssl, data, len);
891 auto err = SSL_get_error(tls.ssl, rv);
893 case SSL_ERROR_WANT_READ:
894 tls.last_readlen = len;
896 case SSL_ERROR_WANT_WRITE:
897 if (LOG_ENABLED(INFO)) {
898 LOG(INFO) << "Close connection due to TLS renegotiation";
900 return SHRPX_ERR_NETWORK;
901 case SSL_ERROR_ZERO_RETURN:
902 return SHRPX_ERR_EOF;
904 if (LOG_ENABLED(INFO)) {
905 LOG(INFO) << "SSL_read: " << ERR_error_string(ERR_get_error(), nullptr);
907 return SHRPX_ERR_NETWORK;
909 if (LOG_ENABLED(INFO)) {
910 LOG(INFO) << "SSL_read: SSL_get_error returned " << err;
912 return SHRPX_ERR_NETWORK;
919 ssize_t Connection::write_clear(const void *data, size_t len) {
920 len = std::min(len, wlimit.avail());
926 while ((nwrite = write(fd, data, len)) == -1 && errno == EINTR)
929 if (errno == EAGAIN || errno == EWOULDBLOCK) {
931 ev_timer_again(loop, &wt);
934 return SHRPX_ERR_NETWORK;
937 wlimit.drain(nwrite);
939 if (ev_is_active(&wt)) {
940 ev_timer_again(loop, &wt);
946 ssize_t Connection::writev_clear(struct iovec *iov, int iovcnt) {
947 iovcnt = limit_iovec(iov, iovcnt, wlimit.avail());
953 while ((nwrite = writev(fd, iov, iovcnt)) == -1 && errno == EINTR)
956 if (errno == EAGAIN || errno == EWOULDBLOCK) {
958 ev_timer_again(loop, &wt);
961 return SHRPX_ERR_NETWORK;
964 wlimit.drain(nwrite);
966 if (ev_is_active(&wt)) {
967 ev_timer_again(loop, &wt);
973 ssize_t Connection::read_clear(void *data, size_t len) {
974 len = std::min(len, rlimit.avail());
980 while ((nread = read(fd, data, len)) == -1 && errno == EINTR)
983 if (errno == EAGAIN || errno == EWOULDBLOCK) {
986 return SHRPX_ERR_NETWORK;
990 return SHRPX_ERR_EOF;
998 void Connection::handle_tls_pending_read() {
999 if (!ev_is_active(&rev)) {
1002 rlimit.handle_tls_pending_read();
1005 int Connection::get_tcp_hint(TCPHint *hint) const {
1006 #if defined(TCP_INFO) && defined(TCP_NOTSENT_LOWAT)
1007 struct tcp_info tcp_info;
1008 socklen_t tcp_info_len = sizeof(tcp_info);
1011 rv = getsockopt(fd, IPPROTO_TCP, TCP_INFO, &tcp_info, &tcp_info_len);
1017 auto avail_packets = tcp_info.tcpi_snd_cwnd > tcp_info.tcpi_unacked
1018 ? tcp_info.tcpi_snd_cwnd - tcp_info.tcpi_unacked
1021 // http://www.slideshare.net/kazuho/programming-tcp-for-responsiveness
1023 // TODO 29 (5 (header) + 8 (explicit nonce) + 16 (tag)) is TLS
1024 // overhead for AES-GCM. For CHACHA20_POLY1305, it is 21 since it
1025 // does not need 8 bytes explicit nonce.
1027 // For TLSv1.3, AES-GCM and CHACHA20_POLY1305 overhead are now 22
1028 // bytes (5 (header) + 1 (ContentType) + 16 (tag)).
1029 size_t tls_overhead;
1030 # ifdef TLS1_3_VERSION
1031 if (SSL_version(tls.ssl) == TLS1_3_VERSION) {
1034 # endif // TLS1_3_VERSION
1039 auto writable_size =
1040 (avail_packets + 2) * (tcp_info.tcpi_snd_mss - tls_overhead);
1041 if (writable_size > 16_k) {
1042 writable_size = writable_size & ~(16_k - 1);
1044 if (writable_size < 536) {
1045 LOG(INFO) << "writable_size is too small: " << writable_size;
1047 // TODO is this required?
1048 writable_size = std::max(writable_size, static_cast<size_t>(536 * 2));
1051 // if (LOG_ENABLED(INFO)) {
1052 // LOG(INFO) << "snd_cwnd=" << tcp_info.tcpi_snd_cwnd
1053 // << ", unacked=" << tcp_info.tcpi_unacked
1054 // << ", snd_mss=" << tcp_info.tcpi_snd_mss
1055 // << ", rtt=" << tcp_info.tcpi_rtt << "us"
1056 // << ", rcv_space=" << tcp_info.tcpi_rcv_space
1057 // << ", writable=" << writable_size;
1060 hint->write_buffer_size = writable_size;
1061 // TODO tcpi_rcv_space is considered as rwin, is that correct?
1062 hint->rwin = tcp_info.tcpi_rcv_space;
1065 #else // !defined(TCP_INFO) || !defined(TCP_NOTSENT_LOWAT)
1067 #endif // !defined(TCP_INFO) || !defined(TCP_NOTSENT_LOWAT)
1070 void Connection::again_rt(ev_tstamp t) {
1073 ev_timer_again(loop, &rt);
1074 last_read = ev_now(loop);
1077 void Connection::again_rt() {
1078 rt.repeat = read_timeout;
1079 ev_timer_again(loop, &rt);
1080 last_read = ev_now(loop);
1083 bool Connection::expired_rt() {
1084 auto delta = read_timeout - (ev_now(loop) - last_read);
1089 ev_timer_again(loop, &rt);
1093 } // namespace shrpx