2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2013 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 "HttpServer.h"
28 #ifdef HAVE_SYS_SOCKET_H
29 # include <sys/socket.h>
30 #endif // HAVE_SYS_SOCKET_H
33 #endif // HAVE_NETDB_H
36 #endif // HAVE_UNISTD_H
39 #endif // HAVE_FCNTL_H
40 #ifdef HAVE_NETINET_IN_H
41 # include <netinet/in.h>
42 #endif // HAVE_NETINET_IN_H
43 #include <netinet/tcp.h>
44 #ifdef HAVE_ARPA_INET_H
45 # include <arpa/inet.h>
46 #endif // HAVE_ARPA_INET_H
55 #include <openssl/err.h>
56 #include <openssl/dh.h>
60 #include "app_helper.h"
73 // TODO could be constexpr
74 constexpr auto DEFAULT_HTML = StringRef::from_lit("index.html");
75 constexpr auto NGHTTPD_SERVER =
76 StringRef::from_lit("nghttpd nghttp2/" NGHTTP2_VERSION);
80 void delete_handler(Http2Handler *handler) {
81 handler->remove_self();
87 void print_session_id(int64_t id) { std::cout << "[id=" << id << "] "; }
91 : mime_types_file("/etc/mime.types"),
92 stream_read_timeout(1_min),
93 stream_write_timeout(1_min),
97 max_concurrent_streams(100),
98 header_table_size(-1),
99 encoder_header_table_size(-1),
101 connection_window_bits(-1),
105 verify_client(false),
108 early_response(false),
111 no_content_length(false) {}
116 void stream_timeout_cb(struct ev_loop *loop, ev_timer *w, int revents) {
118 auto stream = static_cast<Stream *>(w->data);
119 auto hd = stream->handler;
120 auto config = hd->get_config();
122 ev_timer_stop(hd->get_loop(), &stream->rtimer);
123 ev_timer_stop(hd->get_loop(), &stream->wtimer);
125 if (config->verbose) {
126 print_session_id(hd->session_id());
128 std::cout << " timeout stream_id=" << stream->stream_id << std::endl;
131 hd->submit_rst_stream(stream, NGHTTP2_INTERNAL_ERROR);
141 void add_stream_read_timeout(Stream *stream) {
142 auto hd = stream->handler;
143 ev_timer_again(hd->get_loop(), &stream->rtimer);
148 void add_stream_read_timeout_if_pending(Stream *stream) {
149 auto hd = stream->handler;
150 if (ev_is_active(&stream->rtimer)) {
151 ev_timer_again(hd->get_loop(), &stream->rtimer);
157 void add_stream_write_timeout(Stream *stream) {
158 auto hd = stream->handler;
159 ev_timer_again(hd->get_loop(), &stream->wtimer);
164 void remove_stream_read_timeout(Stream *stream) {
165 auto hd = stream->handler;
166 ev_timer_stop(hd->get_loop(), &stream->rtimer);
171 void remove_stream_write_timeout(Stream *stream) {
172 auto hd = stream->handler;
173 ev_timer_stop(hd->get_loop(), &stream->wtimer);
178 void fill_callback(nghttp2_session_callbacks *callbacks, const Config *config);
182 constexpr ev_tstamp RELEASE_FD_TIMEOUT = 2.;
186 void release_fd_cb(struct ev_loop *loop, ev_timer *w, int revents);
190 constexpr ev_tstamp FILE_ENTRY_MAX_AGE = 10.;
194 constexpr size_t FILE_ENTRY_EVICT_THRES = 2048;
198 bool need_validation_file_entry(const FileEntry *ent, ev_tstamp now) {
199 return ent->last_valid + FILE_ENTRY_MAX_AGE < now;
204 bool validate_file_entry(FileEntry *ent, ev_tstamp now) {
208 rv = fstat(ent->fd, &stbuf);
214 if (stbuf.st_nlink == 0 || ent->mtime != stbuf.st_mtime) {
219 ent->mtime = stbuf.st_mtime;
220 ent->last_valid = now;
228 Sessions(HttpServer *sv, struct ev_loop *loop, const Config *config,
237 tstamp_cached_(ev_now(loop)),
238 cached_date_(util::http_date(tstamp_cached_)) {
239 nghttp2_session_callbacks_new(&callbacks_);
241 fill_callback(callbacks_, config_);
243 nghttp2_option_new(&option_);
245 if (config_->encoder_header_table_size != -1) {
246 nghttp2_option_set_max_deflate_dynamic_table_size(
247 option_, config_->encoder_header_table_size);
250 ev_timer_init(&release_fd_timer_, release_fd_cb, 0., RELEASE_FD_TIMEOUT);
251 release_fd_timer_.data = this;
254 ev_timer_stop(loop_, &release_fd_timer_);
255 for (auto handler : handlers_) {
258 nghttp2_option_del(option_);
259 nghttp2_session_callbacks_del(callbacks_);
261 void add_handler(Http2Handler *handler) { handlers_.insert(handler); }
262 void remove_handler(Http2Handler *handler) {
263 handlers_.erase(handler);
264 if (handlers_.empty() && !fd_cache_.empty()) {
265 ev_timer_again(loop_, &release_fd_timer_);
268 SSL_CTX *get_ssl_ctx() const { return ssl_ctx_; }
269 SSL *ssl_session_new(int fd) {
270 SSL *ssl = SSL_new(ssl_ctx_);
272 std::cerr << "SSL_new() failed" << std::endl;
275 if (SSL_set_fd(ssl, fd) == 0) {
276 std::cerr << "SSL_set_fd() failed" << std::endl;
282 const Config *get_config() const { return config_; }
283 struct ev_loop *get_loop() const {
286 int64_t get_next_session_id() {
287 auto session_id = next_session_id_;
288 if (next_session_id_ == std::numeric_limits<int64_t>::max()) {
289 next_session_id_ = 1;
295 const nghttp2_session_callbacks *get_callbacks() const { return callbacks_; }
296 const nghttp2_option *get_option() const { return option_; }
297 void accept_connection(int fd) {
298 util::make_socket_nodelay(fd);
301 ssl = ssl_session_new(fd);
308 std::make_unique<Http2Handler>(this, fd, ssl, get_next_session_id());
310 if (handler->connection_made() != 0) {
314 add_handler(handler.release());
316 void update_cached_date() { cached_date_ = util::http_date(tstamp_cached_); }
317 const std::string &get_cached_date() {
318 auto t = ev_now(loop_);
319 if (t != tstamp_cached_) {
321 update_cached_date();
325 FileEntry *get_cached_fd(const std::string &path) {
326 auto range = fd_cache_.equal_range(path);
327 if (range.first == range.second) {
331 auto now = ev_now(loop_);
333 for (auto it = range.first; it != range.second;) {
334 auto &ent = (*it).second;
339 if (need_validation_file_entry(ent.get(), now) &&
340 !validate_file_entry(ent.get(), now)) {
341 if (ent->usecount == 0) {
342 fd_cache_lru_.remove(ent.get());
344 it = fd_cache_.erase(it);
351 fd_cache_lru_.remove(ent.get());
352 fd_cache_lru_.append(ent.get());
359 FileEntry *cache_fd(const std::string &path, const FileEntry &ent) {
360 #ifdef HAVE_STD_MAP_EMPLACE
361 auto rv = fd_cache_.emplace(path, std::make_unique<FileEntry>(ent));
362 #else // !HAVE_STD_MAP_EMPLACE
364 auto rv = fd_cache_.insert(
365 std::make_pair(path, std::make_unique<FileEntry>(ent)));
366 #endif // !HAVE_STD_MAP_EMPLACE
367 auto &res = (*rv).second;
369 fd_cache_lru_.append(res.get());
371 while (fd_cache_.size() > FILE_ENTRY_EVICT_THRES) {
372 auto ent = fd_cache_lru_.head;
376 fd_cache_lru_.remove(ent);
378 fd_cache_.erase(ent->it);
383 void release_fd(FileEntry *target) {
386 if (target->usecount == 0 && target->stale) {
387 fd_cache_lru_.remove(target);
389 fd_cache_.erase(target->it);
393 // We use timer to close file descriptor and delete the entry from
394 // cache. The timer will be started when there is no handler.
396 void release_unused_fd() {
397 for (auto i = std::begin(fd_cache_); i != std::end(fd_cache_);) {
398 auto &ent = (*i).second;
399 if (ent->usecount != 0) {
404 fd_cache_lru_.remove(ent.get());
406 i = fd_cache_.erase(i);
409 const HttpServer *get_server() const { return sv_; }
410 bool handlers_empty() const { return handlers_.empty(); }
413 std::set<Http2Handler *> handlers_;
414 // cache for file descriptors to read file.
415 std::multimap<std::string, std::unique_ptr<FileEntry>> fd_cache_;
416 DList<FileEntry> fd_cache_lru_;
418 struct ev_loop *loop_;
419 const Config *config_;
421 nghttp2_session_callbacks *callbacks_;
422 nghttp2_option *option_;
423 ev_timer release_fd_timer_;
424 int64_t next_session_id_;
425 ev_tstamp tstamp_cached_;
426 std::string cached_date_;
430 void release_fd_cb(struct ev_loop *loop, ev_timer *w, int revents) {
431 auto sessions = static_cast<Sessions *>(w->data);
433 ev_timer_stop(loop, w);
435 if (!sessions->handlers_empty()) {
439 sessions->release_unused_fd();
443 Stream::Stream(Http2Handler *handler, int32_t stream_id)
444 : balloc(1024, 1024),
450 header_buffer_size(0),
451 stream_id(stream_id),
453 auto config = handler->get_config();
454 ev_timer_init(&rtimer, stream_timeout_cb, 0., config->stream_read_timeout);
455 ev_timer_init(&wtimer, stream_timeout_cb, 0., config->stream_write_timeout);
461 if (file_ent != nullptr) {
462 auto sessions = handler->get_sessions();
463 sessions->release_fd(file_ent);
466 auto &rcbuf = header.rcbuf;
467 nghttp2_rcbuf_decref(rcbuf.method);
468 nghttp2_rcbuf_decref(rcbuf.scheme);
469 nghttp2_rcbuf_decref(rcbuf.authority);
470 nghttp2_rcbuf_decref(rcbuf.host);
471 nghttp2_rcbuf_decref(rcbuf.path);
472 nghttp2_rcbuf_decref(rcbuf.ims);
473 nghttp2_rcbuf_decref(rcbuf.expect);
475 auto loop = handler->get_loop();
476 ev_timer_stop(loop, &rtimer);
477 ev_timer_stop(loop, &wtimer);
481 void on_session_closed(Http2Handler *hd, int64_t session_id) {
482 if (hd->get_config()->verbose) {
483 print_session_id(session_id);
485 std::cout << " closed" << std::endl;
491 void settings_timeout_cb(struct ev_loop *loop, ev_timer *w, int revents) {
493 auto hd = static_cast<Http2Handler *>(w->data);
494 hd->terminate_session(NGHTTP2_SETTINGS_TIMEOUT);
503 void readcb(struct ev_loop *loop, ev_io *w, int revents) {
505 auto handler = static_cast<Http2Handler *>(w->data);
507 rv = handler->on_read();
509 delete_handler(handler);
515 void writecb(struct ev_loop *loop, ev_io *w, int revents) {
517 auto handler = static_cast<Http2Handler *>(w->data);
519 rv = handler->on_write();
521 delete_handler(handler);
526 Http2Handler::Http2Handler(Sessions *sessions, int fd, SSL *ssl,
528 : session_id_(session_id),
532 data_pending_(nullptr),
535 ev_timer_init(&settings_timerev_, settings_timeout_cb, 10., 0.);
536 ev_io_init(&wev_, writecb, fd, EV_WRITE);
537 ev_io_init(&rev_, readcb, fd, EV_READ);
539 settings_timerev_.data = this;
543 auto loop = sessions_->get_loop();
544 ev_io_start(loop, &rev_);
547 SSL_set_accept_state(ssl);
548 read_ = &Http2Handler::tls_handshake;
549 write_ = &Http2Handler::tls_handshake;
551 read_ = &Http2Handler::read_clear;
552 write_ = &Http2Handler::write_clear;
556 Http2Handler::~Http2Handler() {
557 on_session_closed(this, session_id_);
558 nghttp2_session_del(session_);
560 SSL_set_shutdown(ssl_, SSL_get_shutdown(ssl_) | SSL_RECEIVED_SHUTDOWN);
564 auto loop = sessions_->get_loop();
565 ev_timer_stop(loop, &settings_timerev_);
566 ev_io_stop(loop, &rev_);
567 ev_io_stop(loop, &wev_);
571 shutdown(fd_, SHUT_WR);
575 void Http2Handler::remove_self() { sessions_->remove_handler(this); }
577 struct ev_loop *Http2Handler::get_loop() const {
578 return sessions_->get_loop();
581 Http2Handler::WriteBuf *Http2Handler::get_wb() { return &wb_; }
583 void Http2Handler::start_settings_timer() {
584 ev_timer_start(sessions_->get_loop(), &settings_timerev_);
587 int Http2Handler::fill_wb() {
589 auto n = std::min(wb_.wleft(), data_pendinglen_);
590 wb_.write(data_pending_, n);
591 if (n < data_pendinglen_) {
593 data_pendinglen_ -= n;
597 data_pending_ = nullptr;
598 data_pendinglen_ = 0;
603 auto datalen = nghttp2_session_mem_send(session_, &data);
606 std::cerr << "nghttp2_session_mem_send() returned error: "
607 << nghttp2_strerror(datalen) << std::endl;
613 auto n = wb_.write(data, datalen);
614 if (n < static_cast<decltype(n)>(datalen)) {
615 data_pending_ = data + n;
616 data_pendinglen_ = datalen - n;
623 int Http2Handler::read_clear() {
625 std::array<uint8_t, 8_k> buf;
628 while ((nread = read(fd_, buf.data(), buf.size())) == -1 && errno == EINTR)
631 if (errno == EAGAIN || errno == EWOULDBLOCK) {
632 return write_(*this);
640 if (get_config()->hexdump) {
641 util::hexdump(stdout, buf.data(), nread);
644 rv = nghttp2_session_mem_recv(session_, buf.data(), nread);
646 if (rv != NGHTTP2_ERR_BAD_CLIENT_MAGIC) {
647 std::cerr << "nghttp2_session_mem_recv() returned error: "
648 << nghttp2_strerror(rv) << std::endl;
653 return write_(*this);
656 int Http2Handler::write_clear() {
657 auto loop = sessions_->get_loop();
659 if (wb_.rleft() > 0) {
661 while ((nwrite = write(fd_, wb_.pos, wb_.rleft())) == -1 &&
665 if (errno == EAGAIN || errno == EWOULDBLOCK) {
666 ev_io_start(loop, &wev_);
675 if (fill_wb() != 0) {
678 if (wb_.rleft() == 0) {
683 if (wb_.rleft() == 0) {
684 ev_io_stop(loop, &wev_);
686 ev_io_start(loop, &wev_);
689 if (nghttp2_session_want_read(session_) == 0 &&
690 nghttp2_session_want_write(session_) == 0 && wb_.rleft() == 0) {
697 int Http2Handler::tls_handshake() {
698 ev_io_stop(sessions_->get_loop(), &wev_);
702 auto rv = SSL_do_handshake(ssl_);
705 auto err = SSL_get_error(ssl_, rv);
707 case SSL_ERROR_WANT_READ:
709 case SSL_ERROR_WANT_WRITE:
710 ev_io_start(sessions_->get_loop(), &wev_);
717 if (sessions_->get_config()->verbose) {
718 std::cerr << "SSL/TLS handshake completed" << std::endl;
721 if (verify_npn_result() != 0) {
725 read_ = &Http2Handler::read_tls;
726 write_ = &Http2Handler::write_tls;
728 if (connection_made() != 0) {
732 if (sessions_->get_config()->verbose) {
733 if (SSL_session_reused(ssl_)) {
734 std::cerr << "SSL/TLS session reused" << std::endl;
741 int Http2Handler::read_tls() {
742 std::array<uint8_t, 8_k> buf;
746 auto rv = SSL_read(ssl_, buf.data(), buf.size());
749 auto err = SSL_get_error(ssl_, rv);
751 case SSL_ERROR_WANT_READ:
752 return write_(*this);
753 case SSL_ERROR_WANT_WRITE:
754 // renegotiation started
763 if (get_config()->hexdump) {
764 util::hexdump(stdout, buf.data(), nread);
767 rv = nghttp2_session_mem_recv(session_, buf.data(), nread);
769 if (rv != NGHTTP2_ERR_BAD_CLIENT_MAGIC) {
770 std::cerr << "nghttp2_session_mem_recv() returned error: "
771 << nghttp2_strerror(rv) << std::endl;
776 return write_(*this);
779 int Http2Handler::write_tls() {
780 auto loop = sessions_->get_loop();
785 if (wb_.rleft() > 0) {
786 auto rv = SSL_write(ssl_, wb_.pos, wb_.rleft());
789 auto err = SSL_get_error(ssl_, rv);
791 case SSL_ERROR_WANT_READ:
792 // renegotiation started
794 case SSL_ERROR_WANT_WRITE:
795 ev_io_start(sessions_->get_loop(), &wev_);
806 if (fill_wb() != 0) {
809 if (wb_.rleft() == 0) {
814 if (wb_.rleft() == 0) {
815 ev_io_stop(loop, &wev_);
817 ev_io_start(loop, &wev_);
820 if (nghttp2_session_want_read(session_) == 0 &&
821 nghttp2_session_want_write(session_) == 0 && wb_.rleft() == 0) {
828 int Http2Handler::on_read() { return read_(*this); }
830 int Http2Handler::on_write() { return write_(*this); }
832 int Http2Handler::connection_made() {
835 r = nghttp2_session_server_new2(&session_, sessions_->get_callbacks(), this,
836 sessions_->get_option());
842 auto config = sessions_->get_config();
843 std::array<nghttp2_settings_entry, 4> entry;
846 entry[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
847 entry[0].value = config->max_concurrent_streams;
849 if (config->header_table_size >= 0) {
850 entry[niv].settings_id = NGHTTP2_SETTINGS_HEADER_TABLE_SIZE;
851 entry[niv].value = config->header_table_size;
855 if (config->window_bits != -1) {
856 entry[niv].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
857 entry[niv].value = (1 << config->window_bits) - 1;
861 r = nghttp2_submit_settings(session_, NGHTTP2_FLAG_NONE, entry.data(), niv);
866 if (config->connection_window_bits != -1) {
867 r = nghttp2_session_set_local_window_size(
868 session_, NGHTTP2_FLAG_NONE, 0,
869 (1 << config->connection_window_bits) - 1);
875 if (ssl_ && !nghttp2::tls::check_http2_requirement(ssl_)) {
876 terminate_session(NGHTTP2_INADEQUATE_SECURITY);
882 int Http2Handler::verify_npn_result() {
883 const unsigned char *next_proto = nullptr;
884 unsigned int next_proto_len;
885 // Check the negotiated protocol in NPN or ALPN
886 #ifndef OPENSSL_NO_NEXTPROTONEG
887 SSL_get0_next_proto_negotiated(ssl_, &next_proto, &next_proto_len);
888 #endif // !OPENSSL_NO_NEXTPROTONEG
889 for (int i = 0; i < 2; ++i) {
891 auto proto = StringRef{next_proto, next_proto_len};
892 if (sessions_->get_config()->verbose) {
893 std::cout << "The negotiated protocol: " << proto << std::endl;
895 if (util::check_h2_is_selected(proto)) {
900 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
901 SSL_get0_alpn_selected(ssl_, &next_proto, &next_proto_len);
902 #else // OPENSSL_VERSION_NUMBER < 0x10002000L
904 #endif // OPENSSL_VERSION_NUMBER < 0x10002000L
907 if (sessions_->get_config()->verbose) {
908 std::cerr << "Client did not advertise HTTP/2 protocol."
909 << " (nghttp2 expects " << NGHTTP2_PROTO_VERSION_ID << ")"
915 int Http2Handler::submit_file_response(const StringRef &status, Stream *stream,
916 time_t last_modified, off_t file_length,
917 const std::string *content_type,
918 nghttp2_data_provider *data_prd) {
919 std::string last_modified_str;
920 auto nva = make_array(http2::make_nv_ls_nocopy(":status", status),
921 http2::make_nv_ls_nocopy("server", NGHTTPD_SERVER),
922 http2::make_nv_ll("cache-control", "max-age=3600"),
923 http2::make_nv_ls("date", sessions_->get_cached_date()),
924 http2::make_nv_ll("", ""), http2::make_nv_ll("", ""),
925 http2::make_nv_ll("", ""), http2::make_nv_ll("", ""));
927 if (!get_config()->no_content_length) {
928 nva[nvlen++] = http2::make_nv_ls_nocopy(
930 util::make_string_ref_uint(stream->balloc, file_length));
932 if (last_modified != 0) {
933 last_modified_str = util::http_date(last_modified);
934 nva[nvlen++] = http2::make_nv_ls("last-modified", last_modified_str);
937 nva[nvlen++] = http2::make_nv_ls("content-type", *content_type);
939 auto &trailer_names = get_config()->trailer_names;
940 if (!trailer_names.empty()) {
941 nva[nvlen++] = http2::make_nv_ls_nocopy("trailer", trailer_names);
943 return nghttp2_submit_response(session_, stream->stream_id, nva.data(), nvlen,
947 int Http2Handler::submit_response(const StringRef &status, int32_t stream_id,
948 const HeaderRefs &headers,
949 nghttp2_data_provider *data_prd) {
950 auto nva = std::vector<nghttp2_nv>();
951 nva.reserve(4 + headers.size());
952 nva.push_back(http2::make_nv_ls_nocopy(":status", status));
953 nva.push_back(http2::make_nv_ls_nocopy("server", NGHTTPD_SERVER));
954 nva.push_back(http2::make_nv_ls("date", sessions_->get_cached_date()));
957 auto &trailer_names = get_config()->trailer_names;
958 if (!trailer_names.empty()) {
959 nva.push_back(http2::make_nv_ls_nocopy("trailer", trailer_names));
963 for (auto &nv : headers) {
964 nva.push_back(http2::make_nv_nocopy(nv.name, nv.value, nv.no_index));
966 int r = nghttp2_submit_response(session_, stream_id, nva.data(), nva.size(),
971 int Http2Handler::submit_response(const StringRef &status, int32_t stream_id,
972 nghttp2_data_provider *data_prd) {
973 auto nva = make_array(http2::make_nv_ls_nocopy(":status", status),
974 http2::make_nv_ls_nocopy("server", NGHTTPD_SERVER),
975 http2::make_nv_ls("date", sessions_->get_cached_date()),
976 http2::make_nv_ll("", ""));
980 auto &trailer_names = get_config()->trailer_names;
981 if (!trailer_names.empty()) {
982 nva[nvlen++] = http2::make_nv_ls_nocopy("trailer", trailer_names);
986 return nghttp2_submit_response(session_, stream_id, nva.data(), nvlen,
990 int Http2Handler::submit_non_final_response(const std::string &status,
992 auto nva = make_array(http2::make_nv_ls(":status", status));
993 return nghttp2_submit_headers(session_, NGHTTP2_FLAG_NONE, stream_id, nullptr,
994 nva.data(), nva.size(), nullptr);
997 int Http2Handler::submit_push_promise(Stream *stream,
998 const StringRef &push_path) {
999 auto authority = stream->header.authority;
1001 if (authority.empty()) {
1002 authority = stream->header.host;
1005 auto scheme = get_config()->no_tls ? StringRef::from_lit("http")
1006 : StringRef::from_lit("https");
1008 auto nva = make_array(http2::make_nv_ll(":method", "GET"),
1009 http2::make_nv_ls_nocopy(":path", push_path),
1010 http2::make_nv_ls_nocopy(":scheme", scheme),
1011 http2::make_nv_ls_nocopy(":authority", authority));
1013 auto promised_stream_id = nghttp2_submit_push_promise(
1014 session_, NGHTTP2_FLAG_END_HEADERS, stream->stream_id, nva.data(),
1015 nva.size(), nullptr);
1017 if (promised_stream_id < 0) {
1018 return promised_stream_id;
1021 auto promised_stream = std::make_unique<Stream>(this, promised_stream_id);
1023 auto &promised_header = promised_stream->header;
1024 promised_header.method = StringRef::from_lit("GET");
1025 promised_header.path = push_path;
1026 promised_header.scheme = scheme;
1027 promised_header.authority =
1028 make_string_ref(promised_stream->balloc, authority);
1030 add_stream(promised_stream_id, std::move(promised_stream));
1035 int Http2Handler::submit_rst_stream(Stream *stream, uint32_t error_code) {
1036 remove_stream_read_timeout(stream);
1037 remove_stream_write_timeout(stream);
1039 return nghttp2_submit_rst_stream(session_, NGHTTP2_FLAG_NONE,
1040 stream->stream_id, error_code);
1043 void Http2Handler::add_stream(int32_t stream_id,
1044 std::unique_ptr<Stream> stream) {
1045 id2stream_[stream_id] = std::move(stream);
1048 void Http2Handler::remove_stream(int32_t stream_id) {
1049 id2stream_.erase(stream_id);
1052 Stream *Http2Handler::get_stream(int32_t stream_id) {
1053 auto itr = id2stream_.find(stream_id);
1054 if (itr == std::end(id2stream_)) {
1057 return (*itr).second.get();
1061 int64_t Http2Handler::session_id() const { return session_id_; }
1063 Sessions *Http2Handler::get_sessions() const { return sessions_; }
1065 const Config *Http2Handler::get_config() const {
1066 return sessions_->get_config();
1069 void Http2Handler::remove_settings_timer() {
1070 ev_timer_stop(sessions_->get_loop(), &settings_timerev_);
1073 void Http2Handler::terminate_session(uint32_t error_code) {
1074 nghttp2_session_terminate_session(session_, error_code);
1077 ssize_t file_read_callback(nghttp2_session *session, int32_t stream_id,
1078 uint8_t *buf, size_t length, uint32_t *data_flags,
1079 nghttp2_data_source *source, void *user_data) {
1081 auto hd = static_cast<Http2Handler *>(user_data);
1082 auto stream = hd->get_stream(stream_id);
1084 auto nread = std::min(stream->body_length - stream->body_offset,
1085 static_cast<int64_t>(length));
1087 *data_flags |= NGHTTP2_DATA_FLAG_NO_COPY;
1089 if (nread == 0 || stream->body_length == stream->body_offset + nread) {
1090 *data_flags |= NGHTTP2_DATA_FLAG_EOF;
1092 auto config = hd->get_config();
1093 if (!config->trailer.empty()) {
1094 std::vector<nghttp2_nv> nva;
1095 nva.reserve(config->trailer.size());
1096 for (auto &kv : config->trailer) {
1097 nva.push_back(http2::make_nv(kv.name, kv.value, kv.no_index));
1099 rv = nghttp2_submit_trailer(session, stream_id, nva.data(), nva.size());
1101 if (nghttp2_is_fatal(rv)) {
1102 return NGHTTP2_ERR_CALLBACK_FAILURE;
1105 *data_flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
1109 if (nghttp2_session_get_stream_remote_close(session, stream_id) == 0) {
1110 remove_stream_read_timeout(stream);
1111 remove_stream_write_timeout(stream);
1113 hd->submit_rst_stream(stream, NGHTTP2_NO_ERROR);
1121 void prepare_status_response(Stream *stream, Http2Handler *hd, int status) {
1122 auto sessions = hd->get_sessions();
1123 auto status_page = sessions->get_server()->get_status_page(status);
1124 auto file_ent = &status_page->file_ent;
1126 // we don't set stream->file_ent since we don't want to expire it.
1127 stream->body_length = file_ent->length;
1128 nghttp2_data_provider data_prd;
1129 data_prd.source.fd = file_ent->fd;
1130 data_prd.read_callback = file_read_callback;
1134 headers.emplace_back(StringRef::from_lit("content-type"),
1135 StringRef::from_lit("text/html; charset=UTF-8"));
1136 headers.emplace_back(
1137 StringRef::from_lit("content-length"),
1138 util::make_string_ref_uint(stream->balloc, file_ent->length));
1139 hd->submit_response(StringRef{status_page->status}, stream->stream_id,
1140 headers, &data_prd);
1145 void prepare_echo_response(Stream *stream, Http2Handler *hd) {
1146 auto length = lseek(stream->file_ent->fd, 0, SEEK_END);
1148 hd->submit_rst_stream(stream, NGHTTP2_INTERNAL_ERROR);
1151 stream->body_length = length;
1152 if (lseek(stream->file_ent->fd, 0, SEEK_SET) == -1) {
1153 hd->submit_rst_stream(stream, NGHTTP2_INTERNAL_ERROR);
1156 nghttp2_data_provider data_prd;
1157 data_prd.source.fd = stream->file_ent->fd;
1158 data_prd.read_callback = file_read_callback;
1161 headers.emplace_back(StringRef::from_lit("nghttpd-response"),
1162 StringRef::from_lit("echo"));
1163 if (!hd->get_config()->no_content_length) {
1164 headers.emplace_back(StringRef::from_lit("content-length"),
1165 util::make_string_ref_uint(stream->balloc, length));
1168 hd->submit_response(StringRef::from_lit("200"), stream->stream_id, headers,
1174 bool prepare_upload_temp_store(Stream *stream, Http2Handler *hd) {
1175 auto sessions = hd->get_sessions();
1177 char tempfn[] = "/tmp/nghttpd.temp.XXXXXX";
1178 auto fd = mkstemp(tempfn);
1183 // Ordinary request never start with "echo:". The length is 0 for
1184 // now. We will update it when we get whole request body.
1185 auto path = std::string("echo:") + tempfn;
1187 sessions->cache_fd(path, FileEntry(path, 0, 0, fd, nullptr, 0, true));
1188 stream->echo_upload = true;
1194 void prepare_redirect_response(Stream *stream, Http2Handler *hd,
1195 const StringRef &path, int status) {
1196 auto scheme = stream->header.scheme;
1198 auto authority = stream->header.authority;
1199 if (authority.empty()) {
1200 authority = stream->header.host;
1203 auto location = concat_string_ref(
1204 stream->balloc, scheme, StringRef::from_lit("://"), authority, path);
1206 auto headers = HeaderRefs{{StringRef::from_lit("location"), location}};
1208 auto sessions = hd->get_sessions();
1209 auto status_page = sessions->get_server()->get_status_page(status);
1211 hd->submit_response(StringRef{status_page->status}, stream->stream_id,
1217 void prepare_response(Stream *stream, Http2Handler *hd,
1218 bool allow_push = true) {
1220 auto reqpath = stream->header.path;
1221 if (reqpath.empty()) {
1222 prepare_status_response(stream, hd, 405);
1226 auto ims = stream->header.ims;
1228 time_t last_mod = 0;
1229 bool last_mod_found = false;
1231 last_mod_found = true;
1232 last_mod = util::parse_http_date(ims);
1235 StringRef raw_path, raw_query;
1236 auto query_pos = std::find(std::begin(reqpath), std::end(reqpath), '?');
1237 if (query_pos != std::end(reqpath)) {
1238 // Do not response to this request to allow clients to test timeouts.
1239 if (util::streq_l("nghttpd_do_not_respond_to_req=yes",
1240 StringRef{query_pos, std::end(reqpath)})) {
1243 raw_path = StringRef{std::begin(reqpath), query_pos};
1244 raw_query = StringRef{query_pos, std::end(reqpath)};
1249 auto sessions = hd->get_sessions();
1252 if (std::find(std::begin(raw_path), std::end(raw_path), '%') ==
1253 std::end(raw_path)) {
1256 path = util::percent_decode(stream->balloc, raw_path);
1259 path = http2::path_join(stream->balloc, StringRef{}, StringRef{}, path,
1262 if (std::find(std::begin(path), std::end(path), '\\') != std::end(path)) {
1263 if (stream->file_ent) {
1264 sessions->release_fd(stream->file_ent);
1265 stream->file_ent = nullptr;
1267 prepare_status_response(stream, hd, 404);
1271 if (!hd->get_config()->push.empty()) {
1272 auto push_itr = hd->get_config()->push.find(path.str());
1273 if (allow_push && push_itr != std::end(hd->get_config()->push)) {
1274 for (auto &push_path : (*push_itr).second) {
1275 rv = hd->submit_push_promise(stream, StringRef{push_path});
1277 std::cerr << "nghttp2_submit_push_promise() returned error: "
1278 << nghttp2_strerror(rv) << std::endl;
1284 std::string file_path;
1286 auto len = hd->get_config()->htdocs.size() + path.size();
1288 auto trailing_slash = path[path.size() - 1] == '/';
1289 if (trailing_slash) {
1290 len += DEFAULT_HTML.size();
1293 file_path.resize(len);
1295 auto p = &file_path[0];
1297 auto &htdocs = hd->get_config()->htdocs;
1298 p = std::copy(std::begin(htdocs), std::end(htdocs), p);
1299 p = std::copy(std::begin(path), std::end(path), p);
1300 if (trailing_slash) {
1301 std::copy(std::begin(DEFAULT_HTML), std::end(DEFAULT_HTML), p);
1305 if (stream->echo_upload) {
1306 assert(stream->file_ent);
1307 prepare_echo_response(stream, hd);
1311 auto file_ent = sessions->get_cached_fd(file_path);
1313 if (file_ent == nullptr) {
1314 int file = open(file_path.c_str(), O_RDONLY | O_BINARY);
1316 prepare_status_response(stream, hd, 404);
1323 if (fstat(file, &buf) == -1) {
1325 prepare_status_response(stream, hd, 404);
1330 if (buf.st_mode & S_IFDIR) {
1333 auto reqpath = concat_string_ref(stream->balloc, raw_path,
1334 StringRef::from_lit("/"), raw_query);
1336 prepare_redirect_response(stream, hd, reqpath, 301);
1341 const std::string *content_type = nullptr;
1343 auto ext = file_path.c_str() + file_path.size() - 1;
1344 for (; file_path.c_str() < ext && *ext != '.' && *ext != '/'; --ext)
1349 const auto &mime_types = hd->get_config()->mime_types;
1350 auto content_type_itr = mime_types.find(ext);
1351 if (content_type_itr != std::end(mime_types)) {
1352 content_type = &(*content_type_itr).second;
1356 file_ent = sessions->cache_fd(
1357 file_path, FileEntry(file_path, buf.st_size, buf.st_mtime, file,
1358 content_type, ev_now(sessions->get_loop())));
1361 stream->file_ent = file_ent;
1363 if (last_mod_found && file_ent->mtime <= last_mod) {
1364 hd->submit_response(StringRef::from_lit("304"), stream->stream_id, nullptr);
1369 auto method = stream->header.method;
1370 if (method == StringRef::from_lit("HEAD")) {
1371 hd->submit_file_response(StringRef::from_lit("200"), stream,
1372 file_ent->mtime, file_ent->length,
1373 file_ent->content_type, nullptr);
1377 stream->body_length = file_ent->length;
1379 nghttp2_data_provider data_prd;
1381 data_prd.source.fd = file_ent->fd;
1382 data_prd.read_callback = file_read_callback;
1384 hd->submit_file_response(StringRef::from_lit("200"), stream, file_ent->mtime,
1385 file_ent->length, file_ent->content_type, &data_prd);
1390 int on_header_callback2(nghttp2_session *session, const nghttp2_frame *frame,
1391 nghttp2_rcbuf *name, nghttp2_rcbuf *value,
1392 uint8_t flags, void *user_data) {
1393 auto hd = static_cast<Http2Handler *>(user_data);
1395 auto namebuf = nghttp2_rcbuf_get_buf(name);
1396 auto valuebuf = nghttp2_rcbuf_get_buf(value);
1398 if (hd->get_config()->verbose) {
1399 print_session_id(hd->session_id());
1400 verbose_on_header_callback(session, frame, namebuf.base, namebuf.len,
1401 valuebuf.base, valuebuf.len, flags, user_data);
1403 if (frame->hd.type != NGHTTP2_HEADERS ||
1404 frame->headers.cat != NGHTTP2_HCAT_REQUEST) {
1407 auto stream = hd->get_stream(frame->hd.stream_id);
1412 if (stream->header_buffer_size + namebuf.len + valuebuf.len > 64_k) {
1413 hd->submit_rst_stream(stream, NGHTTP2_INTERNAL_ERROR);
1417 stream->header_buffer_size += namebuf.len + valuebuf.len;
1419 auto token = http2::lookup_token(namebuf.base, namebuf.len);
1421 auto &header = stream->header;
1424 case http2::HD__METHOD:
1425 header.method = StringRef{valuebuf.base, valuebuf.len};
1426 header.rcbuf.method = value;
1427 nghttp2_rcbuf_incref(value);
1429 case http2::HD__SCHEME:
1430 header.scheme = StringRef{valuebuf.base, valuebuf.len};
1431 header.rcbuf.scheme = value;
1432 nghttp2_rcbuf_incref(value);
1434 case http2::HD__AUTHORITY:
1435 header.authority = StringRef{valuebuf.base, valuebuf.len};
1436 header.rcbuf.authority = value;
1437 nghttp2_rcbuf_incref(value);
1439 case http2::HD_HOST:
1440 header.host = StringRef{valuebuf.base, valuebuf.len};
1441 header.rcbuf.host = value;
1442 nghttp2_rcbuf_incref(value);
1444 case http2::HD__PATH:
1445 header.path = StringRef{valuebuf.base, valuebuf.len};
1446 header.rcbuf.path = value;
1447 nghttp2_rcbuf_incref(value);
1449 case http2::HD_IF_MODIFIED_SINCE:
1450 header.ims = StringRef{valuebuf.base, valuebuf.len};
1451 header.rcbuf.ims = value;
1452 nghttp2_rcbuf_incref(value);
1454 case http2::HD_EXPECT:
1455 header.expect = StringRef{valuebuf.base, valuebuf.len};
1456 header.rcbuf.expect = value;
1457 nghttp2_rcbuf_incref(value);
1466 int on_begin_headers_callback(nghttp2_session *session,
1467 const nghttp2_frame *frame, void *user_data) {
1468 auto hd = static_cast<Http2Handler *>(user_data);
1470 if (frame->hd.type != NGHTTP2_HEADERS ||
1471 frame->headers.cat != NGHTTP2_HCAT_REQUEST) {
1475 auto stream = std::make_unique<Stream>(hd, frame->hd.stream_id);
1477 add_stream_read_timeout(stream.get());
1479 hd->add_stream(frame->hd.stream_id, std::move(stream));
1486 int hd_on_frame_recv_callback(nghttp2_session *session,
1487 const nghttp2_frame *frame, void *user_data) {
1488 auto hd = static_cast<Http2Handler *>(user_data);
1489 if (hd->get_config()->verbose) {
1490 print_session_id(hd->session_id());
1491 verbose_on_frame_recv_callback(session, frame, user_data);
1493 switch (frame->hd.type) {
1494 case NGHTTP2_DATA: {
1496 auto stream = hd->get_stream(frame->hd.stream_id);
1501 if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1502 remove_stream_read_timeout(stream);
1503 if (stream->echo_upload || !hd->get_config()->early_response) {
1504 prepare_response(stream, hd);
1507 add_stream_read_timeout(stream);
1512 case NGHTTP2_HEADERS: {
1513 auto stream = hd->get_stream(frame->hd.stream_id);
1518 if (frame->headers.cat == NGHTTP2_HCAT_REQUEST) {
1520 auto expect100 = stream->header.expect;
1522 if (util::strieq_l("100-continue", expect100)) {
1523 hd->submit_non_final_response("100", frame->hd.stream_id);
1526 auto method = stream->header.method;
1527 if (hd->get_config()->echo_upload &&
1528 (method == StringRef::from_lit("POST") ||
1529 method == StringRef::from_lit("PUT"))) {
1530 if (!prepare_upload_temp_store(stream, hd)) {
1531 hd->submit_rst_stream(stream, NGHTTP2_INTERNAL_ERROR);
1534 } else if (hd->get_config()->early_response) {
1535 prepare_response(stream, hd);
1539 if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1540 remove_stream_read_timeout(stream);
1541 if (stream->echo_upload || !hd->get_config()->early_response) {
1542 prepare_response(stream, hd);
1545 add_stream_read_timeout(stream);
1550 case NGHTTP2_SETTINGS:
1551 if (frame->hd.flags & NGHTTP2_FLAG_ACK) {
1552 hd->remove_settings_timer();
1563 int hd_on_frame_send_callback(nghttp2_session *session,
1564 const nghttp2_frame *frame, void *user_data) {
1565 auto hd = static_cast<Http2Handler *>(user_data);
1567 if (hd->get_config()->verbose) {
1568 print_session_id(hd->session_id());
1569 verbose_on_frame_send_callback(session, frame, user_data);
1572 switch (frame->hd.type) {
1574 case NGHTTP2_HEADERS: {
1575 auto stream = hd->get_stream(frame->hd.stream_id);
1581 if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1582 remove_stream_write_timeout(stream);
1583 } else if (std::min(nghttp2_session_get_stream_remote_window_size(
1584 session, frame->hd.stream_id),
1585 nghttp2_session_get_remote_window_size(session)) <= 0) {
1586 // If stream is blocked by flow control, enable write timeout.
1587 add_stream_read_timeout_if_pending(stream);
1588 add_stream_write_timeout(stream);
1590 add_stream_read_timeout_if_pending(stream);
1591 remove_stream_write_timeout(stream);
1596 case NGHTTP2_SETTINGS: {
1597 if (frame->hd.flags & NGHTTP2_FLAG_ACK) {
1601 hd->start_settings_timer();
1605 case NGHTTP2_PUSH_PROMISE: {
1606 auto promised_stream_id = frame->push_promise.promised_stream_id;
1607 auto promised_stream = hd->get_stream(promised_stream_id);
1608 auto stream = hd->get_stream(frame->hd.stream_id);
1610 if (!stream || !promised_stream) {
1614 add_stream_read_timeout_if_pending(stream);
1615 add_stream_write_timeout(stream);
1617 prepare_response(promised_stream, hd, /*allow_push */ false);
1625 int send_data_callback(nghttp2_session *session, nghttp2_frame *frame,
1626 const uint8_t *framehd, size_t length,
1627 nghttp2_data_source *source, void *user_data) {
1628 auto hd = static_cast<Http2Handler *>(user_data);
1629 auto wb = hd->get_wb();
1630 auto padlen = frame->data.padlen;
1631 auto stream = hd->get_stream(frame->hd.stream_id);
1633 if (wb->wleft() < 9 + length + padlen) {
1634 return NGHTTP2_ERR_WOULDBLOCK;
1637 int fd = source->fd;
1641 p = std::copy_n(framehd, 9, p);
1649 while ((nread = pread(fd, p, length, stream->body_offset)) == -1 &&
1654 remove_stream_read_timeout(stream);
1655 remove_stream_write_timeout(stream);
1657 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
1660 stream->body_offset += nread;
1666 std::fill(p, p + padlen - 1, 0);
1677 ssize_t select_padding_callback(nghttp2_session *session,
1678 const nghttp2_frame *frame, size_t max_payload,
1680 auto hd = static_cast<Http2Handler *>(user_data);
1681 return std::min(max_payload, frame->hd.length + hd->get_config()->padding);
1686 int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags,
1687 int32_t stream_id, const uint8_t *data,
1688 size_t len, void *user_data) {
1689 auto hd = static_cast<Http2Handler *>(user_data);
1690 auto stream = hd->get_stream(stream_id);
1696 if (stream->echo_upload) {
1697 assert(stream->file_ent);
1700 while ((n = write(stream->file_ent->fd, data, len)) == -1 &&
1704 hd->submit_rst_stream(stream, NGHTTP2_INTERNAL_ERROR);
1713 add_stream_read_timeout(stream);
1720 int on_stream_close_callback(nghttp2_session *session, int32_t stream_id,
1721 uint32_t error_code, void *user_data) {
1722 auto hd = static_cast<Http2Handler *>(user_data);
1723 hd->remove_stream(stream_id);
1724 if (hd->get_config()->verbose) {
1725 print_session_id(hd->session_id());
1727 printf(" stream_id=%d closed\n", stream_id);
1735 void fill_callback(nghttp2_session_callbacks *callbacks, const Config *config) {
1736 nghttp2_session_callbacks_set_on_stream_close_callback(
1737 callbacks, on_stream_close_callback);
1739 nghttp2_session_callbacks_set_on_frame_recv_callback(
1740 callbacks, hd_on_frame_recv_callback);
1742 nghttp2_session_callbacks_set_on_frame_send_callback(
1743 callbacks, hd_on_frame_send_callback);
1745 if (config->verbose) {
1746 nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(
1747 callbacks, verbose_on_invalid_frame_recv_callback);
1749 nghttp2_session_callbacks_set_error_callback2(callbacks,
1750 verbose_error_callback);
1753 nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
1754 callbacks, on_data_chunk_recv_callback);
1756 nghttp2_session_callbacks_set_on_header_callback2(callbacks,
1757 on_header_callback2);
1759 nghttp2_session_callbacks_set_on_begin_headers_callback(
1760 callbacks, on_begin_headers_callback);
1762 nghttp2_session_callbacks_set_send_data_callback(callbacks,
1763 send_data_callback);
1765 if (config->padding) {
1766 nghttp2_session_callbacks_set_select_padding_callback(
1767 callbacks, select_padding_callback);
1777 std::unique_ptr<Sessions> sessions;
1781 std::deque<ClientInfo> q;
1785 void worker_acceptcb(struct ev_loop *loop, ev_async *w, int revents) {
1786 auto worker = static_cast<Worker *>(w->data);
1787 auto &sessions = worker->sessions;
1789 std::deque<ClientInfo> q;
1791 std::lock_guard<std::mutex> lock(worker->m);
1796 sessions->accept_connection(c.fd);
1802 void run_worker(Worker *worker) {
1803 auto loop = worker->sessions->get_loop();
1810 int get_ev_loop_flags() {
1811 if (ev_supported_backends() & ~ev_recommended_backends() & EVBACKEND_KQUEUE) {
1812 return ev_recommended_backends() | EVBACKEND_KQUEUE;
1819 class AcceptHandler {
1821 AcceptHandler(HttpServer *sv, Sessions *sessions, const Config *config)
1822 : sessions_(sessions), config_(config), next_worker_(0) {
1823 if (config_->num_worker == 1) {
1826 for (size_t i = 0; i < config_->num_worker; ++i) {
1827 if (config_->verbose) {
1828 std::cerr << "spawning thread #" << i << std::endl;
1830 auto worker = std::make_unique<Worker>();
1831 auto loop = ev_loop_new(get_ev_loop_flags());
1832 worker->sessions = std::make_unique<Sessions>(sv, loop, config_,
1833 sessions_->get_ssl_ctx());
1834 ev_async_init(&worker->w, worker_acceptcb);
1835 worker->w.data = worker.get();
1836 ev_async_start(loop, &worker->w);
1838 auto t = std::thread(run_worker, worker.get());
1840 workers_.push_back(std::move(worker));
1843 void accept_connection(int fd) {
1844 if (config_->num_worker == 1) {
1845 sessions_->accept_connection(fd);
1849 // Dispatch client to the one of the worker threads, in a round
1851 auto &worker = workers_[next_worker_];
1852 if (next_worker_ == config_->num_worker - 1) {
1858 std::lock_guard<std::mutex> lock(worker->m);
1859 worker->q.push_back({fd});
1861 ev_async_send(worker->sessions->get_loop(), &worker->w);
1865 std::vector<std::unique_ptr<Worker>> workers_;
1866 Sessions *sessions_;
1867 const Config *config_;
1868 // In multi threading mode, this points to the next thread that
1869 // client will be dispatched.
1870 size_t next_worker_;
1874 void acceptcb(struct ev_loop *loop, ev_io *w, int revents);
1877 class ListenEventHandler {
1879 ListenEventHandler(Sessions *sessions, int fd,
1880 std::shared_ptr<AcceptHandler> acceptor)
1881 : acceptor_(acceptor), sessions_(sessions), fd_(fd) {
1882 ev_io_init(&w_, acceptcb, fd, EV_READ);
1884 ev_io_start(sessions_->get_loop(), &w_);
1886 void accept_connection() {
1889 auto fd = accept4(fd_, nullptr, nullptr, SOCK_NONBLOCK);
1890 #else // !HAVE_ACCEPT4
1891 auto fd = accept(fd_, nullptr, nullptr);
1892 #endif // !HAVE_ACCEPT4
1896 #ifndef HAVE_ACCEPT4
1897 util::make_socket_nonblocking(fd);
1898 #endif // !HAVE_ACCEPT4
1899 acceptor_->accept_connection(fd);
1905 std::shared_ptr<AcceptHandler> acceptor_;
1906 Sessions *sessions_;
1911 void acceptcb(struct ev_loop *loop, ev_io *w, int revents) {
1912 auto handler = static_cast<ListenEventHandler *>(w->data);
1913 handler->accept_connection();
1918 FileEntry make_status_body(int status, uint16_t port) {
1919 BlockAllocator balloc(1024, 1024);
1921 auto status_string = http2::stringify_status(balloc, status);
1922 auto reason_pharase = http2::get_reason_phrase(status);
1925 body = "<html><head><title>";
1926 body += status_string;
1928 body += reason_pharase;
1929 body += "</title></head><body><h1>";
1930 body += status_string;
1932 body += reason_pharase;
1933 body += "</h1><hr><address>";
1934 body += NGHTTPD_SERVER;
1935 body += " at port ";
1936 body += util::utos(port);
1937 body += "</address>";
1938 body += "</body></html>";
1940 char tempfn[] = "/tmp/nghttpd.temp.XXXXXX";
1941 int fd = mkstemp(tempfn);
1944 std::cerr << "Could not open status response body file: errno=" << error;
1949 while ((nwrite = write(fd, body.c_str(), body.size())) == -1 &&
1954 std::cerr << "Could not write status response body into file: errno="
1959 return FileEntry(util::utos(status), nwrite, 0, fd, nullptr, 0);
1963 // index into HttpServer::status_pages_
1972 HttpServer::HttpServer(const Config *config) : config_(config) {
1973 status_pages_ = std::vector<StatusPage>{
1974 {"200", make_status_body(200, config_->port)},
1975 {"301", make_status_body(301, config_->port)},
1976 {"400", make_status_body(400, config_->port)},
1977 {"404", make_status_body(404, config_->port)},
1978 {"405", make_status_body(405, config_->port)},
1982 #ifndef OPENSSL_NO_NEXTPROTONEG
1984 int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len,
1986 auto next_proto = static_cast<std::vector<unsigned char> *>(arg);
1987 *data = next_proto->data();
1988 *len = next_proto->size();
1989 return SSL_TLSEXT_ERR_OK;
1992 #endif // !OPENSSL_NO_NEXTPROTONEG
1995 int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
1996 // We don't verify the client certificate. Just request it for the
2003 int start_listen(HttpServer *sv, struct ev_loop *loop, Sessions *sessions,
2004 const Config *config) {
2007 const char *addr = nullptr;
2009 std::shared_ptr<AcceptHandler> acceptor;
2010 auto service = util::utos(config->port);
2013 hints.ai_family = AF_UNSPEC;
2014 hints.ai_socktype = SOCK_STREAM;
2015 hints.ai_flags = AI_PASSIVE;
2016 #ifdef AI_ADDRCONFIG
2017 hints.ai_flags |= AI_ADDRCONFIG;
2018 #endif // AI_ADDRCONFIG
2020 if (!config->address.empty()) {
2021 addr = config->address.c_str();
2025 r = getaddrinfo(addr, service.c_str(), &hints, &res);
2027 std::cerr << "getaddrinfo() failed: " << gai_strerror(r) << std::endl;
2031 for (rp = res; rp; rp = rp->ai_next) {
2032 int fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2037 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val,
2038 static_cast<socklen_t>(sizeof(val))) == -1) {
2042 (void)util::make_socket_nonblocking(fd);
2044 if (rp->ai_family == AF_INET6) {
2045 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &val,
2046 static_cast<socklen_t>(sizeof(val))) == -1) {
2051 #endif // IPV6_V6ONLY
2052 if (bind(fd, rp->ai_addr, rp->ai_addrlen) == 0 && listen(fd, 1000) == 0) {
2054 acceptor = std::make_shared<AcceptHandler>(sv, sessions, config);
2056 new ListenEventHandler(sessions, fd, acceptor);
2058 if (config->verbose) {
2059 std::string s = util::numeric_name(rp->ai_addr, rp->ai_addrlen);
2060 std::cout << (rp->ai_family == AF_INET ? "IPv4" : "IPv6") << ": listen "
2061 << s << ":" << config->port << std::endl;
2066 std::cerr << strerror(errno) << std::endl;
2079 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2081 int alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
2082 unsigned char *outlen, const unsigned char *in,
2083 unsigned int inlen, void *arg) {
2084 auto config = static_cast<HttpServer *>(arg)->get_config();
2085 if (config->verbose) {
2086 std::cout << "[ALPN] client offers:" << std::endl;
2088 if (config->verbose) {
2089 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
2091 std::cout.write(reinterpret_cast<const char *>(&in[i + 1]), in[i]);
2092 std::cout << std::endl;
2095 if (!util::select_h2(out, outlen, in, inlen)) {
2096 return SSL_TLSEXT_ERR_NOACK;
2098 return SSL_TLSEXT_ERR_OK;
2101 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
2103 int HttpServer::run() {
2104 SSL_CTX *ssl_ctx = nullptr;
2105 std::vector<unsigned char> next_proto;
2107 if (!config_->no_tls) {
2108 ssl_ctx = SSL_CTX_new(SSLv23_server_method());
2110 std::cerr << ERR_error_string(ERR_get_error(), nullptr) << std::endl;
2114 auto ssl_opts = (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
2115 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION |
2116 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
2117 SSL_OP_SINGLE_ECDH_USE | SSL_OP_NO_TICKET |
2118 SSL_OP_CIPHER_SERVER_PREFERENCE;
2120 SSL_CTX_set_options(ssl_ctx, ssl_opts);
2121 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
2122 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
2124 if (nghttp2::tls::ssl_ctx_set_proto_versions(
2125 ssl_ctx, nghttp2::tls::NGHTTP2_TLS_MIN_VERSION,
2126 nghttp2::tls::NGHTTP2_TLS_MAX_VERSION) != 0) {
2127 std::cerr << "Could not set TLS versions" << std::endl;
2131 if (SSL_CTX_set_cipher_list(ssl_ctx, tls::DEFAULT_CIPHER_LIST) == 0) {
2132 std::cerr << ERR_error_string(ERR_get_error(), nullptr) << std::endl;
2136 const unsigned char sid_ctx[] = "nghttpd";
2137 SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
2138 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);
2140 #ifndef OPENSSL_NO_EC
2142 // Disabled SSL_CTX_set_ecdh_auto, because computational cost of
2143 // chosen curve is much higher than P-256.
2145 // #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2146 // SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
2147 // #else // OPENSSL_VERSION_NUBMER < 0x10002000L
2148 // Use P-256, which is sufficiently secure at the time of this
2150 auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2151 if (ecdh == nullptr) {
2152 std::cerr << "EC_KEY_new_by_curv_name failed: "
2153 << ERR_error_string(ERR_get_error(), nullptr);
2156 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh);
2158 // #endif // OPENSSL_VERSION_NUBMER < 0x10002000L
2160 #endif // OPENSSL_NO_EC
2162 if (!config_->dh_param_file.empty()) {
2163 // Read DH parameters from file
2164 auto bio = BIO_new_file(config_->dh_param_file.c_str(), "r");
2165 if (bio == nullptr) {
2166 std::cerr << "BIO_new_file() failed: "
2167 << ERR_error_string(ERR_get_error(), nullptr) << std::endl;
2171 auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
2173 if (dh == nullptr) {
2174 std::cerr << "PEM_read_bio_DHparams() failed: "
2175 << ERR_error_string(ERR_get_error(), nullptr) << std::endl;
2179 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
2184 if (SSL_CTX_use_PrivateKey_file(ssl_ctx, config_->private_key_file.c_str(),
2185 SSL_FILETYPE_PEM) != 1) {
2186 std::cerr << "SSL_CTX_use_PrivateKey_file failed." << std::endl;
2189 if (SSL_CTX_use_certificate_chain_file(ssl_ctx,
2190 config_->cert_file.c_str()) != 1) {
2191 std::cerr << "SSL_CTX_use_certificate_file failed." << std::endl;
2194 if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
2195 std::cerr << "SSL_CTX_check_private_key failed." << std::endl;
2198 if (config_->verify_client) {
2199 SSL_CTX_set_verify(ssl_ctx,
2200 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
2201 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2205 next_proto = util::get_default_alpn();
2207 #ifndef OPENSSL_NO_NEXTPROTONEG
2208 SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_proto_cb, &next_proto);
2209 #endif // !OPENSSL_NO_NEXTPROTONEG
2210 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2211 // ALPN selection callback
2212 SSL_CTX_set_alpn_select_cb(ssl_ctx, alpn_select_proto_cb, this);
2213 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
2216 auto loop = EV_DEFAULT;
2218 Sessions sessions(this, loop, config_, ssl_ctx);
2219 if (start_listen(this, loop, &sessions, config_) != 0) {
2220 std::cerr << "Could not listen" << std::endl;
2222 SSL_CTX_free(ssl_ctx);
2231 const Config *HttpServer::get_config() const { return config_; }
2233 const StatusPage *HttpServer::get_status_page(int status) const {
2236 return &status_pages_[IDX_200];
2238 return &status_pages_[IDX_301];
2240 return &status_pages_[IDX_400];
2242 return &status_pages_[IDX_404];
2244 return &status_pages_[IDX_405];
2251 } // namespace nghttp2