Imported Upstream version 1.46.0
[platform/upstream/nghttp2.git] / src / shrpx_connection.cc
1 /*
2  * nghttp2 - HTTP/2 C Library
3  *
4  * Copyright (c) 2015 Tatsuhiro Tsujikawa
5  *
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:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
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.
24  */
25 #include "shrpx_connection.h"
26
27 #ifdef HAVE_UNISTD_H
28 #  include <unistd.h>
29 #endif // HAVE_UNISTD_H
30 #include <netinet/tcp.h>
31
32 #include <limits>
33
34 #include <openssl/err.h>
35
36 #include "shrpx_tls.h"
37 #include "shrpx_memcached_request.h"
38 #include "shrpx_log.h"
39 #include "memchunk.h"
40 #include "util.h"
41 #include "ssl_compat.h"
42
43 using namespace nghttp2;
44
45 namespace shrpx {
46
47 #if !LIBRESSL_2_7_API && !OPENSSL_1_1_API
48
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; }
52
53 #endif // !LIBRESSL_2_7_API && !OPENSSL_1_1_API
54
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),
67       loop(loop),
68       data(data),
69       fd(fd),
70       tls_dyn_rec_warmup_threshold(tls_dyn_rec_warmup_threshold),
71       tls_dyn_rec_idle_timeout(tls_dyn_rec_idle_timeout),
72       proto(proto),
73       last_read(0.),
74       read_timeout(read_timeout) {
75
76   ev_io_init(&wev, writecb, fd, EV_WRITE);
77   ev_io_init(&rev, readcb, proto == Proto::HTTP3 ? 0 : fd, EV_READ);
78
79   wev.data = this;
80   rev.data = this;
81
82   ev_timer_init(&wt, timeoutcb, 0., write_timeout);
83   ev_timer_init(&rt, timeoutcb, 0., read_timeout);
84
85   wt.data = this;
86   rt.data = this;
87
88   // set 0. to double field explicitly just in case
89   tls.last_write_idle = 0.;
90
91   if (ssl) {
92     set_ssl(ssl);
93   }
94 }
95
96 Connection::~Connection() { disconnect(); }
97
98 void Connection::disconnect() {
99   if (tls.ssl) {
100     SSL_set_shutdown(tls.ssl,
101                      SSL_get_shutdown(tls.ssl) | SSL_RECEIVED_SHUTDOWN);
102     ERR_clear_error();
103
104     if (tls.cached_session) {
105       SSL_SESSION_free(tls.cached_session);
106       tls.cached_session = nullptr;
107     }
108
109     if (tls.cached_session_lookup_req) {
110       tls.cached_session_lookup_req->canceled = true;
111       tls.cached_session_lookup_req = nullptr;
112     }
113
114     SSL_shutdown(tls.ssl);
115     SSL_free(tls.ssl);
116     tls.ssl = nullptr;
117
118     tls.wbuf.reset();
119     tls.rbuf.reset();
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;
129   }
130
131   if (proto != Proto::HTTP3 && fd != -1) {
132     shutdown(fd, SHUT_WR);
133     close(fd);
134     fd = -1;
135   }
136
137   // Stop watchers here because they could be activated in
138   // SSL_shutdown().
139   ev_timer_stop(loop, &rt);
140   ev_timer_stop(loop, &wt);
141
142   rlimit.stopw();
143   wlimit.stopw();
144 }
145
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;
150 }
151
152 void Connection::prepare_server_handshake() {
153   SSL_set_accept_state(tls.ssl);
154   tls.server_handshake = true;
155 }
156
157 // BIO implementation is inspired by openldap implementation:
158 // http://www.openldap.org/devel/cvsweb.cgi/~checkout~/libraries/libldap/tls_o.c
159 namespace {
160 int shrpx_bio_write(BIO *b, const char *buf, int len) {
161   if (buf == nullptr || len <= 0) {
162     return 0;
163   }
164
165   auto conn = static_cast<Connection *>(BIO_get_data(b));
166   auto &wbuf = conn->tls.wbuf;
167
168   BIO_clear_retry_flags(b);
169
170   if (conn->tls.initial_handshake_done) {
171     // After handshake finished, send |buf| of length |len| to the
172     // socket directly.
173
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.
178     if (wbuf.rleft()) {
179       return -1;
180     }
181     auto nwrite = conn->write_clear(buf, len);
182     if (nwrite < 0) {
183       return -1;
184     }
185
186     if (nwrite == 0) {
187       BIO_set_retry_write(b);
188       return -1;
189     }
190
191     return nwrite;
192   }
193
194   wbuf.append(buf, len);
195
196   return len;
197 }
198 } // namespace
199
200 namespace {
201 int shrpx_bio_read(BIO *b, char *buf, int len) {
202   if (buf == nullptr || len <= 0) {
203     return 0;
204   }
205
206   auto conn = static_cast<Connection *>(BIO_get_data(b));
207   auto &rbuf = conn->tls.rbuf;
208
209   BIO_clear_retry_flags(b);
210
211   if (conn->tls.initial_handshake_done && rbuf.rleft() == 0) {
212     auto nread = conn->read_clear(buf, len);
213     if (nread < 0) {
214       return -1;
215     }
216     if (nread == 0) {
217       BIO_set_retry_read(b);
218       return -1;
219     }
220     return nread;
221   }
222
223   if (rbuf.rleft() == 0) {
224     BIO_set_retry_read(b);
225     return -1;
226   }
227
228   return rbuf.remove(buf, len);
229 }
230 } // namespace
231
232 namespace {
233 int shrpx_bio_puts(BIO *b, const char *str) {
234   return shrpx_bio_write(b, str, strlen(str));
235 }
236 } // namespace
237
238 namespace {
239 int shrpx_bio_gets(BIO *b, char *buf, int len) { return -1; }
240 } // namespace
241
242 namespace {
243 long shrpx_bio_ctrl(BIO *b, int cmd, long num, void *ptr) {
244   switch (cmd) {
245   case BIO_CTRL_FLUSH:
246     return 1;
247   }
248
249   return 0;
250 }
251 } // namespace
252
253 namespace {
254 int shrpx_bio_create(BIO *b) {
255 #if OPENSSL_1_1_API
256   BIO_set_init(b, 1);
257 #else  // !OPENSSL_1_1_API
258   b->init = 1;
259   b->num = 0;
260   b->ptr = nullptr;
261   b->flags = 0;
262 #endif // !OPENSSL_1_1_API
263   return 1;
264 }
265 } // namespace
266
267 namespace {
268 int shrpx_bio_destroy(BIO *b) {
269   if (b == nullptr) {
270     return 0;
271   }
272
273 #if !OPENSSL_1_1_API
274   b->ptr = nullptr;
275   b->init = 0;
276   b->flags = 0;
277 #endif // !OPENSSL_1_1_API
278
279   return 1;
280 }
281 } // namespace
282
283 #if OPENSSL_1_1_API
284
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);
294
295   return meth;
296 }
297
298 #else // !OPENSSL_1_1_API
299
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,
305   };
306
307   return meth;
308 }
309
310 #endif // !OPENSSL_1_1_API
311
312 void Connection::set_ssl(SSL *ssl) {
313   tls.ssl = ssl;
314
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);
320   }
321
322   SSL_set_app_data(tls.ssl, this);
323 }
324
325 namespace {
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;
332 }
333 } // namespace
334
335 int Connection::tls_handshake() {
336   wlimit.stopw();
337   ev_timer_stop(loop, &wt);
338
339   std::array<uint8_t, 16_k> buf;
340
341   if (ev_is_active(&rev)) {
342     auto nread = read_clear(buf.data(), buf.size());
343     if (nread < 0) {
344       if (LOG_ENABLED(INFO)) {
345         LOG(INFO) << "tls: handshake read error";
346       }
347       return -1;
348     }
349     tls.rbuf.append(buf.data(), nread);
350     if (read_buffer_full(tls.rbuf)) {
351       rlimit.stopw();
352     }
353   }
354
355   if (tls.initial_handshake_done) {
356     return write_tls_pending_handshake();
357   }
358
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.
364
365     // Discard all outgoing data.
366     tls.wbuf.reset();
367     // Rewind buffered incoming data to replay client hello.
368     tls.rbuf.disable_peek(false);
369
370     auto ssl_ctx = SSL_get_SSL_CTX(tls.ssl);
371     auto ssl_opts = SSL_get_options(tls.ssl);
372     SSL_free(tls.ssl);
373
374     auto ssl = tls::create_ssl(ssl_ctx);
375     if (!ssl) {
376       return -1;
377     }
378     if (ssl_opts & SSL_OP_NO_TICKET) {
379       SSL_set_options(ssl, SSL_OP_NO_TICKET);
380     }
381
382     set_ssl(ssl);
383
384     SSL_set_accept_state(tls.ssl);
385
386     tls.handshake_state = TLSHandshakeState::NORMAL;
387     break;
388   }
389   case TLSHandshakeState::CANCEL_SESSION_CACHE:
390     tls.handshake_state = TLSHandshakeState::NORMAL;
391     break;
392   default:
393     break;
394   }
395
396   int rv;
397
398   ERR_clear_error();
399
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)
403
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);
407   } else {
408     for (;;) {
409       size_t nread;
410
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 ||
421              tls.wbuf.rleft()) &&
422             tls.earlybuf.rleft()) {
423           rv = 1;
424         }
425
426         break;
427       }
428
429       if (LOG_ENABLED(INFO)) {
430         LOG(INFO) << "tls: read early data " << nread << " bytes";
431       }
432
433       tls.earlybuf.append(buf.data(), nread);
434
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";
439         }
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 ||
444              tls.wbuf.rleft()) &&
445             tls.earlybuf.rleft()) {
446           rv = 1;
447         } else {
448           ERR_clear_error();
449           rv = SSL_do_handshake(tls.ssl);
450         }
451         break;
452       }
453     }
454   }
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))
458
459   if (rv <= 0) {
460     auto err = SSL_get_error(tls.ssl, rv);
461     switch (err) {
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";
466         }
467         return -1;
468       }
469       break;
470     case SSL_ERROR_WANT_WRITE:
471       break;
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);
476       }
477
478       struct iovec iov[1];
479       auto iovcnt = tls.wbuf.riovec(iov, 1);
480       auto nwrite = writev_clear(iov, iovcnt);
481       if (nwrite > 0) {
482         tls.wbuf.drain(nwrite);
483       }
484
485       return SHRPX_ERR_NETWORK;
486     }
487     default:
488       if (LOG_ENABLED(INFO)) {
489         LOG(INFO) << "tls: handshake libssl error " << err;
490       }
491       return SHRPX_ERR_NETWORK;
492     }
493   }
494
495   if (tls.handshake_state == TLSHandshakeState::WAIT_FOR_SESSION_CACHE) {
496     if (LOG_ENABLED(INFO)) {
497       LOG(INFO) << "tls: handshake is still in progress";
498     }
499     return SHRPX_ERR_INPROGRESS;
500   }
501
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.
505   if ((rv != 1
506 #ifdef OPENSSL_IS_BORINGSSL
507        || SSL_in_init(tls.ssl)
508 #endif // OPENSSL_IS_BORINGSSL
509            ) &&
510       tls.wbuf.rleft()) {
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);
516     }
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);
520     if (nwrite < 0) {
521       if (LOG_ENABLED(INFO)) {
522         LOG(INFO) << "tls: handshake write error";
523       }
524       return -1;
525     }
526     tls.wbuf.drain(nwrite);
527
528     if (tls.wbuf.rleft()) {
529       wlimit.startw();
530       ev_timer_again(loop, &wt);
531     }
532   }
533
534   if (!read_buffer_full(tls.rbuf)) {
535     // We may have stopped reading
536     rlimit.startw();
537   }
538
539   if (rv != 1) {
540     if (LOG_ENABLED(INFO)) {
541       LOG(INFO) << "tls: handshake is still in progress";
542     }
543     return SHRPX_ERR_INPROGRESS;
544   }
545
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());
550     if (nread <= 0) {
551       auto err = SSL_get_error(tls.ssl, nread);
552       switch (err) {
553       case SSL_ERROR_WANT_READ:
554       case SSL_ERROR_WANT_WRITE:
555         break;
556       case SSL_ERROR_ZERO_RETURN:
557         return SHRPX_ERR_EOF;
558       case SSL_ERROR_SSL:
559         if (LOG_ENABLED(INFO)) {
560           LOG(INFO) << "SSL_read: "
561                     << ERR_error_string(ERR_get_error(), nullptr);
562         }
563         return SHRPX_ERR_NETWORK;
564       default:
565         if (LOG_ENABLED(INFO)) {
566           LOG(INFO) << "SSL_read: SSL_get_error returned " << err;
567         }
568         return SHRPX_ERR_NETWORK;
569       }
570     } else {
571       tls.earlybuf.append(buf.data(), nread);
572     }
573
574     if (SSL_in_init(tls.ssl)) {
575       return SHRPX_ERR_INPROGRESS;
576     }
577   }
578 #endif // OPENSSL_IS_BORINGSSL
579
580   // Handshake was done
581
582   rv = check_http2_requirement();
583   if (rv != 0) {
584     return -1;
585   }
586
587   // Just in case
588   tls.rbuf.disable_peek(true);
589
590   tls.initial_handshake_done = true;
591
592   return write_tls_pending_handshake();
593 }
594
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);
601     if (nwrite < 0) {
602       if (LOG_ENABLED(INFO)) {
603         LOG(INFO) << "tls: handshake write error";
604       }
605       return -1;
606     }
607     if (nwrite == 0) {
608       wlimit.startw();
609       ev_timer_again(loop, &wt);
610
611       return SHRPX_ERR_INPROGRESS;
612     }
613     tls.wbuf.drain(nwrite);
614   }
615
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);
620     if (nwrite < 0) {
621       auto err = SSL_get_error(tls.ssl, nwrite);
622       switch (err) {
623       case SSL_ERROR_WANT_READ:
624         if (LOG_ENABLED(INFO)) {
625           LOG(INFO) << "Close connection due to TLS renegotiation";
626         }
627         return SHRPX_ERR_NETWORK;
628       case SSL_ERROR_WANT_WRITE:
629         break;
630       case SSL_ERROR_SSL:
631         if (LOG_ENABLED(INFO)) {
632           LOG(INFO) << "SSL_write: "
633                     << ERR_error_string(ERR_get_error(), nullptr);
634         }
635         return SHRPX_ERR_NETWORK;
636       default:
637         if (LOG_ENABLED(INFO)) {
638           LOG(INFO) << "SSL_write: SSL_get_error returned " << err;
639         }
640         return SHRPX_ERR_NETWORK;
641       }
642     }
643   }
644 #endif // OPENSSL_IS_BORINGSSL
645
646   // We have to start read watcher, since later stage of code expects
647   // this.
648   rlimit.startw();
649
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
652   // HTTP/1.1.
653   handle_tls_pending_read();
654
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")
662                 << " session_id="
663                 << util::format_hex(tls_info.session_id,
664                                     tls_info.session_id_length);
665     }
666   }
667
668   return 0;
669 }
670
671 int Connection::check_http2_requirement() {
672   const unsigned char *next_proto = nullptr;
673   unsigned int next_proto_len;
674
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);
681   }
682 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
683   if (next_proto == nullptr ||
684       !util::check_h2_is_selected(StringRef{next_proto, next_proto_len})) {
685     return 0;
686   }
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.";
690     }
691     return -1;
692   }
693
694   auto check_block_list = false;
695   if (tls.server_handshake) {
696     check_block_list = !get_config()->tls.no_http2_cipher_block_list;
697   } else {
698     check_block_list = !get_config()->tls.client.no_http2_cipher_block_list;
699   }
700
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.";
706     }
707     return -1;
708   }
709
710   return 0;
711 }
712
713 namespace {
714 constexpr size_t SHRPX_SMALL_WRITE_LIMIT = 1300;
715 } // namespace
716
717 size_t Connection::get_tls_write_limit() {
718
719   if (tls_dyn_rec_warmup_threshold == 0) {
720     return std::numeric_limits<ssize_t>::max();
721   }
722
723   auto t = ev_now(loop);
724
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;
730   }
731
732   if (tls.warmup_writelen >= tls_dyn_rec_warmup_threshold) {
733     return std::numeric_limits<ssize_t>::max();
734   }
735
736   return SHRPX_SMALL_WRITE_LIMIT;
737 }
738
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;
742   }
743 }
744
745 void Connection::start_tls_write_idle() {
746   if (tls.last_write_idle < 0.) {
747     tls.last_write_idle = ev_now(loop);
748   }
749 }
750
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());
761     if (len == 0) {
762       return 0;
763     }
764   } else {
765     len = tls.last_writelen;
766     tls.last_writelen = 0;
767   }
768
769   tls.last_write_idle = -1.;
770
771   ERR_clear_error();
772
773 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
774   int rv;
775   if (SSL_is_init_finished(tls.ssl)) {
776     rv = SSL_write(tls.ssl, data, len);
777   } else {
778     size_t nwrite;
779     rv = SSL_write_early_data(tls.ssl, data, len, &nwrite);
780     // Use the same semantics with SSL_write.
781     if (rv == 1) {
782       rv = nwrite;
783     }
784   }
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))
788
789   if (rv <= 0) {
790     auto err = SSL_get_error(tls.ssl, rv);
791     switch (err) {
792     case SSL_ERROR_WANT_READ:
793       if (LOG_ENABLED(INFO)) {
794         LOG(INFO) << "Close connection due to TLS renegotiation";
795       }
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
800       // bio.
801       return 0;
802     case SSL_ERROR_SSL:
803       if (LOG_ENABLED(INFO)) {
804         LOG(INFO) << "SSL_write: "
805                   << ERR_error_string(ERR_get_error(), nullptr);
806       }
807       return SHRPX_ERR_NETWORK;
808     default:
809       if (LOG_ENABLED(INFO)) {
810         LOG(INFO) << "SSL_write: SSL_get_error returned " << err;
811       }
812       return SHRPX_ERR_NETWORK;
813     }
814   }
815
816   update_tls_warmup_writelen(rv);
817
818   return rv;
819 }
820
821 ssize_t Connection::read_tls(void *data, size_t len) {
822   ERR_clear_error();
823
824 #if OPENSSL_1_1_1_API
825   if (tls.earlybuf.rleft()) {
826     return tls.earlybuf.remove(data, len);
827   }
828 #endif // OPENSSL_1_1_1_API
829
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
836   // blocking.
837   if (tls.last_readlen == 0) {
838     len = std::min(len, rlimit.avail());
839     if (len == 0) {
840       return 0;
841     }
842   } else {
843     len = tls.last_readlen;
844     tls.last_readlen = 0;
845   }
846
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.
850     size_t nread;
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);
854       switch (err) {
855       case SSL_ERROR_WANT_READ:
856         tls.last_readlen = len;
857         return 0;
858       case SSL_ERROR_SSL:
859         if (LOG_ENABLED(INFO)) {
860           LOG(INFO) << "SSL_read: "
861                     << ERR_error_string(ERR_get_error(), nullptr);
862         }
863         return SHRPX_ERR_NETWORK;
864       default:
865         if (LOG_ENABLED(INFO)) {
866           LOG(INFO) << "SSL_read: SSL_get_error returned " << err;
867         }
868         return SHRPX_ERR_NETWORK;
869       }
870     }
871
872     if (LOG_ENABLED(INFO)) {
873       LOG(INFO) << "tls: read early data " << nread << " bytes";
874     }
875
876     if (rv == SSL_READ_EARLY_DATA_FINISH) {
877       if (LOG_ENABLED(INFO)) {
878         LOG(INFO) << "tls: read all early data";
879       }
880       tls.early_data_finish = true;
881       // We may have stopped write watcher in write_tls.
882       wlimit.startw();
883     }
884     return nread;
885   }
886 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
887
888   auto rv = SSL_read(tls.ssl, data, len);
889
890   if (rv <= 0) {
891     auto err = SSL_get_error(tls.ssl, rv);
892     switch (err) {
893     case SSL_ERROR_WANT_READ:
894       tls.last_readlen = len;
895       return 0;
896     case SSL_ERROR_WANT_WRITE:
897       if (LOG_ENABLED(INFO)) {
898         LOG(INFO) << "Close connection due to TLS renegotiation";
899       }
900       return SHRPX_ERR_NETWORK;
901     case SSL_ERROR_ZERO_RETURN:
902       return SHRPX_ERR_EOF;
903     case SSL_ERROR_SSL:
904       if (LOG_ENABLED(INFO)) {
905         LOG(INFO) << "SSL_read: " << ERR_error_string(ERR_get_error(), nullptr);
906       }
907       return SHRPX_ERR_NETWORK;
908     default:
909       if (LOG_ENABLED(INFO)) {
910         LOG(INFO) << "SSL_read: SSL_get_error returned " << err;
911       }
912       return SHRPX_ERR_NETWORK;
913     }
914   }
915
916   return rv;
917 }
918
919 ssize_t Connection::write_clear(const void *data, size_t len) {
920   len = std::min(len, wlimit.avail());
921   if (len == 0) {
922     return 0;
923   }
924
925   ssize_t nwrite;
926   while ((nwrite = write(fd, data, len)) == -1 && errno == EINTR)
927     ;
928   if (nwrite == -1) {
929     if (errno == EAGAIN || errno == EWOULDBLOCK) {
930       wlimit.startw();
931       ev_timer_again(loop, &wt);
932       return 0;
933     }
934     return SHRPX_ERR_NETWORK;
935   }
936
937   wlimit.drain(nwrite);
938
939   if (ev_is_active(&wt)) {
940     ev_timer_again(loop, &wt);
941   }
942
943   return nwrite;
944 }
945
946 ssize_t Connection::writev_clear(struct iovec *iov, int iovcnt) {
947   iovcnt = limit_iovec(iov, iovcnt, wlimit.avail());
948   if (iovcnt == 0) {
949     return 0;
950   }
951
952   ssize_t nwrite;
953   while ((nwrite = writev(fd, iov, iovcnt)) == -1 && errno == EINTR)
954     ;
955   if (nwrite == -1) {
956     if (errno == EAGAIN || errno == EWOULDBLOCK) {
957       wlimit.startw();
958       ev_timer_again(loop, &wt);
959       return 0;
960     }
961     return SHRPX_ERR_NETWORK;
962   }
963
964   wlimit.drain(nwrite);
965
966   if (ev_is_active(&wt)) {
967     ev_timer_again(loop, &wt);
968   }
969
970   return nwrite;
971 }
972
973 ssize_t Connection::read_clear(void *data, size_t len) {
974   len = std::min(len, rlimit.avail());
975   if (len == 0) {
976     return 0;
977   }
978
979   ssize_t nread;
980   while ((nread = read(fd, data, len)) == -1 && errno == EINTR)
981     ;
982   if (nread == -1) {
983     if (errno == EAGAIN || errno == EWOULDBLOCK) {
984       return 0;
985     }
986     return SHRPX_ERR_NETWORK;
987   }
988
989   if (nread == 0) {
990     return SHRPX_ERR_EOF;
991   }
992
993   rlimit.drain(nread);
994
995   return nread;
996 }
997
998 void Connection::handle_tls_pending_read() {
999   if (!ev_is_active(&rev)) {
1000     return;
1001   }
1002   rlimit.handle_tls_pending_read();
1003 }
1004
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);
1009   int rv;
1010
1011   rv = getsockopt(fd, IPPROTO_TCP, TCP_INFO, &tcp_info, &tcp_info_len);
1012
1013   if (rv != 0) {
1014     return -1;
1015   }
1016
1017   auto avail_packets = tcp_info.tcpi_snd_cwnd > tcp_info.tcpi_unacked
1018                            ? tcp_info.tcpi_snd_cwnd - tcp_info.tcpi_unacked
1019                            : 0;
1020
1021   // http://www.slideshare.net/kazuho/programming-tcp-for-responsiveness
1022
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.
1026   //
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) {
1032     tls_overhead = 22;
1033   } else
1034 #  endif // TLS1_3_VERSION
1035   {
1036     tls_overhead = 29;
1037   }
1038
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);
1043   } else {
1044     if (writable_size < 536) {
1045       LOG(INFO) << "writable_size is too small: " << writable_size;
1046     }
1047     // TODO is this required?
1048     writable_size = std::max(writable_size, static_cast<size_t>(536 * 2));
1049   }
1050
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;
1058   // }
1059
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;
1063
1064   return 0;
1065 #else  // !defined(TCP_INFO) || !defined(TCP_NOTSENT_LOWAT)
1066   return -1;
1067 #endif // !defined(TCP_INFO) || !defined(TCP_NOTSENT_LOWAT)
1068 }
1069
1070 void Connection::again_rt(ev_tstamp t) {
1071   read_timeout = t;
1072   rt.repeat = t;
1073   ev_timer_again(loop, &rt);
1074   last_read = ev_now(loop);
1075 }
1076
1077 void Connection::again_rt() {
1078   rt.repeat = read_timeout;
1079   ev_timer_again(loop, &rt);
1080   last_read = ev_now(loop);
1081 }
1082
1083 bool Connection::expired_rt() {
1084   auto delta = read_timeout - (ev_now(loop) - last_read);
1085   if (delta < 1e-9) {
1086     return true;
1087   }
1088   rt.repeat = delta;
1089   ev_timer_again(loop, &rt);
1090   return false;
1091 }
1092
1093 } // namespace shrpx