Upgrade to 1.46.0
[platform/upstream/nghttp2.git] / src / includes / nghttp2 / asio_http2_server.h
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 #ifndef ASIO_HTTP2_SERVER_H
26 #define ASIO_HTTP2_SERVER_H
27
28 #include <nghttp2/asio_http2.h>
29
30 namespace nghttp2 {
31
32 namespace asio_http2 {
33
34 namespace server {
35
36 class request_impl;
37 class response_impl;
38
39 class request {
40 public:
41   // Application must not call this directly.
42   request();
43   ~request();
44
45   // Returns request header fields.  The pseudo header fields, which
46   // start with colon (:), are excluded from this list.
47   const header_map &header() const;
48
49   // Returns method (e.g., GET).
50   const std::string &method() const;
51
52   // Returns request URI, split into components.
53   const uri_ref &uri() const;
54
55   // Sets callback which is invoked when chunk of request body is
56   // received.
57   void on_data(data_cb cb) const;
58
59   // Application must not call this directly.
60   request_impl &impl() const;
61
62   // Returns the remote endpoint of the request
63   const boost::asio::ip::tcp::endpoint &remote_endpoint() const;
64
65 private:
66   std::unique_ptr<request_impl> impl_;
67 };
68
69 class response {
70 public:
71   // Application must not call this directly.
72   response();
73   ~response();
74
75   // Write response header using |status_code| (e.g., 200) and
76   // additional header fields in |h|.
77   void write_head(unsigned int status_code, header_map h = header_map{}) const;
78
79   // Sends |data| as request body.  No further call of end() is
80   // allowed.
81   void end(std::string data = "") const;
82
83   // Sets callback as a generator of the response body.  No further
84   // call of end() is allowed.
85   void end(generator_cb cb) const;
86
87   // Write trailer part.  This must be called after setting both
88   // NGHTTP2_DATA_FLAG_EOF and NGHTTP2_DATA_FLAG_NO_END_STREAM set in
89   // *data_flag parameter in generator_cb passed to end() function.
90   void write_trailer(header_map h) const;
91
92   // Sets callback which is invoked when this request and response are
93   // finished.  After the invocation of this callback, the application
94   // must not access request and response object.
95   void on_close(close_cb cb) const;
96
97   // Cancels this request and response with given error code.
98   void cancel(uint32_t error_code = NGHTTP2_INTERNAL_ERROR) const;
99
100   // Resumes deferred response.
101   void resume() const;
102
103   // Pushes resource denoted by |raw_path_query| using |method|.  The
104   // additional header fields can be given in |h|.  This function
105   // returns pointer to response object for promised stream, otherwise
106   // nullptr and error code is filled in |ec|.  Be aware that the
107   // header field name given in |h| must be lower-cased.
108   const response *push(boost::system::error_code &ec, std::string method,
109                        std::string raw_path_query,
110                        header_map h = header_map{}) const;
111
112   // Returns status code.
113   unsigned int status_code() const;
114
115   // Returns boost::asio::io_service this response is running on.
116   boost::asio::io_service &io_service() const;
117
118   // Application must not call this directly.
119   response_impl &impl() const;
120
121 private:
122   std::unique_ptr<response_impl> impl_;
123 };
124
125 // This is so called request callback.  Called every time request is
126 // received.  The life time of |request| and |response| objects end
127 // when callback set by response::on_close() is called.  After that,
128 // the application must not access to those objects.
129 typedef std::function<void(const request &, const response &)> request_cb;
130
131 class http2_impl;
132
133 class http2 {
134 public:
135   http2();
136   ~http2();
137
138   http2(http2 &&other) noexcept;
139   http2 &operator=(http2 &&other) noexcept;
140
141   // Starts listening connection on given address and port and serves
142   // incoming requests in cleartext TCP connection.  If |asynchronous|
143   // is false, this function blocks forever unless there is an error.
144   // If it is true, after server has started, this function returns
145   // immediately, and the caller should call stop() and join() to
146   // shutdown server gracefully.
147   boost::system::error_code listen_and_serve(boost::system::error_code &ec,
148                                              const std::string &address,
149                                              const std::string &port,
150                                              bool asynchronous = false);
151
152   // Starts listening connection on given address and port and serves
153   // incoming requests in SSL/TLS encrypted connection.  For
154   // |asynchronous| parameter, see cleartext version
155   // |listen_and_serve|.
156   boost::system::error_code
157   listen_and_serve(boost::system::error_code &ec,
158                    boost::asio::ssl::context &tls_context,
159                    const std::string &address, const std::string &port,
160                    bool asynchronous = false);
161
162   // Registers request handler |cb| with path pattern |pattern|.  This
163   // function will fail and returns false if same pattern has been
164   // already registered or |pattern| is empty string.  Otherwise
165   // returns true.  The pattern match rule is the same as
166   // net/http/ServeMux in golang.  Quoted from golang manual
167   // (http://golang.org/pkg/net/http/#ServeMux):
168   //
169   //   Patterns name fixed, rooted paths, like "/favicon.ico", or
170   //   rooted subtrees, like "/images/" (note the trailing
171   //   slash). Longer patterns take precedence over shorter ones, so
172   //   that if there are handlers registered for both "/images/" and
173   //   "/images/thumbnails/", the latter handler will be called for
174   //   paths beginning "/images/thumbnails/" and the former will
175   //   receive requests for any other paths in the "/images/" subtree.
176   //
177   //   Note that since a pattern ending in a slash names a rooted
178   //   subtree, the pattern "/" matches all paths not matched by other
179   //   registered patterns, not just the URL with Path == "/".
180   //
181   //   Patterns may optionally begin with a host name, restricting
182   //   matches to URLs on that host only. Host-specific patterns take
183   //   precedence over general patterns, so that a handler might
184   //   register for the two patterns "/codesearch" and
185   //   "codesearch.google.com/" without also taking over requests for
186   //   "http://www.google.com/".
187   //
188   // Just like ServeMux in golang, URL request path is sanitized and
189   // if they contains . or .. elements, they are redirected to an
190   // equivalent .- and ..-free URL.
191   bool handle(std::string pattern, request_cb cb);
192
193   // Sets number of native threads to handle incoming HTTP request.
194   // It defaults to 1.
195   void num_threads(size_t num_threads);
196
197   // Sets the maximum length to which the queue of pending
198   // connections.
199   void backlog(int backlog);
200
201   // Sets TLS handshake timeout, which defaults to 60 seconds.
202   void tls_handshake_timeout(const boost::posix_time::time_duration &t);
203
204   // Sets read timeout, which defaults to 60 seconds.
205   void read_timeout(const boost::posix_time::time_duration &t);
206
207   // Gracefully stop http2 server
208   void stop();
209
210   // Join on http2 server and wait for it to fully stop
211   void join();
212
213   // Get access to the io_service objects.
214   const std::vector<std::shared_ptr<boost::asio::io_service>> &
215   io_services() const;
216
217   // Returns a vector with the ports in use
218   std::vector<int> ports() const;
219
220 private:
221   std::unique_ptr<http2_impl> impl_;
222 };
223
224 // Configures |tls_context| for server use.  This function sets couple
225 // of OpenSSL options (disables SSLv2 and SSLv3 and compression) and
226 // enables ECDHE ciphers.  NPN callback is also configured.
227 boost::system::error_code
228 configure_tls_context_easy(boost::system::error_code &ec,
229                            boost::asio::ssl::context &tls_context);
230
231 // Returns request handler to do redirect to |uri| using
232 // |status_code|.  The |uri| appears in "location" header field as is.
233 request_cb redirect_handler(int status_code, std::string uri);
234
235 // Returns request handler to reply with given |status_code| and HTML
236 // including message about status code.
237 request_cb status_handler(int status_code);
238
239 } // namespace server
240
241 } // namespace asio_http2
242
243 } // namespace nghttp2
244
245 #endif // ASIO_HTTP2_SERVER_H