tizen 2.4 release
[external/nghttp2.git] / src / shrpx_client_handler.cc
1 /*
2  * nghttp2 - HTTP/2 C Library
3  *
4  * Copyright (c) 2012 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_client_handler.h"
26
27 #include <unistd.h>
28 #include <cerrno>
29
30 #include "shrpx_upstream.h"
31 #include "shrpx_http2_upstream.h"
32 #include "shrpx_https_upstream.h"
33 #include "shrpx_config.h"
34 #include "shrpx_http_downstream_connection.h"
35 #include "shrpx_http2_downstream_connection.h"
36 #include "shrpx_ssl.h"
37 #include "shrpx_worker.h"
38 #include "shrpx_worker_config.h"
39 #include "shrpx_downstream_connection_pool.h"
40 #include "shrpx_downstream.h"
41 #ifdef HAVE_SPDYLAY
42 #include "shrpx_spdy_upstream.h"
43 #endif // HAVE_SPDYLAY
44 #include "util.h"
45 #include "template.h"
46
47 using namespace nghttp2;
48
49 namespace shrpx {
50
51 namespace {
52 void timeoutcb(struct ev_loop *loop, ev_timer *w, int revents) {
53   auto conn = static_cast<Connection *>(w->data);
54   auto handler = static_cast<ClientHandler *>(conn->data);
55
56   if (LOG_ENABLED(INFO)) {
57     CLOG(INFO, handler) << "Time out";
58   }
59
60   delete handler;
61 }
62 } // namespace
63
64 namespace {
65 void shutdowncb(struct ev_loop *loop, ev_timer *w, int revents) {
66   auto handler = static_cast<ClientHandler *>(w->data);
67
68   if (LOG_ENABLED(INFO)) {
69     CLOG(INFO, handler) << "Close connection due to TLS renegotiation";
70   }
71
72   delete handler;
73 }
74 } // namespace
75
76 namespace {
77 void readcb(struct ev_loop *loop, ev_io *w, int revents) {
78   auto conn = static_cast<Connection *>(w->data);
79   auto handler = static_cast<ClientHandler *>(conn->data);
80
81   if (handler->do_read() != 0) {
82     delete handler;
83     return;
84   }
85 }
86 } // namespace
87
88 namespace {
89 void writecb(struct ev_loop *loop, ev_io *w, int revents) {
90   auto conn = static_cast<Connection *>(w->data);
91   auto handler = static_cast<ClientHandler *>(conn->data);
92
93   if (handler->do_write() != 0) {
94     delete handler;
95     return;
96   }
97 }
98 } // namespace
99
100 int ClientHandler::read_clear() {
101   ev_timer_again(conn_.loop, &conn_.rt);
102
103   for (;;) {
104     // we should process buffered data first before we read EOF.
105     if (rb_.rleft() && on_read() != 0) {
106       return -1;
107     }
108     if (rb_.rleft()) {
109       return 0;
110     }
111     rb_.reset();
112
113     auto nread = conn_.read_clear(rb_.last, rb_.wleft());
114
115     if (nread == 0) {
116       return 0;
117     }
118
119     if (nread < 0) {
120       return -1;
121     }
122
123     rb_.write(nread);
124   }
125 }
126
127 int ClientHandler::write_clear() {
128   ev_timer_again(conn_.loop, &conn_.rt);
129
130   for (;;) {
131     if (wb_.rleft() > 0) {
132       auto nwrite = conn_.write_clear(wb_.pos, wb_.rleft());
133       if (nwrite == 0) {
134         return 0;
135       }
136       if (nwrite < 0) {
137         return -1;
138       }
139       wb_.drain(nwrite);
140       continue;
141     }
142     wb_.reset();
143     if (on_write() != 0) {
144       return -1;
145     }
146     if (wb_.rleft() == 0) {
147       break;
148     }
149   }
150
151   conn_.wlimit.stopw();
152   ev_timer_stop(conn_.loop, &conn_.wt);
153
154   return 0;
155 }
156
157 int ClientHandler::tls_handshake() {
158   ev_timer_again(conn_.loop, &conn_.rt);
159
160   ERR_clear_error();
161
162   auto rv = conn_.tls_handshake();
163
164   if (rv == SHRPX_ERR_INPROGRESS) {
165     return 0;
166   }
167
168   if (rv < 0) {
169     return -1;
170   }
171
172   if (LOG_ENABLED(INFO)) {
173     CLOG(INFO, this) << "SSL/TLS handshake completed";
174   }
175
176   if (validate_next_proto() != 0) {
177     return -1;
178   }
179
180   read_ = &ClientHandler::read_tls;
181   write_ = &ClientHandler::write_tls;
182
183   return 0;
184 }
185
186 int ClientHandler::read_tls() {
187   ev_timer_again(conn_.loop, &conn_.rt);
188
189   ERR_clear_error();
190
191   for (;;) {
192     // we should process buffered data first before we read EOF.
193     if (rb_.rleft() && on_read() != 0) {
194       return -1;
195     }
196     if (rb_.rleft()) {
197       return 0;
198     }
199     rb_.reset();
200
201     auto nread = conn_.read_tls(rb_.last, rb_.wleft());
202
203     if (nread == 0) {
204       return 0;
205     }
206
207     if (nread < 0) {
208       return -1;
209     }
210
211     rb_.write(nread);
212   }
213 }
214
215 int ClientHandler::write_tls() {
216   ev_timer_again(conn_.loop, &conn_.rt);
217
218   ERR_clear_error();
219
220   for (;;) {
221     if (wb_.rleft() > 0) {
222       auto nwrite = conn_.write_tls(wb_.pos, wb_.rleft());
223
224       if (nwrite == 0) {
225         return 0;
226       }
227
228       if (nwrite < 0) {
229         return -1;
230       }
231
232       wb_.drain(nwrite);
233
234       continue;
235     }
236     wb_.reset();
237     if (on_write() != 0) {
238       return -1;
239     }
240     if (wb_.rleft() == 0) {
241       break;
242     }
243   }
244
245   conn_.wlimit.stopw();
246   ev_timer_stop(conn_.loop, &conn_.wt);
247
248   return 0;
249 }
250
251 int ClientHandler::upstream_noop() { return 0; }
252
253 int ClientHandler::upstream_read() {
254   assert(upstream_);
255   if (upstream_->on_read() != 0) {
256     return -1;
257   }
258   return 0;
259 }
260
261 int ClientHandler::upstream_write() {
262   assert(upstream_);
263   if (upstream_->on_write() != 0) {
264     return -1;
265   }
266
267   if (get_should_close_after_write() && wb_.rleft() == 0) {
268     return -1;
269   }
270
271   return 0;
272 }
273
274 int ClientHandler::upstream_http2_connhd_read() {
275   auto nread = std::min(left_connhd_len_, rb_.rleft());
276   if (memcmp(NGHTTP2_CLIENT_CONNECTION_PREFACE +
277                  NGHTTP2_CLIENT_CONNECTION_PREFACE_LEN - left_connhd_len_,
278              rb_.pos, nread) != 0) {
279     // There is no downgrade path here. Just drop the connection.
280     if (LOG_ENABLED(INFO)) {
281       CLOG(INFO, this) << "invalid client connection header";
282     }
283
284     return -1;
285   }
286
287   left_connhd_len_ -= nread;
288   rb_.drain(nread);
289
290   if (left_connhd_len_ == 0) {
291     on_read_ = &ClientHandler::upstream_read;
292     // Run on_read to process data left in buffer since they are not
293     // notified further
294     if (on_read() != 0) {
295       return -1;
296     }
297     return 0;
298   }
299
300   return 0;
301 }
302
303 int ClientHandler::upstream_http1_connhd_read() {
304   auto nread = std::min(left_connhd_len_, rb_.rleft());
305   if (memcmp(NGHTTP2_CLIENT_CONNECTION_PREFACE +
306                  NGHTTP2_CLIENT_CONNECTION_PREFACE_LEN - left_connhd_len_,
307              rb_.pos, nread) != 0) {
308     if (LOG_ENABLED(INFO)) {
309       CLOG(INFO, this) << "This is HTTP/1.1 connection, "
310                        << "but may be upgraded to HTTP/2 later.";
311     }
312
313     // Reset header length for later HTTP/2 upgrade
314     left_connhd_len_ = NGHTTP2_CLIENT_CONNECTION_PREFACE_LEN;
315     on_read_ = &ClientHandler::upstream_read;
316     on_write_ = &ClientHandler::upstream_write;
317
318     if (on_read() != 0) {
319       return -1;
320     }
321
322     return 0;
323   }
324
325   left_connhd_len_ -= nread;
326   rb_.drain(nread);
327
328   if (left_connhd_len_ == 0) {
329     if (LOG_ENABLED(INFO)) {
330       CLOG(INFO, this) << "direct HTTP/2 connection";
331     }
332
333     direct_http2_upgrade();
334     on_read_ = &ClientHandler::upstream_read;
335     on_write_ = &ClientHandler::upstream_write;
336
337     // Run on_read to process data left in buffer since they are not
338     // notified further
339     if (on_read() != 0) {
340       return -1;
341     }
342
343     return 0;
344   }
345
346   return 0;
347 }
348
349 ClientHandler::ClientHandler(struct ev_loop *loop, int fd, SSL *ssl,
350                              const char *ipaddr, const char *port,
351                              WorkerStat *worker_stat,
352                              DownstreamConnectionPool *dconn_pool)
353     : conn_(loop, fd, ssl, get_config()->upstream_write_timeout,
354             get_config()->upstream_read_timeout, get_config()->write_rate,
355             get_config()->write_burst, get_config()->read_rate,
356             get_config()->read_burst, writecb, readcb, timeoutcb, this),
357       ipaddr_(ipaddr), port_(port), dconn_pool_(dconn_pool),
358       http2session_(nullptr), http1_connect_blocker_(nullptr),
359       worker_stat_(worker_stat),
360       left_connhd_len_(NGHTTP2_CLIENT_CONNECTION_PREFACE_LEN),
361       should_close_after_write_(false) {
362
363   ++worker_stat->num_connections;
364
365   ev_timer_init(&reneg_shutdown_timer_, shutdowncb, 0., 0.);
366
367   reneg_shutdown_timer_.data = this;
368
369   conn_.rlimit.startw();
370   ev_timer_again(conn_.loop, &conn_.rt);
371
372   if (conn_.tls.ssl) {
373     SSL_set_app_data(conn_.tls.ssl, &conn_);
374     read_ = write_ = &ClientHandler::tls_handshake;
375     on_read_ = &ClientHandler::upstream_noop;
376     on_write_ = &ClientHandler::upstream_write;
377   } else {
378     // For non-TLS version, first create HttpsUpstream. It may be
379     // upgraded to HTTP/2 through HTTP Upgrade or direct HTTP/2
380     // connection.
381     upstream_ = make_unique<HttpsUpstream>(this);
382     alpn_ = "http/1.1";
383     read_ = &ClientHandler::read_clear;
384     write_ = &ClientHandler::write_clear;
385     on_read_ = &ClientHandler::upstream_http1_connhd_read;
386     on_write_ = &ClientHandler::upstream_noop;
387   }
388 }
389
390 ClientHandler::~ClientHandler() {
391   if (LOG_ENABLED(INFO)) {
392     CLOG(INFO, this) << "Deleting";
393   }
394
395   if (upstream_) {
396     upstream_->on_handler_delete();
397   }
398
399   --worker_stat_->num_connections;
400
401   ev_timer_stop(conn_.loop, &reneg_shutdown_timer_);
402
403   // TODO If backend is http/2, and it is in CONNECTED state, signal
404   // it and make it loopbreak when output is zero.
405   if (worker_config->graceful_shutdown && worker_stat_->num_connections == 0) {
406     ev_break(conn_.loop);
407   }
408
409   if (LOG_ENABLED(INFO)) {
410     CLOG(INFO, this) << "Deleted";
411   }
412 }
413
414 Upstream *ClientHandler::get_upstream() { return upstream_.get(); }
415
416 struct ev_loop *ClientHandler::get_loop() const {
417   return conn_.loop;
418 }
419
420 void ClientHandler::reset_upstream_read_timeout(ev_tstamp t) {
421   conn_.rt.repeat = t;
422   if (ev_is_active(&conn_.rt)) {
423     ev_timer_again(conn_.loop, &conn_.rt);
424   }
425 }
426
427 void ClientHandler::reset_upstream_write_timeout(ev_tstamp t) {
428   conn_.wt.repeat = t;
429   if (ev_is_active(&conn_.wt)) {
430     ev_timer_again(conn_.loop, &conn_.wt);
431   }
432 }
433
434 int ClientHandler::validate_next_proto() {
435   const unsigned char *next_proto = nullptr;
436   unsigned int next_proto_len;
437   int rv;
438
439   // First set callback for catch all cases
440   on_read_ = &ClientHandler::upstream_read;
441
442   SSL_get0_next_proto_negotiated(conn_.tls.ssl, &next_proto, &next_proto_len);
443   for (int i = 0; i < 2; ++i) {
444     if (next_proto) {
445       if (LOG_ENABLED(INFO)) {
446         std::string proto(next_proto, next_proto + next_proto_len);
447         CLOG(INFO, this) << "The negotiated next protocol: " << proto;
448       }
449       if (!ssl::in_proto_list(get_config()->npn_list, next_proto,
450                               next_proto_len)) {
451         break;
452       }
453       if (util::check_h2_is_selected(next_proto, next_proto_len) ||
454           (next_proto_len == sizeof("h2-16") - 1 &&
455            memcmp("h2-16", next_proto, next_proto_len) == 0)) {
456
457         on_read_ = &ClientHandler::upstream_http2_connhd_read;
458
459         auto http2_upstream = make_unique<Http2Upstream>(this);
460
461         if (!ssl::check_http2_requirement(conn_.tls.ssl)) {
462           rv = http2_upstream->terminate_session(NGHTTP2_INADEQUATE_SECURITY);
463
464           if (rv != 0) {
465             return -1;
466           }
467         }
468
469         upstream_ = std::move(http2_upstream);
470         alpn_.assign(next_proto, next_proto + next_proto_len);
471
472         // At this point, input buffer is already filled with some
473         // bytes.  The read callback is not called until new data
474         // come. So consume input buffer here.
475         if (on_read() != 0) {
476           return -1;
477         }
478
479         return 0;
480       } else {
481 #ifdef HAVE_SPDYLAY
482         uint16_t version = spdylay_npn_get_version(next_proto, next_proto_len);
483         if (version) {
484           upstream_ = make_unique<SpdyUpstream>(version, this);
485
486           switch (version) {
487           case SPDYLAY_PROTO_SPDY2:
488             alpn_ = "spdy/2";
489             break;
490           case SPDYLAY_PROTO_SPDY3:
491             alpn_ = "spdy/3";
492             break;
493           case SPDYLAY_PROTO_SPDY3_1:
494             alpn_ = "spdy/3.1";
495             break;
496           default:
497             alpn_ = "spdy/unknown";
498           }
499
500           // At this point, input buffer is already filled with some
501           // bytes.  The read callback is not called until new data
502           // come. So consume input buffer here.
503           if (on_read() != 0) {
504             return -1;
505           }
506
507           return 0;
508         }
509 #endif // HAVE_SPDYLAY
510         if (next_proto_len == 8 && memcmp("http/1.1", next_proto, 8) == 0) {
511           upstream_ = make_unique<HttpsUpstream>(this);
512           alpn_ = "http/1.1";
513
514           // At this point, input buffer is already filled with some
515           // bytes.  The read callback is not called until new data
516           // come. So consume input buffer here.
517           if (on_read() != 0) {
518             return -1;
519           }
520
521           return 0;
522         }
523       }
524       break;
525     }
526 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
527     SSL_get0_alpn_selected(conn_.tls.ssl, &next_proto, &next_proto_len);
528 #else  // OPENSSL_VERSION_NUMBER < 0x10002000L
529     break;
530 #endif // OPENSSL_VERSION_NUMBER < 0x10002000L
531   }
532   if (!next_proto) {
533     if (LOG_ENABLED(INFO)) {
534       CLOG(INFO, this) << "No protocol negotiated. Fallback to HTTP/1.1";
535     }
536     upstream_ = make_unique<HttpsUpstream>(this);
537     alpn_ = "http/1.1";
538
539     // At this point, input buffer is already filled with some bytes.
540     // The read callback is not called until new data come. So consume
541     // input buffer here.
542     if (on_read() != 0) {
543       return -1;
544     }
545
546     return 0;
547   }
548   if (LOG_ENABLED(INFO)) {
549     CLOG(INFO, this) << "The negotiated protocol is not supported";
550   }
551   return -1;
552 }
553
554 int ClientHandler::do_read() { return read_(*this); }
555 int ClientHandler::do_write() { return write_(*this); }
556
557 int ClientHandler::on_read() { return on_read_(*this); }
558 int ClientHandler::on_write() { return on_write_(*this); }
559
560 const std::string &ClientHandler::get_ipaddr() const { return ipaddr_; }
561
562 bool ClientHandler::get_should_close_after_write() const {
563   return should_close_after_write_;
564 }
565
566 void ClientHandler::set_should_close_after_write(bool f) {
567   should_close_after_write_ = f;
568 }
569
570 void ClientHandler::pool_downstream_connection(
571     std::unique_ptr<DownstreamConnection> dconn) {
572   if (LOG_ENABLED(INFO)) {
573     CLOG(INFO, this) << "Pooling downstream connection DCONN:" << dconn.get();
574   }
575   dconn->set_client_handler(nullptr);
576   dconn_pool_->add_downstream_connection(std::move(dconn));
577 }
578
579 void ClientHandler::remove_downstream_connection(DownstreamConnection *dconn) {
580   if (LOG_ENABLED(INFO)) {
581     CLOG(INFO, this) << "Removing downstream connection DCONN:" << dconn
582                      << " from pool";
583   }
584   dconn_pool_->remove_downstream_connection(dconn);
585 }
586
587 std::unique_ptr<DownstreamConnection>
588 ClientHandler::get_downstream_connection() {
589   auto dconn = dconn_pool_->pop_downstream_connection();
590
591   if (!dconn) {
592     if (LOG_ENABLED(INFO)) {
593       CLOG(INFO, this) << "Downstream connection pool is empty."
594                        << " Create new one";
595     }
596
597     if (http2session_) {
598       dconn =
599           make_unique<Http2DownstreamConnection>(dconn_pool_, http2session_);
600     } else {
601       dconn = make_unique<HttpDownstreamConnection>(dconn_pool_, conn_.loop);
602     }
603     dconn->set_client_handler(this);
604     return dconn;
605   }
606
607   dconn->set_client_handler(this);
608
609   if (LOG_ENABLED(INFO)) {
610     CLOG(INFO, this) << "Reuse downstream connection DCONN:" << dconn.get()
611                      << " from pool";
612   }
613
614   return dconn;
615 }
616
617 SSL *ClientHandler::get_ssl() const { return conn_.tls.ssl; }
618
619 void ClientHandler::set_http2_session(Http2Session *http2session) {
620   http2session_ = http2session;
621 }
622
623 Http2Session *ClientHandler::get_http2_session() const { return http2session_; }
624
625 void ClientHandler::set_http1_connect_blocker(
626     ConnectBlocker *http1_connect_blocker) {
627   http1_connect_blocker_ = http1_connect_blocker;
628 }
629
630 ConnectBlocker *ClientHandler::get_http1_connect_blocker() const {
631   return http1_connect_blocker_;
632 }
633
634 void ClientHandler::direct_http2_upgrade() {
635   upstream_ = make_unique<Http2Upstream>(this);
636   // TODO We don't know exact h2 draft version in direct upgrade.  We
637   // just use library default for now.
638   alpn_ = NGHTTP2_CLEARTEXT_PROTO_VERSION_ID;
639   on_read_ = &ClientHandler::upstream_read;
640 }
641
642 int ClientHandler::perform_http2_upgrade(HttpsUpstream *http) {
643   auto upstream = make_unique<Http2Upstream>(this);
644   if (upstream->upgrade_upstream(http) != 0) {
645     return -1;
646   }
647   // http pointer is now owned by upstream.
648   upstream_.release();
649   upstream_ = std::move(upstream);
650   // TODO We might get other version id in HTTP2-settings, if we
651   // support aliasing for h2, but we just use library default for now.
652   alpn_ = NGHTTP2_CLEARTEXT_PROTO_VERSION_ID;
653   on_read_ = &ClientHandler::upstream_http2_connhd_read;
654
655   static char res[] = "HTTP/1.1 101 Switching Protocols\r\n"
656                       "Connection: Upgrade\r\n"
657                       "Upgrade: " NGHTTP2_CLEARTEXT_PROTO_VERSION_ID "\r\n"
658                       "\r\n";
659   wb_.write(res, sizeof(res) - 1);
660   return 0;
661 }
662
663 bool ClientHandler::get_http2_upgrade_allowed() const { return !conn_.tls.ssl; }
664
665 std::string ClientHandler::get_upstream_scheme() const {
666   if (conn_.tls.ssl) {
667     return "https";
668   } else {
669     return "http";
670   }
671 }
672
673 void ClientHandler::start_immediate_shutdown() {
674   ev_timer_start(conn_.loop, &reneg_shutdown_timer_);
675 }
676
677 void ClientHandler::write_accesslog(Downstream *downstream) {
678   LogSpec lgsp = {
679       downstream, ipaddr_.c_str(), downstream->get_request_method().c_str(),
680
681       downstream->get_request_path().empty()
682           ? downstream->get_request_http2_authority().c_str()
683           : downstream->get_request_path().c_str(),
684
685       alpn_.c_str(),
686
687       std::chrono::system_clock::now(),          // time_now
688       downstream->get_request_start_time(),      // request_start_time
689       std::chrono::high_resolution_clock::now(), // request_end_time
690
691       downstream->get_request_major(), downstream->get_request_minor(),
692       downstream->get_response_http_status(),
693       downstream->get_response_sent_bodylen(), port_.c_str(),
694       get_config()->port, get_config()->pid,
695   };
696
697   upstream_accesslog(get_config()->accesslog_format, &lgsp);
698 }
699
700 void ClientHandler::write_accesslog(int major, int minor, unsigned int status,
701                                     int64_t body_bytes_sent) {
702   auto time_now = std::chrono::system_clock::now();
703   auto highres_now = std::chrono::high_resolution_clock::now();
704
705   LogSpec lgsp = {
706       nullptr,            ipaddr_.c_str(),
707       "-", // method
708       "-", // path,
709       alpn_.c_str(),      time_now,
710       highres_now,               // request_start_time TODO is
711                                  // there a better value?
712       highres_now,               // request_end_time
713       major,              minor, // major, minor
714       status,             body_bytes_sent,   port_.c_str(),
715       get_config()->port, get_config()->pid,
716   };
717
718   upstream_accesslog(get_config()->accesslog_format, &lgsp);
719 }
720
721 WorkerStat *ClientHandler::get_worker_stat() const { return worker_stat_; }
722
723 ClientHandler::WriteBuf *ClientHandler::get_wb() { return &wb_; }
724
725 ClientHandler::ReadBuf *ClientHandler::get_rb() { return &rb_; }
726
727 void ClientHandler::signal_write() { conn_.wlimit.startw(); }
728
729 RateLimit *ClientHandler::get_rlimit() { return &conn_.rlimit; }
730 RateLimit *ClientHandler::get_wlimit() { return &conn_.wlimit; }
731
732 } // namespace shrpx