]> granicus.if.org Git - libevent/blob - http.c
Change code for samples
[libevent] / http.c
1 /*
2  * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "event2/event-config.h"
29 #include "evconfig-private.h"
30
31 #define member_size(type, member) sizeof(((type *)0)->member)
32
33 #ifdef EVENT__HAVE_SYS_PARAM_H
34 #include <sys/param.h>
35 #endif
36 #ifdef EVENT__HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39
40 #ifdef HAVE_SYS_IOCCOM_H
41 #include <sys/ioccom.h>
42 #endif
43 #ifdef EVENT__HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif
46 #ifdef EVENT__HAVE_SYS_TIME_H
47 #include <sys/time.h>
48 #endif
49 #ifdef EVENT__HAVE_SYS_WAIT_H
50 #include <sys/wait.h>
51 #endif
52
53 #ifndef _WIN32
54 #include <sys/socket.h>
55 #include <sys/stat.h>
56 #else /* _WIN32 */
57 #include <winsock2.h>
58 #include <ws2tcpip.h>
59 #endif /* _WIN32 */
60
61 #ifdef EVENT__HAVE_SYS_UN_H
62 #include <sys/un.h>
63 #endif
64 #ifdef EVENT__HAVE_AFUNIX_H
65 #include <afunix.h>
66 #endif
67
68 #include <sys/queue.h>
69
70 #ifdef EVENT__HAVE_NETINET_IN_H
71 #include <netinet/in.h>
72 #endif
73 #ifdef EVENT__HAVE_ARPA_INET_H
74 #include <arpa/inet.h>
75 #endif
76 #ifdef EVENT__HAVE_NETDB_H
77 #include <netdb.h>
78 #endif
79
80 #ifdef _WIN32
81 #include <winsock2.h>
82 #endif
83
84 #include <errno.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #ifndef _WIN32
89 #include <syslog.h>
90 #endif /* !_WIN32 */
91 #include <signal.h>
92 #ifdef EVENT__HAVE_UNISTD_H
93 #include <unistd.h>
94 #endif
95 #ifdef EVENT__HAVE_FCNTL_H
96 #include <fcntl.h>
97 #endif
98
99 #undef timeout_pending
100 #undef timeout_initialized
101
102 #include "strlcpy-internal.h"
103 #include "event2/http.h"
104 #include "event2/event.h"
105 #include "event2/buffer.h"
106 #include "event2/bufferevent.h"
107 #include "event2/http_struct.h"
108 #include "event2/http_compat.h"
109 #include "event2/util.h"
110 #include "event2/ws.h"
111 #include "event2/listener.h"
112 #include "log-internal.h"
113 #include "util-internal.h"
114 #include "http-internal.h"
115 #include "mm-internal.h"
116 #include "bufferevent-internal.h"
117
118 #ifndef EVENT__HAVE_GETNAMEINFO
119 #define NI_MAXSERV 32
120 #define NI_MAXHOST 1025
121
122 #ifndef NI_NUMERICHOST
123 #define NI_NUMERICHOST 1
124 #endif
125
126 #ifndef NI_NUMERICSERV
127 #define NI_NUMERICSERV 2
128 #endif
129
130 static int
131 fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
132         size_t hostlen, char *serv, size_t servlen, int flags)
133 {
134         struct sockaddr_in *sin = (struct sockaddr_in *)sa;
135
136         if (serv != NULL) {
137                 char tmpserv[16];
138                 evutil_snprintf(tmpserv, sizeof(tmpserv),
139                     "%d", ntohs(sin->sin_port));
140                 if (strlcpy(serv, tmpserv, servlen) >= servlen)
141                         return (-1);
142         }
143
144         if (host != NULL) {
145                 if (flags & NI_NUMERICHOST) {
146                         if (strlcpy(host, inet_ntoa(sin->sin_addr),
147                             hostlen) >= hostlen)
148                                 return (-1);
149                         else
150                                 return (0);
151                 } else {
152                         struct hostent *hp;
153                         hp = gethostbyaddr((char *)&sin->sin_addr,
154                             sizeof(struct in_addr), AF_INET);
155                         if (hp == NULL)
156                                 return (-2);
157
158                         if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
159                                 return (-1);
160                         else
161                                 return (0);
162                 }
163         }
164         return (0);
165 }
166
167 #endif
168
169 #define REQ_VERSION_BEFORE(req, major_v, minor_v)                       \
170         ((req)->major < (major_v) ||                                    \
171             ((req)->major == (major_v) && (req)->minor < (minor_v)))
172
173 #define REQ_VERSION_ATLEAST(req, major_v, minor_v)                      \
174         ((req)->major > (major_v) ||                                    \
175             ((req)->major == (major_v) && (req)->minor >= (minor_v)))
176
177 #ifndef MIN
178 #define MIN(a,b) (((a)<(b))?(a):(b))
179 #endif
180
181 extern int debug;
182
183 static evutil_socket_t create_bind_socket_nonblock(struct evutil_addrinfo *, int reuse);
184 static evutil_socket_t bind_socket(const char *, ev_uint16_t, int reuse);
185 static void name_from_addr(struct sockaddr *, ev_socklen_t, char **, char **);
186 static struct evhttp_uri *evhttp_uri_parse_authority(char *source_uri, unsigned flags);
187 static int evhttp_associate_new_request_with_connection(
188         struct evhttp_connection *evcon);
189 static void evhttp_connection_start_detectclose(
190         struct evhttp_connection *evcon);
191 static void evhttp_connection_stop_detectclose(
192         struct evhttp_connection *evcon);
193 static void evhttp_request_dispatch(struct evhttp_connection* evcon);
194 static void evhttp_read_firstline(struct evhttp_connection *evcon,
195                                   struct evhttp_request *req);
196 static void evhttp_read_header(struct evhttp_connection *evcon,
197     struct evhttp_request *req);
198 static int evhttp_add_header_internal(struct evkeyvalq *headers,
199     const char *key, const char *value);
200 static const char *evhttp_response_phrase_internal(int code);
201 static void evhttp_get_request(struct evhttp *, evutil_socket_t, struct sockaddr *, ev_socklen_t, struct bufferevent *bev);
202 static void evhttp_write_buffer(struct evhttp_connection *,
203     void (*)(struct evhttp_connection *, void *), void *);
204 static void evhttp_make_header(struct evhttp_connection *, struct evhttp_request *);
205 static int evhttp_method_may_have_body_(struct evhttp_connection *, enum evhttp_cmd_type);
206
207 /* callbacks for bufferevent */
208 static void evhttp_read_cb(struct bufferevent *, void *);
209 static void evhttp_write_cb(struct bufferevent *, void *);
210 static void evhttp_error_cb(struct bufferevent *bufev, short what, void *arg);
211 static int evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp, const char *hostname);
212 static const char *evhttp_method_(struct evhttp_connection *evcon,
213         enum evhttp_cmd_type type, ev_uint16_t *flags);
214
215 #ifndef EVENT__HAVE_STRSEP
216 /* strsep replacement for platforms that lack it.  Only works if
217  * del is one character long. */
218 static char *
219 strsep(char **s, const char *del)
220 {
221         char *d, *tok;
222         EVUTIL_ASSERT(strlen(del) == 1);
223         if (!s || !*s)
224                 return NULL;
225         tok = *s;
226         d = strstr(tok, del);
227         if (d) {
228                 *d = '\0';
229                 *s = d + 1;
230         } else
231                 *s = NULL;
232         return tok;
233 }
234 #endif
235
236 static size_t
237 html_replace(const char ch, const char **escaped)
238 {
239         switch (ch) {
240         case '<':
241                 *escaped = "&lt;";
242                 return 4;
243         case '>':
244                 *escaped = "&gt;";
245                 return 4;
246         case '"':
247                 *escaped = "&quot;";
248                 return 6;
249         case '\'':
250                 *escaped = "&#039;";
251                 return 6;
252         case '&':
253                 *escaped = "&amp;";
254                 return 5;
255         default:
256                 break;
257         }
258
259         return 1;
260 }
261
262 /*
263  * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
264  * &#039; and &amp; correspondingly.
265  *
266  * The returned string needs to be freed by the caller.
267  */
268
269 char *
270 evhttp_htmlescape(const char *html)
271 {
272         size_t i;
273         size_t new_size = 0, old_size = 0;
274         char *escaped_html, *p;
275
276         if (html == NULL)
277                 return (NULL);
278
279         old_size = strlen(html);
280         for (i = 0; i < old_size; ++i) {
281                 const char *replaced = NULL;
282                 const size_t replace_size = html_replace(html[i], &replaced);
283                 if (replace_size > EV_SIZE_MAX - new_size) {
284                         event_warn("%s: html_replace overflow", __func__);
285                         return (NULL);
286                 }
287                 new_size += replace_size;
288         }
289
290         if (new_size == EV_SIZE_MAX)
291                 return (NULL);
292         p = escaped_html = mm_malloc(new_size + 1);
293         if (escaped_html == NULL) {
294                 event_warn("%s: malloc(%lu)", __func__,
295                            (unsigned long)(new_size + 1));
296                 return (NULL);
297         }
298         for (i = 0; i < old_size; ++i) {
299                 const char *replaced = &html[i];
300                 const size_t len = html_replace(html[i], &replaced);
301                 memcpy(p, replaced, len);
302                 p += len;
303         }
304
305         *p = '\0';
306
307         return (escaped_html);
308 }
309
310 /** Given an evhttp_cmd_type, returns a constant string containing the
311  * equivalent HTTP command, or NULL if the evhttp_cmd_type is
312  * unrecognized. */
313 static const char *
314 evhttp_method_(struct evhttp_connection *evcon,
315               enum evhttp_cmd_type type, ev_uint16_t *flags)
316 {
317         struct evhttp_ext_method ext_method;
318         const char *method    = NULL;
319         ev_uint16_t tmp_flags = EVHTTP_METHOD_HAS_BODY;
320
321         switch (type) {
322         case EVHTTP_REQ_GET:
323                 method = "GET";
324                 break;
325         case EVHTTP_REQ_POST:
326                 method = "POST";
327                 break;
328         case EVHTTP_REQ_HEAD:
329                 method = "HEAD";
330                 tmp_flags &= ~EVHTTP_METHOD_HAS_BODY;
331                 break;
332         case EVHTTP_REQ_PUT:
333                 method = "PUT";
334                 break;
335         case EVHTTP_REQ_DELETE:
336                 method = "DELETE";
337                 break;
338         case EVHTTP_REQ_OPTIONS:
339                 method = "OPTIONS";
340                 break;
341         case EVHTTP_REQ_TRACE:
342                 method = "TRACE";
343                 tmp_flags &= ~EVHTTP_METHOD_HAS_BODY;
344                 break;
345         case EVHTTP_REQ_CONNECT:
346                 method = "CONNECT";
347                 break;
348         case EVHTTP_REQ_PATCH:
349                 method = "PATCH";
350                 break;
351         case EVHTTP_REQ_PROPFIND:
352                 method = "PROPFIND";
353                 break;
354         case EVHTTP_REQ_PROPPATCH:
355                 method = "PROPPATCH";
356                 break;
357         case EVHTTP_REQ_MKCOL:
358                 method = "MKCOL";
359                 break;
360         case EVHTTP_REQ_LOCK:
361                 method = "LOCK";
362                 break;
363         case EVHTTP_REQ_UNLOCK:
364                 method = "UNLOCK";
365                 break;
366         case EVHTTP_REQ_COPY:
367                 method = "COPY";
368                 break;
369         case EVHTTP_REQ_MOVE:
370                 method = "MOVE";
371                 break;
372         default:
373                 /* setup the structure to allow for the cmp.
374                  *
375                  * if the cmp function is set, it has the ability to
376                  * modify method and flags. Other fields will be
377                  * ignored.
378                  *
379                  * NOTE: the flags returned are OR'd with the current
380                  *       flags.
381                  */
382                 tmp_flags = 0;
383                 ext_method.method = NULL;
384                 ext_method.type   = type;
385                 ext_method.flags  = tmp_flags;
386
387                 if (evcon->ext_method_cmp != NULL &&
388                         evcon->ext_method_cmp(&ext_method) == 0) {
389
390                         if (ext_method.type != type) {
391                                 event_debug(("%s: callback modified type from %u to %u, not allowed",
392                                             __func__, type, ext_method.type));
393                                 return NULL;
394                         }
395
396                         method     = ext_method.method;
397                         tmp_flags |= ext_method.flags;
398                 }
399
400                 break;
401         }
402
403         event_debug(("%s: type=%04x => '%s' flags=%04x",
404                      __func__, (int)type, method, tmp_flags));
405
406         if (flags)
407                 *flags = tmp_flags;
408         return (method);
409 }
410
411 /**
412  * Determines if a response should have a body.
413  * Follows the rules in RFC 2616 section 4.3.
414  * @return 1 if the response MUST have a body; 0 if the response MUST NOT have
415  *     a body.
416  */
417 static int
418 evhttp_response_needs_body(struct evhttp_request *req)
419 {
420         return (req->response_code != HTTP_NOCONTENT &&
421                 req->response_code != HTTP_NOTMODIFIED &&
422                 (req->response_code < 100 || req->response_code >= 200) &&
423                 req->type != EVHTTP_REQ_CONNECT &&
424                 req->type != EVHTTP_REQ_HEAD);
425 }
426
427 /** Helper: called after we've added some data to an evcon's bufferevent's
428  * output buffer.  Sets the evconn's writing-is-done callback, and puts
429  * the bufferevent into writing mode.
430  */
431 static void
432 evhttp_write_buffer(struct evhttp_connection *evcon,
433     void (*cb)(struct evhttp_connection *, void *), void *arg)
434 {
435         event_debug(("%s: preparing to write buffer\n", __func__));
436
437         /* Set call back */
438         evcon->cb = cb;
439         evcon->cb_arg = arg;
440
441         /* Disable the read callback: we don't actually care about data;
442          * we only care about close detection. (We don't disable reading --
443          * EV_READ, since we *do* want to learn about any close events.) */
444         bufferevent_setcb(evcon->bufev,
445             NULL, /*read*/
446             evhttp_write_cb,
447             evhttp_error_cb,
448             evcon);
449
450         bufferevent_enable(evcon->bufev, EV_READ|EV_WRITE);
451 }
452
453 static void
454 evhttp_send_continue_done(struct evhttp_connection *evcon, void *arg)
455 {
456         bufferevent_disable(evcon->bufev, EV_WRITE);
457 }
458
459 static void
460 evhttp_send_continue(struct evhttp_connection *evcon,
461                         struct evhttp_request *req)
462 {
463         bufferevent_enable(evcon->bufev, EV_WRITE);
464         evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
465                         "HTTP/%d.%d 100 Continue\r\n\r\n",
466                         req->major, req->minor);
467         evcon->cb = evhttp_send_continue_done;
468         evcon->cb_arg = NULL;
469         bufferevent_setcb(evcon->bufev,
470             evhttp_read_cb,
471             evhttp_write_cb,
472             evhttp_error_cb,
473             evcon);
474 }
475
476 /** Helper: returns true iff evconn is in any connected state. */
477 static int
478 evhttp_connected(struct evhttp_connection *evcon)
479 {
480         switch (evcon->state) {
481         case EVCON_DISCONNECTED:
482         case EVCON_CONNECTING:
483                 return (0);
484         case EVCON_IDLE:
485         case EVCON_READING_FIRSTLINE:
486         case EVCON_READING_HEADERS:
487         case EVCON_READING_BODY:
488         case EVCON_READING_TRAILER:
489         case EVCON_WRITING:
490         default:
491                 return (1);
492         }
493 }
494
495 /* Create the headers needed for an outgoing HTTP request, adds them to
496  * the request's header list, and writes the request line to the
497  * connection's output buffer.
498  */
499 static void
500 evhttp_make_header_request(struct evhttp_connection *evcon,
501     struct evhttp_request *req)
502 {
503         const char *method;
504         /* NOTE: some version of GCC reports a warning that flags may be uninitialized, hence assignment */
505         ev_uint16_t flags = 0;
506
507         evhttp_remove_header(req->output_headers, "Proxy-Connection");
508
509         /* Generate request line */
510         if (!(method = evhttp_method_(evcon, req->type, &flags))) {
511                 method = "NULL";
512         }
513
514         evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
515             "%s %s HTTP/%d.%d\r\n",
516             method, req->uri, req->major, req->minor);
517
518         /* Add the content length on a request if missing
519          * Always add it for POST and PUT requests as clients expect it */
520         if ((flags & EVHTTP_METHOD_HAS_BODY) &&
521             (evbuffer_get_length(req->output_buffer) > 0 ||
522              req->type == EVHTTP_REQ_POST || req->type == EVHTTP_REQ_PUT) &&
523             evhttp_find_header(req->output_headers, "Content-Length") == NULL) {
524                 char size[22];
525                 evutil_snprintf(size, sizeof(size), EV_SIZE_FMT,
526                     EV_SIZE_ARG(evbuffer_get_length(req->output_buffer)));
527                 evhttp_add_header(req->output_headers, "Content-Length", size);
528         }
529 }
530
531 /** Return true if the list of headers in 'headers', intepreted with respect
532  * to flags, means that we should send a "connection: close" when the request
533  * is done. */
534 static int
535 evhttp_is_connection_close(int flags, struct evkeyvalq* headers)
536 {
537         if (flags & EVHTTP_PROXY_REQUEST) {
538                 /* proxy connection */
539                 const char *connection = evhttp_find_header(headers, "Proxy-Connection");
540                 return (connection == NULL || evutil_ascii_strcasecmp(connection, "keep-alive") != 0);
541         } else {
542                 const char *connection = evhttp_find_header(headers, "Connection");
543                 return (connection != NULL && evutil_ascii_strcasecmp(connection, "close") == 0);
544         }
545 }
546 static int
547 evhttp_is_request_connection_close(struct evhttp_request *req)
548 {
549         if (req->type == EVHTTP_REQ_CONNECT)
550                 return 0;
551
552         return
553                 evhttp_is_connection_close(req->flags, req->input_headers) ||
554                 evhttp_is_connection_close(req->flags, req->output_headers);
555 }
556
557 /* Return true iff 'headers' contains 'Connection: keep-alive' */
558 static int
559 evhttp_is_connection_keepalive(struct evkeyvalq* headers)
560 {
561         const char *connection = evhttp_find_header(headers, "Connection");
562         return (connection != NULL
563             && evutil_ascii_strncasecmp(connection, "keep-alive", 10) == 0);
564 }
565
566 /* Add a correct "Date" header to headers, unless it already has one. */
567 static void
568 evhttp_maybe_add_date_header(struct evkeyvalq *headers)
569 {
570         if (evhttp_find_header(headers, "Date") == NULL) {
571                 char date[50];
572                 if ((signed)sizeof(date) > evutil_date_rfc1123(date, sizeof(date), NULL)) {
573                         evhttp_add_header(headers, "Date", date);
574                 }
575         }
576 }
577
578 /* Add a "Content-Length" header with value 'content_length' to headers,
579  * unless it already has a content-length or transfer-encoding header. */
580 static void
581 evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
582     size_t content_length)
583 {
584         if (evhttp_find_header(headers, "Transfer-Encoding") == NULL &&
585             evhttp_find_header(headers, "Content-Length") == NULL) {
586                 char len[22];
587                 evutil_snprintf(len, sizeof(len), EV_SIZE_FMT,
588                     EV_SIZE_ARG(content_length));
589                 evhttp_add_header(headers, "Content-Length", len);
590         }
591 }
592
593 /*
594  * Create the headers needed for an HTTP reply in req->output_headers,
595  * and write the first HTTP response for req line to evcon.
596  */
597 static void
598 evhttp_make_header_response(struct evhttp_connection *evcon,
599     struct evhttp_request *req)
600 {
601         int is_keepalive = evhttp_is_connection_keepalive(req->input_headers);
602         evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
603             "HTTP/%d.%d %d %s\r\n",
604             req->major, req->minor, req->response_code,
605             req->response_code_line);
606
607         if (req->major == 1) {
608                 if (req->minor >= 1)
609                         evhttp_maybe_add_date_header(req->output_headers);
610
611                 /*
612                  * if the protocol is 1.0; and the connection was keep-alive
613                  * we need to add a keep-alive header, too.
614                  */
615                 if (req->minor == 0 && is_keepalive)
616                         evhttp_add_header(req->output_headers,
617                             "Connection", "keep-alive");
618
619                 if ((req->minor >= 1 || is_keepalive) &&
620                     evhttp_response_needs_body(req)) {
621                         /*
622                          * we need to add the content length if the
623                          * user did not give it, this is required for
624                          * persistent connections to work.
625                          */
626                         evhttp_maybe_add_content_length_header(
627                                 req->output_headers,
628                                 evbuffer_get_length(req->output_buffer));
629                 }
630         }
631
632         /* Potentially add headers for unidentified content. */
633         if (evhttp_response_needs_body(req)) {
634                 if (evhttp_find_header(req->output_headers,
635                         "Content-Type") == NULL
636                     && evcon->http_server->default_content_type) {
637                         evhttp_add_header(req->output_headers,
638                             "Content-Type",
639                             evcon->http_server->default_content_type);
640                 }
641         }
642
643         /* if the request asked for a close, we send a close, too */
644         if (evhttp_is_connection_close(req->flags, req->input_headers)) {
645                 evhttp_remove_header(req->output_headers, "Connection");
646                 if (!(req->flags & EVHTTP_PROXY_REQUEST))
647                     evhttp_add_header(req->output_headers, "Connection", "close");
648                 evhttp_remove_header(req->output_headers, "Proxy-Connection");
649         }
650 }
651
652 enum expect { NO, CONTINUE, OTHER };
653 static enum expect evhttp_have_expect(struct evhttp_request *req, int input)
654 {
655         const char *expect;
656         struct evkeyvalq *h = input ? req->input_headers : req->output_headers;
657
658         if (!(req->kind == EVHTTP_REQUEST) || !REQ_VERSION_ATLEAST(req, 1, 1))
659                 return NO;
660
661         expect = evhttp_find_header(h, "Expect");
662         if (!expect)
663                 return NO;
664
665         return !evutil_ascii_strcasecmp(expect, "100-continue") ? CONTINUE : OTHER;
666 }
667
668
669 /** Generate all headers appropriate for sending the http request in req (or
670  * the response, if we're sending a response), and write them to evcon's
671  * bufferevent. Also writes all data from req->output_buffer */
672 static void
673 evhttp_make_header(struct evhttp_connection *evcon, struct evhttp_request *req)
674 {
675         struct evkeyval *header;
676         struct evbuffer *output = bufferevent_get_output(evcon->bufev);
677
678         /*
679          * Depending if this is a HTTP request or response, we might need to
680          * add some new headers or remove existing headers.
681          */
682         if (req->kind == EVHTTP_REQUEST) {
683                 evhttp_make_header_request(evcon, req);
684         } else {
685                 evhttp_make_header_response(evcon, req);
686         }
687
688         TAILQ_FOREACH(header, req->output_headers, next) {
689                 evbuffer_add_printf(output, "%s: %s\r\n",
690                     header->key, header->value);
691         }
692         evbuffer_add(output, "\r\n", 2);
693
694         if (evhttp_have_expect(req, 0) != CONTINUE &&
695                 evbuffer_get_length(req->output_buffer)) {
696                 /*
697                  * For a request, we add the POST data, for a reply, this
698                  * is the regular data.
699                  */
700                 evbuffer_add_buffer(output, req->output_buffer);
701         }
702 }
703
704 void
705 evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
706     ev_ssize_t new_max_headers_size)
707 {
708         if (new_max_headers_size<0)
709                 evcon->max_headers_size = EV_SIZE_MAX;
710         else
711                 evcon->max_headers_size = new_max_headers_size;
712 }
713 void
714 evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
715     ev_ssize_t new_max_body_size)
716 {
717         if (new_max_body_size<0)
718                 evcon->max_body_size = EV_UINT64_MAX;
719         else
720                 evcon->max_body_size = new_max_body_size;
721 }
722
723 static int
724 evhttp_connection_incoming_fail(struct evhttp_request *req,
725     enum evhttp_request_error error)
726 {
727         switch (error) {
728                 case EVREQ_HTTP_DATA_TOO_LONG:
729                         req->response_code = HTTP_ENTITYTOOLARGE;
730                         break;
731                 default:
732                         req->response_code = HTTP_BADREQUEST;
733         }
734
735         switch (error) {
736         case EVREQ_HTTP_TIMEOUT:
737         case EVREQ_HTTP_EOF:
738                 /*
739                  * these are cases in which we probably should just
740                  * close the connection and not send a reply.  this
741                  * case may happen when a browser keeps a persistent
742                  * connection open and we timeout on the read.  when
743                  * the request is still being used for sending, we
744                  * need to disassociated it from the connection here.
745                  */
746                 if (!req->userdone) {
747                         /* remove it so that it will not be freed */
748                         TAILQ_REMOVE(&req->evcon->requests, req, next);
749                         /* indicate that this request no longer has a
750                          * connection object
751                          */
752                         req->evcon = NULL;
753                 }
754                 return (-1);
755         case EVREQ_HTTP_INVALID_HEADER:
756         case EVREQ_HTTP_BUFFER_ERROR:
757         case EVREQ_HTTP_REQUEST_CANCEL:
758         case EVREQ_HTTP_DATA_TOO_LONG:
759         default:        /* xxx: probably should just error on default */
760                 /* the callback looks at the uri to determine errors */
761                 if (req->uri) {
762                         mm_free(req->uri);
763                         req->uri = NULL;
764                 }
765                 if (req->uri_elems) {
766                         evhttp_uri_free(req->uri_elems);
767                         req->uri_elems = NULL;
768                 }
769
770                 /*
771                  * the callback needs to send a reply, once the reply has
772                  * been send, the connection should get freed.
773                  */
774                 (*req->cb)(req, req->cb_arg);
775         }
776
777         return (0);
778 }
779
780 /* Free connection ownership of which can be acquired by user using
781  * evhttp_request_own(). */
782 static inline void
783 evhttp_request_free_auto(struct evhttp_request *req)
784 {
785         if (!(req->flags & EVHTTP_USER_OWNED))
786                 evhttp_request_free(req);
787 }
788
789 static void
790 evhttp_request_free_(struct evhttp_connection *evcon, struct evhttp_request *req)
791 {
792         TAILQ_REMOVE(&evcon->requests, req, next);
793         evhttp_request_free_auto(req);
794 }
795
796 static void
797 evhttp_set_timeout_tv_(struct timeval *tv, const struct timeval *timeout, int def)
798 {
799         if (timeout == NULL && def != -1) {
800                 tv->tv_sec = def;
801                 tv->tv_usec = 0;
802                 return;
803         }
804
805         if (timeout) {
806                 *tv = *timeout;
807         } else {
808                 evutil_timerclear(tv);
809         }
810 }
811 static void
812 evhttp_set_timeout_(struct timeval *tv, int timeout, int def)
813 {
814         if (timeout == -1) {
815                 timeout = def;
816         }
817
818         if (timeout == -1) {
819                 evutil_timerclear(tv);
820         } else {
821                 struct timeval timeout_tv;
822                 timeout_tv.tv_sec = timeout;
823                 timeout_tv.tv_usec = 0;
824                 *tv = timeout_tv;
825         }
826 }
827
828 /* Called when evcon has experienced a (non-recoverable? -NM) error, as
829  * given in error. If it's an outgoing connection, reset the connection,
830  * retry any pending requests, and inform the user.  If it's incoming,
831  * delegates to evhttp_connection_incoming_fail(). */
832 void
833 evhttp_connection_fail_(struct evhttp_connection *evcon,
834     enum evhttp_request_error error)
835 {
836         const int errsave = EVUTIL_SOCKET_ERROR();
837         struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
838         void (*cb)(struct evhttp_request *, void *);
839         void *cb_arg;
840         void (*error_cb)(enum evhttp_request_error, void *);
841         void *error_cb_arg;
842         EVUTIL_ASSERT(req != NULL);
843
844         bufferevent_disable(evcon->bufev, EV_READ|EV_WRITE);
845
846         if (evcon->flags & EVHTTP_CON_INCOMING) {
847                 /*
848                  * for incoming requests, there are two different
849                  * failure cases.  it's either a network level error
850                  * or an http layer error. for problems on the network
851                  * layer like timeouts we just drop the connections.
852                  * For HTTP problems, we might have to send back a
853                  * reply before the connection can be freed.
854                  */
855                 if (evhttp_connection_incoming_fail(req, error) == -1)
856                         evhttp_connection_free(evcon);
857                 return;
858         }
859
860         error_cb = req->error_cb;
861         error_cb_arg = req->cb_arg;
862         /* when the request was canceled, the callback is not executed */
863         if (error != EVREQ_HTTP_REQUEST_CANCEL) {
864                 /* save the callback for later; the cb might free our object */
865                 cb = req->cb;
866                 cb_arg = req->cb_arg;
867         } else {
868                 cb = NULL;
869                 cb_arg = NULL;
870         }
871
872         /* do not fail all requests; the next request is going to get
873          * send over a new connection.   when a user cancels a request,
874          * all other pending requests should be processed as normal
875          */
876         evhttp_request_free_(evcon, req);
877
878         /* reset the connection */
879         evhttp_connection_reset_(evcon, 1);
880
881         /* We are trying the next request that was queued on us */
882         if (TAILQ_FIRST(&evcon->requests) != NULL)
883                 evhttp_connection_connect_(evcon);
884         else
885                 if ((evcon->flags & EVHTTP_CON_OUTGOING) &&
886                     (evcon->flags & EVHTTP_CON_AUTOFREE)) {
887                         evhttp_connection_free(evcon);
888                 }
889
890         /* The call to evhttp_connection_reset_ overwrote errno.
891          * Let's restore the original errno, so that the user's
892          * callback can have a better idea of what the error was.
893          */
894         EVUTIL_SET_SOCKET_ERROR(errsave);
895
896         /* inform the user */
897         if (error_cb != NULL)
898                 error_cb(error, error_cb_arg);
899         if (cb != NULL)
900                 (*cb)(NULL, cb_arg);
901 }
902
903 /* Bufferevent callback: invoked when any data has been written from an
904  * http connection's bufferevent */
905 static void
906 evhttp_write_cb(struct bufferevent *bufev, void *arg)
907 {
908         struct evhttp_connection *evcon = arg;
909
910         /* Activate our call back */
911         if (evcon->cb != NULL)
912                 (*evcon->cb)(evcon, evcon->cb_arg);
913 }
914
915 /**
916  * Advance the connection state.
917  * - If this is an outgoing connection, we've just processed the response;
918  *   idle or close the connection.
919  * - If this is an incoming connection, we've just processed the request;
920  *   respond.
921  */
922 static void
923 evhttp_connection_done(struct evhttp_connection *evcon)
924 {
925         struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
926         int con_outgoing = evcon->flags & EVHTTP_CON_OUTGOING;
927         int free_evcon = 0;
928
929         if (con_outgoing) {
930                 /* idle or close the connection */
931                 int need_close = evhttp_is_request_connection_close(req);
932                 TAILQ_REMOVE(&evcon->requests, req, next);
933                 req->evcon = NULL;
934
935                 evcon->state = EVCON_IDLE;
936
937                 /* check if we got asked to close the connection */
938                 if (need_close)
939                         evhttp_connection_reset_(evcon, 1);
940
941                 if (TAILQ_FIRST(&evcon->requests) != NULL) {
942                         /*
943                          * We have more requests; reset the connection
944                          * and deal with the next request.
945                          */
946                         if (!evhttp_connected(evcon))
947                                 evhttp_connection_connect_(evcon);
948                         else
949                                 evhttp_request_dispatch(evcon);
950                 } else if (!need_close) {
951                         /*
952                          * The connection is going to be persistent, but we
953                          * need to detect if the other side closes it.
954                          */
955                         evhttp_connection_start_detectclose(evcon);
956                 } else if ((evcon->flags & EVHTTP_CON_AUTOFREE)) {
957                         /*
958                          * If we have no more requests that need completion
959                          * and we're not waiting for the connection to close
960                          */
961                          free_evcon = 1;
962                 }
963         } else {
964                 /*
965                  * incoming connection - we need to leave the request on the
966                  * connection so that we can reply to it.
967                  */
968                 evcon->state = EVCON_WRITING;
969         }
970
971         /* notify the user of the request */
972         (*req->cb)(req, req->cb_arg);
973
974         /* if this was an outgoing request, we own and it's done. so free it. */
975         if (con_outgoing) {
976                 evhttp_request_free_auto(req);
977         }
978
979         /* If this was the last request of an outgoing connection and we're
980          * not waiting to receive a connection close event and we want to
981          * automatically free the connection. We check to ensure our request
982          * list is empty one last time just in case our callback added a
983          * new request.
984          */
985         if (free_evcon && TAILQ_FIRST(&evcon->requests) == NULL) {
986                 evhttp_connection_free(evcon);
987         }
988 }
989
990 /*
991  * Handles reading from a chunked request.
992  *   return ALL_DATA_READ:
993  *     all data has been read
994  *   return MORE_DATA_EXPECTED:
995  *     more data is expected
996  *   return DATA_CORRUPTED:
997  *     data is corrupted
998  *   return REQUEST_CANCELED:
999  *     request was canceled by the user calling evhttp_cancel_request
1000  *   return DATA_TOO_LONG:
1001  *     ran over the maximum limit
1002  */
1003
1004 static enum message_read_status
1005 evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
1006 {
1007         if (req == NULL || buf == NULL) {
1008             return DATA_CORRUPTED;
1009         }
1010
1011         while (1) {
1012                 size_t buflen;
1013
1014                 if ((buflen = evbuffer_get_length(buf)) == 0) {
1015                         break;
1016                 }
1017
1018                 /* evbuffer_get_length returns size_t, but len variable is ssize_t,
1019                  * check for overflow conditions */
1020                 if (buflen > EV_SSIZE_MAX) {
1021                         return DATA_CORRUPTED;
1022                 }
1023
1024                 if (req->ntoread < 0) {
1025                         /* Read chunk size */
1026                         ev_int64_t ntoread;
1027                         char *p = evbuffer_readln(buf, NULL, EVBUFFER_EOL_CRLF);
1028                         char *endp;
1029                         int error;
1030                         if (p == NULL)
1031                                 break;
1032                         /* the last chunk is on a new line? */
1033                         if (strlen(p) == 0) {
1034                                 mm_free(p);
1035                                 continue;
1036                         }
1037                         ntoread = evutil_strtoll(p, &endp, 16);
1038                         error = (*p == '\0' ||
1039                             (*endp != '\0' && *endp != ' ') ||
1040                             ntoread < 0);
1041                         mm_free(p);
1042                         if (error) {
1043                                 /* could not get chunk size */
1044                                 return (DATA_CORRUPTED);
1045                         }
1046
1047                         /* ntoread is signed int64, body_size is unsigned size_t, check for under/overflow conditions */
1048                         if ((ev_uint64_t)ntoread > EV_SIZE_MAX - req->body_size) {
1049                             return DATA_CORRUPTED;
1050                         }
1051
1052                         if (req->body_size + (size_t)ntoread > req->evcon->max_body_size) {
1053                                 /* failed body length test */
1054                                 event_debug(("Request body is too long"));
1055                                 return (DATA_TOO_LONG);
1056                         }
1057
1058                         req->body_size += (size_t)ntoread;
1059                         req->ntoread = ntoread;
1060                         if (req->ntoread == 0) {
1061                                 /* Last chunk */
1062                                 return (ALL_DATA_READ);
1063                         }
1064                         continue;
1065                 }
1066
1067                 /* req->ntoread is signed int64, len is ssize_t, based on arch,
1068                  * ssize_t could only be 32b, check for these conditions */
1069                 if (req->ntoread > EV_SSIZE_MAX) {
1070                         return DATA_CORRUPTED;
1071                 }
1072
1073                 /* don't have enough to complete a chunk; wait for more */
1074                 if (req->ntoread > 0 && buflen < (ev_uint64_t)req->ntoread)
1075                         return (MORE_DATA_EXPECTED);
1076
1077                 /* Completed chunk */
1078                 evbuffer_remove_buffer(buf, req->input_buffer, (size_t)req->ntoread);
1079                 req->ntoread = -1;
1080                 if (req->chunk_cb != NULL) {
1081                         req->flags |= EVHTTP_REQ_DEFER_FREE;
1082                         (*req->chunk_cb)(req, req->cb_arg);
1083                         evbuffer_drain(req->input_buffer,
1084                             evbuffer_get_length(req->input_buffer));
1085                         req->flags &= ~EVHTTP_REQ_DEFER_FREE;
1086                         if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
1087                                 return (REQUEST_CANCELED);
1088                         }
1089                 }
1090         }
1091
1092         return (MORE_DATA_EXPECTED);
1093 }
1094
1095 static void
1096 evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
1097 {
1098         struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
1099
1100         switch (evhttp_parse_headers_(req, buf)) {
1101         case DATA_CORRUPTED:
1102         case DATA_TOO_LONG:
1103                 evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
1104                 break;
1105         case ALL_DATA_READ:
1106                 bufferevent_disable(evcon->bufev, EV_READ);
1107                 evhttp_connection_done(evcon);
1108                 break;
1109         case MORE_DATA_EXPECTED:
1110         case REQUEST_CANCELED: /* ??? */
1111         default:
1112                 break;
1113         }
1114 }
1115
1116 static void
1117 evhttp_lingering_close(struct evhttp_connection *evcon,
1118         struct evhttp_request *req)
1119 {
1120         struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
1121
1122         size_t n = evbuffer_get_length(buf);
1123         if (n > (size_t) req->ntoread)
1124                 n = (size_t) req->ntoread;
1125         req->ntoread -= n;
1126         req->body_size += n;
1127
1128         event_debug(("Request body is too long, left " EV_I64_FMT,
1129                 EV_I64_ARG(req->ntoread)));
1130
1131         evbuffer_drain(buf, n);
1132         if (!req->ntoread)
1133                 evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
1134 }
1135 static void
1136 evhttp_lingering_fail(struct evhttp_connection *evcon,
1137         struct evhttp_request *req)
1138 {
1139         if (evcon->flags & EVHTTP_CON_LINGERING_CLOSE)
1140                 evhttp_lingering_close(evcon, req);
1141         else
1142                 evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
1143 }
1144
1145 static void
1146 evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
1147 {
1148         struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
1149
1150         if (req->chunked) {
1151                 switch (evhttp_handle_chunked_read(req, buf)) {
1152                 case ALL_DATA_READ:
1153                         /* finished last chunk */
1154                         evcon->state = EVCON_READING_TRAILER;
1155                         evhttp_read_trailer(evcon, req);
1156                         return;
1157                 case DATA_CORRUPTED:
1158                 case DATA_TOO_LONG:
1159                         /* corrupted data */
1160                         evhttp_connection_fail_(evcon,
1161                             EVREQ_HTTP_DATA_TOO_LONG);
1162                         return;
1163                 case REQUEST_CANCELED:
1164                         /* request canceled */
1165                         evhttp_request_free_auto(req);
1166                         return;
1167                 case MORE_DATA_EXPECTED:
1168                 default:
1169                         break;
1170                 }
1171         } else if (req->ntoread < 0) {
1172                 /* Read until connection close. */
1173                 if ((size_t)(req->body_size + evbuffer_get_length(buf)) < req->body_size) {
1174                         evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
1175                         return;
1176                 }
1177
1178                 req->body_size += evbuffer_get_length(buf);
1179                 evbuffer_add_buffer(req->input_buffer, buf);
1180         } else if (req->chunk_cb != NULL || evbuffer_get_length(buf) >= (size_t)req->ntoread) {
1181                 /* XXX: the above get_length comparison has to be fixed for overflow conditions! */
1182                 /* We've postponed moving the data until now, but we're
1183                  * about to use it. */
1184                 size_t n = evbuffer_get_length(buf);
1185
1186                 if (n > (size_t) req->ntoread)
1187                         n = (size_t) req->ntoread;
1188                 req->ntoread -= n;
1189                 req->body_size += n;
1190                 evbuffer_remove_buffer(buf, req->input_buffer, n);
1191         }
1192
1193         if (req->body_size > req->evcon->max_body_size ||
1194             (!req->chunked && req->ntoread >= 0 &&
1195                 (size_t)req->ntoread > req->evcon->max_body_size)) {
1196                 /* XXX: The above casted comparison must checked for overflow */
1197                 /* failed body length test */
1198
1199                 evhttp_lingering_fail(evcon, req);
1200                 return;
1201         }
1202
1203         if (evbuffer_get_length(req->input_buffer) > 0 && req->chunk_cb != NULL) {
1204                 req->flags |= EVHTTP_REQ_DEFER_FREE;
1205                 (*req->chunk_cb)(req, req->cb_arg);
1206                 req->flags &= ~EVHTTP_REQ_DEFER_FREE;
1207                 evbuffer_drain(req->input_buffer,
1208                     evbuffer_get_length(req->input_buffer));
1209                 if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
1210                         evhttp_request_free_auto(req);
1211                         return;
1212                 }
1213         }
1214
1215         if (!req->ntoread) {
1216                 bufferevent_disable(evcon->bufev, EV_READ);
1217                 /* Completed content length */
1218                 evhttp_connection_done(evcon);
1219                 return;
1220         }
1221 }
1222
1223 #define get_deferred_queue(evcon)               \
1224         ((evcon)->base)
1225
1226 /*
1227  * Gets called when more data becomes available
1228  */
1229
1230 static void
1231 evhttp_read_cb(struct bufferevent *bufev, void *arg)
1232 {
1233         struct evhttp_connection *evcon = arg;
1234         struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
1235
1236         /* Cancel if it's pending. */
1237         event_deferred_cb_cancel_(get_deferred_queue(evcon),
1238             &evcon->read_more_deferred_cb);
1239
1240         switch (evcon->state) {
1241         case EVCON_READING_FIRSTLINE:
1242                 evhttp_read_firstline(evcon, req);
1243                 /* note the request may have been freed in
1244                  * evhttp_read_body */
1245                 break;
1246         case EVCON_READING_HEADERS:
1247                 evhttp_read_header(evcon, req);
1248                 /* note the request may have been freed in
1249                  * evhttp_read_body */
1250                 break;
1251         case EVCON_READING_BODY:
1252                 evhttp_read_body(evcon, req);
1253                 /* note the request may have been freed in
1254                  * evhttp_read_body */
1255                 break;
1256         case EVCON_READING_TRAILER:
1257                 evhttp_read_trailer(evcon, req);
1258                 break;
1259         case EVCON_IDLE:
1260                 {
1261 #ifdef USE_DEBUG
1262                         struct evbuffer *input;
1263                         size_t total_len;
1264
1265                         input = bufferevent_get_input(evcon->bufev);
1266                         total_len = evbuffer_get_length(input);
1267                         event_debug(("%s: read "EV_SIZE_FMT
1268                                 " bytes in EVCON_IDLE state,"
1269                                 " resetting connection",
1270                                 __func__, EV_SIZE_ARG(total_len)));
1271 #endif
1272
1273                         evhttp_connection_reset_(evcon, 1);
1274                 }
1275                 break;
1276         case EVCON_DISCONNECTED:
1277         case EVCON_CONNECTING:
1278         case EVCON_WRITING:
1279         default:
1280                 event_errx(1, "%s: illegal connection state %d",
1281                            __func__, evcon->state);
1282         }
1283 }
1284
1285 static void
1286 evhttp_deferred_read_cb(struct event_callback *cb, void *data)
1287 {
1288         struct evhttp_connection *evcon = data;
1289         struct bufferevent *bev = evcon->bufev;
1290         if (bev->readcb)
1291                 (bev->readcb)(evcon->bufev, evcon);
1292 }
1293
1294 static void
1295 evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
1296 {
1297         /* This is after writing the request to the server */
1298         struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
1299         struct evbuffer *output = bufferevent_get_output(evcon->bufev);
1300         EVUTIL_ASSERT(req != NULL);
1301
1302         EVUTIL_ASSERT(evcon->state == EVCON_WRITING);
1303
1304         /* We need to wait until we've written all of our output data before we can
1305          * continue */
1306         if (evbuffer_get_length(output) > 0)
1307                 return;
1308
1309         /* We are done writing our header and are now expecting the response */
1310         req->kind = EVHTTP_RESPONSE;
1311
1312         evhttp_start_read_(evcon);
1313 }
1314
1315 /*
1316  * Clean up a connection object
1317  */
1318
1319 void
1320 evhttp_connection_free(struct evhttp_connection *evcon)
1321 {
1322         struct evhttp_request *req;
1323
1324         /* notify interested parties that this connection is going down */
1325         if (evhttp_connected(evcon) && evcon->closecb != NULL)
1326                 (*evcon->closecb)(evcon, evcon->closecb_arg);
1327
1328         /* remove all requests that might be queued on this
1329          * connection.  for server connections, this should be empty.
1330          * because it gets dequeued either in evhttp_connection_done or
1331          * evhttp_connection_fail_.
1332          */
1333         while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
1334                 evhttp_request_free_(evcon, req);
1335         }
1336
1337         if (evcon->http_server != NULL) {
1338                 struct evhttp *http = evcon->http_server;
1339                 TAILQ_REMOVE(&http->connections, evcon, next);
1340                 http->connection_cnt--;
1341         }
1342
1343         if (event_initialized(&evcon->retry_ev)) {
1344                 event_del(&evcon->retry_ev);
1345                 event_debug_unassign(&evcon->retry_ev);
1346         }
1347
1348         event_deferred_cb_cancel_(get_deferred_queue(evcon),
1349             &evcon->read_more_deferred_cb);
1350
1351         if (evcon->bufev != NULL) {
1352                 bufferevent_free(evcon->bufev);
1353         }
1354
1355         if (evcon->bind_address != NULL)
1356                 mm_free(evcon->bind_address);
1357
1358         if (evcon->address != NULL)
1359                 mm_free(evcon->address);
1360
1361 #ifndef _WIN32
1362         if (evcon->unixsocket != NULL)
1363                 mm_free(evcon->unixsocket);
1364 #endif
1365
1366         mm_free(evcon);
1367 }
1368
1369 void
1370 evhttp_connection_free_on_completion(struct evhttp_connection *evcon) {
1371         evcon->flags |= EVHTTP_CON_AUTOFREE;
1372 }
1373
1374 void
1375 evhttp_connection_set_local_address(struct evhttp_connection *evcon,
1376     const char *address)
1377 {
1378         EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
1379         if (evcon->bind_address)
1380                 mm_free(evcon->bind_address);
1381         if ((evcon->bind_address = mm_strdup(address)) == NULL)
1382                 event_warn("%s: strdup", __func__);
1383 }
1384
1385 void
1386 evhttp_connection_set_local_port(struct evhttp_connection *evcon,
1387     ev_uint16_t port)
1388 {
1389         EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
1390         evcon->bind_port = port;
1391 }
1392
1393 static void
1394 evhttp_request_dispatch(struct evhttp_connection* evcon)
1395 {
1396         struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
1397
1398         /* this should not usually happy but it's possible */
1399         if (req == NULL)
1400                 return;
1401
1402         EVUTIL_ASSERT(req->kind == EVHTTP_REQUEST);
1403
1404         /* delete possible close detection events */
1405         evhttp_connection_stop_detectclose(evcon);
1406
1407         /* we assume that the connection is connected already */
1408         EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
1409
1410         evcon->state = EVCON_WRITING;
1411
1412         /* Create the header from the store arguments */
1413         evhttp_make_header(evcon, req);
1414
1415         evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
1416 }
1417
1418 /** Hard-reset our connection state
1419  *
1420  * This will:
1421  * - reset fd
1422  * - clears out buffers
1423  * - call closecb
1424  */
1425 static void
1426 evhttp_connection_reset_hard_(struct evhttp_connection *evcon)
1427 {
1428         struct evbuffer *tmp;
1429         int err;
1430
1431         /* XXXX This is not actually an optimal fix.  Instead we ought to have
1432            an API for "stop connecting", or use bufferevent_replacefd to turn off
1433            connecting.  But for Libevent 2.0, this seems like a minimal change
1434            least likely to disrupt the rest of the bufferevent and http code.
1435
1436            Why is this here?  If the fd is set in the bufferevent, and the
1437            bufferevent is connecting, then you can't actually stop the
1438            bufferevent from trying to connect with bufferevent_disable().  The
1439            connect will never trigger, since we close the fd, but the timeout
1440            might.  That caused an assertion failure in evhttp_connection_fail_.
1441         */
1442         bufferevent_disable_hard_(evcon->bufev, EV_READ|EV_WRITE);
1443
1444         /* inform interested parties about connection close */
1445         if (evhttp_connected(evcon) && evcon->closecb != NULL)
1446                 (*evcon->closecb)(evcon, evcon->closecb_arg);
1447
1448         /** FIXME: manipulating with fd is unwanted */
1449         err = bufferevent_replacefd(evcon->bufev, -1);
1450         EVUTIL_ASSERT(!err && "setfd");
1451
1452         /* we need to clean up any buffered data */
1453         tmp = bufferevent_get_output(evcon->bufev);
1454         err = evbuffer_drain(tmp, -1);
1455         EVUTIL_ASSERT(!err && "drain output");
1456         tmp = bufferevent_get_input(evcon->bufev);
1457         err = evbuffer_drain(tmp, -1);
1458         EVUTIL_ASSERT(!err && "drain input");
1459 }
1460
1461 /** Reset our connection state
1462  *
1463  * This will:
1464  * - disables reading/writing
1465  * - puts us in DISCONNECTED state
1466  *
1467  * @param hard - hard reset will (@see evhttp_connection_reset_hard_())
1468  */
1469 void
1470 evhttp_connection_reset_(struct evhttp_connection *evcon, int hard)
1471 {
1472         bufferevent_setcb(evcon->bufev, NULL, NULL, NULL, NULL);
1473
1474         if (hard) {
1475                 evhttp_connection_reset_hard_(evcon);
1476         }
1477
1478         evcon->flags &= ~EVHTTP_CON_READING_ERROR;
1479         evcon->state = EVCON_DISCONNECTED;
1480 }
1481
1482 static void
1483 evhttp_connection_start_detectclose(struct evhttp_connection *evcon)
1484 {
1485         evcon->flags |= EVHTTP_CON_CLOSEDETECT;
1486         bufferevent_enable(evcon->bufev, EV_READ);
1487 }
1488
1489 static void
1490 evhttp_connection_stop_detectclose(struct evhttp_connection *evcon)
1491 {
1492         evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
1493         bufferevent_disable(evcon->bufev, EV_READ);
1494 }
1495
1496 static void
1497 evhttp_connection_retry(evutil_socket_t fd, short what, void *arg)
1498 {
1499         struct evhttp_connection *evcon = arg;
1500
1501         evcon->state = EVCON_DISCONNECTED;
1502         evhttp_connection_connect_(evcon);
1503 }
1504
1505 static void
1506 evhttp_connection_cb_cleanup(struct evhttp_connection *evcon)
1507 {
1508         struct evcon_requestq requests;
1509         EVUTIL_ASSERT(evcon->flags & EVHTTP_CON_OUTGOING);
1510
1511         evhttp_connection_reset_(evcon, 1);
1512
1513         if (evcon->retry_max < 0 || evcon->retry_cnt < evcon->retry_max) {
1514                 struct timeval tv_retry = evcon->initial_retry_timeout;
1515                 int i;
1516                 evtimer_assign(&evcon->retry_ev, evcon->base, evhttp_connection_retry, evcon);
1517                 /* XXXX handle failure from evhttp_add_event */
1518                 for (i=0; i < evcon->retry_cnt; ++i) {
1519                         tv_retry.tv_usec *= 2;
1520                         if (tv_retry.tv_usec > 1000000) {
1521                                 tv_retry.tv_usec -= 1000000;
1522                                 tv_retry.tv_sec += 1;
1523                         }
1524                         tv_retry.tv_sec *= 2;
1525                         if (tv_retry.tv_sec > 3600) {
1526                                 tv_retry.tv_sec = 3600;
1527                                 tv_retry.tv_usec = 0;
1528                         }
1529                 }
1530                 event_add(&evcon->retry_ev, &tv_retry);
1531                 evcon->retry_cnt++;
1532                 return;
1533         }
1534
1535         /*
1536          * User callback can do evhttp_make_request() on the same
1537          * evcon so new request will be added to evcon->requests.  To
1538          * avoid freeing it prematurely we iterate over the copy of
1539          * the queue.
1540          */
1541         TAILQ_INIT(&requests);
1542         while (TAILQ_FIRST(&evcon->requests) != NULL) {
1543                 struct evhttp_request *request = TAILQ_FIRST(&evcon->requests);
1544                 TAILQ_REMOVE(&evcon->requests, request, next);
1545                 TAILQ_INSERT_TAIL(&requests, request, next);
1546         }
1547
1548         /* for now, we just signal all requests by executing their callbacks */
1549         while (TAILQ_FIRST(&requests) != NULL) {
1550                 struct evhttp_request *request = TAILQ_FIRST(&requests);
1551                 TAILQ_REMOVE(&requests, request, next);
1552                 request->evcon = NULL;
1553
1554                 /* we might want to set an error here */
1555                 request->cb(request, request->cb_arg);
1556                 evhttp_request_free_auto(request);
1557         }
1558
1559         if (TAILQ_FIRST(&evcon->requests) == NULL
1560           && (evcon->flags & EVHTTP_CON_AUTOFREE)) {
1561                 evhttp_connection_free(evcon);
1562         }
1563
1564 }
1565
1566 static void
1567 evhttp_connection_read_on_write_error(struct evhttp_connection *evcon,
1568     struct evhttp_request *req)
1569 {
1570         struct evbuffer *buf;
1571
1572         /** Second time, we can't read anything */
1573         if (evcon->flags & EVHTTP_CON_READING_ERROR) {
1574                 evcon->flags &= ~EVHTTP_CON_READING_ERROR;
1575                 evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
1576                 return;
1577         }
1578
1579         req->kind = EVHTTP_RESPONSE;
1580
1581         buf = bufferevent_get_output(evcon->bufev);
1582         evbuffer_unfreeze(buf, 1);
1583         evbuffer_drain(buf, evbuffer_get_length(buf));
1584         evbuffer_freeze(buf, 1);
1585
1586         evhttp_start_read_(evcon);
1587         evcon->flags |= EVHTTP_CON_READING_ERROR;
1588 }
1589
1590 static void
1591 evhttp_error_cb(struct bufferevent *bufev, short what, void *arg)
1592 {
1593         struct evhttp_connection *evcon = arg;
1594         struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
1595
1596         switch (evcon->state) {
1597         case EVCON_CONNECTING:
1598                 if (what & BEV_EVENT_TIMEOUT) {
1599                         event_debug(("%s: connection timeout for \"%s:%d\" on "
1600                                 EV_SOCK_FMT,
1601                                 __func__, evcon->address, evcon->port,
1602                                 EV_SOCK_ARG(bufferevent_getfd(bufev))));
1603                         evhttp_connection_cb_cleanup(evcon);
1604                         return;
1605                 }
1606                 break;
1607
1608         case EVCON_READING_BODY:
1609                 if (!req->chunked && req->ntoread < 0
1610                     && what == (BEV_EVENT_READING|BEV_EVENT_EOF)) {
1611                         /* EOF on read can be benign */
1612                         evhttp_connection_done(evcon);
1613                         return;
1614                 }
1615                 break;
1616
1617         case EVCON_DISCONNECTED:
1618         case EVCON_IDLE:
1619         case EVCON_READING_FIRSTLINE:
1620         case EVCON_READING_HEADERS:
1621         case EVCON_READING_TRAILER:
1622         case EVCON_WRITING:
1623         default:
1624                 break;
1625         }
1626
1627         /* when we are in close detect mode, a read error means that
1628          * the other side closed their connection.
1629          */
1630         if (evcon->flags & EVHTTP_CON_CLOSEDETECT) {
1631                 evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
1632                 EVUTIL_ASSERT(evcon->http_server == NULL);
1633                 /* For connections from the client, we just
1634                  * reset the connection so that it becomes
1635                  * disconnected.
1636                  */
1637                 EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
1638                 evhttp_connection_reset_(evcon, 1);
1639
1640                 /*
1641                  * If we have no more requests that need completion
1642                  * and we want to auto-free the connection when all
1643                  * requests have been completed.
1644                  */
1645                 if (TAILQ_FIRST(&evcon->requests) == NULL
1646                   && (evcon->flags & EVHTTP_CON_OUTGOING)
1647                   && (evcon->flags & EVHTTP_CON_AUTOFREE)) {
1648                         evhttp_connection_free(evcon);
1649                 }
1650                 return;
1651         }
1652
1653         if (what & BEV_EVENT_TIMEOUT) {
1654                 evhttp_connection_fail_(evcon, EVREQ_HTTP_TIMEOUT);
1655         } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
1656                 if (what & BEV_EVENT_WRITING &&
1657                         evcon->flags & EVHTTP_CON_READ_ON_WRITE_ERROR) {
1658                         evhttp_connection_read_on_write_error(evcon, req);
1659                         return;
1660                 }
1661
1662                 if (what & BEV_EVENT_READING &&
1663                         evcon->flags & EVHTTP_CON_READ_ON_WRITE_ERROR &&
1664                         evbuffer_get_length(bufferevent_get_input(bufev))) {
1665                         event_deferred_cb_schedule_(get_deferred_queue(evcon),
1666                             &evcon->read_more_deferred_cb);
1667                         return;
1668                 }
1669
1670                 evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
1671         } else if (what == BEV_EVENT_CONNECTED) {
1672         } else {
1673                 evhttp_connection_fail_(evcon, EVREQ_HTTP_BUFFER_ERROR);
1674         }
1675 }
1676
1677 /*
1678  * Event callback for asynchronous connection attempt.
1679  */
1680 static void
1681 evhttp_connection_cb(struct bufferevent *bufev, short what, void *arg)
1682 {
1683         struct evhttp_connection *evcon = arg;
1684
1685         if (!(what & BEV_EVENT_CONNECTED)) {
1686                 /* some operating systems return ECONNREFUSED immediately
1687                  * when connecting to a local address.  the cleanup is going
1688                  * to reschedule this function call.
1689                  */
1690 #ifndef _WIN32
1691                 if (errno == ECONNREFUSED)
1692                         goto cleanup;
1693 #endif
1694                 evhttp_error_cb(bufev, what, arg);
1695                 return;
1696         }
1697
1698         /* We are connected to the server now */
1699         event_debug(("%s: connected to \"%s:%d\" on "EV_SOCK_FMT"\n",
1700                         __func__, evcon->address, evcon->port,
1701                         EV_SOCK_ARG(bufferevent_getfd(bufev))));
1702
1703         /* Reset the retry count as we were successful in connecting */
1704         evcon->retry_cnt = 0;
1705         evcon->state = EVCON_IDLE;
1706
1707         /* reset the bufferevent cbs */
1708         bufferevent_setcb(evcon->bufev,
1709             evhttp_read_cb,
1710             evhttp_write_cb,
1711             evhttp_error_cb,
1712             evcon);
1713
1714         bufferevent_set_timeouts(evcon->bufev,
1715             &evcon->timeout_read, &evcon->timeout_write);
1716
1717         /* try to start requests that have queued up on this connection */
1718         evhttp_request_dispatch(evcon);
1719         return;
1720
1721  cleanup:
1722         evhttp_connection_cb_cleanup(evcon);
1723 }
1724
1725 /*
1726  * Check if we got a valid response code.
1727  */
1728
1729 static int
1730 evhttp_valid_response_code(int code)
1731 {
1732         if (code == 0)
1733                 return (0);
1734
1735         return (1);
1736 }
1737
1738 static int
1739 evhttp_parse_http_version(const char *version, struct evhttp_request *req)
1740 {
1741         int major, minor;
1742         char ch;
1743         int n = sscanf(version, "HTTP/%d.%d%c", &major, &minor, &ch);
1744         if (n != 2 || major > 1) {
1745                 event_debug(("%s: bad version %s on message %p from %s",
1746                         __func__, version, (void *)req, req->remote_host));
1747                 return (-1);
1748         }
1749         req->major = major;
1750         req->minor = minor;
1751         return (0);
1752 }
1753
1754 /* Parses the status line of a web server */
1755
1756 static int
1757 evhttp_parse_response_line(struct evhttp_request *req, char *line)
1758 {
1759         char *protocol;
1760         char *number;
1761         const char *readable = "";
1762
1763         protocol = strsep(&line, " ");
1764         if (line == NULL)
1765                 return (-1);
1766         number = strsep(&line, " ");
1767         if (line != NULL)
1768                 readable = line;
1769
1770         if (evhttp_parse_http_version(protocol, req) < 0)
1771                 return (-1);
1772
1773         req->response_code = atoi(number);
1774         if (!evhttp_valid_response_code(req->response_code)) {
1775                 event_debug(("%s: bad response code \"%s\"",
1776                         __func__, number));
1777                 return (-1);
1778         }
1779
1780         if (req->response_code_line != NULL)
1781                 mm_free(req->response_code_line);
1782         if ((req->response_code_line = mm_strdup(readable)) == NULL) {
1783                 event_warn("%s: strdup", __func__);
1784                 return (-1);
1785         }
1786
1787         return (0);
1788 }
1789
1790 /* Parse the first line of a HTTP request */
1791
1792 static int
1793 evhttp_parse_request_line(struct evhttp_request *req, char *line, size_t len)
1794 {
1795         char *eos = line + len;
1796         char *method;
1797         char *uri;
1798         char *version;
1799         const char *hostname;
1800         const char *scheme;
1801         size_t method_len;
1802         enum evhttp_cmd_type type = 0;
1803
1804         while (eos > line && *(eos-1) == ' ') {
1805                 *(eos-1) = '\0';
1806                 --eos;
1807                 --len;
1808         }
1809         if (len < strlen("GET / HTTP/1.0"))
1810                 return -1;
1811
1812         /* Parse the request line */
1813         method = strsep(&line, " ");
1814         if (!line)
1815                 return -1;
1816         uri = line;
1817         version = strrchr(uri, ' ');
1818         if (!version || uri == version)
1819                 return -1;
1820         *version = '\0';
1821         version++;
1822
1823         method_len = (uri - method) - 1;
1824
1825         /* First line */
1826         switch (method_len) {
1827             case 3:
1828                 /* The length of the method string is 3, meaning it can only be one of two methods: GET or PUT */
1829             
1830                 /* Since both GET and PUT share the same character 'T' at the end,
1831                  * if the string doesn't have 'T', we can immediately determine this
1832                  * is an invalid HTTP method */
1833             
1834                 if (method[2] != 'T') {
1835                     break;
1836                 }
1837             
1838                 switch (*method) {
1839                     case 'G':
1840                         /* This first byte is 'G', so make sure the next byte is
1841                          * 'E', if it isn't then this isn't a valid method */
1842                     
1843                         if (method[1] == 'E') {
1844                             type = EVHTTP_REQ_GET;
1845                         }
1846                     
1847                         break;
1848                     case 'P':
1849                         /* First byte is P, check second byte for 'U', if not,
1850                          * we know it's an invalid method */
1851                         if (method[1] == 'U') {
1852                             type = EVHTTP_REQ_PUT;
1853                         }
1854                         break;
1855                     default:
1856                         break;
1857                 }
1858                 break;
1859             case 4:
1860                 /* The method length is 4 bytes, leaving only the methods POST, HEAD, LOCK, COPY and MOVE */
1861                 switch (*method) {
1862                     case 'P':
1863                         if (method[3] == 'T' && method[2] == 'S' && method[1] == 'O') {
1864                             type = EVHTTP_REQ_POST;
1865                         }
1866                         break;
1867                     case 'H':
1868                         if (method[3] == 'D' && method[2] == 'A' && method[1] == 'E') {
1869                             type = EVHTTP_REQ_HEAD;
1870                         }
1871                         break;
1872                     case 'L':
1873                         if (method[3] == 'K' && method[2] == 'C' && method[1] == 'O') {
1874                             type = EVHTTP_REQ_LOCK;
1875                         }
1876                         break;
1877                     case 'C':
1878                         if (method[3] == 'Y' && method[2] == 'P' && method[1] == 'O') {
1879                             type = EVHTTP_REQ_COPY;
1880                         }
1881                         break;
1882                     case 'M':
1883                         if (method[3] == 'E' && method[2] == 'V' && method[1] == 'O') {
1884                             type = EVHTTP_REQ_MOVE;
1885                         }
1886                         break;
1887                     default:
1888                         break;
1889                 }
1890                 break;
1891             case 5:
1892                 /* Method length is 5 bytes, which can only encompass PATCH, TRACE and MKCOL */
1893                 switch (*method) {
1894                     case 'P':
1895                         if (method[4] == 'H' && method[3] == 'C' && method[2] == 'T' && method[1] == 'A') {
1896                             type = EVHTTP_REQ_PATCH;
1897                         }
1898                         break;
1899                     case 'T':
1900                         if (method[4] == 'E' && method[3] == 'C' && method[2] == 'A' && method[1] == 'R') {
1901                             type = EVHTTP_REQ_TRACE;
1902                         }
1903                     
1904                         break;
1905                     case 'M':
1906                         if (method[4] == 'L' && method[3] == 'O' && method[2] == 'C' && method[1] == 'K') {
1907                             type = EVHTTP_REQ_MKCOL;
1908                         }
1909                         break;
1910                     default:
1911                         break;
1912                 }
1913                 break;
1914             case 6:
1915                 /* Method length is 6, only valid methods 6 bytes in length is DELETE and UNLOCK */
1916                 switch (*method) {
1917                     case 'D':
1918                         if (method[5] == 'E' && method[4] == 'T' && method[3] == 'E' &&
1919                                 method[2] == 'L' && method[1] == 'E') {
1920                             type = EVHTTP_REQ_DELETE;
1921                         }
1922                         break;
1923                     case 'U':
1924                         if (method[5] == 'K' && method[4] == 'C' && method[3] == 'O' &&
1925                                 method[2] == 'L' && method[1] == 'N') {
1926                             type = EVHTTP_REQ_UNLOCK;
1927                         }
1928                         break;
1929                     default:
1930                         break;
1931                 }
1932                 break;
1933             case 7:
1934                 /* Method length is 7, only valid methods are "OPTIONS" and "CONNECT" */
1935                 switch (*method) {
1936                     case 'O':
1937                         if (method[6] == 'S' && method[5] == 'N' && method[4] == 'O' &&
1938                                 method[3] == 'I' && method[2] == 'T' && method[1] == 'P') {
1939                             type = EVHTTP_REQ_OPTIONS;
1940                         }
1941                    
1942                         break;
1943                     case 'C':
1944                         if (method[6] == 'T' && method[5] == 'C' && method[4] == 'E' &&
1945                                 method[3] == 'N' && method[2] == 'N' && method[1] == 'O') {
1946                             type = EVHTTP_REQ_CONNECT;
1947                         }
1948                     
1949                         break;
1950                     default:
1951                         break;
1952                 }
1953                 break;
1954             case 8:
1955                 /* Method length is 8, only valid method 8 bytes in length is PROPFIND */
1956
1957                 /* If the first byte isn't 'P' then it's invalid */
1958                 if (*method != 'P') {
1959                     break;
1960                 }
1961
1962                 if (method[7] == 'D' && method[6] == 'N' && method[5] == 'I' &&
1963                         method[4] == 'F' && method[3] == 'P' && method[2] == 'O' &&
1964                         method[1] == 'R') {
1965                     type = EVHTTP_REQ_PROPFIND;
1966                 }
1967
1968                 break;
1969             case 9:
1970                 /* Method length is 9, only valid method 9 bytes in length is PROPPATCH */
1971
1972                 /* If the first byte isn't 'P' then it's invalid */
1973                 if (*method != 'P') {
1974                     break;
1975                 }
1976
1977                 if (method[8] == 'H' && method[7] == 'C' && method[6] == 'T' &&
1978                         method[5] == 'A' && method[4] == 'P' && method[3] == 'P' &&
1979                         method[2] == 'O' && method[1] == 'R') {
1980                     type = EVHTTP_REQ_PROPPATCH;
1981                 }
1982
1983                 break;
1984         } /* switch */
1985
1986         if (!type) {
1987                 /* check extended methods, we only care about the
1988                  * type set by the cmp function if the cmp function
1989                  * returns a 0 value.
1990                  */
1991                 struct evhttp_ext_method ext_method;
1992
1993                 ext_method.method = method;
1994                 ext_method.type = 0;
1995                 ext_method.flags = 0;
1996
1997                 if (req->evcon->ext_method_cmp &&
1998                     req->evcon->ext_method_cmp(&ext_method) == 0) {
1999                         /* make sure the other fields in ext_method are
2000                          * not changed by the callback.
2001                          */
2002                         if (strcmp(ext_method.method, method) != 0) {
2003                                 event_warn("%s: modifying the 'method' field of ext_method_cmp's "
2004                                         "parameter is not allowed", __func__);
2005                                 return -1;
2006                         }
2007                         if (ext_method.flags != 0) {
2008                                 event_warn("%s: modifying the 'flags' field of ext_method_cmp's "
2009                                         "parameter is not allowed", __func__);
2010                                 return -1;
2011                         }
2012                         type = ext_method.type;
2013                 }
2014         }
2015
2016         if (!type) {
2017                 event_debug(("%s: bad method %s on request %p from %s",
2018                             __func__, method, (void *)req, req->remote_host));
2019                 /* No error yet; we'll give a better error later when
2020                  * we see that req->type is unsupported. */
2021         }
2022
2023         req->type = type;
2024
2025         if (evhttp_parse_http_version(version, req) < 0)
2026                 return -1;
2027
2028         if ((req->uri = mm_strdup(uri)) == NULL) {
2029                 event_debug(("%s: mm_strdup", __func__));
2030                 return -1;
2031         }
2032
2033         if (type == EVHTTP_REQ_CONNECT) {
2034                 if ((req->uri_elems = evhttp_uri_parse_authority(req->uri, 0)) == NULL) {
2035                         return -1;
2036                 }
2037         } else {
2038                 if ((req->uri_elems = evhttp_uri_parse_with_flags(req->uri,
2039                             EVHTTP_URI_NONCONFORMANT)) == NULL) {
2040                         return -1;
2041                 }
2042         }
2043
2044         /* If we have an absolute-URI, check to see if it is an http request
2045            for a known vhost or server alias. If we don't know about this
2046            host, we consider it a proxy request. */
2047         scheme = evhttp_uri_get_scheme(req->uri_elems);
2048         hostname = evhttp_uri_get_host(req->uri_elems);
2049         if (scheme && (!evutil_ascii_strcasecmp(scheme, "http") ||
2050                        !evutil_ascii_strcasecmp(scheme, "https")) &&
2051             hostname &&
2052             !evhttp_find_vhost(req->evcon->http_server, NULL, hostname))
2053                 req->flags |= EVHTTP_PROXY_REQUEST;
2054
2055         return 0;
2056 }
2057
2058 const char *
2059 evhttp_find_header(const struct evkeyvalq *headers, const char *key)
2060 {
2061         struct evkeyval *header;
2062
2063         TAILQ_FOREACH(header, headers, next) {
2064                 if (evutil_ascii_strcasecmp(header->key, key) == 0)
2065                         return (header->value);
2066         }
2067
2068         return (NULL);
2069 }
2070
2071 void
2072 evhttp_clear_headers(struct evkeyvalq *headers)
2073 {
2074         struct evkeyval *header;
2075
2076         for (header = TAILQ_FIRST(headers);
2077             header != NULL;
2078             header = TAILQ_FIRST(headers)) {
2079                 TAILQ_REMOVE(headers, header, next);
2080                 mm_free(header->key);
2081                 mm_free(header->value);
2082                 mm_free(header);
2083         }
2084 }
2085
2086 /*
2087  * Returns 0,  if the header was successfully removed.
2088  * Returns -1, if the header could not be found.
2089  */
2090
2091 int
2092 evhttp_remove_header(struct evkeyvalq *headers, const char *key)
2093 {
2094         struct evkeyval *header;
2095
2096         TAILQ_FOREACH(header, headers, next) {
2097                 if (evutil_ascii_strcasecmp(header->key, key) == 0)
2098                         break;
2099         }
2100
2101         if (header == NULL)
2102                 return (-1);
2103
2104         /* Free and remove the header that we found */
2105         TAILQ_REMOVE(headers, header, next);
2106         mm_free(header->key);
2107         mm_free(header->value);
2108         mm_free(header);
2109
2110         return (0);
2111 }
2112
2113 static int
2114 evhttp_header_is_valid_value(const char *value)
2115 {
2116         const char *p = value;
2117
2118         while ((p = strpbrk(p, "\r\n")) != NULL) {
2119                 /* we really expect only one new line */
2120                 p += strspn(p, "\r\n");
2121                 /* we expect a space or tab for continuation */
2122                 if (*p != ' ' && *p != '\t')
2123                         return (0);
2124         }
2125         return (1);
2126 }
2127
2128 int
2129 evhttp_add_header(struct evkeyvalq *headers,
2130     const char *key, const char *value)
2131 {
2132         event_debug(("%s: key: %s val: %s\n", __func__, key, value));
2133
2134         if (strchr(key, '\r') != NULL || strchr(key, '\n') != NULL) {
2135                 /* drop illegal headers */
2136                 event_debug(("%s: dropping illegal header key\n", __func__));
2137                 return (-1);
2138         }
2139
2140         if (!evhttp_header_is_valid_value(value)) {
2141                 event_debug(("%s: dropping illegal header value\n", __func__));
2142                 return (-1);
2143         }
2144
2145         return (evhttp_add_header_internal(headers, key, value));
2146 }
2147
2148 static int
2149 evhttp_add_header_internal(struct evkeyvalq *headers,
2150     const char *key, const char *value)
2151 {
2152         struct evkeyval *header = mm_calloc(1, sizeof(struct evkeyval));
2153         if (header == NULL) {
2154                 event_warn("%s: calloc", __func__);
2155                 return (-1);
2156         }
2157         if ((header->key = mm_strdup(key)) == NULL) {
2158                 mm_free(header);
2159                 event_warn("%s: strdup", __func__);
2160                 return (-1);
2161         }
2162         if ((header->value = mm_strdup(value)) == NULL) {
2163                 mm_free(header->key);
2164                 mm_free(header);
2165                 event_warn("%s: strdup", __func__);
2166                 return (-1);
2167         }
2168
2169         TAILQ_INSERT_TAIL(headers, header, next);
2170
2171         return (0);
2172 }
2173
2174 /*
2175  * Parses header lines from a request or a response into the specified
2176  * request object given an event buffer.
2177  *
2178  * Returns
2179  *   DATA_CORRUPTED      on error
2180  *   MORE_DATA_EXPECTED  when we need to read more headers
2181  *   ALL_DATA_READ       when all headers have been read.
2182  */
2183
2184 enum message_read_status
2185 evhttp_parse_firstline_(struct evhttp_request *req, struct evbuffer *buffer)
2186 {
2187         char *line;
2188         enum message_read_status status = ALL_DATA_READ;
2189
2190         size_t len;
2191         /* XXX try */
2192         line = evbuffer_readln(buffer, &len, EVBUFFER_EOL_CRLF);
2193         if (line == NULL) {
2194                 if (req->evcon != NULL &&
2195                     evbuffer_get_length(buffer) > req->evcon->max_headers_size)
2196                         return (DATA_TOO_LONG);
2197                 else
2198                         return (MORE_DATA_EXPECTED);
2199         }
2200
2201         if (req->evcon != NULL && len > req->evcon->max_headers_size) {
2202                 mm_free(line);
2203                 return (DATA_TOO_LONG);
2204         }
2205
2206         req->headers_size = len;
2207
2208         switch (req->kind) {
2209         case EVHTTP_REQUEST:
2210                 if (evhttp_parse_request_line(req, line, len) == -1)
2211                         status = DATA_CORRUPTED;
2212                 break;
2213         case EVHTTP_RESPONSE:
2214                 if (evhttp_parse_response_line(req, line) == -1)
2215                         status = DATA_CORRUPTED;
2216                 break;
2217         default:
2218                 status = DATA_CORRUPTED;
2219         }
2220
2221         mm_free(line);
2222         return (status);
2223 }
2224
2225 static int
2226 evhttp_append_to_last_header(struct evkeyvalq *headers, char *line)
2227 {
2228         struct evkeyval *header = TAILQ_LAST(headers, evkeyvalq);
2229         char *newval;
2230         size_t old_len, line_len;
2231
2232         if (header == NULL)
2233                 return (-1);
2234
2235         old_len = strlen(header->value);
2236
2237         /* Strip space from start and end of line. */
2238         while (*line == ' ' || *line == '\t')
2239                 ++line;
2240         evutil_rtrim_lws_(line);
2241
2242         line_len = strlen(line);
2243
2244         newval = mm_realloc(header->value, old_len + line_len + 2);
2245         if (newval == NULL)
2246                 return (-1);
2247
2248         newval[old_len] = ' ';
2249         memcpy(newval + old_len + 1, line, line_len + 1);
2250         header->value = newval;
2251
2252         return (0);
2253 }
2254
2255 enum message_read_status
2256 evhttp_parse_headers_(struct evhttp_request *req, struct evbuffer* buffer)
2257 {
2258         enum message_read_status errcode = DATA_CORRUPTED;
2259         char *line;
2260         enum message_read_status status = MORE_DATA_EXPECTED;
2261
2262         struct evkeyvalq* headers = req->input_headers;
2263         size_t len;
2264         while ((line = evbuffer_readln(buffer, &len, EVBUFFER_EOL_CRLF))
2265                != NULL) {
2266                 char *skey, *svalue;
2267
2268                 req->headers_size += len;
2269
2270                 if (req->evcon != NULL &&
2271                     req->headers_size > req->evcon->max_headers_size) {
2272                         errcode = DATA_TOO_LONG;
2273                         goto error;
2274                 }
2275
2276                 if (*line == '\0') { /* Last header - Done */
2277                         status = ALL_DATA_READ;
2278                         mm_free(line);
2279                         break;
2280                 }
2281
2282                 /* Check if this is a continuation line */
2283                 if (*line == ' ' || *line == '\t') {
2284                         if (evhttp_append_to_last_header(headers, line) == -1)
2285                                 goto error;
2286                         mm_free(line);
2287                         continue;
2288                 }
2289
2290                 /* Processing of header lines */
2291                 svalue = line;
2292                 skey = strsep(&svalue, ":");
2293                 if (svalue == NULL)
2294                         goto error;
2295
2296                 svalue += strspn(svalue, " ");
2297                 evutil_rtrim_lws_(svalue);
2298
2299                 if (evhttp_add_header(headers, skey, svalue) == -1)
2300                         goto error;
2301
2302                 mm_free(line);
2303         }
2304
2305         if (status == MORE_DATA_EXPECTED) {
2306                 if (req->evcon != NULL &&
2307                 req->headers_size + evbuffer_get_length(buffer) > req->evcon->max_headers_size)
2308                         return (DATA_TOO_LONG);
2309         }
2310
2311         return (status);
2312
2313  error:
2314         mm_free(line);
2315         return (errcode);
2316 }
2317
2318 static int
2319 evhttp_get_body_length(struct evhttp_request *req)
2320 {
2321         struct evkeyvalq *headers = req->input_headers;
2322         const char *content_length;
2323         const char *connection;
2324
2325         content_length = evhttp_find_header(headers, "Content-Length");
2326         connection = evhttp_find_header(headers, "Connection");
2327
2328         if (content_length == NULL && connection == NULL)
2329                 req->ntoread = -1;
2330         else if (content_length == NULL &&
2331             evutil_ascii_strcasecmp(connection, "Close") != 0) {
2332                 req->ntoread = 0;
2333         } else if (content_length == NULL) {
2334                 req->ntoread = -1;
2335         } else {
2336                 char *endp;
2337                 ev_int64_t ntoread = evutil_strtoll(content_length, &endp, 10);
2338                 if (*content_length == '\0' || *endp != '\0' || ntoread < 0) {
2339                         event_debug(("%s: illegal content length: %s",
2340                                 __func__, content_length));
2341                         return (-1);
2342                 }
2343                 req->ntoread = ntoread;
2344         }
2345
2346         event_debug(("%s: bytes to read: "EV_I64_FMT" (in buffer "EV_SIZE_FMT")\n",
2347                 __func__, EV_I64_ARG(req->ntoread),
2348                 EV_SIZE_ARG(evbuffer_get_length(bufferevent_get_input(req->evcon->bufev)))));
2349
2350         return (0);
2351 }
2352
2353 static int
2354 evhttp_method_may_have_body_(struct evhttp_connection *evcon, enum evhttp_cmd_type type)
2355 {
2356         /* NOTE: some version of GCC reports a warning that flags may be uninitialized, hence assignment */
2357         ev_uint16_t flags = 0;
2358         evhttp_method_(evcon, type, &flags);
2359         return (flags & EVHTTP_METHOD_HAS_BODY) ? 1 : 0;
2360 }
2361
2362 static void
2363 evhttp_get_body(struct evhttp_connection *evcon, struct evhttp_request *req)
2364 {
2365         const char *xfer_enc;
2366
2367         /* If this is a request without a body, then we are done */
2368         if (req->kind == EVHTTP_REQUEST &&
2369             !evhttp_method_may_have_body_(evcon, req->type)) {
2370                 evhttp_connection_done(evcon);
2371                 return;
2372         }
2373         evcon->state = EVCON_READING_BODY;
2374         xfer_enc = evhttp_find_header(req->input_headers, "Transfer-Encoding");
2375         if (xfer_enc != NULL && evutil_ascii_strcasecmp(xfer_enc, "chunked") == 0) {
2376                 req->chunked = 1;
2377                 req->ntoread = -1;
2378         } else {
2379                 if (evhttp_get_body_length(req) == -1) {
2380                         evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
2381                         return;
2382                 }
2383                 if (req->kind == EVHTTP_REQUEST && req->ntoread < 1) {
2384                         /* An incoming request with no content-length and no
2385                          * transfer-encoding has no body. */
2386                         evhttp_connection_done(evcon);
2387                         return;
2388                 }
2389         }
2390
2391         /* Should we send a 100 Continue status line? */
2392         switch (evhttp_have_expect(req, 1)) {
2393                 case CONTINUE:
2394                                 /* XXX It would be nice to do some sanity
2395                                    checking here. Does the resource exist?
2396                                    Should the resource accept post requests? If
2397                                    no, we should respond with an error. For
2398                                    now, just optimistically tell the client to
2399                                    send their message body. */
2400                                 if (req->ntoread > 0) {
2401                                         /* ntoread is ev_int64_t, max_body_size is ev_uint64_t */ 
2402                                         if ((req->evcon->max_body_size <= EV_INT64_MAX) &&
2403                                                 (ev_uint64_t)req->ntoread > req->evcon->max_body_size) {
2404                                                 evhttp_lingering_fail(evcon, req);
2405                                                 return;
2406                                         }
2407                                 }
2408                                 if (!evbuffer_get_length(bufferevent_get_input(evcon->bufev)))
2409                                         evhttp_send_continue(evcon, req);
2410                         break;
2411                 case OTHER:
2412                         evhttp_send_error(req, HTTP_EXPECTATIONFAILED, NULL);
2413                         return;
2414                 case NO: break;
2415         }
2416
2417         evhttp_read_body(evcon, req);
2418         /* note the request may have been freed in evhttp_read_body */
2419 }
2420
2421 static void
2422 evhttp_read_firstline(struct evhttp_connection *evcon,
2423                       struct evhttp_request *req)
2424 {
2425         enum message_read_status res;
2426
2427         res = evhttp_parse_firstline_(req, bufferevent_get_input(evcon->bufev));
2428         if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
2429                 /* Error while reading, terminate */
2430                 event_debug(("%s: bad header lines on "EV_SOCK_FMT"\n",
2431                         __func__, EV_SOCK_ARG(bufferevent_getfd(evcon->bufev))));
2432                 evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
2433                 return;
2434         } else if (res == MORE_DATA_EXPECTED) {
2435                 /* Need more header lines */
2436                 return;
2437         }
2438
2439         evcon->state = EVCON_READING_HEADERS;
2440         evhttp_read_header(evcon, req);
2441 }
2442
2443 static void
2444 evhttp_read_header(struct evhttp_connection *evcon,
2445                    struct evhttp_request *req)
2446 {
2447         enum message_read_status res;
2448         evutil_socket_t fd = bufferevent_getfd(evcon->bufev);
2449
2450         res = evhttp_parse_headers_(req, bufferevent_get_input(evcon->bufev));
2451         if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
2452                 /* Error while reading, terminate */
2453                 event_debug(("%s: bad header lines on "EV_SOCK_FMT"\n",
2454                         __func__, EV_SOCK_ARG(fd)));
2455                 evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
2456                 return;
2457         } else if (res == MORE_DATA_EXPECTED) {
2458                 /* Need more header lines */
2459                 return;
2460         }
2461
2462         /* Callback can shut down connection with negative return value */
2463         if (req->header_cb != NULL) {
2464                 if ((*req->header_cb)(req, req->cb_arg) < 0) {
2465                         evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
2466                         return;
2467                 }
2468         }
2469
2470         /* Done reading headers, do the real work */
2471         switch (req->kind) {
2472         case EVHTTP_REQUEST:
2473                 event_debug(("%s: checking for post data on "EV_SOCK_FMT"\n",
2474                         __func__, EV_SOCK_ARG(fd)));
2475                 evhttp_get_body(evcon, req);
2476                 /* note the request may have been freed in evhttp_get_body */
2477                 break;
2478
2479         case EVHTTP_RESPONSE:
2480                 /* Start over if we got a 100 Continue response. */
2481                 if (req->response_code == 100) {
2482                         struct evbuffer *output = bufferevent_get_output(evcon->bufev);
2483                         evbuffer_add_buffer(output, req->output_buffer);
2484                         evhttp_start_write_(evcon);
2485                         return;
2486                 }
2487                 if (!evhttp_response_needs_body(req)) {
2488                         event_debug(("%s: skipping body for code %d\n",
2489                                         __func__, req->response_code));
2490                         evhttp_connection_done(evcon);
2491                 } else {
2492                         event_debug(("%s: start of read body for %s on "
2493                                 EV_SOCK_FMT"\n",
2494                                 __func__, req->remote_host, EV_SOCK_ARG(fd)));
2495                         evhttp_get_body(evcon, req);
2496                         /* note the request may have been freed in
2497                          * evhttp_get_body */
2498                 }
2499                 break;
2500
2501         default:
2502                 event_warnx("%s: bad header on "EV_SOCK_FMT, __func__,
2503                     EV_SOCK_ARG(fd));
2504                 evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
2505                 break;
2506         }
2507         /* request may have been freed above */
2508 }
2509
2510 /*
2511  * Creates a TCP connection to the specified port and executes a callback
2512  * when finished.  Failure or success is indicate by the passed connection
2513  * object.
2514  *
2515  * Although this interface accepts a hostname, it is intended to take
2516  * only numeric hostnames so that non-blocking DNS resolution can
2517  * happen elsewhere.
2518  */
2519
2520 struct evhttp_connection *
2521 evhttp_connection_new(const char *address, ev_uint16_t port)
2522 {
2523         return (evhttp_connection_base_new(NULL, NULL, address, port));
2524 }
2525
2526 static struct evhttp_connection *
2527 evhttp_connection_new_(struct event_base *base, struct bufferevent* bev)
2528 {
2529         struct evhttp_connection *evcon;
2530
2531         if ((evcon = mm_calloc(1, sizeof(struct evhttp_connection))) == NULL) {
2532                 event_warn("%s: calloc failed", __func__);
2533                 goto error;
2534         }
2535
2536         evcon->max_headers_size = EV_SIZE_MAX;
2537         evcon->max_body_size = EV_SIZE_MAX;
2538
2539         evcon->timeout_connect.tv_sec = HTTP_CONNECT_TIMEOUT;
2540         evcon->timeout_read.tv_sec    = HTTP_READ_TIMEOUT;
2541         evcon->timeout_write.tv_sec   = HTTP_WRITE_TIMEOUT;
2542         evcon->initial_retry_timeout.tv_sec = HTTP_INITIAL_RETRY_TIMEOUT;
2543
2544         evcon->retry_cnt = evcon->retry_max = 0;
2545
2546         if (bev == NULL) {
2547                 if (!(bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE))) {
2548                         event_warn("%s: bufferevent_socket_new failed", __func__);
2549                         goto error;
2550                 }
2551         }
2552
2553         bufferevent_setcb(bev, evhttp_read_cb, evhttp_write_cb, evhttp_error_cb, evcon);
2554         evcon->bufev = bev;
2555
2556         evcon->state = EVCON_DISCONNECTED;
2557         TAILQ_INIT(&evcon->requests);
2558
2559         if (base != NULL) {
2560                 evcon->base = base;
2561                 if (bufferevent_get_base(bev) != base)
2562                         bufferevent_base_set(base, evcon->bufev);
2563         }
2564
2565         event_deferred_cb_init_(
2566             &evcon->read_more_deferred_cb,
2567             bufferevent_get_priority(bev),
2568             evhttp_deferred_read_cb, evcon);
2569
2570         evcon->ai_family = AF_UNSPEC;
2571
2572         return (evcon);
2573
2574  error:
2575         if (evcon != NULL)
2576                 evhttp_connection_free(evcon);
2577         return (NULL);
2578 }
2579
2580 #ifndef _WIN32
2581 struct evhttp_connection *
2582 evhttp_connection_base_bufferevent_unix_new(struct event_base *base, struct bufferevent* bev, const char *unixsocket)
2583 {
2584         struct evhttp_connection *evcon;
2585
2586         if (strlen(unixsocket) >= member_size(struct sockaddr_un, sun_path)) {
2587                 event_warn("%s: unix socket too long", __func__);
2588                 return NULL;
2589         }
2590
2591         evcon = evhttp_connection_new_(base, bev);
2592         if (evcon == NULL)
2593                 goto error;
2594
2595         if ((evcon->unixsocket = mm_strdup(unixsocket)) == NULL) {
2596                 event_warn("%s: strdup failed", __func__);
2597                 goto error;
2598         }
2599
2600         evcon->ai_family = AF_UNIX;
2601
2602         return (evcon);
2603  error:
2604         if (evcon != NULL)
2605                 evhttp_connection_free(evcon);
2606         return (NULL);
2607 }
2608 #endif
2609
2610 struct evhttp_connection *
2611 evhttp_connection_base_bufferevent_new(struct event_base *base, struct evdns_base *dnsbase, struct bufferevent* bev,
2612     const char *address, unsigned short port)
2613 {
2614         struct evhttp_connection *evcon;
2615
2616         event_debug(("Attempting connection to %s:%d\n", address, port));
2617
2618         evcon = evhttp_connection_new_(base, bev);
2619         if (evcon == NULL)
2620                 goto error;
2621
2622         if ((evcon->address = mm_strdup(address)) == NULL) {
2623                 event_warn("%s: strdup failed", __func__);
2624                 goto error;
2625         }
2626         evcon->port = port;
2627         evcon->dns_base = dnsbase;
2628
2629         return (evcon);
2630 error:
2631         if (evcon != NULL)
2632                 evhttp_connection_free(evcon);
2633         return (NULL);
2634 }
2635
2636
2637 struct bufferevent* evhttp_connection_get_bufferevent(struct evhttp_connection *evcon)
2638 {
2639         return evcon->bufev;
2640 }
2641
2642 struct evhttp *
2643 evhttp_connection_get_server(struct evhttp_connection *evcon)
2644 {
2645         return evcon->http_server;
2646 }
2647
2648 struct evhttp_connection *
2649 evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
2650     const char *address, ev_uint16_t port)
2651 {
2652         return evhttp_connection_base_bufferevent_new(base, dnsbase, NULL, address, port);
2653 }
2654
2655 void evhttp_connection_set_family(struct evhttp_connection *evcon,
2656         int family)
2657 {
2658         evcon->ai_family = family;
2659 }
2660
2661 int evhttp_connection_set_flags(struct evhttp_connection *evcon,
2662         int flags)
2663 {
2664         int avail_flags = 0;
2665         avail_flags |= EVHTTP_CON_REUSE_CONNECTED_ADDR;
2666         avail_flags |= EVHTTP_CON_READ_ON_WRITE_ERROR;
2667
2668         if (flags & ~avail_flags || flags > EVHTTP_CON_PUBLIC_FLAGS_END)
2669                 return 1;
2670         evcon->flags &= ~avail_flags;
2671
2672         evcon->flags |= flags;
2673
2674         return 0;
2675 }
2676
2677 void
2678 evhttp_connection_set_ext_method_cmp(struct evhttp_connection *evcon,
2679         evhttp_ext_method_cb cmp)
2680 {
2681         evcon->ext_method_cmp = cmp;
2682 }
2683
2684 void
2685 evhttp_connection_set_base(struct evhttp_connection *evcon,
2686     struct event_base *base)
2687 {
2688         EVUTIL_ASSERT(evcon->base == NULL);
2689         EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
2690         evcon->base = base;
2691         bufferevent_base_set(base, evcon->bufev);
2692 }
2693
2694 void
2695 evhttp_connection_set_timeout(struct evhttp_connection *evcon,
2696     int timeout)
2697 {
2698         if (timeout != -1) {
2699                 evcon->flags |= EVHTTP_CON_TIMEOUT_ADJUSTED;
2700         } else {
2701                 evcon->flags &= ~EVHTTP_CON_TIMEOUT_ADJUSTED;
2702         }
2703         evhttp_set_timeout_(&evcon->timeout_read,  timeout, HTTP_READ_TIMEOUT);
2704         evhttp_set_timeout_(&evcon->timeout_write, timeout, HTTP_WRITE_TIMEOUT);
2705         bufferevent_set_timeouts(evcon->bufev,
2706             &evcon->timeout_read, &evcon->timeout_write);
2707 }
2708 void
2709 evhttp_connection_set_timeout_tv(struct evhttp_connection *evcon,
2710     const struct timeval* tv)
2711 {
2712         if (tv) {
2713                 evcon->flags |= EVHTTP_CON_TIMEOUT_ADJUSTED;
2714         } else {
2715                 evcon->flags &= ~EVHTTP_CON_TIMEOUT_ADJUSTED;
2716         }
2717         evhttp_set_timeout_tv_(&evcon->timeout_read,  tv, HTTP_READ_TIMEOUT);
2718         evhttp_set_timeout_tv_(&evcon->timeout_write, tv, HTTP_WRITE_TIMEOUT);
2719         bufferevent_set_timeouts(evcon->bufev,
2720             &evcon->timeout_read, &evcon->timeout_write);
2721 }
2722 void evhttp_connection_set_connect_timeout_tv(struct evhttp_connection *evcon,
2723     const struct timeval *tv)
2724 {
2725         evcon->flags |= EVHTTP_CON_TIMEOUT_ADJUSTED;
2726         evhttp_set_timeout_tv_(&evcon->timeout_connect, tv, -1);
2727         if (evcon->state == EVCON_CONNECTING)
2728                 bufferevent_set_timeouts(evcon->bufev,
2729                     &evcon->timeout_connect, &evcon->timeout_connect);
2730 }
2731 void evhttp_connection_set_read_timeout_tv(struct evhttp_connection *evcon,
2732     const struct timeval *tv)
2733 {
2734         evcon->flags |= EVHTTP_CON_TIMEOUT_ADJUSTED;
2735         evhttp_set_timeout_tv_(&evcon->timeout_read, tv, -1);
2736         if (evcon->state != EVCON_CONNECTING)
2737                 bufferevent_set_timeouts(evcon->bufev,
2738                     &evcon->timeout_read, &evcon->timeout_write);
2739 }
2740 void evhttp_connection_set_write_timeout_tv(struct evhttp_connection *evcon,
2741     const struct timeval *tv)
2742 {
2743         evcon->flags |= EVHTTP_CON_TIMEOUT_ADJUSTED;
2744         evhttp_set_timeout_tv_(&evcon->timeout_write, tv, -1);
2745         if (evcon->state != EVCON_CONNECTING)
2746                 bufferevent_set_timeouts(evcon->bufev,
2747                     &evcon->timeout_read, &evcon->timeout_write);
2748 }
2749
2750 void
2751 evhttp_connection_set_initial_retry_tv(struct evhttp_connection *evcon,
2752     const struct timeval *tv)
2753 {
2754         if (tv) {
2755                 evcon->initial_retry_timeout = *tv;
2756         } else {
2757                 evutil_timerclear(&evcon->initial_retry_timeout);
2758                 evcon->initial_retry_timeout.tv_sec = 2;
2759         }
2760 }
2761
2762 void
2763 evhttp_connection_set_retries(struct evhttp_connection *evcon,
2764     int retry_max)
2765 {
2766         evcon->retry_max = retry_max;
2767 }
2768
2769 void
2770 evhttp_connection_set_closecb(struct evhttp_connection *evcon,
2771     void (*cb)(struct evhttp_connection *, void *), void *cbarg)
2772 {
2773         evcon->closecb = cb;
2774         evcon->closecb_arg = cbarg;
2775 }
2776
2777 void
2778 evhttp_connection_get_peer(struct evhttp_connection *evcon,
2779     const char **address, ev_uint16_t *port)
2780 {
2781         *address = evcon->address;
2782         *port = evcon->port;
2783 }
2784
2785 const struct sockaddr*
2786 evhttp_connection_get_addr(struct evhttp_connection *evcon)
2787 {
2788         return bufferevent_socket_get_conn_address_(evcon->bufev);
2789 }
2790
2791 int
2792 evhttp_connection_connect_(struct evhttp_connection *evcon)
2793 {
2794         int old_state = evcon->state;
2795         const char *address = evcon->address;
2796         const struct sockaddr *sa = evhttp_connection_get_addr(evcon);
2797         int ret;
2798
2799         if (evcon->state == EVCON_CONNECTING)
2800                 return (0);
2801
2802         /* Do not do hard reset, since this will reset the fd, but someone may
2803          * change some options for it (i.e. setsockopt(), #875)
2804          *
2805          * However don't think that this options will be preserved for all
2806          * connection lifetime, they will be reseted in the following cases:
2807          * - evhttp_connection_set_local_address()
2808          * - evhttp_connection_set_local_port()
2809          * - evhttp_connection_set_retries()
2810          * */
2811         evhttp_connection_reset_(evcon, 0);
2812
2813         EVUTIL_ASSERT(!(evcon->flags & EVHTTP_CON_INCOMING));
2814         evcon->flags |= EVHTTP_CON_OUTGOING;
2815
2816         if (evcon->bind_address || evcon->bind_port) {
2817                 int fd = bind_socket(evcon->bind_address, evcon->bind_port,
2818                         0 /*reuse*/);
2819                 if (fd == -1) {
2820                         event_debug(("%s: failed to bind to \"%s\"",
2821                                 __func__, evcon->bind_address));
2822                         return (-1);
2823                 }
2824
2825                 if (bufferevent_replacefd(evcon->bufev, fd))
2826                         return (-1);
2827         }
2828
2829         /* Set up a callback for successful connection setup */
2830         bufferevent_setcb(evcon->bufev,
2831             NULL /* evhttp_read_cb */,
2832             NULL /* evhttp_write_cb */,
2833             evhttp_connection_cb,
2834             evcon);
2835         bufferevent_set_timeouts(evcon->bufev,
2836             &evcon->timeout_connect, &evcon->timeout_connect);
2837         /* make sure that we get a write callback */
2838         if (bufferevent_enable(evcon->bufev, EV_WRITE))
2839                 return (-1);
2840
2841         evcon->state = EVCON_CONNECTING;
2842
2843         if (evcon->flags & EVHTTP_CON_REUSE_CONNECTED_ADDR &&
2844                 sa &&
2845                 (sa->sa_family == AF_INET || sa->sa_family == AF_INET6)) {
2846                 int socklen = sizeof(struct sockaddr_in);
2847                 if (sa->sa_family == AF_INET6) {
2848                         socklen = sizeof(struct sockaddr_in6);
2849                 }
2850                 ret = bufferevent_socket_connect(evcon->bufev, sa, socklen);
2851         }
2852 #ifndef _WIN32
2853         else if (evcon->unixsocket) {
2854                 struct sockaddr_un sockaddr;
2855                 sockaddr.sun_family = AF_UNIX;
2856                 strcpy(sockaddr.sun_path, evcon->unixsocket);
2857                 ret = bufferevent_socket_connect(evcon->bufev, (const struct sockaddr*)&sockaddr, sizeof(sockaddr));
2858         }
2859 #endif
2860         else {
2861                 ret = bufferevent_socket_connect_hostname(evcon->bufev,
2862                                 evcon->dns_base, evcon->ai_family, address, evcon->port);
2863         }
2864
2865         if (ret < 0) {
2866                 evcon->state = old_state;
2867                 event_sock_warn(bufferevent_getfd(evcon->bufev), "%s: connection to \"%s\" failed",
2868                     __func__, evcon->address);
2869                 /* some operating systems return ECONNREFUSED immediately
2870                  * when connecting to a local address.  the cleanup is going
2871                  * to reschedule this function call.
2872                  */
2873                 evhttp_connection_cb_cleanup(evcon);
2874                 return (0);
2875         }
2876
2877         return (0);
2878 }
2879
2880 /*
2881  * Starts an HTTP request on the provided evhttp_connection object.
2882  * If the connection object is not connected to the web server already,
2883  * this will start the connection.
2884  */
2885
2886 int
2887 evhttp_make_request(struct evhttp_connection *evcon,
2888     struct evhttp_request *req,
2889     enum evhttp_cmd_type type, const char *uri)
2890 {
2891         /* We are making a request */
2892         req->kind = EVHTTP_REQUEST;
2893         req->type = type;
2894         if (req->uri != NULL)
2895                 mm_free(req->uri);
2896         if ((req->uri = mm_strdup(uri)) == NULL) {
2897                 event_warn("%s: strdup", __func__);
2898                 evhttp_request_free_auto(req);
2899                 return (-1);
2900         }
2901
2902         /* Set the protocol version if it is not supplied */
2903         if (!req->major && !req->minor) {
2904                 req->major = 1;
2905                 req->minor = 1;
2906         }
2907
2908         EVUTIL_ASSERT(req->evcon == NULL);
2909         req->evcon = evcon;
2910         EVUTIL_ASSERT(!(req->flags & EVHTTP_REQ_OWN_CONNECTION));
2911
2912         TAILQ_INSERT_TAIL(&evcon->requests, req, next);
2913
2914         /* We do not want to conflict with retry_ev */
2915         if (evcon->retry_cnt)
2916                 return (0);
2917
2918         /* If the connection object is not connected; make it so */
2919         if (!evhttp_connected(evcon)) {
2920                 int res = evhttp_connection_connect_(evcon);
2921                 /* evhttp_connection_fail_(), which is called through
2922                  * evhttp_connection_connect_(), assumes that req lies in
2923                  * evcon->requests.  Thus, enqueue the request in advance and
2924                  * remove it in the error case. */
2925                 if (res != 0)
2926                         TAILQ_REMOVE(&evcon->requests, req, next);
2927
2928                 return (res);
2929         }
2930
2931         /*
2932          * If it's connected already and we are the first in the queue,
2933          * then we can dispatch this request immediately.  Otherwise, it
2934          * will be dispatched once the pending requests are completed.
2935          */
2936         if (TAILQ_FIRST(&evcon->requests) == req)
2937                 evhttp_request_dispatch(evcon);
2938
2939         return (0);
2940 }
2941
2942 void
2943 evhttp_cancel_request(struct evhttp_request *req)
2944 {
2945         struct evhttp_connection *evcon = req->evcon;
2946         if (evcon != NULL) {
2947                 /* We need to remove it from the connection */
2948                 if (TAILQ_FIRST(&evcon->requests) == req) {
2949                         /* it's currently being worked on, so reset
2950                          * the connection.
2951                          */
2952                         evhttp_connection_fail_(evcon,
2953                             EVREQ_HTTP_REQUEST_CANCEL);
2954
2955                         /* connection fail freed the request */
2956                         return;
2957                 } else {
2958                         /* otherwise, we can just remove it from the
2959                          * queue
2960                          */
2961                         TAILQ_REMOVE(&evcon->requests, req, next);
2962                 }
2963         }
2964
2965         evhttp_request_free_auto(req);
2966 }
2967
2968 /*
2969  * Reads data from file descriptor into request structure
2970  * Request structure needs to be set up correctly.
2971  */
2972
2973 void
2974 evhttp_start_read_(struct evhttp_connection *evcon)
2975 {
2976         bufferevent_disable(evcon->bufev, EV_WRITE);
2977         bufferevent_enable(evcon->bufev, EV_READ);
2978
2979         evcon->state = EVCON_READING_FIRSTLINE;
2980         /* Reset the bufferevent callbacks */
2981         bufferevent_setcb(evcon->bufev,
2982             evhttp_read_cb,
2983             evhttp_write_cb,
2984             evhttp_error_cb,
2985             evcon);
2986
2987         /* If there's still data pending, process it next time through the
2988          * loop.  Don't do it now; that could get recusive. */
2989         if (evbuffer_get_length(bufferevent_get_input(evcon->bufev))) {
2990                 event_deferred_cb_schedule_(get_deferred_queue(evcon),
2991                     &evcon->read_more_deferred_cb);
2992         }
2993 }
2994
2995 void
2996 evhttp_start_write_(struct evhttp_connection *evcon)
2997 {
2998         bufferevent_disable(evcon->bufev, EV_WRITE);
2999         bufferevent_enable(evcon->bufev, EV_READ);
3000
3001         evcon->state = EVCON_WRITING;
3002         evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
3003 }
3004
3005 static void
3006 evhttp_send_done(struct evhttp_connection *evcon, void *arg)
3007 {
3008         int need_close;
3009         struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
3010         TAILQ_REMOVE(&evcon->requests, req, next);
3011
3012         if (req->on_complete_cb != NULL) {
3013                 req->on_complete_cb(req, req->on_complete_cb_arg);
3014         }
3015
3016         need_close =
3017             (REQ_VERSION_BEFORE(req, 1, 1) &&
3018             !evhttp_is_connection_keepalive(req->input_headers)) ||
3019             evhttp_is_request_connection_close(req);
3020
3021         EVUTIL_ASSERT(req->flags & EVHTTP_REQ_OWN_CONNECTION);
3022         evhttp_request_free(req);
3023
3024         if (need_close) {
3025                 evhttp_connection_free(evcon);
3026                 return;
3027         }
3028
3029         /* we have a persistent connection; try to accept another request. */
3030         if (evhttp_associate_new_request_with_connection(evcon) == -1) {
3031                 evhttp_connection_free(evcon);
3032         }
3033 }
3034
3035 /*
3036  * Returns an error page.
3037  */
3038 void
3039 evhttp_send_error(struct evhttp_request *req, int error, const char *reason)
3040 {
3041 #define ERR_FORMAT "<html><head>" \
3042         "<title>%d %s</title>" \
3043         "</head><body>" \
3044         "<h1>%d %s</h1>%s" \
3045         "</body></html>"
3046
3047         struct evbuffer *buf = evbuffer_new();
3048         struct evhttp *http = req->evcon->http_server;
3049
3050         if (buf == NULL) {
3051                 /* if we cannot allocate memory; we just drop the connection */
3052                 evhttp_connection_free(req->evcon);
3053                 return;
3054         }
3055
3056         evhttp_response_code_(req, error, reason);
3057
3058         /* Output error using callback for connection's evhttp, if available */
3059         if ((http->errorcb == NULL) ||
3060             ((*http->errorcb)(req, buf, error, reason, http->errorcbarg) < 0))
3061         {
3062                 const char *heading = evhttp_response_phrase_internal(error);
3063
3064                 evbuffer_drain(buf, evbuffer_get_length(buf));
3065                 evbuffer_add_printf(buf, ERR_FORMAT,
3066                    error, heading, error, heading,
3067                    (reason ? reason : ""));
3068         }
3069
3070         evhttp_send_page_(req, buf);
3071
3072         evbuffer_free(buf);
3073 #undef ERR_FORMAT
3074 }
3075 static void
3076 evhttp_send_notfound(struct evhttp_request *req, const char *url)
3077 {
3078 #define REASON_FORMAT "<p>The requested URL %s was not found on this server.</p>"
3079         char   *escaped_url = NULL;
3080         char   *reason = NULL;
3081         size_t reason_len;
3082
3083         url = (url != NULL ? url : req->uri);
3084         if (url != NULL)
3085                 escaped_url = evhttp_htmlescape(url);
3086
3087         if (escaped_url != NULL) {
3088                 reason_len = strlen(REASON_FORMAT)+strlen(escaped_url)+1;
3089                 reason = mm_malloc(reason_len);
3090         }
3091
3092         if ((escaped_url != NULL) && (reason != NULL))
3093                 evutil_snprintf(reason, reason_len, REASON_FORMAT, escaped_url);
3094
3095         evhttp_send_error(req, HTTP_NOTFOUND, reason);
3096
3097         if (reason != NULL)
3098                 mm_free(reason);
3099         if (escaped_url != NULL)
3100                 mm_free(escaped_url);
3101 #undef REASON_FORMAT
3102 }
3103
3104
3105 /* Requires that headers and response code are already set up */
3106
3107 static inline void
3108 evhttp_send(struct evhttp_request *req, struct evbuffer *databuf)
3109 {
3110         struct evhttp_connection *evcon = req->evcon;
3111
3112         if (evcon == NULL) {
3113                 evhttp_request_free(req);
3114                 return;
3115         }
3116
3117         EVUTIL_ASSERT(TAILQ_FIRST(&evcon->requests) == req);
3118
3119         /* we expect no more calls form the user on this request */
3120         req->userdone = 1;
3121
3122         /* xxx: not sure if we really should expose the data buffer this way */
3123         if (databuf != NULL)
3124                 evbuffer_add_buffer(req->output_buffer, databuf);
3125
3126         /* Adds headers to the response */
3127         evhttp_make_header(evcon, req);
3128
3129         evhttp_write_buffer(evcon, evhttp_send_done, NULL);
3130 }
3131
3132 void
3133 evhttp_send_reply(struct evhttp_request *req, int code, const char *reason,
3134     struct evbuffer *databuf)
3135 {
3136         evhttp_response_code_(req, code, reason);
3137
3138         evhttp_send(req, databuf);
3139 }
3140
3141 void
3142 evhttp_send_reply_start(struct evhttp_request *req, int code,
3143     const char *reason)
3144 {
3145         evhttp_response_code_(req, code, reason);
3146
3147         if (req->evcon == NULL)
3148                 return;
3149
3150         if (evhttp_find_header(req->output_headers, "Content-Length") == NULL &&
3151             REQ_VERSION_ATLEAST(req, 1, 1) &&
3152             evhttp_response_needs_body(req)) {
3153                 /*
3154                  * prefer HTTP/1.1 chunked encoding to closing the connection;
3155                  * note RFC 2616 section 4.4 forbids it with Content-Length:
3156                  * and it's not necessary then anyway.
3157                  */
3158                 evhttp_add_header(req->output_headers, "Transfer-Encoding",
3159                     "chunked");
3160                 req->chunked = 1;
3161         } else {
3162                 req->chunked = 0;
3163         }
3164         evhttp_make_header(req->evcon, req);
3165         evhttp_write_buffer(req->evcon, NULL, NULL);
3166 }
3167
3168 void
3169 evhttp_send_reply_chunk_with_cb(struct evhttp_request *req, struct evbuffer *databuf,
3170     void (*cb)(struct evhttp_connection *, void *), void *arg)
3171 {
3172         struct evhttp_connection *evcon = req->evcon;
3173         struct evbuffer *output;
3174
3175         if (evcon == NULL)
3176                 return;
3177
3178         output = bufferevent_get_output(evcon->bufev);
3179
3180         if (evbuffer_get_length(databuf) == 0)
3181                 return;
3182         if (!evhttp_response_needs_body(req))
3183                 return;
3184         if (req->chunked) {
3185                 evbuffer_add_printf(output, "%x\r\n",
3186                                     (unsigned)evbuffer_get_length(databuf));
3187         }
3188         evbuffer_add_buffer(output, databuf);
3189         if (req->chunked) {
3190                 evbuffer_add(output, "\r\n", 2);
3191         }
3192         evhttp_write_buffer(evcon, cb, arg);
3193 }
3194
3195 struct bufferevent *
3196 evhttp_start_ws_(struct evhttp_request *req)
3197 {
3198         struct evhttp_connection *evcon = req->evcon;
3199         struct bufferevent *bufev;
3200
3201         evhttp_response_code_(req, HTTP_SWITCH_PROTOCOLS, "Switching Protocols");
3202
3203         if (req->evcon == NULL)
3204                 return NULL;
3205
3206         evhttp_make_header(req->evcon, req);
3207         evhttp_write_buffer(req->evcon, NULL, NULL);
3208
3209         TAILQ_REMOVE(&evcon->requests, req, next);
3210
3211         bufev = evcon->bufev;
3212         evcon->bufev = NULL;
3213         evcon->closecb = NULL;
3214
3215         evhttp_request_free(req);
3216         evhttp_connection_free(evcon);
3217         return bufev;
3218 }
3219
3220 void
3221 evhttp_send_reply_chunk(struct evhttp_request *req, struct evbuffer *databuf)
3222 {
3223         evhttp_send_reply_chunk_with_cb(req, databuf, NULL, NULL);
3224 }
3225 void
3226 evhttp_send_reply_end(struct evhttp_request *req)
3227 {
3228         struct evhttp_connection *evcon = req->evcon;
3229         struct evbuffer *output;
3230
3231         if (evcon == NULL) {
3232                 evhttp_request_free(req);
3233                 return;
3234         }
3235
3236         output = bufferevent_get_output(evcon->bufev);
3237
3238         /* we expect no more calls form the user on this request */
3239         req->userdone = 1;
3240
3241         if (req->chunked) {
3242                 evbuffer_add(output, "0\r\n\r\n", 5);
3243                 evhttp_write_buffer(req->evcon, evhttp_send_done, NULL);
3244                 req->chunked = 0;
3245         } else if (evbuffer_get_length(output) == 0) {
3246                 /* let the connection know that we are done with the request */
3247                 evhttp_send_done(evcon, NULL);
3248         } else {
3249                 /* make the callback execute after all data has been written */
3250                 evcon->cb = evhttp_send_done;
3251                 evcon->cb_arg = NULL;
3252         }
3253 }
3254
3255 static const char *informational_phrases[] = {
3256         /* 100 */ "Continue",
3257         /* 101 */ "Switching Protocols"
3258 };
3259
3260 static const char *success_phrases[] = {
3261         /* 200 */ "OK",
3262         /* 201 */ "Created",
3263         /* 202 */ "Accepted",
3264         /* 203 */ "Non-Authoritative Information",
3265         /* 204 */ "No Content",
3266         /* 205 */ "Reset Content",
3267         /* 206 */ "Partial Content"
3268 };
3269
3270 static const char *redirection_phrases[] = {
3271         /* 300 */ "Multiple Choices",
3272         /* 301 */ "Moved Permanently",
3273         /* 302 */ "Found",
3274         /* 303 */ "See Other",
3275         /* 304 */ "Not Modified",
3276         /* 305 */ "Use Proxy",
3277         /* 307 */ "Temporary Redirect"
3278 };
3279
3280 static const char *client_error_phrases[] = {
3281         /* 400 */ "Bad Request",
3282         /* 401 */ "Unauthorized",
3283         /* 402 */ "Payment Required",
3284         /* 403 */ "Forbidden",
3285         /* 404 */ "Not Found",
3286         /* 405 */ "Method Not Allowed",
3287         /* 406 */ "Not Acceptable",
3288         /* 407 */ "Proxy Authentication Required",
3289         /* 408 */ "Request Time-out",
3290         /* 409 */ "Conflict",
3291         /* 410 */ "Gone",
3292         /* 411 */ "Length Required",
3293         /* 412 */ "Precondition Failed",
3294         /* 413 */ "Request Entity Too Large",
3295         /* 414 */ "Request-URI Too Large",
3296         /* 415 */ "Unsupported Media Type",
3297         /* 416 */ "Requested range not satisfiable",
3298         /* 417 */ "Expectation Failed"
3299 };
3300
3301 static const char *server_error_phrases[] = {
3302         /* 500 */ "Internal Server Error",
3303         /* 501 */ "Not Implemented",
3304         /* 502 */ "Bad Gateway",
3305         /* 503 */ "Service Unavailable",
3306         /* 504 */ "Gateway Time-out",
3307         /* 505 */ "HTTP Version not supported"
3308 };
3309
3310 struct response_class {
3311         const char *name;
3312         size_t num_responses;
3313         const char **responses;
3314 };
3315
3316 #ifndef MEMBERSOF
3317 #define MEMBERSOF(x) (sizeof(x)/sizeof(x[0]))
3318 #endif
3319
3320 static const struct response_class response_classes[] = {
3321         /* 1xx */ { "Informational", MEMBERSOF(informational_phrases), informational_phrases },
3322         /* 2xx */ { "Success", MEMBERSOF(success_phrases), success_phrases },
3323         /* 3xx */ { "Redirection", MEMBERSOF(redirection_phrases), redirection_phrases },
3324         /* 4xx */ { "Client Error", MEMBERSOF(client_error_phrases), client_error_phrases },
3325         /* 5xx */ { "Server Error", MEMBERSOF(server_error_phrases), server_error_phrases }
3326 };
3327
3328 static const char *
3329 evhttp_response_phrase_internal(int code)
3330 {
3331         int klass = code / 100 - 1;
3332         int subcode = code % 100;
3333
3334         /* Unknown class - can't do any better here */
3335         if (klass < 0 || klass >= (int) MEMBERSOF(response_classes))
3336                 return "Unknown Status Class";
3337
3338         /* Unknown sub-code, return class name at least */
3339         if (subcode >= (int) response_classes[klass].num_responses)
3340                 return response_classes[klass].name;
3341
3342         return response_classes[klass].responses[subcode];
3343 }
3344
3345 void
3346 evhttp_response_code_(struct evhttp_request *req, int code, const char *reason)
3347 {
3348         req->kind = EVHTTP_RESPONSE;
3349         req->response_code = code;
3350         if (req->response_code_line != NULL)
3351                 mm_free(req->response_code_line);
3352         if (reason == NULL)
3353                 reason = evhttp_response_phrase_internal(code);
3354         req->response_code_line = mm_strdup(reason);
3355         if (req->response_code_line == NULL) {
3356                 event_warn("%s: strdup", __func__);
3357                 /* XXX what else can we do? */
3358         }
3359 }
3360
3361 void
3362 evhttp_send_page_(struct evhttp_request *req, struct evbuffer *databuf)
3363 {
3364         if (!req->major || !req->minor) {
3365                 req->major = 1;
3366                 req->minor = 1;
3367         }
3368
3369         if (req->kind != EVHTTP_RESPONSE)
3370                 evhttp_response_code_(req, 200, "OK");
3371
3372         evhttp_clear_headers(req->output_headers);
3373         evhttp_add_header(req->output_headers, "Content-Type", "text/html");
3374         evhttp_add_header(req->output_headers, "Connection", "close");
3375
3376         evhttp_send(req, databuf);
3377 }
3378
3379 static const char uri_chars[256] = {
3380         /* 0 */
3381         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3382         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3383         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 1, 1, 0,
3384         1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,
3385         /* 64 */
3386         0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
3387         1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 1,
3388         0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
3389         1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 1, 0,
3390         /* 128 */
3391         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3392         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3393         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3394         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3395         /* 192 */
3396         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3397         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3398         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3399         0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
3400 };
3401
3402 #define CHAR_IS_UNRESERVED(c)                   \
3403         (uri_chars[(unsigned char)(c)])
3404
3405 /*
3406  * Helper functions to encode/decode a string for inclusion in a URI.
3407  * The returned string must be freed by the caller.
3408  */
3409 char *
3410 evhttp_uriencode(const char *uri, ev_ssize_t len, int space_as_plus)
3411 {
3412         struct evbuffer *buf = evbuffer_new();
3413         const char *p, *end;
3414         char *result = NULL;
3415
3416         if (!buf) {
3417                 goto out;
3418         }
3419
3420         if (len >= 0) {
3421                 if (uri + len < uri) {
3422                         goto out;
3423                 }
3424
3425                 end = uri + len;
3426         } else {
3427                 size_t slen = strlen(uri);
3428
3429                 if (slen >= EV_SSIZE_MAX) {
3430                         /* we don't want to mix signed and unsigned */
3431                         goto out;
3432                 }
3433
3434                 if (uri + slen < uri) {
3435                         goto out;
3436                 }
3437
3438                 end = uri + slen;
3439         }
3440
3441         for (p = uri; p < end; p++) {
3442                 if (CHAR_IS_UNRESERVED(*p)) {
3443                         evbuffer_add(buf, p, 1);
3444                 } else if (*p == ' ' && space_as_plus) {
3445                         evbuffer_add(buf, "+", 1);
3446                 } else {
3447                         evbuffer_add_printf(buf, "%%%02X", (unsigned char)(*p));
3448                 }
3449         }
3450
3451         evbuffer_add(buf, "", 1); /* NUL-terminator. */
3452         result = mm_malloc(evbuffer_get_length(buf));
3453
3454         if (result)
3455                 evbuffer_remove(buf, result, evbuffer_get_length(buf));
3456
3457 out:
3458         if (buf)
3459                 evbuffer_free(buf);
3460         return result;
3461 }
3462
3463 char *
3464 evhttp_encode_uri(const char *str)
3465 {
3466         return evhttp_uriencode(str, -1, 0);
3467 }
3468
3469 /*
3470  * @param decode_plus_ctl: if 1, we decode plus into space.  If 0, we don't.
3471  *     If -1, when true we transform plus to space only after we've seen
3472  *     a ?.  -1 is deprecated.
3473  * @return the number of bytes written to 'ret'.
3474  */
3475 int
3476 evhttp_decode_uri_internal(
3477         const char *uri, size_t length, char *ret, int decode_plus_ctl)
3478 {
3479         char c;
3480         int j;
3481         int decode_plus = (decode_plus_ctl == 1) ? 1: 0;
3482         unsigned i;
3483
3484         for (i = j = 0; i < length; i++) {
3485                 c = uri[i];
3486                 if (c == '?') {
3487                         if (decode_plus_ctl < 0)
3488                                 decode_plus = 1;
3489                 } else if (c == '+' && decode_plus) {
3490                         c = ' ';
3491                 } else if ((i + 2) < length && c == '%' &&
3492                         EVUTIL_ISXDIGIT_(uri[i+1]) && EVUTIL_ISXDIGIT_(uri[i+2])) {
3493                         char tmp[3];
3494                         tmp[0] = uri[i+1];
3495                         tmp[1] = uri[i+2];
3496                         tmp[2] = '\0';
3497                         c = (char)strtol(tmp, NULL, 16);
3498                         i += 2;
3499                 }
3500                 ret[j++] = c;
3501         }
3502         ret[j] = '\0';
3503
3504         return (j);
3505 }
3506
3507 /* deprecated */
3508 char *
3509 evhttp_decode_uri(const char *uri)
3510 {
3511         char *ret;
3512
3513         if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
3514                 event_warn("%s: malloc(%lu)", __func__,
3515                           (unsigned long)(strlen(uri) + 1));
3516                 return (NULL);
3517         }
3518
3519         evhttp_decode_uri_internal(uri, strlen(uri),
3520             ret, -1 /*always_decode_plus*/);
3521
3522         return (ret);
3523 }
3524
3525 char *
3526 evhttp_uridecode(const char *uri, int decode_plus, size_t *size_out)
3527 {
3528         char *ret;
3529         int n;
3530
3531         if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
3532                 event_warn("%s: malloc(%lu)", __func__,
3533                           (unsigned long)(strlen(uri) + 1));
3534                 return (NULL);
3535         }
3536
3537         n = evhttp_decode_uri_internal(uri, strlen(uri),
3538             ret, !!decode_plus/*always_decode_plus*/);
3539
3540         if (size_out) {
3541                 EVUTIL_ASSERT(n >= 0);
3542                 *size_out = (size_t)n;
3543         }
3544
3545         return (ret);
3546 }
3547
3548 /*
3549  * Helper function to parse out arguments in a query.
3550  * The arguments are separated by key and value.
3551  */
3552
3553 static int
3554 evhttp_parse_query_impl(const char *str, struct evkeyvalq *headers,
3555     int is_whole_uri, unsigned flags)
3556 {
3557         char *line=NULL;
3558         char *argument;
3559         char *p;
3560         const char *query_part;
3561         int result = -1;
3562         struct evhttp_uri *uri=NULL;
3563
3564         TAILQ_INIT(headers);
3565
3566         if (is_whole_uri) {
3567                 uri = evhttp_uri_parse(str);
3568                 if (!uri)
3569                         goto error;
3570                 query_part = evhttp_uri_get_query(uri);
3571         } else {
3572                 query_part = str;
3573         }
3574
3575         /* No arguments - we are done */
3576         if (!query_part || !strlen(query_part)) {
3577                 result = 0;
3578                 goto done;
3579         }
3580
3581         if ((line = mm_strdup(query_part)) == NULL) {
3582                 event_warn("%s: strdup", __func__);
3583                 goto error;
3584         }
3585
3586         p = argument = line;
3587         while (p != NULL && *p != '\0') {
3588                 char *key, *value, *decoded_value;
3589                 int err;
3590                 argument = strsep(&p, "&");
3591
3592                 value = argument;
3593                 key = strsep(&value, "=");
3594                 if (flags & EVHTTP_URI_QUERY_NONCONFORMANT) {
3595                         if (value == NULL)
3596                                 value = (char *)"";
3597                         if (*key == '\0')
3598                                 continue;
3599                 } else {
3600                         if (value == NULL || *key == '\0')
3601                                 goto error;
3602                 }
3603
3604                 if ((decoded_value = mm_malloc(strlen(value) + 1)) == NULL) {
3605                         event_warn("%s: mm_malloc", __func__);
3606                         goto error;
3607                 }
3608                 evhttp_decode_uri_internal(value, strlen(value),
3609                     decoded_value, 1 /*always_decode_plus*/);
3610                 event_debug(("Query Param: %s -> %s\n", key, decoded_value));
3611                 if (flags & EVHTTP_URI_QUERY_LAST_VAL)
3612                         evhttp_remove_header(headers, key);
3613                 err = evhttp_add_header_internal(headers, key, decoded_value);
3614                 mm_free(decoded_value);
3615                 if (err)
3616                         goto error;
3617         }
3618
3619         result = 0;
3620         goto done;
3621 error:
3622         evhttp_clear_headers(headers);
3623 done:
3624         if (line)
3625                 mm_free(line);
3626         if (uri)
3627                 evhttp_uri_free(uri);
3628         return result;
3629 }
3630
3631 int
3632 evhttp_parse_query(const char *uri, struct evkeyvalq *headers)
3633 {
3634         return evhttp_parse_query_impl(uri, headers, 1, 0);
3635 }
3636 int
3637 evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers)
3638 {
3639         return evhttp_parse_query_impl(uri, headers, 0, 0);
3640 }
3641 int
3642 evhttp_parse_query_str_flags(const char *uri, struct evkeyvalq *headers, unsigned flags)
3643 {
3644         return evhttp_parse_query_impl(uri, headers, 0, flags);
3645 }
3646
3647 static struct evhttp_cb *
3648 evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req)
3649 {
3650         struct evhttp_cb *cb;
3651         size_t offset = 0;
3652         char *translated;
3653         const char *path;
3654
3655         /* Test for different URLs */
3656         path = evhttp_uri_get_path(req->uri_elems);
3657         offset = strlen(path);
3658         if ((translated = mm_malloc(offset + 1)) == NULL)
3659                 return (NULL);
3660         evhttp_decode_uri_internal(path, offset, translated,
3661             0 /* decode_plus */);
3662
3663         TAILQ_FOREACH(cb, callbacks, next) {
3664                 if (!strcmp(cb->what, translated)) {
3665                         mm_free(translated);
3666                         return (cb);
3667                 }
3668         }
3669
3670         mm_free(translated);
3671         return (NULL);
3672 }
3673
3674
3675 static int
3676 prefix_suffix_match(const char *pattern, const char *name, int ignorecase)
3677 {
3678         char c;
3679
3680         while (1) {
3681                 switch (c = *pattern++) {
3682                 case '\0':
3683                         return *name == '\0';
3684
3685                 case '*':
3686                         while (*name != '\0') {
3687                                 if (prefix_suffix_match(pattern, name,
3688                                         ignorecase))
3689                                         return (1);
3690                                 ++name;
3691                         }
3692                         return (0);
3693                 default:
3694                         if (c != *name) {
3695                                 if (!ignorecase ||
3696                                     EVUTIL_TOLOWER_(c) != EVUTIL_TOLOWER_(*name))
3697                                         return (0);
3698                         }
3699                         ++name;
3700                 }
3701         }
3702         /* NOTREACHED */
3703 }
3704
3705 /*
3706    Search the vhost hierarchy beginning with http for a server alias
3707    matching hostname.  If a match is found, and outhttp is non-null,
3708    outhttp is set to the matching http object and 1 is returned.
3709 */
3710
3711 static int
3712 evhttp_find_alias(struct evhttp *http, struct evhttp **outhttp,
3713                   const char *hostname)
3714 {
3715         struct evhttp_server_alias *alias;
3716         struct evhttp *vhost;
3717
3718         TAILQ_FOREACH(alias, &http->aliases, next) {
3719                 /* XXX Do we need to handle IP addresses? */
3720                 if (!evutil_ascii_strcasecmp(alias->alias, hostname)) {
3721                         if (outhttp)
3722                                 *outhttp = http;
3723                         return 1;
3724                 }
3725         }
3726
3727         /* XXX It might be good to avoid recursion here, but I don't
3728            see a way to do that w/o a list. */
3729         TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
3730                 if (evhttp_find_alias(vhost, outhttp, hostname))
3731                         return 1;
3732         }
3733
3734         return 0;
3735 }
3736
3737 /*
3738    Attempts to find the best http object to handle a request for a hostname.
3739    All aliases for the root http object and vhosts are searched for an exact
3740    match. Then, the vhost hierarchy is traversed again for a matching
3741    pattern.
3742
3743    If an alias or vhost is matched, 1 is returned, and outhttp, if non-null,
3744    is set with the best matching http object. If there are no matches, the
3745    root http object is stored in outhttp and 0 is returned.
3746 */
3747
3748 static int
3749 evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
3750                   const char *hostname)
3751 {
3752         struct evhttp *vhost;
3753         struct evhttp *oldhttp;
3754         int match_found = 0;
3755
3756         if (evhttp_find_alias(http, outhttp, hostname))
3757                 return 1;
3758
3759         do {
3760                 oldhttp = http;
3761                 TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
3762                         if (prefix_suffix_match(vhost->vhost_pattern,
3763                                 hostname, 1 /* ignorecase */)) {
3764                                 http = vhost;
3765                                 match_found = 1;
3766                                 break;
3767                         }
3768                 }
3769         } while (oldhttp != http);
3770
3771         if (outhttp)
3772                 *outhttp = http;
3773
3774         return match_found;
3775 }
3776
3777 static void
3778 evhttp_handle_request(struct evhttp_request *req, void *arg)
3779 {
3780         struct evhttp *http = arg;
3781         struct evhttp_cb *cb = NULL;
3782         const char *hostname;
3783
3784         /* we have a new request on which the user needs to take action */
3785         req->userdone = 0;
3786
3787         bufferevent_disable(req->evcon->bufev, EV_READ);
3788
3789         if (req->uri == NULL) {
3790                 evhttp_send_error(req, req->response_code, NULL);
3791                 return;
3792         }
3793
3794         if ((http->allowed_methods & req->type) == 0) {
3795                 event_debug(("Rejecting disallowed method %x (allowed: %x)\n",
3796                         (unsigned)req->type, (unsigned)http->allowed_methods));
3797                 evhttp_send_error(req, HTTP_NOTIMPLEMENTED, NULL);
3798                 return;
3799         }
3800
3801         /* handle potential virtual hosts */
3802         hostname = evhttp_request_get_host(req);
3803         if (hostname != NULL) {
3804                 evhttp_find_vhost(http, &http, hostname);
3805         }
3806
3807         if ((cb = evhttp_dispatch_callback(&http->callbacks, req)) != NULL) {
3808                 (*cb->cb)(req, cb->cbarg);
3809                 return;
3810         }
3811
3812         /* Generic call back */
3813         if (http->gencb) {
3814                 (*http->gencb)(req, http->gencbarg);
3815                 return;
3816         } else
3817                 evhttp_send_notfound(req, NULL);
3818 }
3819
3820 /* Listener callback when a connection arrives at a server. */
3821 static void
3822 accept_socket_cb(struct evconnlistener *listener, evutil_socket_t nfd, struct sockaddr *peer_sa, int peer_socklen, void *arg)
3823 {
3824         struct evhttp_bound_socket *bound = arg;
3825
3826         struct evhttp *http = bound->http;
3827
3828         struct bufferevent *bev = NULL;
3829         if (bound->bevcb)
3830                 bev = bound->bevcb(http->base, bound->bevcbarg);
3831
3832         evhttp_get_request(http, nfd, peer_sa, peer_socklen, bev);
3833 }
3834
3835 int
3836 evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port)
3837 {
3838         struct evhttp_bound_socket *bound =
3839                 evhttp_bind_socket_with_handle(http, address, port);
3840         if (bound == NULL)
3841                 return (-1);
3842         return (0);
3843 }
3844
3845 struct evhttp_bound_socket *
3846 evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port)
3847 {
3848         evutil_socket_t fd;
3849         struct evhttp_bound_socket *bound;
3850         int serrno;
3851
3852         if ((fd = bind_socket(address, port, 1 /*reuse*/)) == -1)
3853                 return (NULL);
3854
3855         if (listen(fd, 128) == -1) {
3856                 serrno = EVUTIL_SOCKET_ERROR();
3857                 event_sock_warn(fd, "%s: listen", __func__);
3858                 evutil_closesocket(fd);
3859                 EVUTIL_SET_SOCKET_ERROR(serrno);
3860                 return (NULL);
3861         }
3862
3863         bound = evhttp_accept_socket_with_handle(http, fd);
3864
3865         if (bound != NULL) {
3866                 event_debug(("Bound to port %d - Awaiting connections ... ",
3867                         port));
3868                 return (bound);
3869         }
3870
3871         return (NULL);
3872 }
3873
3874 int
3875 evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd)
3876 {
3877         struct evhttp_bound_socket *bound =
3878                 evhttp_accept_socket_with_handle(http, fd);
3879         if (bound == NULL)
3880                 return (-1);
3881         return (0);
3882 }
3883
3884 void
3885 evhttp_foreach_bound_socket(struct evhttp *http,
3886                             evhttp_bound_socket_foreach_fn *function,
3887                             void *argument)
3888 {
3889         struct evhttp_bound_socket *bound;
3890
3891         TAILQ_FOREACH(bound, &http->sockets, next)
3892                 function(bound, argument);
3893 }
3894
3895 struct evhttp_bound_socket *
3896 evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd)
3897 {
3898         struct evhttp_bound_socket *bound;
3899         struct evconnlistener *listener;
3900         const int flags =
3901             LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_CLOSE_ON_FREE;
3902
3903         listener = evconnlistener_new(http->base, NULL, NULL,
3904             flags,
3905             0, /* Backlog is '0' because we already said 'listen' */
3906             fd);
3907         if (!listener)
3908                 return (NULL);
3909
3910         bound = evhttp_bind_listener(http, listener);
3911         if (!bound) {
3912                 evconnlistener_free(listener);
3913                 return (NULL);
3914         }
3915         return (bound);
3916 }
3917
3918 struct evhttp_bound_socket *
3919 evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener)
3920 {
3921         struct evhttp_bound_socket *bound;
3922
3923         bound = mm_malloc(sizeof(struct evhttp_bound_socket));
3924         if (bound == NULL)
3925                 return (NULL);
3926
3927         bound->listener = listener;
3928         bound->bevcb = NULL;
3929         bound->http = http;
3930         TAILQ_INSERT_TAIL(&http->sockets, bound, next);
3931
3932         evconnlistener_set_cb(listener, accept_socket_cb, bound);
3933         return bound;
3934 }
3935
3936 evutil_socket_t
3937 evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound)
3938 {
3939         return evconnlistener_get_fd(bound->listener);
3940 }
3941
3942 struct evconnlistener *
3943 evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound)
3944 {
3945         return bound->listener;
3946 }
3947
3948 void
3949 evhttp_bound_set_bevcb(struct evhttp_bound_socket *bound,
3950     struct bufferevent* (*cb)(struct event_base *, void *), void *cbarg)
3951 {
3952         bound->bevcb = cb;
3953         bound->bevcbarg = cbarg;
3954 }
3955
3956 void
3957 evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound)
3958 {
3959         TAILQ_REMOVE(&http->sockets, bound, next);
3960         evconnlistener_free(bound->listener);
3961         mm_free(bound);
3962 }
3963
3964 static struct evhttp*
3965 evhttp_new_object(void)
3966 {
3967         struct evhttp *http = NULL;
3968
3969         if ((http = mm_calloc(1, sizeof(struct evhttp))) == NULL) {
3970                 event_warn("%s: calloc", __func__);
3971                 return (NULL);
3972         }
3973
3974         evutil_timerclear(&http->timeout_read);
3975         evutil_timerclear(&http->timeout_write);
3976
3977         evhttp_set_max_headers_size(http, EV_SIZE_MAX);
3978         evhttp_set_max_body_size(http, EV_SIZE_MAX);
3979         evhttp_set_default_content_type(http, "text/html; charset=ISO-8859-1");
3980         evhttp_set_allowed_methods(http,
3981             EVHTTP_REQ_GET |
3982             EVHTTP_REQ_POST |
3983             EVHTTP_REQ_HEAD |
3984             EVHTTP_REQ_PUT |
3985             EVHTTP_REQ_DELETE);
3986
3987         TAILQ_INIT(&http->sockets);
3988         TAILQ_INIT(&http->callbacks);
3989         TAILQ_INIT(&http->connections);
3990         TAILQ_INIT(&http->ws_sessions);
3991         TAILQ_INIT(&http->virtualhosts);
3992         TAILQ_INIT(&http->aliases);
3993
3994         return (http);
3995 }
3996
3997 struct evhttp *
3998 evhttp_new(struct event_base *base)
3999 {
4000         struct evhttp *http = NULL;
4001
4002         http = evhttp_new_object();
4003         if (http == NULL)
4004                 return (NULL);
4005         http->base = base;
4006
4007         return (http);
4008 }
4009
4010 /*
4011  * Start a web server on the specified address and port.
4012  */
4013
4014 struct evhttp *
4015 evhttp_start(const char *address, ev_uint16_t port)
4016 {
4017         struct evhttp *http = NULL;
4018
4019         http = evhttp_new_object();
4020         if (http == NULL)
4021                 return (NULL);
4022         if (evhttp_bind_socket(http, address, port) == -1) {
4023                 mm_free(http);
4024                 return (NULL);
4025         }
4026
4027         return (http);
4028 }
4029
4030 void
4031 evhttp_free(struct evhttp* http)
4032 {
4033         struct evhttp_cb *http_cb;
4034         struct evhttp_connection *evcon;
4035         struct evws_connection *evws;
4036         struct evhttp_bound_socket *bound;
4037         struct evhttp* vhost;
4038         struct evhttp_server_alias *alias;
4039
4040         /* Remove the accepting part */
4041         while ((bound = TAILQ_FIRST(&http->sockets)) != NULL) {
4042                 TAILQ_REMOVE(&http->sockets, bound, next);
4043
4044                 evconnlistener_free(bound->listener);
4045
4046                 mm_free(bound);
4047         }
4048
4049         while ((evcon = TAILQ_FIRST(&http->connections)) != NULL) {
4050                 /* evhttp_connection_free removes the connection */
4051                 evhttp_connection_free(evcon);
4052         }
4053
4054         while ((evws = TAILQ_FIRST(&http->ws_sessions)) != NULL) {
4055                 evws_connection_free(evws);
4056         }
4057
4058         while ((http_cb = TAILQ_FIRST(&http->callbacks)) != NULL) {
4059                 TAILQ_REMOVE(&http->callbacks, http_cb, next);
4060                 mm_free(http_cb->what);
4061                 mm_free(http_cb);
4062         }
4063
4064         while ((vhost = TAILQ_FIRST(&http->virtualhosts)) != NULL) {
4065                 TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
4066
4067                 evhttp_free(vhost);
4068         }
4069
4070         if (http->vhost_pattern != NULL)
4071                 mm_free(http->vhost_pattern);
4072
4073         while ((alias = TAILQ_FIRST(&http->aliases)) != NULL) {
4074                 TAILQ_REMOVE(&http->aliases, alias, next);
4075                 mm_free(alias->alias);
4076                 mm_free(alias);
4077         }
4078
4079         mm_free(http);
4080 }
4081
4082 int
4083 evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
4084     struct evhttp* vhost)
4085 {
4086         /* a vhost can only be a vhost once and should not have bound sockets */
4087         if (vhost->vhost_pattern != NULL ||
4088             TAILQ_FIRST(&vhost->sockets) != NULL)
4089                 return (-1);
4090
4091         vhost->vhost_pattern = mm_strdup(pattern);
4092         if (vhost->vhost_pattern == NULL)
4093                 return (-1);
4094
4095         TAILQ_INSERT_TAIL(&http->virtualhosts, vhost, next_vhost);
4096
4097         return (0);
4098 }
4099
4100 int
4101 evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost)
4102 {
4103         if (vhost->vhost_pattern == NULL)
4104                 return (-1);
4105
4106         TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
4107
4108         mm_free(vhost->vhost_pattern);
4109         vhost->vhost_pattern = NULL;
4110
4111         return (0);
4112 }
4113
4114 int
4115 evhttp_add_server_alias(struct evhttp *http, const char *alias)
4116 {
4117         struct evhttp_server_alias *evalias;
4118
4119         evalias = mm_calloc(1, sizeof(*evalias));
4120         if (!evalias)
4121                 return -1;
4122
4123         evalias->alias = mm_strdup(alias);
4124         if (!evalias->alias) {
4125                 mm_free(evalias);
4126                 return -1;
4127         }
4128
4129         TAILQ_INSERT_TAIL(&http->aliases, evalias, next);
4130
4131         return 0;
4132 }
4133
4134 int
4135 evhttp_remove_server_alias(struct evhttp *http, const char *alias)
4136 {
4137         struct evhttp_server_alias *evalias;
4138
4139         TAILQ_FOREACH(evalias, &http->aliases, next) {
4140                 if (evutil_ascii_strcasecmp(evalias->alias, alias) == 0) {
4141                         TAILQ_REMOVE(&http->aliases, evalias, next);
4142                         mm_free(evalias->alias);
4143                         mm_free(evalias);
4144                         return 0;
4145                 }
4146         }
4147
4148         return -1;
4149 }
4150
4151 void
4152 evhttp_set_timeout(struct evhttp* http, int timeout)
4153 {
4154         evhttp_set_timeout_(&http->timeout_read,  timeout, -1);
4155         evhttp_set_timeout_(&http->timeout_write, timeout, -1);
4156 }
4157 void
4158 evhttp_set_timeout_tv(struct evhttp* http, const struct timeval* tv)
4159 {
4160         evhttp_set_timeout_tv_(&http->timeout_read, tv, -1);
4161         evhttp_set_timeout_tv_(&http->timeout_write, tv, -1);
4162 }
4163 void
4164 evhttp_set_read_timeout_tv(struct evhttp* http, const struct timeval* tv)
4165 {
4166         evhttp_set_timeout_tv_(&http->timeout_read, tv, -1);
4167 }
4168 void
4169 evhttp_set_write_timeout_tv(struct evhttp* http, const struct timeval* tv)
4170 {
4171         evhttp_set_timeout_tv_(&http->timeout_write, tv, -1);
4172 }
4173
4174 int evhttp_set_flags(struct evhttp *http, int flags)
4175 {
4176         int avail_flags = 0;
4177         avail_flags |= EVHTTP_SERVER_LINGERING_CLOSE;
4178
4179         if (flags & ~avail_flags)
4180                 return 1;
4181         http->flags &= ~avail_flags;
4182
4183         http->flags |= flags;
4184
4185         return 0;
4186 }
4187
4188 void
4189 evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size)
4190 {
4191         if (max_headers_size < 0)
4192                 http->default_max_headers_size = EV_SIZE_MAX;
4193         else
4194                 http->default_max_headers_size = max_headers_size;
4195 }
4196
4197 void
4198 evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size)
4199 {
4200         if (max_body_size < 0)
4201                 http->default_max_body_size = EV_UINT64_MAX;
4202         else
4203                 http->default_max_body_size = max_body_size;
4204 }
4205
4206 void
4207 evhttp_set_max_connections(struct evhttp* http, int max_connections)
4208 {
4209         if (max_connections < 0)
4210                 http->connection_max = 0;
4211         else
4212                 http->connection_max = max_connections;
4213 }
4214
4215 int
4216 evhttp_get_connection_count(struct evhttp* http)
4217 {
4218         return http->connection_cnt;
4219 }
4220
4221 void
4222 evhttp_set_default_content_type(struct evhttp *http,
4223         const char *content_type) {
4224         http->default_content_type = content_type;
4225 }
4226
4227 void
4228 evhttp_set_allowed_methods(struct evhttp* http, ev_uint32_t methods)
4229 {
4230         http->allowed_methods = methods;
4231 }
4232
4233 void
4234 evhttp_set_ext_method_cmp(struct evhttp *http, evhttp_ext_method_cb cmp)
4235 {
4236         http->ext_method_cmp = cmp;
4237 }
4238
4239 int
4240 evhttp_set_cb(struct evhttp *http, const char *uri,
4241     void (*cb)(struct evhttp_request *, void *), void *cbarg)
4242 {
4243         struct evhttp_cb *http_cb;
4244
4245         TAILQ_FOREACH(http_cb, &http->callbacks, next) {
4246                 if (strcmp(http_cb->what, uri) == 0)
4247                         return (-1);
4248         }
4249
4250         if ((http_cb = mm_calloc(1, sizeof(struct evhttp_cb))) == NULL) {
4251                 event_warn("%s: calloc", __func__);
4252                 return (-2);
4253         }
4254
4255         http_cb->what = mm_strdup(uri);
4256         if (http_cb->what == NULL) {
4257                 event_warn("%s: strdup", __func__);
4258                 mm_free(http_cb);
4259                 return (-3);
4260         }
4261         http_cb->cb = cb;
4262         http_cb->cbarg = cbarg;
4263
4264         TAILQ_INSERT_TAIL(&http->callbacks, http_cb, next);
4265
4266         return (0);
4267 }
4268
4269 int
4270 evhttp_del_cb(struct evhttp *http, const char *uri)
4271 {
4272         struct evhttp_cb *http_cb;
4273
4274         TAILQ_FOREACH(http_cb, &http->callbacks, next) {
4275                 if (strcmp(http_cb->what, uri) == 0)
4276                         break;
4277         }
4278         if (http_cb == NULL)
4279                 return (-1);
4280
4281         TAILQ_REMOVE(&http->callbacks, http_cb, next);
4282         mm_free(http_cb->what);
4283         mm_free(http_cb);
4284
4285         return (0);
4286 }
4287
4288 void
4289 evhttp_set_gencb(struct evhttp *http,
4290     void (*cb)(struct evhttp_request *, void *), void *cbarg)
4291 {
4292         http->gencb = cb;
4293         http->gencbarg = cbarg;
4294 }
4295
4296 void
4297 evhttp_set_bevcb(struct evhttp *http,
4298     struct bufferevent* (*cb)(struct event_base *, void *), void *cbarg)
4299 {
4300         http->bevcb = cb;
4301         http->bevcbarg = cbarg;
4302 }
4303
4304 void
4305 evhttp_set_newreqcb(struct evhttp *http,
4306     int (*cb)(struct evhttp_request *, void *), void *cbarg)
4307 {
4308         http->newreqcb = cb;
4309         http->newreqcbarg = cbarg;
4310 }
4311 void
4312 evhttp_set_errorcb(struct evhttp *http,
4313     int (*cb)(struct evhttp_request *, struct evbuffer *, int, const char *, void *),
4314     void *cbarg)
4315 {
4316         http->errorcb = cb;
4317         http->errorcbarg = cbarg;
4318 }
4319
4320 /*
4321  * Request related functions
4322  */
4323
4324 struct evhttp_request *
4325 evhttp_request_new(void (*cb)(struct evhttp_request *, void *), void *arg)
4326 {
4327         struct evhttp_request *req = NULL;
4328
4329         /* Allocate request structure */
4330         if ((req = mm_calloc(1, sizeof(struct evhttp_request))) == NULL) {
4331                 event_warn("%s: calloc", __func__);
4332                 goto error;
4333         }
4334
4335         req->headers_size = 0;
4336         req->body_size = 0;
4337
4338         req->kind = EVHTTP_RESPONSE;
4339         req->input_headers = mm_calloc(1, sizeof(struct evkeyvalq));
4340         if (req->input_headers == NULL) {
4341                 event_warn("%s: calloc", __func__);
4342                 goto error;
4343         }
4344         TAILQ_INIT(req->input_headers);
4345
4346         req->output_headers = mm_calloc(1, sizeof(struct evkeyvalq));
4347         if (req->output_headers == NULL) {
4348                 event_warn("%s: calloc", __func__);
4349                 goto error;
4350         }
4351         TAILQ_INIT(req->output_headers);
4352
4353         if ((req->input_buffer = evbuffer_new()) == NULL) {
4354                 event_warn("%s: evbuffer_new", __func__);
4355                 goto error;
4356         }
4357
4358         if ((req->output_buffer = evbuffer_new()) == NULL) {
4359                 event_warn("%s: evbuffer_new", __func__);
4360                 goto error;
4361         }
4362
4363         req->cb = cb;
4364         req->cb_arg = arg;
4365
4366         return (req);
4367
4368  error:
4369         if (req != NULL)
4370                 evhttp_request_free(req);
4371         return (NULL);
4372 }
4373
4374 void
4375 evhttp_request_free(struct evhttp_request *req)
4376 {
4377         if ((req->flags & EVHTTP_REQ_DEFER_FREE) != 0) {
4378                 req->flags |= EVHTTP_REQ_NEEDS_FREE;
4379                 return;
4380         }
4381
4382         if (req->remote_host != NULL)
4383                 mm_free(req->remote_host);
4384         if (req->uri != NULL)
4385                 mm_free(req->uri);
4386         if (req->uri_elems != NULL)
4387                 evhttp_uri_free(req->uri_elems);
4388         if (req->response_code_line != NULL)
4389                 mm_free(req->response_code_line);
4390         if (req->host_cache != NULL)
4391                 mm_free(req->host_cache);
4392
4393         evhttp_clear_headers(req->input_headers);
4394         mm_free(req->input_headers);
4395
4396         evhttp_clear_headers(req->output_headers);
4397         mm_free(req->output_headers);
4398
4399         if (req->input_buffer != NULL)
4400                 evbuffer_free(req->input_buffer);
4401
4402         if (req->output_buffer != NULL)
4403                 evbuffer_free(req->output_buffer);
4404
4405         mm_free(req);
4406 }
4407
4408 void
4409 evhttp_request_own(struct evhttp_request *req)
4410 {
4411         req->flags |= EVHTTP_USER_OWNED;
4412 }
4413
4414 int
4415 evhttp_request_is_owned(struct evhttp_request *req)
4416 {
4417         return (req->flags & EVHTTP_USER_OWNED) != 0;
4418 }
4419
4420 struct evhttp_connection *
4421 evhttp_request_get_connection(struct evhttp_request *req)
4422 {
4423         return req->evcon;
4424 }
4425
4426 struct event_base *
4427 evhttp_connection_get_base(struct evhttp_connection *conn)
4428 {
4429         return conn->base;
4430 }
4431
4432 void
4433 evhttp_request_set_chunked_cb(struct evhttp_request *req,
4434     void (*cb)(struct evhttp_request *, void *))
4435 {
4436         req->chunk_cb = cb;
4437 }
4438
4439 void
4440 evhttp_request_set_header_cb(struct evhttp_request *req,
4441     int (*cb)(struct evhttp_request *, void *))
4442 {
4443         req->header_cb = cb;
4444 }
4445
4446 void
4447 evhttp_request_set_error_cb(struct evhttp_request *req,
4448     void (*cb)(enum evhttp_request_error, void *))
4449 {
4450         req->error_cb = cb;
4451 }
4452
4453 void
4454 evhttp_request_set_on_complete_cb(struct evhttp_request *req,
4455     void (*cb)(struct evhttp_request *, void *), void *cb_arg)
4456 {
4457         req->on_complete_cb = cb;
4458         req->on_complete_cb_arg = cb_arg;
4459 }
4460
4461 /*
4462  * Allows for inspection of the request URI
4463  */
4464
4465 const char *
4466 evhttp_request_get_uri(const struct evhttp_request *req) {
4467         if (req->uri == NULL)
4468                 event_debug(("%s: request %p has no uri\n", __func__, (void *)req));
4469         return (req->uri);
4470 }
4471
4472 const struct evhttp_uri *
4473 evhttp_request_get_evhttp_uri(const struct evhttp_request *req) {
4474         if (req->uri_elems == NULL)
4475                 event_debug(("%s: request %p has no uri elems\n",
4476                             __func__, (void *)req));
4477         return (req->uri_elems);
4478 }
4479
4480 const char *
4481 evhttp_request_get_host(struct evhttp_request *req)
4482 {
4483         const char *host = NULL;
4484
4485         if (req->host_cache)
4486                 return req->host_cache;
4487
4488         if (req->uri_elems)
4489                 host = evhttp_uri_get_host(req->uri_elems);
4490         if (!host && req->input_headers) {
4491                 const char *p;
4492                 size_t len;
4493
4494                 host = evhttp_find_header(req->input_headers, "Host");
4495                 /* The Host: header may include a port. Remove it here
4496                    to be consistent with uri_elems case above. */
4497                 if (host) {
4498                         p = host + strlen(host) - 1;
4499                         while (p > host && EVUTIL_ISDIGIT_(*p))
4500                                 --p;
4501                         if (p > host && *p == ':') {
4502                                 len = p - host;
4503                                 req->host_cache = mm_malloc(len + 1);
4504                                 if (!req->host_cache) {
4505                                         event_warn("%s: malloc", __func__);
4506                                         return NULL;
4507                                 }
4508                                 memcpy(req->host_cache, host, len);
4509                                 req->host_cache[len] = '\0';
4510                                 host = req->host_cache;
4511                         }
4512                 }
4513         }
4514
4515         return host;
4516 }
4517
4518 enum evhttp_cmd_type
4519 evhttp_request_get_command(const struct evhttp_request *req) {
4520         return (req->type);
4521 }
4522
4523 int
4524 evhttp_request_get_response_code(const struct evhttp_request *req)
4525 {
4526         return req->response_code;
4527 }
4528
4529 const char *
4530 evhttp_request_get_response_code_line(const struct evhttp_request *req)
4531 {
4532         return req->response_code_line;
4533 }
4534
4535 /** Returns the input headers */
4536 struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req)
4537 {
4538         return (req->input_headers);
4539 }
4540
4541 /** Returns the output headers */
4542 struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req)
4543 {
4544         return (req->output_headers);
4545 }
4546
4547 /** Returns the input buffer */
4548 struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req)
4549 {
4550         return (req->input_buffer);
4551 }
4552
4553 /** Returns the output buffer */
4554 struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req)
4555 {
4556         return (req->output_buffer);
4557 }
4558
4559
4560 /*
4561  * Takes a file descriptor to read a request from.
4562  * The callback is executed once the whole request has been read.
4563  */
4564
4565 static struct evhttp_connection*
4566 evhttp_get_request_connection(
4567         struct evhttp* http,
4568         evutil_socket_t fd, struct sockaddr *sa, ev_socklen_t salen,
4569         struct bufferevent* bev)
4570 {
4571         struct evhttp_connection *evcon;
4572
4573 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
4574         if (sa->sa_family == AF_UNIX) {
4575                 struct sockaddr_un *sa_un = (struct sockaddr_un *)sa;
4576                 sa_un->sun_path[0] = '\0';
4577         }
4578 #endif
4579
4580 #ifndef _WIN32
4581         if (sa->sa_family == AF_UNIX) {
4582                 struct sockaddr_un *sockaddr = (struct sockaddr_un *)sa;
4583
4584                 event_debug(("%s: new request from unix socket on "
4585                         EV_SOCK_FMT"\n", __func__, EV_SOCK_ARG(fd)));
4586
4587                 /* we need a connection object to put the http request on */
4588                 if (!bev && http->bevcb != NULL) {
4589                         bev = (*http->bevcb)(http->base, http->bevcbarg);
4590                 }
4591
4592                 evcon = evhttp_connection_base_bufferevent_unix_new(http->base,
4593                         bev, sockaddr->sun_path);
4594         }
4595         else
4596 #endif
4597         {
4598                 char *hostname = NULL, *portname = NULL;
4599
4600                 name_from_addr(sa, salen, &hostname, &portname);
4601                 if (hostname == NULL || portname == NULL) {
4602                         if (hostname) mm_free(hostname);
4603                         if (portname) mm_free(portname);
4604                         return (NULL);
4605                 }
4606
4607                 event_debug(("%s: new request from %s:%s on "EV_SOCK_FMT"\n",
4608                         __func__, hostname, portname, EV_SOCK_ARG(fd)));
4609
4610                 /* we need a connection object to put the http request on */
4611                 if (!bev && http->bevcb != NULL) {
4612                         bev = (*http->bevcb)(http->base, http->bevcbarg);
4613                 }
4614                 evcon = evhttp_connection_base_bufferevent_new(
4615                         http->base, NULL, bev, hostname, atoi(portname));
4616                 mm_free(hostname);
4617                 mm_free(portname);
4618         }
4619         if (evcon == NULL)
4620                 return (NULL);
4621
4622         evcon->max_headers_size = http->default_max_headers_size;
4623         evcon->max_body_size = http->default_max_body_size;
4624         if (http->flags & EVHTTP_SERVER_LINGERING_CLOSE)
4625                 evcon->flags |= EVHTTP_CON_LINGERING_CLOSE;
4626
4627         evcon->flags |= EVHTTP_CON_INCOMING;
4628         evcon->state = EVCON_READING_FIRSTLINE;
4629
4630         if (bufferevent_replacefd(evcon->bufev, fd))
4631                 goto err;
4632         if (bufferevent_enable(evcon->bufev, EV_READ))
4633                 goto err;
4634         if (bufferevent_disable(evcon->bufev, EV_WRITE))
4635                 goto err;
4636         bufferevent_socket_set_conn_address_(evcon->bufev, sa, salen);
4637
4638         return (evcon);
4639
4640 err:
4641         evhttp_connection_free(evcon);
4642         return (NULL);
4643 }
4644
4645 static int
4646 evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
4647 {
4648         struct evhttp *http = evcon->http_server;
4649         struct evhttp_request *req;
4650         if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL)
4651                 return (-1);
4652
4653         if (evcon->address != NULL) {
4654                 if ((req->remote_host = mm_strdup(evcon->address)) == NULL) {
4655                         event_warn("%s: strdup", __func__);
4656                         evhttp_request_free(req);
4657                         return (-1);
4658                 }
4659         }
4660         req->remote_port = evcon->port;
4661
4662         req->evcon = evcon;     /* the request ends up owning the connection */
4663         req->flags |= EVHTTP_REQ_OWN_CONNECTION;
4664
4665         /* We did not present the request to the user yet, so treat it
4666          * as if the user was done with the request.  This allows us
4667          * to free the request on a persistent connection if the
4668          * client drops it without sending a request.
4669          */
4670         req->userdone = 1;
4671         req->kind = EVHTTP_REQUEST;
4672
4673         if (http->newreqcb && http->newreqcb(req, http->newreqcbarg) == -1) {
4674                 evhttp_request_free(req);
4675                 return (-1);
4676         }
4677
4678         TAILQ_INSERT_TAIL(&evcon->requests, req, next);
4679
4680         evhttp_start_read_(evcon);
4681
4682         return (0);
4683 }
4684
4685 static void
4686 evhttp_get_request(struct evhttp *http, evutil_socket_t fd,
4687     struct sockaddr *sa, ev_socklen_t salen,
4688     struct bufferevent *bev)
4689 {
4690         struct evhttp_connection *evcon;
4691
4692         evcon = evhttp_get_request_connection(http, fd, sa, salen, bev);
4693         if (evcon == NULL) {
4694                 event_sock_warn(fd, "%s: cannot get connection on "EV_SOCK_FMT,
4695                     __func__, EV_SOCK_ARG(fd));
4696                 evutil_closesocket(fd);
4697                 return;
4698         }
4699
4700         /* the timeout can be used by the server to close idle connections */
4701         if (evutil_timerisset(&http->timeout_read))
4702                 evhttp_connection_set_read_timeout_tv(evcon,  &http->timeout_read);
4703         if (evutil_timerisset(&http->timeout_write))
4704                 evhttp_connection_set_write_timeout_tv(evcon, &http->timeout_write);
4705
4706         /*
4707          * if we want to accept more than one request on a connection,
4708          * we need to know which http server it belongs to.
4709          */
4710         evcon->http_server = http;
4711         evcon->ext_method_cmp = http->ext_method_cmp;
4712         TAILQ_INSERT_TAIL(&http->connections, evcon, next);
4713         http->connection_cnt++;
4714
4715         /* send "service unavailable" if we've reached the connection limit */
4716         if (http->connection_max && http->connection_max < http->connection_cnt) {
4717                 struct evhttp_request *req;
4718
4719                 if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL) {
4720                         evhttp_connection_free(evcon);
4721                         return;
4722                 }
4723
4724                 req->evcon = evcon;     /* the request owns the connection */
4725                 req->flags |= EVHTTP_REQ_OWN_CONNECTION;
4726                 req->kind = EVHTTP_REQUEST;
4727                 /* note, req->remote_host not needed since we don't read */
4728
4729                 TAILQ_INSERT_TAIL(&evcon->requests, req, next);
4730
4731                 /* send error to client */
4732                 evcon->state = EVCON_WRITING;
4733                 bufferevent_enable(evcon->bufev, EV_READ); /* enable close events */
4734                 evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
4735
4736         } else if (evhttp_associate_new_request_with_connection(evcon) == -1)
4737                 evhttp_connection_free(evcon);
4738 }
4739
4740
4741 /*
4742  * Network helper functions that we do not want to export to the rest of
4743  * the world.
4744  */
4745
4746 static void
4747 name_from_addr(struct sockaddr *sa, ev_socklen_t salen,
4748     char **phost, char **pport)
4749 {
4750         char ntop[NI_MAXHOST];
4751         char strport[NI_MAXSERV];
4752         int ni_result;
4753
4754 #ifdef EVENT__HAVE_GETNAMEINFO
4755         ni_result = getnameinfo(sa, salen,
4756                 ntop, sizeof(ntop), strport, sizeof(strport),
4757                 NI_NUMERICHOST|NI_NUMERICSERV);
4758
4759         if (ni_result != 0) {
4760 #ifdef EAI_SYSTEM
4761                 /* Windows doesn't have an EAI_SYSTEM. */
4762                 if (ni_result == EAI_SYSTEM)
4763                         event_err(1, "getnameinfo failed");
4764                 else
4765 #endif
4766                         event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
4767                 return;
4768         }
4769 #else
4770         ni_result = fake_getnameinfo(sa, salen,
4771                 ntop, sizeof(ntop), strport, sizeof(strport),
4772                 NI_NUMERICHOST|NI_NUMERICSERV);
4773         if (ni_result != 0)
4774                         return;
4775 #endif
4776
4777         *phost = mm_strdup(ntop);
4778         *pport = mm_strdup(strport);
4779 }
4780
4781 /* Create a non-blocking socket and bind it */
4782 static evutil_socket_t
4783 create_bind_socket_nonblock(struct evutil_addrinfo *ai, int reuse)
4784 {
4785         evutil_socket_t fd;
4786
4787         int on = 1, r;
4788         int serrno;
4789
4790         /* Create listen socket */
4791         fd = evutil_socket_(ai ? ai->ai_family : AF_INET,
4792             SOCK_STREAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
4793         if (fd == -1) {
4794                         event_sock_warn(-1, "socket");
4795                         return (-1);
4796         }
4797
4798         if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on))<0)
4799                 goto out;
4800         if (reuse) {
4801                 if (evutil_make_listen_socket_reuseable(fd) < 0)
4802                         goto out;
4803         }
4804
4805         if (ai != NULL) {
4806                 r = bind(fd, ai->ai_addr, (ev_socklen_t)ai->ai_addrlen);
4807                 if (r == -1)
4808                         goto out;
4809         }
4810
4811         return (fd);
4812
4813  out:
4814         serrno = EVUTIL_SOCKET_ERROR();
4815         evutil_closesocket(fd);
4816         EVUTIL_SET_SOCKET_ERROR(serrno);
4817         return (-1);
4818 }
4819
4820 static struct evutil_addrinfo *
4821 make_addrinfo(const char *address, ev_uint16_t port)
4822 {
4823         struct evutil_addrinfo *ai = NULL;
4824
4825         struct evutil_addrinfo hints;
4826         char strport[NI_MAXSERV];
4827         int ai_result;
4828
4829         memset(&hints, 0, sizeof(hints));
4830         hints.ai_family = AF_UNSPEC;
4831         hints.ai_socktype = SOCK_STREAM;
4832         /* turn NULL hostname into INADDR_ANY, and skip looking up any address
4833          * types we don't have an interface to connect to. */
4834         hints.ai_flags = EVUTIL_AI_PASSIVE|EVUTIL_AI_ADDRCONFIG;
4835         evutil_snprintf(strport, sizeof(strport), "%d", port);
4836         if ((ai_result = evutil_getaddrinfo(address, strport, &hints, &ai))
4837             != 0) {
4838                 if (ai_result == EVUTIL_EAI_SYSTEM)
4839                         event_warn("getaddrinfo");
4840                 else
4841                         event_warnx("getaddrinfo: %s",
4842                             evutil_gai_strerror(ai_result));
4843                 return (NULL);
4844         }
4845
4846         return (ai);
4847 }
4848
4849 static evutil_socket_t
4850 bind_socket(const char *address, ev_uint16_t port, int reuse)
4851 {
4852         evutil_socket_t fd;
4853         struct evutil_addrinfo *aitop = NULL;
4854
4855         /* just create an unbound socket */
4856         if (address == NULL && port == 0)
4857                 return create_bind_socket_nonblock(NULL, 0);
4858
4859         aitop = make_addrinfo(address, port);
4860
4861         if (aitop == NULL)
4862                 return (-1);
4863
4864         fd = create_bind_socket_nonblock(aitop, reuse);
4865
4866         evutil_freeaddrinfo(aitop);
4867
4868         return (fd);
4869 }
4870
4871 struct evhttp_uri {
4872         unsigned flags;
4873         char *scheme; /* scheme; e.g http, ftp etc */
4874         char *userinfo; /* userinfo (typically username:pass), or NULL */
4875         char *host; /* hostname, IP address, or NULL */
4876         int port; /* port, or zero */
4877 #ifndef _WIN32
4878         char *unixsocket; /* unix domain socket or NULL */
4879 #endif
4880         char *path; /* path, or "". */
4881         char *query; /* query, or NULL */
4882         char *fragment; /* fragment or NULL */
4883 };
4884
4885 struct evhttp_uri *
4886 evhttp_uri_new(void)
4887 {
4888         struct evhttp_uri *uri = mm_calloc(sizeof(struct evhttp_uri), 1);
4889         if (uri)
4890                 uri->port = -1;
4891         return uri;
4892 }
4893
4894 void
4895 evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags)
4896 {
4897         uri->flags = flags;
4898 }
4899
4900 /* Return true if the string starting at s and ending immediately before eos
4901  * is a valid URI scheme according to RFC3986
4902  */
4903 static int
4904 scheme_ok(const char *s, const char *eos)
4905 {
4906         /* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
4907         EVUTIL_ASSERT(eos >= s);
4908         if (s == eos)
4909                 return 0;
4910         if (!EVUTIL_ISALPHA_(*s))
4911                 return 0;
4912         while (++s < eos) {
4913                 if (! EVUTIL_ISALNUM_(*s) &&
4914                     *s != '+' && *s != '-' && *s != '.')
4915                         return 0;
4916         }
4917         return 1;
4918 }
4919
4920 #define SUBDELIMS "!$&'()*+,;="
4921
4922 /* Return true iff [s..eos) is a valid userinfo */
4923 static int
4924 userinfo_ok(const char *s, const char *eos)
4925 {
4926         while (s < eos) {
4927                 if (CHAR_IS_UNRESERVED(*s) ||
4928                     strchr(SUBDELIMS, *s) ||
4929                     *s == ':')
4930                         ++s;
4931                 else if (*s == '%' && s+2 < eos &&
4932                     EVUTIL_ISXDIGIT_(s[1]) &&
4933                     EVUTIL_ISXDIGIT_(s[2]))
4934                         s += 3;
4935                 else
4936                         return 0;
4937         }
4938         return 1;
4939 }
4940
4941 static int
4942 regname_ok(const char *s, const char *eos)
4943 {
4944         while (s && s<eos) {
4945                 if (CHAR_IS_UNRESERVED(*s) ||
4946                     strchr(SUBDELIMS, *s))
4947                         ++s;
4948                 else if (*s == '%' &&
4949                     EVUTIL_ISXDIGIT_(s[1]) &&
4950                     EVUTIL_ISXDIGIT_(s[2]))
4951                         s += 3;
4952                 else
4953                         return 0;
4954         }
4955         return 1;
4956 }
4957
4958 static int
4959 parse_port(const char *s, const char *eos)
4960 {
4961         int portnum = 0;
4962         while (s < eos) {
4963                 if (! EVUTIL_ISDIGIT_(*s))
4964                         return -1;
4965                 portnum = (portnum * 10) + (*s - '0');
4966                 if (portnum < 0)
4967                         return -1;
4968                 if (portnum > 65535)
4969                         return -1;
4970                 ++s;
4971         }
4972         return portnum;
4973 }
4974
4975 /* returns 0 for bad, 1 for ipv6, 2 for IPvFuture */
4976 static int
4977 bracket_addr_ok(const char *s, const char *eos)
4978 {
4979         if (s + 3 > eos || *s != '[' || *(eos-1) != ']')
4980                 return 0;
4981         if (s[1] == 'v') {
4982                 /* IPvFuture, or junk.
4983                    "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
4984                  */
4985                 s += 2; /* skip [v */
4986                 --eos;
4987                 if (!EVUTIL_ISXDIGIT_(*s)) /*require at least one*/
4988                         return 0;
4989                 while (s < eos && *s != '.') {
4990                         if (EVUTIL_ISXDIGIT_(*s))
4991                                 ++s;
4992                         else
4993                                 return 0;
4994                 }
4995                 if (*s != '.')
4996                         return 0;
4997                 ++s;
4998                 while (s < eos) {
4999                         if (CHAR_IS_UNRESERVED(*s) ||
5000                             strchr(SUBDELIMS, *s) ||
5001                             *s == ':')
5002                                 ++s;
5003                         else
5004                                 return 0;
5005                 }
5006                 return 2;
5007         } else {
5008                 /* IPv6, or junk */
5009                 char buf[64];
5010                 ev_ssize_t n_chars = eos-s-2;
5011                 struct in6_addr in6;
5012                 if (n_chars >= 64) /* way too long */
5013                         return 0;
5014                 memcpy(buf, s+1, n_chars);
5015                 buf[n_chars]='\0';
5016                 return (evutil_inet_pton(AF_INET6,buf,&in6)==1) ? 1 : 0;
5017         }
5018 }
5019
5020 static int
5021 parse_authority(struct evhttp_uri *uri, char *s, char *eos, unsigned *flags)
5022 {
5023         size_t len;
5024         char *cp, *port;
5025
5026         EVUTIL_ASSERT(eos);
5027         if (eos == s) {
5028                 uri->host = mm_strdup("");
5029                 if (uri->host == NULL) {
5030                         event_warn("%s: strdup", __func__);
5031                         return -1;
5032                 }
5033                 return 0;
5034         }
5035
5036         /* Optionally, we start with "userinfo@" */
5037
5038         cp = strchr(s, '@');
5039         if (cp && cp < eos) {
5040                 if (! userinfo_ok(s,cp))
5041                         return -1;
5042                 *cp++ = '\0';
5043                 uri->userinfo = mm_strdup(s);
5044                 if (uri->userinfo == NULL) {
5045                         event_warn("%s: strdup", __func__);
5046                         return -1;
5047                 }
5048         } else {
5049                 cp = s;
5050         }
5051
5052 #ifndef _WIN32
5053         if (*flags & EVHTTP_URI_UNIX_SOCKET && !strncmp(cp, "unix:", 5)) {
5054                 char *e = strchr(cp + 5, ':');
5055                 if (e) {
5056                         *e = '\0';
5057                         uri->unixsocket = mm_strdup(cp + 5);
5058                         return 0;
5059                 } else {
5060                         return -1;
5061                 }
5062         }
5063 #endif
5064
5065         /* Optionally, we end with ":port" */
5066         for (port=eos-1; port >= cp && EVUTIL_ISDIGIT_(*port); --port)
5067                 ;
5068         if (port >= cp && *port == ':') {
5069                 if (port+1 == eos) /* Leave port unspecified; the RFC allows a
5070                                     * nil port */
5071                         uri->port = -1;
5072                 else if ((uri->port = parse_port(port+1, eos))<0)
5073                         return -1;
5074                 eos = port;
5075         }
5076         /* Now, cp..eos holds the "host" port, which can be an IPv4Address,
5077          * an IP-Literal, or a reg-name */
5078         EVUTIL_ASSERT(eos >= cp);
5079         len = eos-cp;
5080         if (*cp == '[' && eos >= cp+2 && *(eos-1) == ']') {
5081                 /* IPv6address, IP-Literal, or junk. */
5082                 if (! bracket_addr_ok(cp, eos))
5083                         return -1;
5084                 if (*flags & EVHTTP_URI_HOST_STRIP_BRACKETS)
5085                         len = eos-cp-2;
5086         } else {
5087                 /* Make sure the host part is ok. */
5088                 if (! regname_ok(cp,eos)) /* Match IPv4Address or reg-name */
5089                         return -1;
5090         }
5091
5092         uri->host = mm_malloc(len+1);
5093         if (uri->host == NULL) {
5094                 event_warn("%s: malloc", __func__);
5095                 return -1;
5096         }
5097         if (*cp == '[' && *flags & EVHTTP_URI_HOST_STRIP_BRACKETS) {
5098                 memcpy(uri->host, cp+1, len);
5099                 *flags |= _EVHTTP_URI_HOST_HAS_BRACKETS;
5100         } else {
5101                 memcpy(uri->host, cp, len);
5102         }
5103         uri->host[len] = '\0';
5104         return 0;
5105
5106 }
5107
5108 static char *
5109 end_of_authority(char *cp)
5110 {
5111         while (*cp) {
5112                 if (*cp == '?' || *cp == '#' || *cp == '/')
5113                         return cp;
5114                 ++cp;
5115         }
5116         return cp;
5117 }
5118
5119 enum uri_part {
5120         PART_PATH,
5121         PART_QUERY,
5122         PART_FRAGMENT
5123 };
5124
5125 /* Return the character after the longest prefix of 'cp' that matches...
5126  *   *pchar / "/" if allow_qchars is false, or
5127  *   *(pchar / "/" / "?") if allow_qchars is true.
5128  */
5129 static char *
5130 end_of_path(char *cp, enum uri_part part, unsigned flags)
5131 {
5132         if (flags & EVHTTP_URI_NONCONFORMANT) {
5133                 /* If NONCONFORMANT:
5134                  *   Path is everything up to a # or ? or nul.
5135                  *   Query is everything up a # or nul
5136                  *   Fragment is everything up to a nul.
5137                  */
5138                 switch (part) {
5139                 case PART_PATH:
5140                         while (*cp && *cp != '#' && *cp != '?')
5141                                 ++cp;
5142                         break;
5143                 case PART_QUERY:
5144                         while (*cp && *cp != '#')
5145                                 ++cp;
5146                         break;
5147                 case PART_FRAGMENT:
5148                         cp += strlen(cp);
5149                         break;
5150                 };
5151                 return cp;
5152         }
5153
5154         while (*cp) {
5155                 if (CHAR_IS_UNRESERVED(*cp) ||
5156                     strchr(SUBDELIMS, *cp) ||
5157                     *cp == ':' || *cp == '@' || *cp == '/')
5158                         ++cp;
5159                 else if (*cp == '%' && EVUTIL_ISXDIGIT_(cp[1]) &&
5160                     EVUTIL_ISXDIGIT_(cp[2]))
5161                         cp += 3;
5162                 else if (*cp == '?' && part != PART_PATH)
5163                         ++cp;
5164                 else
5165                         return cp;
5166         }
5167         return cp;
5168 }
5169
5170 static int
5171 path_matches_noscheme(const char *cp)
5172 {
5173         while (*cp) {
5174                 if (*cp == ':')
5175                         return 0;
5176                 else if (*cp == '/')
5177                         return 1;
5178                 ++cp;
5179         }
5180         return 1;
5181 }
5182
5183 struct evhttp_uri *
5184 evhttp_uri_parse(const char *source_uri)
5185 {
5186         return evhttp_uri_parse_with_flags(source_uri, 0);
5187 }
5188
5189 struct evhttp_uri *
5190 evhttp_uri_parse_with_flags(const char *source_uri, unsigned flags)
5191 {
5192         char *readbuf = NULL, *readp = NULL, *token = NULL, *query = NULL;
5193         char *path = NULL, *fragment = NULL;
5194         int got_authority = 0;
5195
5196         struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
5197         if (uri == NULL) {
5198                 event_warn("%s: calloc", __func__);
5199                 goto err;
5200         }
5201         uri->port = -1;
5202         uri->flags = flags;
5203
5204         readbuf = mm_strdup(source_uri);
5205         if (readbuf == NULL) {
5206                 event_warn("%s: strdup", __func__);
5207                 goto err;
5208         }
5209
5210         readp = readbuf;
5211         token = NULL;
5212
5213         /* We try to follow RFC3986 here as much as we can, and match
5214            the productions
5215
5216               URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
5217
5218               relative-ref  = relative-part [ "?" query ] [ "#" fragment ]
5219          */
5220
5221         /* 1. scheme: */
5222         token = strchr(readp, ':');
5223         if (token && scheme_ok(readp,token)) {
5224                 *token = '\0';
5225                 uri->scheme = mm_strdup(readp);
5226                 if (uri->scheme == NULL) {
5227                         event_warn("%s: strdup", __func__);
5228                         goto err;
5229                 }
5230                 readp = token+1; /* eat : */
5231         }
5232
5233         /* 2. Optionally, "//" then an 'authority' part. */
5234         if (readp[0]=='/' && readp[1] == '/') {
5235                 char *authority;
5236                 readp += 2;
5237                 authority = readp;
5238                 path = end_of_authority(readp);
5239                 if (parse_authority(uri, authority, path, &uri->flags) < 0)
5240                         goto err;
5241                 readp = path;
5242                 got_authority = 1;
5243         }
5244
5245         /* 3. Query: path-abempty, path-absolute, path-rootless, or path-empty
5246          */
5247         path = readp;
5248         readp = end_of_path(path, PART_PATH, flags);
5249
5250         /* Query */
5251         if (*readp == '?') {
5252                 *readp = '\0';
5253                 ++readp;
5254                 query = readp;
5255                 readp = end_of_path(readp, PART_QUERY, flags);
5256         }
5257         /* fragment */
5258         if (*readp == '#') {
5259                 *readp = '\0';
5260                 ++readp;
5261                 fragment = readp;
5262                 readp = end_of_path(readp, PART_FRAGMENT, flags);
5263         }
5264         if (*readp != '\0') {
5265                 goto err;
5266         }
5267
5268         /* These next two cases may be unreachable; I'm leaving them
5269          * in to be defensive. */
5270         /* If you didn't get an authority, the path can't begin with "//" */
5271         if (!got_authority && path[0]=='/' && path[1]=='/')
5272                 goto err;
5273         /* If you did get an authority, the path must begin with "/" or be
5274          * empty. */
5275         if (got_authority && path[0] != '/' && path[0] != '\0')
5276                 goto err;
5277         /* (End of maybe-unreachable cases) */
5278
5279         /* If there was no scheme, the first part of the path (if any) must
5280          * have no colon in it. */
5281         if (! uri->scheme && !path_matches_noscheme(path))
5282                 goto err;
5283
5284         EVUTIL_ASSERT(path);
5285         uri->path = mm_strdup(path);
5286         if (uri->path == NULL) {
5287                 event_warn("%s: strdup", __func__);
5288                 goto err;
5289         }
5290
5291         if (query) {
5292                 uri->query = mm_strdup(query);
5293                 if (uri->query == NULL) {
5294                         event_warn("%s: strdup", __func__);
5295                         goto err;
5296                 }
5297         }
5298         if (fragment) {
5299                 uri->fragment = mm_strdup(fragment);
5300                 if (uri->fragment == NULL) {
5301                         event_warn("%s: strdup", __func__);
5302                         goto err;
5303                 }
5304         }
5305
5306         mm_free(readbuf);
5307
5308         return uri;
5309 err:
5310         if (uri)
5311                 evhttp_uri_free(uri);
5312         if (readbuf)
5313                 mm_free(readbuf);
5314         return NULL;
5315 }
5316
5317 static struct evhttp_uri *
5318 evhttp_uri_parse_authority(char *source_uri, unsigned flags)
5319 {
5320         struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
5321         char *end;
5322
5323         if (uri == NULL) {
5324                 event_warn("%s: calloc", __func__);
5325                 goto err;
5326         }
5327         uri->port = -1;
5328         uri->flags = flags;
5329
5330         end = end_of_authority(source_uri);
5331         if (parse_authority(uri, source_uri, end, &uri->flags) < 0)
5332                 goto err;
5333
5334         uri->path = mm_strdup("");
5335         if (uri->path == NULL) {
5336                 event_warn("%s: strdup", __func__);
5337                 goto err;
5338         }
5339
5340         return uri;
5341 err:
5342         if (uri)
5343                 evhttp_uri_free(uri);
5344         return NULL;
5345 }
5346
5347 void
5348 evhttp_uri_free(struct evhttp_uri *uri)
5349 {
5350 #define URI_FREE_STR_(f)                \
5351         if (uri->f) {                   \
5352                 mm_free(uri->f);                \
5353         }
5354
5355         URI_FREE_STR_(scheme);
5356         URI_FREE_STR_(userinfo);
5357         URI_FREE_STR_(host);
5358 #ifndef _WIN32
5359         URI_FREE_STR_(unixsocket);
5360 #endif
5361         URI_FREE_STR_(path);
5362         URI_FREE_STR_(query);
5363         URI_FREE_STR_(fragment);
5364
5365         mm_free(uri);
5366 #undef URI_FREE_STR_
5367 }
5368
5369 char *
5370 evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
5371 {
5372         struct evbuffer *tmp = 0;
5373         size_t joined_size = 0;
5374         char *output = NULL;
5375
5376 #define URI_ADD_(f)     evbuffer_add(tmp, uri->f, strlen(uri->f))
5377
5378         if (!uri || !buf || !limit)
5379                 return NULL;
5380
5381         tmp = evbuffer_new();
5382         if (!tmp)
5383                 return NULL;
5384
5385         if (uri->scheme) {
5386                 URI_ADD_(scheme);
5387                 evbuffer_add(tmp, ":", 1);
5388         }
5389 #ifndef _WIN32
5390         if (uri->unixsocket) {
5391                 evbuffer_add(tmp, "//", 2);
5392                 if (uri->userinfo)
5393                         evbuffer_add_printf(tmp, "%s@", uri->userinfo);
5394                 evbuffer_add_printf(tmp, "unix:%s:", uri->unixsocket);
5395         }
5396         else
5397 #endif
5398         if (uri->host) {
5399                 evbuffer_add(tmp, "//", 2);
5400                 if (uri->userinfo)
5401                         evbuffer_add_printf(tmp,"%s@", uri->userinfo);
5402                 if (uri->flags & _EVHTTP_URI_HOST_HAS_BRACKETS) {
5403                         evbuffer_add(tmp, "[", 1);
5404                         URI_ADD_(host);
5405                         evbuffer_add(tmp, "]", 1);
5406                 } else {
5407                         URI_ADD_(host);
5408                 }
5409                 if (uri->port >= 0)
5410                         evbuffer_add_printf(tmp,":%d", uri->port);
5411
5412                 if (uri->path && uri->path[0] != '/' && uri->path[0] != '\0')
5413                         goto err;
5414         }
5415
5416         if (uri->path)
5417                 URI_ADD_(path);
5418
5419         if (uri->query) {
5420                 evbuffer_add(tmp, "?", 1);
5421                 URI_ADD_(query);
5422         }
5423
5424         if (uri->fragment) {
5425                 evbuffer_add(tmp, "#", 1);
5426                 URI_ADD_(fragment);
5427         }
5428
5429         evbuffer_add(tmp, "\0", 1); /* NUL */
5430
5431         joined_size = evbuffer_get_length(tmp);
5432
5433         if (joined_size > limit) {
5434                 /* It doesn't fit. */
5435                 evbuffer_free(tmp);
5436                 return NULL;
5437         }
5438         evbuffer_remove(tmp, buf, joined_size);
5439
5440         output = buf;
5441 err:
5442         evbuffer_free(tmp);
5443
5444         return output;
5445 #undef URI_ADD_
5446 }
5447
5448 const char *
5449 evhttp_uri_get_scheme(const struct evhttp_uri *uri)
5450 {
5451         return uri->scheme;
5452 }
5453 const char *
5454 evhttp_uri_get_userinfo(const struct evhttp_uri *uri)
5455 {
5456         return uri->userinfo;
5457 }
5458 const char *
5459 evhttp_uri_get_host(const struct evhttp_uri *uri)
5460 {
5461         return uri->host;
5462 }
5463 #ifndef _WIN32
5464 const char *
5465 evhttp_uri_get_unixsocket(const struct evhttp_uri *uri)
5466 {
5467         return uri->unixsocket;
5468 }
5469 #endif
5470 int
5471 evhttp_uri_get_port(const struct evhttp_uri *uri)
5472 {
5473         return uri->port;
5474 }
5475 const char *
5476 evhttp_uri_get_path(const struct evhttp_uri *uri)
5477 {
5478         return uri->path;
5479 }
5480 const char *
5481 evhttp_uri_get_query(const struct evhttp_uri *uri)
5482 {
5483         return uri->query;
5484 }
5485 const char *
5486 evhttp_uri_get_fragment(const struct evhttp_uri *uri)
5487 {
5488         return uri->fragment;
5489 }
5490
5491 #define URI_SET_STR_(f) do {                                    \
5492         if (uri->f)                                             \
5493                 mm_free(uri->f);                                \
5494         if (f) {                                                \
5495                 if ((uri->f = mm_strdup(f)) == NULL) {          \
5496                         event_warn("%s: strdup()", __func__);   \
5497                         return -1;                              \
5498                 }                                               \
5499         } else {                                                \
5500                 uri->f = NULL;                                  \
5501         }                                                       \
5502         } while(0)
5503
5504 int
5505 evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme)
5506 {
5507         if (scheme && !scheme_ok(scheme, scheme+strlen(scheme)))
5508                 return -1;
5509
5510         URI_SET_STR_(scheme);
5511         return 0;
5512 }
5513 int
5514 evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo)
5515 {
5516         if (userinfo && !userinfo_ok(userinfo, userinfo+strlen(userinfo)))
5517                 return -1;
5518         URI_SET_STR_(userinfo);
5519         return 0;
5520 }
5521 int
5522 evhttp_uri_set_host(struct evhttp_uri *uri, const char *host)
5523 {
5524         size_t len = 0;
5525
5526         if (host) {
5527                 len = strlen(host);
5528
5529                 if (host[0] == '[') {
5530                         if (! bracket_addr_ok(host, host+len))
5531                                 return -1;
5532                 } else {
5533                         if (! regname_ok(host, host+len))
5534                                 return -1;
5535                 }
5536         }
5537
5538         if (host && host[0] == '[' && uri->flags & EVHTTP_URI_HOST_STRIP_BRACKETS) {
5539                 char *new_host;
5540
5541                 len -= 2;
5542                 new_host = mm_realloc(uri->host, len+1);
5543                 if (!new_host) {
5544                         free(uri->host);
5545                         uri->host = NULL;
5546                 } else {
5547                         memcpy(new_host, host+1, len);
5548                         new_host[len] = '\0';
5549                         uri->host = new_host;
5550                 }
5551                 uri->flags |= _EVHTTP_URI_HOST_HAS_BRACKETS;
5552         } else {
5553                 URI_SET_STR_(host);
5554                 uri->flags &= ~_EVHTTP_URI_HOST_HAS_BRACKETS;
5555         }
5556
5557         return 0;
5558 }
5559 #ifndef _WIN32
5560 int
5561 evhttp_uri_set_unixsocket(struct evhttp_uri *uri, const char *unixsocket)
5562 {
5563         URI_SET_STR_(unixsocket);
5564         return 0;
5565 }
5566 #endif
5567 int
5568 evhttp_uri_set_port(struct evhttp_uri *uri, int port)
5569 {
5570         if (port < -1)
5571                 return -1;
5572         uri->port = port;
5573         return 0;
5574 }
5575 #define end_of_cpath(cp,p,f) \
5576         ((const char*)(end_of_path(((char*)(cp)), (p), (f))))
5577
5578 int
5579 evhttp_uri_set_path(struct evhttp_uri *uri, const char *path)
5580 {
5581         if (path && end_of_cpath(path, PART_PATH, uri->flags) != path+strlen(path))
5582                 return -1;
5583
5584         URI_SET_STR_(path);
5585         return 0;
5586 }
5587 int
5588 evhttp_uri_set_query(struct evhttp_uri *uri, const char *query)
5589 {
5590         if (query && end_of_cpath(query, PART_QUERY, uri->flags) != query+strlen(query))
5591                 return -1;
5592         URI_SET_STR_(query);
5593         return 0;
5594 }
5595 int
5596 evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment)
5597 {
5598         if (fragment && end_of_cpath(fragment, PART_FRAGMENT, uri->flags) != fragment+strlen(fragment))
5599                 return -1;
5600         URI_SET_STR_(fragment);
5601         return 0;
5602 }