xref: /netbsd-src/external/bsd/libevent/dist/include/event2/http.h (revision 657871a79c9a2060a6255a242fa1a1ef76b56ec6)
1 /*	$NetBSD: http.h,v 1.1.1.4 2021/04/07 02:43:14 christos Exp $	*/
2 /*
3  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
4  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 #ifndef EVENT2_HTTP_H_INCLUDED_
29 #define EVENT2_HTTP_H_INCLUDED_
30 
31 /* For int types. */
32 #include <event2/util.h>
33 #include <event2/visibility.h>
34 
35 #ifdef __cplusplus
36 extern "C" {
37 #endif
38 
39 /* In case we haven't included the right headers yet. */
40 struct evbuffer;
41 struct event_base;
42 struct bufferevent;
43 struct evhttp_connection;
44 
45 /** @file event2/http.h
46  *
47  * Basic support for HTTP serving.
48  *
49  * As Libevent is a library for dealing with event notification and most
50  * interesting applications are networked today, I have often found the
51  * need to write HTTP code.  The following prototypes and definitions provide
52  * an application with a minimal interface for making HTTP requests and for
53  * creating a very simple HTTP server.
54  */
55 
56 /* Response codes */
57 #define HTTP_OK			200	/**< request completed ok */
58 #define HTTP_NOCONTENT		204	/**< request does not have content */
59 #define HTTP_MOVEPERM		301	/**< the uri moved permanently */
60 #define HTTP_MOVETEMP		302	/**< the uri moved temporarily */
61 #define HTTP_NOTMODIFIED	304	/**< page was not modified from last */
62 #define HTTP_BADREQUEST		400	/**< invalid http request was made */
63 #define HTTP_NOTFOUND		404	/**< could not find content for uri */
64 #define HTTP_BADMETHOD		405 	/**< method not allowed for this uri */
65 #define HTTP_ENTITYTOOLARGE	413	/**<  */
66 #define HTTP_EXPECTATIONFAILED	417	/**< we can't handle this expectation */
67 #define HTTP_INTERNAL           500     /**< internal error */
68 #define HTTP_NOTIMPLEMENTED     501     /**< not implemented */
69 #define HTTP_SERVUNAVAIL	503	/**< the server is not available */
70 
71 struct evhttp;
72 struct evhttp_request;
73 struct evkeyvalq;
74 struct evhttp_bound_socket;
75 struct evconnlistener;
76 struct evdns_base;
77 
78 /**
79  * Create a new HTTP server.
80  *
81  * @param base (optional) the event base to receive the HTTP events
82  * @return a pointer to a newly initialized evhttp server structure or NULL
83  *   on error
84  * @see evhttp_free()
85  */
86 EVENT2_EXPORT_SYMBOL
87 struct evhttp *evhttp_new(struct event_base *base);
88 
89 /**
90  * Binds an HTTP server on the specified address and port.
91  *
92  * Can be called multiple times to bind the same http server
93  * to multiple different ports.
94  *
95  * @param http a pointer to an evhttp object
96  * @param address a string containing the IP address to listen(2) on
97  * @param port the port number to listen on
98  * @return 0 on success, -1 on failure.
99  * @see evhttp_accept_socket()
100  */
101 EVENT2_EXPORT_SYMBOL
102 int evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port);
103 
104 /**
105  * Like evhttp_bind_socket(), but returns a handle for referencing the socket.
106  *
107  * The returned pointer is not valid after \a http is freed.
108  *
109  * @param http a pointer to an evhttp object
110  * @param address a string containing the IP address to listen(2) on
111  * @param port the port number to listen on
112  * @return Handle for the socket on success, NULL on failure.
113  * @see evhttp_bind_socket(), evhttp_del_accept_socket()
114  */
115 EVENT2_EXPORT_SYMBOL
116 struct evhttp_bound_socket *evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port);
117 
118 /**
119  * Makes an HTTP server accept connections on the specified socket.
120  *
121  * This may be useful to create a socket and then fork multiple instances
122  * of an http server, or when a socket has been communicated via file
123  * descriptor passing in situations where an http servers does not have
124  * permissions to bind to a low-numbered port.
125  *
126  * Can be called multiple times to have the http server listen to
127  * multiple different sockets.
128  *
129  * @param http a pointer to an evhttp object
130  * @param fd a socket fd that is ready for accepting connections
131  * @return 0 on success, -1 on failure.
132  * @see evhttp_bind_socket()
133  */
134 EVENT2_EXPORT_SYMBOL
135 int evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd);
136 
137 /**
138  * Like evhttp_accept_socket(), but returns a handle for referencing the socket.
139  *
140  * The returned pointer is not valid after \a http is freed.
141  *
142  * @param http a pointer to an evhttp object
143  * @param fd a socket fd that is ready for accepting connections
144  * @return Handle for the socket on success, NULL on failure.
145  * @see evhttp_accept_socket(), evhttp_del_accept_socket()
146  */
147 EVENT2_EXPORT_SYMBOL
148 struct evhttp_bound_socket *evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd);
149 
150 /**
151  * The most low-level evhttp_bind/accept method: takes an evconnlistener, and
152  * returns an evhttp_bound_socket.  The listener will be freed when the bound
153  * socket is freed.
154  */
155 EVENT2_EXPORT_SYMBOL
156 struct evhttp_bound_socket *evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener);
157 
158 /**
159  * Return the listener used to implement a bound socket.
160  */
161 EVENT2_EXPORT_SYMBOL
162 struct evconnlistener *evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound);
163 
164 typedef void evhttp_bound_socket_foreach_fn(struct evhttp_bound_socket *, void *);
165 /**
166  * Applies the function specified in the first argument to all
167  * evhttp_bound_sockets associated with "http". The user must not
168  * attempt to free or remove any connections, sockets or listeners
169  * in the callback "function".
170  *
171  * @param http pointer to an evhttp object
172  * @param function function to apply to every bound socket
173  * @param argument pointer value passed to function for every socket iterated
174  */
175 EVENT2_EXPORT_SYMBOL
176 void evhttp_foreach_bound_socket(struct evhttp *http, evhttp_bound_socket_foreach_fn *function, void *argument);
177 
178 /**
179  * Makes an HTTP server stop accepting connections on the specified socket
180  *
181  * This may be useful when a socket has been sent via file descriptor passing
182  * and is no longer needed by the current process.
183  *
184  * If you created this bound socket with evhttp_bind_socket_with_handle or
185  * evhttp_accept_socket_with_handle, this function closes the fd you provided.
186  * If you created this bound socket with evhttp_bind_listener, this function
187  * frees the listener you provided.
188  *
189  * \a bound_socket is an invalid pointer after this call returns.
190  *
191  * @param http a pointer to an evhttp object
192  * @param bound_socket a handle returned by evhttp_{bind,accept}_socket_with_handle
193  * @see evhttp_bind_socket_with_handle(), evhttp_accept_socket_with_handle()
194  */
195 EVENT2_EXPORT_SYMBOL
196 void evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound_socket);
197 
198 /**
199  * Get the raw file descriptor referenced by an evhttp_bound_socket.
200  *
201  * @param bound_socket a handle returned by evhttp_{bind,accept}_socket_with_handle
202  * @return the file descriptor used by the bound socket
203  * @see evhttp_bind_socket_with_handle(), evhttp_accept_socket_with_handle()
204  */
205 EVENT2_EXPORT_SYMBOL
206 evutil_socket_t evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound_socket);
207 
208 /**
209  * Free the previously created HTTP server.
210  *
211  * Works only if no requests are currently being served.
212  *
213  * @param http the evhttp server object to be freed
214  * @see evhttp_start()
215  */
216 EVENT2_EXPORT_SYMBOL
217 void evhttp_free(struct evhttp* http);
218 
219 /** XXX Document. */
220 EVENT2_EXPORT_SYMBOL
221 void evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size);
222 /** XXX Document. */
223 EVENT2_EXPORT_SYMBOL
224 void evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size);
225 
226 /**
227   Set the value to use for the Content-Type header when none was provided. If
228   the content type string is NULL, the Content-Type header will not be
229   automatically added.
230 
231   @param http the http server on which to set the default content type
232   @param content_type the value for the Content-Type header
233 */
234 EVENT2_EXPORT_SYMBOL
235 void evhttp_set_default_content_type(struct evhttp *http,
236 	const char *content_type);
237 
238 /**
239   Sets the what HTTP methods are supported in requests accepted by this
240   server, and passed to user callbacks.
241 
242   If not supported they will generate a "405 Method not allowed" response.
243 
244   By default this includes the following methods: GET, POST, HEAD, PUT, DELETE
245 
246   @param http the http server on which to set the methods
247   @param methods bit mask constructed from evhttp_cmd_type values
248 */
249 EVENT2_EXPORT_SYMBOL
250 void evhttp_set_allowed_methods(struct evhttp* http, ev_uint16_t methods);
251 
252 /**
253    Set a callback for a specified URI
254 
255    @param http the http sever on which to set the callback
256    @param path the path for which to invoke the callback
257    @param cb the callback function that gets invoked on requesting path
258    @param cb_arg an additional context argument for the callback
259    @return 0 on success, -1 if the callback existed already, -2 on failure
260 */
261 EVENT2_EXPORT_SYMBOL
262 int evhttp_set_cb(struct evhttp *http, const char *path,
263     void (*cb)(struct evhttp_request *, void *), void *cb_arg);
264 
265 /** Removes the callback for a specified URI */
266 EVENT2_EXPORT_SYMBOL
267 int evhttp_del_cb(struct evhttp *, const char *);
268 
269 /**
270     Set a callback for all requests that are not caught by specific callbacks
271 
272     Invokes the specified callback for all requests that do not match any of
273     the previously specified request paths.  This is catchall for requests not
274     specifically configured with evhttp_set_cb().
275 
276     @param http the evhttp server object for which to set the callback
277     @param cb the callback to invoke for any unmatched requests
278     @param arg an context argument for the callback
279 */
280 EVENT2_EXPORT_SYMBOL
281 void evhttp_set_gencb(struct evhttp *http,
282     void (*cb)(struct evhttp_request *, void *), void *arg);
283 
284 /**
285    Set a callback used to create new bufferevents for connections
286    to a given evhttp object.
287 
288    You can use this to override the default bufferevent type -- for example,
289    to make this evhttp object use SSL bufferevents rather than unencrypted
290    ones.
291 
292    New bufferevents must be allocated with no fd set on them.
293 
294    @param http the evhttp server object for which to set the callback
295    @param cb the callback to invoke for incoming connections
296    @param arg an context argument for the callback
297  */
298 EVENT2_EXPORT_SYMBOL
299 void evhttp_set_bevcb(struct evhttp *http,
300     struct bufferevent *(*cb)(struct event_base *, void *), void *arg);
301 
302 /**
303    Adds a virtual host to the http server.
304 
305    A virtual host is a newly initialized evhttp object that has request
306    callbacks set on it via evhttp_set_cb() or evhttp_set_gencb().  It
307    most not have any listing sockets associated with it.
308 
309    If the virtual host has not been removed by the time that evhttp_free()
310    is called on the main http server, it will be automatically freed, too.
311 
312    It is possible to have hierarchical vhosts.  For example: A vhost
313    with the pattern *.example.com may have other vhosts with patterns
314    foo.example.com and bar.example.com associated with it.
315 
316    @param http the evhttp object to which to add a virtual host
317    @param pattern the glob pattern against which the hostname is matched.
318      The match is case insensitive and follows otherwise regular shell
319      matching.
320    @param vhost the virtual host to add the regular http server.
321    @return 0 on success, -1 on failure
322    @see evhttp_remove_virtual_host()
323 */
324 EVENT2_EXPORT_SYMBOL
325 int evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
326     struct evhttp* vhost);
327 
328 /**
329    Removes a virtual host from the http server.
330 
331    @param http the evhttp object from which to remove the virtual host
332    @param vhost the virtual host to remove from the regular http server.
333    @return 0 on success, -1 on failure
334    @see evhttp_add_virtual_host()
335 */
336 EVENT2_EXPORT_SYMBOL
337 int evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost);
338 
339 /**
340    Add a server alias to an http object. The http object can be a virtual
341    host or the main server.
342 
343    @param http the evhttp object
344    @param alias the alias to add
345    @see evhttp_add_remove_alias()
346 */
347 EVENT2_EXPORT_SYMBOL
348 int evhttp_add_server_alias(struct evhttp *http, const char *alias);
349 
350 /**
351    Remove a server alias from an http object.
352 
353    @param http the evhttp object
354    @param alias the alias to remove
355    @see evhttp_add_server_alias()
356 */
357 EVENT2_EXPORT_SYMBOL
358 int evhttp_remove_server_alias(struct evhttp *http, const char *alias);
359 
360 /**
361  * Set the timeout for an HTTP request.
362  *
363  * @param http an evhttp object
364  * @param timeout_in_secs the timeout, in seconds
365  */
366 EVENT2_EXPORT_SYMBOL
367 void evhttp_set_timeout(struct evhttp *http, int timeout_in_secs);
368 
369 /**
370  * Set the timeout for an HTTP request.
371  *
372  * @param http an evhttp object
373  * @param tv the timeout, or NULL
374  */
375 EVENT2_EXPORT_SYMBOL
376 void evhttp_set_timeout_tv(struct evhttp *http, const struct timeval* tv);
377 
378 /* Read all the clients body, and only after this respond with an error if the
379  * clients body exceed max_body_size */
380 #define EVHTTP_SERVER_LINGERING_CLOSE	0x0001
381 /**
382  * Set connection flags for HTTP server.
383  *
384  * @see EVHTTP_SERVER_*
385  * @return 0 on success, otherwise non zero (for example if flag doesn't
386  * supported).
387  */
388 EVENT2_EXPORT_SYMBOL
389 int evhttp_set_flags(struct evhttp *http, int flags);
390 
391 /* Request/Response functionality */
392 
393 /**
394  * Send an HTML error message to the client.
395  *
396  * @param req a request object
397  * @param error the HTTP error code
398  * @param reason a brief explanation of the error.  If this is NULL, we'll
399  *    just use the standard meaning of the error code.
400  */
401 EVENT2_EXPORT_SYMBOL
402 void evhttp_send_error(struct evhttp_request *req, int error,
403     const char *reason);
404 
405 /**
406  * Send an HTML reply to the client.
407  *
408  * The body of the reply consists of the data in databuf.  After calling
409  * evhttp_send_reply() databuf will be empty, but the buffer is still
410  * owned by the caller and needs to be deallocated by the caller if
411  * necessary.
412  *
413  * @param req a request object
414  * @param code the HTTP response code to send
415  * @param reason a brief message to send with the response code
416  * @param databuf the body of the response
417  */
418 EVENT2_EXPORT_SYMBOL
419 void evhttp_send_reply(struct evhttp_request *req, int code,
420     const char *reason, struct evbuffer *databuf);
421 
422 /* Low-level response interface, for streaming/chunked replies */
423 
424 /**
425    Initiate a reply that uses Transfer-Encoding chunked.
426 
427    This allows the caller to stream the reply back to the client and is
428    useful when either not all of the reply data is immediately available
429    or when sending very large replies.
430 
431    The caller needs to supply data chunks with evhttp_send_reply_chunk()
432    and complete the reply by calling evhttp_send_reply_end().
433 
434    @param req a request object
435    @param code the HTTP response code to send
436    @param reason a brief message to send with the response code
437 */
438 EVENT2_EXPORT_SYMBOL
439 void evhttp_send_reply_start(struct evhttp_request *req, int code,
440     const char *reason);
441 
442 /**
443    Send another data chunk as part of an ongoing chunked reply.
444 
445    The reply chunk consists of the data in databuf.  After calling
446    evhttp_send_reply_chunk() databuf will be empty, but the buffer is
447    still owned by the caller and needs to be deallocated by the caller
448    if necessary.
449 
450    @param req a request object
451    @param databuf the data chunk to send as part of the reply.
452 */
453 EVENT2_EXPORT_SYMBOL
454 void evhttp_send_reply_chunk(struct evhttp_request *req,
455     struct evbuffer *databuf);
456 
457 /**
458    Send another data chunk as part of an ongoing chunked reply.
459 
460    The reply chunk consists of the data in databuf.  After calling
461    evhttp_send_reply_chunk() databuf will be empty, but the buffer is
462    still owned by the caller and needs to be deallocated by the caller
463    if necessary.
464 
465    @param req a request object
466    @param databuf the data chunk to send as part of the reply.
467    @param cb callback funcion
468    @param call back's argument.
469 */
470 EVENT2_EXPORT_SYMBOL
471 void evhttp_send_reply_chunk_with_cb(struct evhttp_request *, struct evbuffer *,
472     void (*cb)(struct evhttp_connection *, void *), void *arg);
473 
474 /**
475    Complete a chunked reply, freeing the request as appropriate.
476 
477    @param req a request object
478 */
479 EVENT2_EXPORT_SYMBOL
480 void evhttp_send_reply_end(struct evhttp_request *req);
481 
482 /*
483  * Interfaces for making requests
484  */
485 
486 /** The different request types supported by evhttp.  These are as specified
487  * in RFC2616, except for PATCH which is specified by RFC5789.
488  *
489  * By default, only some of these methods are accepted and passed to user
490  * callbacks; use evhttp_set_allowed_methods() to change which methods
491  * are allowed.
492  */
493 enum evhttp_cmd_type {
494 	EVHTTP_REQ_GET     = 1 << 0,
495 	EVHTTP_REQ_POST    = 1 << 1,
496 	EVHTTP_REQ_HEAD    = 1 << 2,
497 	EVHTTP_REQ_PUT     = 1 << 3,
498 	EVHTTP_REQ_DELETE  = 1 << 4,
499 	EVHTTP_REQ_OPTIONS = 1 << 5,
500 	EVHTTP_REQ_TRACE   = 1 << 6,
501 	EVHTTP_REQ_CONNECT = 1 << 7,
502 	EVHTTP_REQ_PATCH   = 1 << 8
503 };
504 
505 /** a request object can represent either a request or a reply */
506 enum evhttp_request_kind { EVHTTP_REQUEST, EVHTTP_RESPONSE };
507 
508 /**
509  * Create and return a connection object that can be used to for making HTTP
510  * requests.  The connection object tries to resolve address and establish the
511  * connection when it is given an http request object.
512  *
513  * @param base the event_base to use for handling the connection
514  * @param dnsbase the dns_base to use for resolving host names; if not
515  *     specified host name resolution will block.
516  * @param bev a bufferevent to use for connecting to the server; if NULL, a
517  *     socket-based bufferevent will be created.  This buffrevent will be freed
518  *     when the connection closes.  It must have no fd set on it.
519  * @param address the address to which to connect
520  * @param port the port to connect to
521  * @return an evhttp_connection object that can be used for making requests or
522  *   NULL on error
523  */
524 EVENT2_EXPORT_SYMBOL
525 struct evhttp_connection *evhttp_connection_base_bufferevent_new(
526 	struct event_base *base, struct evdns_base *dnsbase, struct bufferevent* bev, const char *address, ev_uint16_t port);
527 
528 /**
529  * Return the bufferevent that an evhttp_connection is using.
530  */
531 EVENT2_EXPORT_SYMBOL
532 struct bufferevent* evhttp_connection_get_bufferevent(struct evhttp_connection *evcon);
533 
534 /**
535  * Return the HTTP server associated with this connection, or NULL.
536  */
537 EVENT2_EXPORT_SYMBOL
538 struct evhttp *evhttp_connection_get_server(struct evhttp_connection *evcon);
539 
540 /**
541  * Creates a new request object that needs to be filled in with the request
542  * parameters.  The callback is executed when the request completed or an
543  * error occurred.
544  */
545 EVENT2_EXPORT_SYMBOL
546 struct evhttp_request *evhttp_request_new(
547 	void (*cb)(struct evhttp_request *, void *), void *arg);
548 
549 /**
550  * Enable delivery of chunks to requestor.
551  * @param cb will be called after every read of data with the same argument
552  *           as the completion callback. Will never be called on an empty
553  *           response. May drain the input buffer; it will be drained
554  *           automatically on return.
555  */
556 EVENT2_EXPORT_SYMBOL
557 void evhttp_request_set_chunked_cb(struct evhttp_request *,
558     void (*cb)(struct evhttp_request *, void *));
559 
560 /**
561  * Register callback for additional parsing of request headers.
562  * @param cb will be called after receiving and parsing the full header.
563  * It allows analyzing the header and possibly closing the connection
564  * by returning a value < 0.
565  */
566 EVENT2_EXPORT_SYMBOL
567 void evhttp_request_set_header_cb(struct evhttp_request *,
568     int (*cb)(struct evhttp_request *, void *));
569 
570 /**
571  * The different error types supported by evhttp
572  *
573  * @see evhttp_request_set_error_cb()
574  */
575 enum evhttp_request_error {
576   /**
577    * Timeout reached, also @see evhttp_connection_set_timeout()
578    */
579   EVREQ_HTTP_TIMEOUT,
580   /**
581    * EOF reached
582    */
583   EVREQ_HTTP_EOF,
584   /**
585    * Error while reading header, or invalid header
586    */
587   EVREQ_HTTP_INVALID_HEADER,
588   /**
589    * Error encountered while reading or writing
590    */
591   EVREQ_HTTP_BUFFER_ERROR,
592   /**
593    * The evhttp_cancel_request() called on this request.
594    */
595   EVREQ_HTTP_REQUEST_CANCEL,
596   /**
597    * Body is greater then evhttp_connection_set_max_body_size()
598    */
599   EVREQ_HTTP_DATA_TOO_LONG
600 };
601 /**
602  * Set a callback for errors
603  * @see evhttp_request_error for error types.
604  *
605  * On error, both the error callback and the regular callback will be called,
606  * error callback is called before the regular callback.
607  **/
608 EVENT2_EXPORT_SYMBOL
609 void evhttp_request_set_error_cb(struct evhttp_request *,
610     void (*)(enum evhttp_request_error, void *));
611 
612 /**
613  * Set a callback to be called on request completion of evhttp_send_* function.
614  *
615  * The callback function will be called on the completion of the request after
616  * the output data has been written and before the evhttp_request object
617  * is destroyed. This can be useful for tracking resources associated with a
618  * request (ex: timing metrics).
619  *
620  * @param req a request object
621  * @param cb callback function that will be called on request completion
622  * @param cb_arg an additional context argument for the callback
623  */
624 EVENT2_EXPORT_SYMBOL
625 void evhttp_request_set_on_complete_cb(struct evhttp_request *req,
626     void (*cb)(struct evhttp_request *, void *), void *cb_arg);
627 
628 /** Frees the request object and removes associated events. */
629 EVENT2_EXPORT_SYMBOL
630 void evhttp_request_free(struct evhttp_request *req);
631 
632 /**
633  * Create and return a connection object that can be used to for making HTTP
634  * requests.  The connection object tries to resolve address and establish the
635  * connection when it is given an http request object.
636  *
637  * @param base the event_base to use for handling the connection
638  * @param dnsbase the dns_base to use for resolving host names; if not
639  *     specified host name resolution will block.
640  * @param address the address to which to connect
641  * @param port the port to connect to
642  * @return an evhttp_connection object that can be used for making requests or
643  *   NULL on error
644  */
645 EVENT2_EXPORT_SYMBOL
646 struct evhttp_connection *evhttp_connection_base_new(
647 	struct event_base *base, struct evdns_base *dnsbase,
648 	const char *address, ev_uint16_t port);
649 
650 /**
651  * Set family hint for DNS requests.
652  */
653 EVENT2_EXPORT_SYMBOL
654 void evhttp_connection_set_family(struct evhttp_connection *evcon,
655 	int family);
656 
657 /* reuse connection address on retry */
658 #define EVHTTP_CON_REUSE_CONNECTED_ADDR	0x0008
659 /* Try to read error, since server may already send and close
660  * connection, but if at that time we have some data to send then we
661  * can send get EPIPE and fail, while we can read that HTTP error. */
662 #define EVHTTP_CON_READ_ON_WRITE_ERROR	0x0010
663 /* @see EVHTTP_SERVER_LINGERING_CLOSE */
664 #define EVHTTP_CON_LINGERING_CLOSE	0x0020
665 /* Padding for public flags, @see EVHTTP_CON_* in http-internal.h */
666 #define EVHTTP_CON_PUBLIC_FLAGS_END	0x100000
667 /**
668  * Set connection flags.
669  *
670  * @see EVHTTP_CON_*
671  * @return 0 on success, otherwise non zero (for example if flag doesn't
672  * supported).
673  */
674 EVENT2_EXPORT_SYMBOL
675 int evhttp_connection_set_flags(struct evhttp_connection *evcon,
676 	int flags);
677 
678 /** Takes ownership of the request object
679  *
680  * Can be used in a request callback to keep onto the request until
681  * evhttp_request_free() is explicitly called by the user.
682  */
683 EVENT2_EXPORT_SYMBOL
684 void evhttp_request_own(struct evhttp_request *req);
685 
686 /** Returns 1 if the request is owned by the user */
687 EVENT2_EXPORT_SYMBOL
688 int evhttp_request_is_owned(struct evhttp_request *req);
689 
690 /**
691  * Returns the connection object associated with the request or NULL
692  *
693  * The user needs to either free the request explicitly or call
694  * evhttp_send_reply_end().
695  */
696 EVENT2_EXPORT_SYMBOL
697 struct evhttp_connection *evhttp_request_get_connection(struct evhttp_request *req);
698 
699 /**
700  * Returns the underlying event_base for this connection
701  */
702 EVENT2_EXPORT_SYMBOL
703 struct event_base *evhttp_connection_get_base(struct evhttp_connection *req);
704 
705 EVENT2_EXPORT_SYMBOL
706 void evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
707     ev_ssize_t new_max_headers_size);
708 
709 EVENT2_EXPORT_SYMBOL
710 void evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
711     ev_ssize_t new_max_body_size);
712 
713 /** Frees an http connection */
714 EVENT2_EXPORT_SYMBOL
715 void evhttp_connection_free(struct evhttp_connection *evcon);
716 
717 /** Disowns a given connection object
718  *
719  * Can be used to tell libevent to free the connection object after
720  * the last request has completed or failed.
721  */
722 EVENT2_EXPORT_SYMBOL
723 void evhttp_connection_free_on_completion(struct evhttp_connection *evcon);
724 
725 /** sets the ip address from which http connections are made */
726 EVENT2_EXPORT_SYMBOL
727 void evhttp_connection_set_local_address(struct evhttp_connection *evcon,
728     const char *address);
729 
730 /** sets the local port from which http connections are made */
731 EVENT2_EXPORT_SYMBOL
732 void evhttp_connection_set_local_port(struct evhttp_connection *evcon,
733     ev_uint16_t port);
734 
735 /** Sets the timeout in seconds for events related to this connection */
736 EVENT2_EXPORT_SYMBOL
737 void evhttp_connection_set_timeout(struct evhttp_connection *evcon,
738     int timeout_in_secs);
739 
740 /** Sets the timeout for events related to this connection.  Takes a struct
741  * timeval. */
742 EVENT2_EXPORT_SYMBOL
743 void evhttp_connection_set_timeout_tv(struct evhttp_connection *evcon,
744     const struct timeval *tv);
745 
746 /** Sets the delay before retrying requests on this connection. This is only
747  * used if evhttp_connection_set_retries is used to make the number of retries
748  * at least one. Each retry after the first is twice as long as the one before
749  * it. */
750 EVENT2_EXPORT_SYMBOL
751 void evhttp_connection_set_initial_retry_tv(struct evhttp_connection *evcon,
752     const struct timeval *tv);
753 
754 /** Sets the retry limit for this connection - -1 repeats indefinitely */
755 EVENT2_EXPORT_SYMBOL
756 void evhttp_connection_set_retries(struct evhttp_connection *evcon,
757     int retry_max);
758 
759 /** Set a callback for connection close. */
760 EVENT2_EXPORT_SYMBOL
761 void evhttp_connection_set_closecb(struct evhttp_connection *evcon,
762     void (*)(struct evhttp_connection *, void *), void *);
763 
764 /** Get the remote address and port associated with this connection. */
765 EVENT2_EXPORT_SYMBOL
766 void evhttp_connection_get_peer(struct evhttp_connection *evcon,
767     char **address, ev_uint16_t *port);
768 
769 /** Get the remote address associated with this connection.
770  * extracted from getpeername() OR from nameserver.
771  *
772  * @return NULL if getpeername() return non success,
773  * or connection is not connected,
774  * otherwise it return pointer to struct sockaddr_storage */
775 EVENT2_EXPORT_SYMBOL
776 const struct sockaddr*
777 evhttp_connection_get_addr(struct evhttp_connection *evcon);
778 
779 /**
780     Make an HTTP request over the specified connection.
781 
782     The connection gets ownership of the request.  On failure, the
783     request object is no longer valid as it has been freed.
784 
785     @param evcon the evhttp_connection object over which to send the request
786     @param req the previously created and configured request object
787     @param type the request type EVHTTP_REQ_GET, EVHTTP_REQ_POST, etc.
788     @param uri the URI associated with the request
789     @return 0 on success, -1 on failure
790     @see evhttp_cancel_request()
791 */
792 EVENT2_EXPORT_SYMBOL
793 int evhttp_make_request(struct evhttp_connection *evcon,
794     struct evhttp_request *req,
795     enum evhttp_cmd_type type, const char *uri);
796 
797 /**
798    Cancels a pending HTTP request.
799 
800    Cancels an ongoing HTTP request.  The callback associated with this request
801    is not executed and the request object is freed.  If the request is
802    currently being processed, e.g. it is ongoing, the corresponding
803    evhttp_connection object is going to get reset.
804 
805    A request cannot be canceled if its callback has executed already. A request
806    may be canceled reentrantly from its chunked callback.
807 
808    @param req the evhttp_request to cancel; req becomes invalid after this call.
809 */
810 EVENT2_EXPORT_SYMBOL
811 void evhttp_cancel_request(struct evhttp_request *req);
812 
813 /**
814  * A structure to hold a parsed URI or Relative-Ref conforming to RFC3986.
815  */
816 struct evhttp_uri;
817 
818 /** Returns the request URI */
819 EVENT2_EXPORT_SYMBOL
820 const char *evhttp_request_get_uri(const struct evhttp_request *req);
821 /** Returns the request URI (parsed) */
822 EVENT2_EXPORT_SYMBOL
823 const struct evhttp_uri *evhttp_request_get_evhttp_uri(const struct evhttp_request *req);
824 /** Returns the request command */
825 EVENT2_EXPORT_SYMBOL
826 enum evhttp_cmd_type evhttp_request_get_command(const struct evhttp_request *req);
827 
828 EVENT2_EXPORT_SYMBOL
829 int evhttp_request_get_response_code(const struct evhttp_request *req);
830 EVENT2_EXPORT_SYMBOL
831 const char * evhttp_request_get_response_code_line(const struct evhttp_request *req);
832 
833 /** Returns the input headers */
834 EVENT2_EXPORT_SYMBOL
835 struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req);
836 /** Returns the output headers */
837 EVENT2_EXPORT_SYMBOL
838 struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req);
839 /** Returns the input buffer */
840 EVENT2_EXPORT_SYMBOL
841 struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req);
842 /** Returns the output buffer */
843 EVENT2_EXPORT_SYMBOL
844 struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req);
845 /** Returns the host associated with the request. If a client sends an absolute
846     URI, the host part of that is preferred. Otherwise, the input headers are
847     searched for a Host: header. NULL is returned if no absolute URI or Host:
848     header is provided. */
849 EVENT2_EXPORT_SYMBOL
850 const char *evhttp_request_get_host(struct evhttp_request *req);
851 
852 /* Interfaces for dealing with HTTP headers */
853 
854 /**
855    Finds the value belonging to a header.
856 
857    @param headers the evkeyvalq object in which to find the header
858    @param key the name of the header to find
859    @returns a pointer to the value for the header or NULL if the header
860      could not be found.
861    @see evhttp_add_header(), evhttp_remove_header()
862 */
863 EVENT2_EXPORT_SYMBOL
864 const char *evhttp_find_header(const struct evkeyvalq *headers,
865     const char *key);
866 
867 /**
868    Removes a header from a list of existing headers.
869 
870    @param headers the evkeyvalq object from which to remove a header
871    @param key the name of the header to remove
872    @returns 0 if the header was removed, -1  otherwise.
873    @see evhttp_find_header(), evhttp_add_header()
874 */
875 EVENT2_EXPORT_SYMBOL
876 int evhttp_remove_header(struct evkeyvalq *headers, const char *key);
877 
878 /**
879    Adds a header to a list of existing headers.
880 
881    @param headers the evkeyvalq object to which to add a header
882    @param key the name of the header
883    @param value the value belonging to the header
884    @returns 0 on success, -1  otherwise.
885    @see evhttp_find_header(), evhttp_clear_headers()
886 */
887 EVENT2_EXPORT_SYMBOL
888 int evhttp_add_header(struct evkeyvalq *headers, const char *key, const char *value);
889 
890 /**
891    Removes all headers from the header list.
892 
893    @param headers the evkeyvalq object from which to remove all headers
894 */
895 EVENT2_EXPORT_SYMBOL
896 void evhttp_clear_headers(struct evkeyvalq *headers);
897 
898 /* Miscellaneous utility functions */
899 
900 
901 /**
902    Helper function to encode a string for inclusion in a URI.  All
903    characters are replaced by their hex-escaped (%22) equivalents,
904    except for characters explicitly unreserved by RFC3986 -- that is,
905    ASCII alphanumeric characters, hyphen, dot, underscore, and tilde.
906 
907    The returned string must be freed by the caller.
908 
909    @param str an unencoded string
910    @return a newly allocated URI-encoded string or NULL on failure
911  */
912 EVENT2_EXPORT_SYMBOL
913 char *evhttp_encode_uri(const char *str);
914 
915 /**
916    As evhttp_encode_uri, but if 'size' is nonnegative, treat the string
917    as being 'size' bytes long.  This allows you to encode strings that
918    may contain 0-valued bytes.
919 
920    The returned string must be freed by the caller.
921 
922    @param str an unencoded string
923    @param size the length of the string to encode, or -1 if the string
924       is NUL-terminated
925    @param space_to_plus if true, space characters in 'str' are encoded
926       as +, not %20.
927    @return a newly allocate URI-encoded string, or NULL on failure.
928  */
929 EVENT2_EXPORT_SYMBOL
930 char *evhttp_uriencode(const char *str, ev_ssize_t size, int space_to_plus);
931 
932 /**
933   Helper function to sort of decode a URI-encoded string.  Unlike
934   evhttp_uridecode, it decodes all plus characters that appear
935   _after_ the first question mark character, but no plusses that occur
936   before.  This is not a good way to decode URIs in whole or in part.
937 
938   The returned string must be freed by the caller
939 
940   @deprecated  This function is deprecated; you probably want to use
941      evhttp_uridecode instead.
942 
943   @param uri an encoded URI
944   @return a newly allocated unencoded URI or NULL on failure
945  */
946 EVENT2_EXPORT_SYMBOL
947 char *evhttp_decode_uri(const char *uri);
948 
949 /**
950   Helper function to decode a URI-escaped string or HTTP parameter.
951 
952   If 'decode_plus' is 1, then we decode the string as an HTTP parameter
953   value, and convert all plus ('+') characters to spaces.  If
954   'decode_plus' is 0, we leave all plus characters unchanged.
955 
956   The returned string must be freed by the caller.
957 
958   @param uri a URI-encode encoded URI
959   @param decode_plus determines whether we convert '+' to space.
960   @param size_out if size_out is not NULL, *size_out is set to the size of the
961      returned string
962   @return a newly allocated unencoded URI or NULL on failure
963  */
964 EVENT2_EXPORT_SYMBOL
965 char *evhttp_uridecode(const char *uri, int decode_plus,
966     size_t *size_out);
967 
968 /**
969    Helper function to parse out arguments in a query.
970 
971    Parsing a URI like
972 
973       http://foo.com/?q=test&s=some+thing
974 
975    will result in two entries in the key value queue.
976 
977    The first entry is: key="q", value="test"
978    The second entry is: key="s", value="some thing"
979 
980    @deprecated This function is deprecated as of Libevent 2.0.9.  Use
981      evhttp_uri_parse and evhttp_parse_query_str instead.
982 
983    @param uri the request URI
984    @param headers the head of the evkeyval queue
985    @return 0 on success, -1 on failure
986  */
987 EVENT2_EXPORT_SYMBOL
988 int evhttp_parse_query(const char *uri, struct evkeyvalq *headers);
989 
990 /**
991    Helper function to parse out arguments from the query portion of an
992    HTTP URI.
993 
994    Parsing a query string like
995 
996      q=test&s=some+thing
997 
998    will result in two entries in the key value queue.
999 
1000    The first entry is: key="q", value="test"
1001    The second entry is: key="s", value="some thing"
1002 
1003    @param query_parse the query portion of the URI
1004    @param headers the head of the evkeyval queue
1005    @return 0 on success, -1 on failure
1006  */
1007 EVENT2_EXPORT_SYMBOL
1008 int evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers);
1009 
1010 /**
1011  * Escape HTML character entities in a string.
1012  *
1013  * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
1014  * &#039; and &amp; correspondingly.
1015  *
1016  * The returned string needs to be freed by the caller.
1017  *
1018  * @param html an unescaped HTML string
1019  * @return an escaped HTML string or NULL on error
1020  */
1021 EVENT2_EXPORT_SYMBOL
1022 char *evhttp_htmlescape(const char *html);
1023 
1024 /**
1025  * Return a new empty evhttp_uri with no fields set.
1026  */
1027 EVENT2_EXPORT_SYMBOL
1028 struct evhttp_uri *evhttp_uri_new(void);
1029 
1030 /**
1031  * Changes the flags set on a given URI.  See EVHTTP_URI_* for
1032  * a list of flags.
1033  **/
1034 EVENT2_EXPORT_SYMBOL
1035 void evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags);
1036 
1037 /** Return the scheme of an evhttp_uri, or NULL if there is no scheme has
1038  * been set and the evhttp_uri contains a Relative-Ref. */
1039 EVENT2_EXPORT_SYMBOL
1040 const char *evhttp_uri_get_scheme(const struct evhttp_uri *uri);
1041 /**
1042  * Return the userinfo part of an evhttp_uri, or NULL if it has no userinfo
1043  * set.
1044  */
1045 EVENT2_EXPORT_SYMBOL
1046 const char *evhttp_uri_get_userinfo(const struct evhttp_uri *uri);
1047 /**
1048  * Return the host part of an evhttp_uri, or NULL if it has no host set.
1049  * The host may either be a regular hostname (conforming to the RFC 3986
1050  * "regname" production), or an IPv4 address, or the empty string, or a
1051  * bracketed IPv6 address, or a bracketed 'IP-Future' address.
1052  *
1053  * Note that having a NULL host means that the URI has no authority
1054  * section, but having an empty-string host means that the URI has an
1055  * authority section with no host part.  For example,
1056  * "mailto:user@example.com" has a host of NULL, but "file:///etc/motd"
1057  * has a host of "".
1058  */
1059 EVENT2_EXPORT_SYMBOL
1060 const char *evhttp_uri_get_host(const struct evhttp_uri *uri);
1061 /** Return the port part of an evhttp_uri, or -1 if there is no port set. */
1062 EVENT2_EXPORT_SYMBOL
1063 int evhttp_uri_get_port(const struct evhttp_uri *uri);
1064 /** Return the path part of an evhttp_uri, or NULL if it has no path set */
1065 EVENT2_EXPORT_SYMBOL
1066 const char *evhttp_uri_get_path(const struct evhttp_uri *uri);
1067 /** Return the query part of an evhttp_uri (excluding the leading "?"), or
1068  * NULL if it has no query set */
1069 EVENT2_EXPORT_SYMBOL
1070 const char *evhttp_uri_get_query(const struct evhttp_uri *uri);
1071 /** Return the fragment part of an evhttp_uri (excluding the leading "#"),
1072  * or NULL if it has no fragment set */
1073 EVENT2_EXPORT_SYMBOL
1074 const char *evhttp_uri_get_fragment(const struct evhttp_uri *uri);
1075 
1076 /** Set the scheme of an evhttp_uri, or clear the scheme if scheme==NULL.
1077  * Returns 0 on success, -1 if scheme is not well-formed. */
1078 EVENT2_EXPORT_SYMBOL
1079 int evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme);
1080 /** Set the userinfo of an evhttp_uri, or clear the userinfo if userinfo==NULL.
1081  * Returns 0 on success, -1 if userinfo is not well-formed. */
1082 EVENT2_EXPORT_SYMBOL
1083 int evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo);
1084 /** Set the host of an evhttp_uri, or clear the host if host==NULL.
1085  * Returns 0 on success, -1 if host is not well-formed. */
1086 EVENT2_EXPORT_SYMBOL
1087 int evhttp_uri_set_host(struct evhttp_uri *uri, const char *host);
1088 /** Set the port of an evhttp_uri, or clear the port if port==-1.
1089  * Returns 0 on success, -1 if port is not well-formed. */
1090 EVENT2_EXPORT_SYMBOL
1091 int evhttp_uri_set_port(struct evhttp_uri *uri, int port);
1092 /** Set the path of an evhttp_uri, or clear the path if path==NULL.
1093  * Returns 0 on success, -1 if path is not well-formed. */
1094 EVENT2_EXPORT_SYMBOL
1095 int evhttp_uri_set_path(struct evhttp_uri *uri, const char *path);
1096 /** Set the query of an evhttp_uri, or clear the query if query==NULL.
1097  * The query should not include a leading "?".
1098  * Returns 0 on success, -1 if query is not well-formed. */
1099 EVENT2_EXPORT_SYMBOL
1100 int evhttp_uri_set_query(struct evhttp_uri *uri, const char *query);
1101 /** Set the fragment of an evhttp_uri, or clear the fragment if fragment==NULL.
1102  * The fragment should not include a leading "#".
1103  * Returns 0 on success, -1 if fragment is not well-formed. */
1104 EVENT2_EXPORT_SYMBOL
1105 int evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment);
1106 
1107 /**
1108  * Helper function to parse a URI-Reference as specified by RFC3986.
1109  *
1110  * This function matches the URI-Reference production from RFC3986,
1111  * which includes both URIs like
1112  *
1113  *    scheme://[[userinfo]@]foo.com[:port]]/[path][?query][#fragment]
1114  *
1115  *  and relative-refs like
1116  *
1117  *    [path][?query][#fragment]
1118  *
1119  * Any optional elements portions not present in the original URI are
1120  * left set to NULL in the resulting evhttp_uri.  If no port is
1121  * specified, the port is set to -1.
1122  *
1123  * Note that no decoding is performed on percent-escaped characters in
1124  * the string; if you want to parse them, use evhttp_uridecode or
1125  * evhttp_parse_query_str as appropriate.
1126  *
1127  * Note also that most URI schemes will have additional constraints that
1128  * this function does not know about, and cannot check.  For example,
1129  * mailto://www.example.com/cgi-bin/fortune.pl is not a reasonable
1130  * mailto url, http://www.example.com:99999/ is not a reasonable HTTP
1131  * URL, and ftp:username@example.com is not a reasonable FTP URL.
1132  * Nevertheless, all of these URLs conform to RFC3986, and this function
1133  * accepts all of them as valid.
1134  *
1135  * @param source_uri the request URI
1136  * @param flags Zero or more EVHTTP_URI_* flags to affect the behavior
1137  *              of the parser.
1138  * @return uri container to hold parsed data, or NULL if there is error
1139  * @see evhttp_uri_free()
1140  */
1141 EVENT2_EXPORT_SYMBOL
1142 struct evhttp_uri *evhttp_uri_parse_with_flags(const char *source_uri,
1143     unsigned flags);
1144 
1145 /** Tolerate URIs that do not conform to RFC3986.
1146  *
1147  * Unfortunately, some HTTP clients generate URIs that, according to RFC3986,
1148  * are not conformant URIs.  If you need to support these URIs, you can
1149  * do so by passing this flag to evhttp_uri_parse_with_flags.
1150  *
1151  * Currently, these changes are:
1152  * <ul>
1153  *   <li> Nonconformant URIs are allowed to contain otherwise unreasonable
1154  *        characters in their path, query, and fragment components.
1155  * </ul>
1156  */
1157 #define EVHTTP_URI_NONCONFORMANT 0x01
1158 
1159 /** Alias for evhttp_uri_parse_with_flags(source_uri, 0) */
1160 EVENT2_EXPORT_SYMBOL
1161 struct evhttp_uri *evhttp_uri_parse(const char *source_uri);
1162 
1163 /**
1164  * Free all memory allocated for a parsed uri.  Only use this for URIs
1165  * generated by evhttp_uri_parse.
1166  *
1167  * @param uri container with parsed data
1168  * @see evhttp_uri_parse()
1169  */
1170 EVENT2_EXPORT_SYMBOL
1171 void evhttp_uri_free(struct evhttp_uri *uri);
1172 
1173 /**
1174  * Join together the uri parts from parsed data to form a URI-Reference.
1175  *
1176  * Note that no escaping of reserved characters is done on the members
1177  * of the evhttp_uri, so the generated string might not be a valid URI
1178  * unless the members of evhttp_uri are themselves valid.
1179  *
1180  * @param uri container with parsed data
1181  * @param buf destination buffer
1182  * @param limit destination buffer size
1183  * @return an joined uri as string or NULL on error
1184  * @see evhttp_uri_parse()
1185  */
1186 EVENT2_EXPORT_SYMBOL
1187 char *evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit);
1188 
1189 #ifdef __cplusplus
1190 }
1191 #endif
1192 
1193 #endif /* EVENT2_HTTP_H_INCLUDED_ */
1194