]> granicus.if.org Git - libevent/blob - http.c
Fix the value is never actually read from 'argument' in evhttp_parse_query_impl()
[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 disassociate 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 *p;
3559         const char *query_part;
3560         int result = -1;
3561         struct evhttp_uri *uri=NULL;
3562
3563         TAILQ_INIT(headers);
3564
3565         if (is_whole_uri) {
3566                 uri = evhttp_uri_parse(str);
3567                 if (!uri)
3568                         goto error;
3569                 query_part = evhttp_uri_get_query(uri);
3570         } else {
3571                 query_part = str;
3572         }
3573
3574         /* No arguments - we are done */
3575         if (!query_part || !strlen(query_part)) {
3576                 result = 0;
3577                 goto done;
3578         }
3579
3580         if ((line = mm_strdup(query_part)) == NULL) {
3581                 event_warn("%s: strdup", __func__);
3582                 goto error;
3583         }
3584
3585         p = line;
3586         while (p != NULL && *p != '\0') {
3587                 char *key, *value, *decoded_value;
3588                 int err;
3589
3590                 value = strsep(&p, "&");
3591                 key = strsep(&value, "=");
3592                 if (flags & EVHTTP_URI_QUERY_NONCONFORMANT) {
3593                         if (value == NULL)
3594                                 value = (char *)"";
3595                         if (*key == '\0')
3596                                 continue;
3597                 } else {
3598                         if (value == NULL || *key == '\0')
3599                                 goto error;
3600                 }
3601
3602                 if ((decoded_value = mm_malloc(strlen(value) + 1)) == NULL) {
3603                         event_warn("%s: mm_malloc", __func__);
3604                         goto error;
3605                 }
3606                 evhttp_decode_uri_internal(value, strlen(value),
3607                     decoded_value, 1 /*always_decode_plus*/);
3608                 event_debug(("Query Param: %s -> %s\n", key, decoded_value));
3609                 if (flags & EVHTTP_URI_QUERY_LAST_VAL)
3610                         evhttp_remove_header(headers, key);
3611                 err = evhttp_add_header_internal(headers, key, decoded_value);
3612                 mm_free(decoded_value);
3613                 if (err)
3614                         goto error;
3615         }
3616
3617         result = 0;
3618         goto done;
3619 error:
3620         evhttp_clear_headers(headers);
3621 done:
3622         if (line)
3623                 mm_free(line);
3624         if (uri)
3625                 evhttp_uri_free(uri);
3626         return result;
3627 }
3628
3629 int
3630 evhttp_parse_query(const char *uri, struct evkeyvalq *headers)
3631 {
3632         return evhttp_parse_query_impl(uri, headers, 1, 0);
3633 }
3634 int
3635 evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers)
3636 {
3637         return evhttp_parse_query_impl(uri, headers, 0, 0);
3638 }
3639 int
3640 evhttp_parse_query_str_flags(const char *uri, struct evkeyvalq *headers, unsigned flags)
3641 {
3642         return evhttp_parse_query_impl(uri, headers, 0, flags);
3643 }
3644
3645 static struct evhttp_cb *
3646 evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req)
3647 {
3648         struct evhttp_cb *cb;
3649         size_t offset = 0;
3650         char *translated;
3651         const char *path;
3652
3653         /* Test for different URLs */
3654         path = evhttp_uri_get_path(req->uri_elems);
3655         offset = strlen(path);
3656         if ((translated = mm_malloc(offset + 1)) == NULL)
3657                 return (NULL);
3658         evhttp_decode_uri_internal(path, offset, translated,
3659             0 /* decode_plus */);
3660
3661         TAILQ_FOREACH(cb, callbacks, next) {
3662                 if (!strcmp(cb->what, translated)) {
3663                         mm_free(translated);
3664                         return (cb);
3665                 }
3666         }
3667
3668         mm_free(translated);
3669         return (NULL);
3670 }
3671
3672
3673 static int
3674 prefix_suffix_match(const char *pattern, const char *name, int ignorecase)
3675 {
3676         char c;
3677
3678         while (1) {
3679                 switch (c = *pattern++) {
3680                 case '\0':
3681                         return *name == '\0';
3682
3683                 case '*':
3684                         while (*name != '\0') {
3685                                 if (prefix_suffix_match(pattern, name,
3686                                         ignorecase))
3687                                         return (1);
3688                                 ++name;
3689                         }
3690                         return (0);
3691                 default:
3692                         if (c != *name) {
3693                                 if (!ignorecase ||
3694                                     EVUTIL_TOLOWER_(c) != EVUTIL_TOLOWER_(*name))
3695                                         return (0);
3696                         }
3697                         ++name;
3698                 }
3699         }
3700         /* NOTREACHED */
3701 }
3702
3703 /*
3704    Search the vhost hierarchy beginning with http for a server alias
3705    matching hostname.  If a match is found, and outhttp is non-null,
3706    outhttp is set to the matching http object and 1 is returned.
3707 */
3708
3709 static int
3710 evhttp_find_alias(struct evhttp *http, struct evhttp **outhttp,
3711                   const char *hostname)
3712 {
3713         struct evhttp_server_alias *alias;
3714         struct evhttp *vhost;
3715
3716         TAILQ_FOREACH(alias, &http->aliases, next) {
3717                 /* XXX Do we need to handle IP addresses? */
3718                 if (!evutil_ascii_strcasecmp(alias->alias, hostname)) {
3719                         if (outhttp)
3720                                 *outhttp = http;
3721                         return 1;
3722                 }
3723         }
3724
3725         /* XXX It might be good to avoid recursion here, but I don't
3726            see a way to do that w/o a list. */
3727         TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
3728                 if (evhttp_find_alias(vhost, outhttp, hostname))
3729                         return 1;
3730         }
3731
3732         return 0;
3733 }
3734
3735 /*
3736    Attempts to find the best http object to handle a request for a hostname.
3737    All aliases for the root http object and vhosts are searched for an exact
3738    match. Then, the vhost hierarchy is traversed again for a matching
3739    pattern.
3740
3741    If an alias or vhost is matched, 1 is returned, and outhttp, if non-null,
3742    is set with the best matching http object. If there are no matches, the
3743    root http object is stored in outhttp and 0 is returned.
3744 */
3745
3746 static int
3747 evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
3748                   const char *hostname)
3749 {
3750         struct evhttp *vhost;
3751         struct evhttp *oldhttp;
3752         int match_found = 0;
3753
3754         if (evhttp_find_alias(http, outhttp, hostname))
3755                 return 1;
3756
3757         do {
3758                 oldhttp = http;
3759                 TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
3760                         if (prefix_suffix_match(vhost->vhost_pattern,
3761                                 hostname, 1 /* ignorecase */)) {
3762                                 http = vhost;
3763                                 match_found = 1;
3764                                 break;
3765                         }
3766                 }
3767         } while (oldhttp != http);
3768
3769         if (outhttp)
3770                 *outhttp = http;
3771
3772         return match_found;
3773 }
3774
3775 static void
3776 evhttp_handle_request(struct evhttp_request *req, void *arg)
3777 {
3778         struct evhttp *http = arg;
3779         struct evhttp_cb *cb = NULL;
3780         const char *hostname;
3781
3782         /* we have a new request on which the user needs to take action */
3783         req->userdone = 0;
3784
3785         bufferevent_disable(req->evcon->bufev, EV_READ);
3786
3787         if (req->uri == NULL) {
3788                 evhttp_send_error(req, req->response_code, NULL);
3789                 return;
3790         }
3791
3792         if ((http->allowed_methods & req->type) == 0) {
3793                 event_debug(("Rejecting disallowed method %x (allowed: %x)\n",
3794                         (unsigned)req->type, (unsigned)http->allowed_methods));
3795                 evhttp_send_error(req, HTTP_NOTIMPLEMENTED, NULL);
3796                 return;
3797         }
3798
3799         /* handle potential virtual hosts */
3800         hostname = evhttp_request_get_host(req);
3801         if (hostname != NULL) {
3802                 evhttp_find_vhost(http, &http, hostname);
3803         }
3804
3805         if ((cb = evhttp_dispatch_callback(&http->callbacks, req)) != NULL) {
3806                 (*cb->cb)(req, cb->cbarg);
3807                 return;
3808         }
3809
3810         /* Generic call back */
3811         if (http->gencb) {
3812                 (*http->gencb)(req, http->gencbarg);
3813                 return;
3814         } else
3815                 evhttp_send_notfound(req, NULL);
3816 }
3817
3818 /* Listener callback when a connection arrives at a server. */
3819 static void
3820 accept_socket_cb(struct evconnlistener *listener, evutil_socket_t nfd, struct sockaddr *peer_sa, int peer_socklen, void *arg)
3821 {
3822         struct evhttp_bound_socket *bound = arg;
3823
3824         struct evhttp *http = bound->http;
3825
3826         struct bufferevent *bev = NULL;
3827         if (bound->bevcb)
3828                 bev = bound->bevcb(http->base, bound->bevcbarg);
3829
3830         evhttp_get_request(http, nfd, peer_sa, peer_socklen, bev);
3831 }
3832
3833 int
3834 evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port)
3835 {
3836         struct evhttp_bound_socket *bound =
3837                 evhttp_bind_socket_with_handle(http, address, port);
3838         if (bound == NULL)
3839                 return (-1);
3840         return (0);
3841 }
3842
3843 struct evhttp_bound_socket *
3844 evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port)
3845 {
3846         evutil_socket_t fd;
3847         struct evhttp_bound_socket *bound;
3848         int serrno;
3849
3850         if ((fd = bind_socket(address, port, 1 /*reuse*/)) == -1)
3851                 return (NULL);
3852
3853         if (listen(fd, 128) == -1) {
3854                 serrno = EVUTIL_SOCKET_ERROR();
3855                 event_sock_warn(fd, "%s: listen", __func__);
3856                 evutil_closesocket(fd);
3857                 EVUTIL_SET_SOCKET_ERROR(serrno);
3858                 return (NULL);
3859         }
3860
3861         bound = evhttp_accept_socket_with_handle(http, fd);
3862
3863         if (bound != NULL) {
3864                 event_debug(("Bound to port %d - Awaiting connections ... ",
3865                         port));
3866                 return (bound);
3867         }
3868
3869         return (NULL);
3870 }
3871
3872 int
3873 evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd)
3874 {
3875         struct evhttp_bound_socket *bound =
3876                 evhttp_accept_socket_with_handle(http, fd);
3877         if (bound == NULL)
3878                 return (-1);
3879         return (0);
3880 }
3881
3882 void
3883 evhttp_foreach_bound_socket(struct evhttp *http,
3884                             evhttp_bound_socket_foreach_fn *function,
3885                             void *argument)
3886 {
3887         struct evhttp_bound_socket *bound;
3888
3889         TAILQ_FOREACH(bound, &http->sockets, next)
3890                 function(bound, argument);
3891 }
3892
3893 struct evhttp_bound_socket *
3894 evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd)
3895 {
3896         struct evhttp_bound_socket *bound;
3897         struct evconnlistener *listener;
3898         const int flags =
3899             LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_CLOSE_ON_FREE;
3900
3901         listener = evconnlistener_new(http->base, NULL, NULL,
3902             flags,
3903             0, /* Backlog is '0' because we already said 'listen' */
3904             fd);
3905         if (!listener)
3906                 return (NULL);
3907
3908         bound = evhttp_bind_listener(http, listener);
3909         if (!bound) {
3910                 evconnlistener_free(listener);
3911                 return (NULL);
3912         }
3913         return (bound);
3914 }
3915
3916 struct evhttp_bound_socket *
3917 evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener)
3918 {
3919         struct evhttp_bound_socket *bound;
3920
3921         bound = mm_malloc(sizeof(struct evhttp_bound_socket));
3922         if (bound == NULL)
3923                 return (NULL);
3924
3925         bound->listener = listener;
3926         bound->bevcb = NULL;
3927         bound->http = http;
3928         TAILQ_INSERT_TAIL(&http->sockets, bound, next);
3929
3930         evconnlistener_set_cb(listener, accept_socket_cb, bound);
3931         return bound;
3932 }
3933
3934 evutil_socket_t
3935 evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound)
3936 {
3937         return evconnlistener_get_fd(bound->listener);
3938 }
3939
3940 struct evconnlistener *
3941 evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound)
3942 {
3943         return bound->listener;
3944 }
3945
3946 void
3947 evhttp_bound_set_bevcb(struct evhttp_bound_socket *bound,
3948     struct bufferevent* (*cb)(struct event_base *, void *), void *cbarg)
3949 {
3950         bound->bevcb = cb;
3951         bound->bevcbarg = cbarg;
3952 }
3953
3954 void
3955 evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound)
3956 {
3957         TAILQ_REMOVE(&http->sockets, bound, next);
3958         evconnlistener_free(bound->listener);
3959         mm_free(bound);
3960 }
3961
3962 static struct evhttp*
3963 evhttp_new_object(void)
3964 {
3965         struct evhttp *http = NULL;
3966
3967         if ((http = mm_calloc(1, sizeof(struct evhttp))) == NULL) {
3968                 event_warn("%s: calloc", __func__);
3969                 return (NULL);
3970         }
3971
3972         evutil_timerclear(&http->timeout_read);
3973         evutil_timerclear(&http->timeout_write);
3974
3975         evhttp_set_max_headers_size(http, EV_SIZE_MAX);
3976         evhttp_set_max_body_size(http, EV_SIZE_MAX);
3977         evhttp_set_default_content_type(http, "text/html; charset=ISO-8859-1");
3978         evhttp_set_allowed_methods(http,
3979             EVHTTP_REQ_GET |
3980             EVHTTP_REQ_POST |
3981             EVHTTP_REQ_HEAD |
3982             EVHTTP_REQ_PUT |
3983             EVHTTP_REQ_DELETE);
3984
3985         TAILQ_INIT(&http->sockets);
3986         TAILQ_INIT(&http->callbacks);
3987         TAILQ_INIT(&http->connections);
3988         TAILQ_INIT(&http->ws_sessions);
3989         TAILQ_INIT(&http->virtualhosts);
3990         TAILQ_INIT(&http->aliases);
3991
3992         return (http);
3993 }
3994
3995 struct evhttp *
3996 evhttp_new(struct event_base *base)
3997 {
3998         struct evhttp *http = NULL;
3999
4000         http = evhttp_new_object();
4001         if (http == NULL)
4002                 return (NULL);
4003         http->base = base;
4004
4005         return (http);
4006 }
4007
4008 /*
4009  * Start a web server on the specified address and port.
4010  */
4011
4012 struct evhttp *
4013 evhttp_start(const char *address, ev_uint16_t port)
4014 {
4015         struct evhttp *http = NULL;
4016
4017         http = evhttp_new_object();
4018         if (http == NULL)
4019                 return (NULL);
4020         if (evhttp_bind_socket(http, address, port) == -1) {
4021                 mm_free(http);
4022                 return (NULL);
4023         }
4024
4025         return (http);
4026 }
4027
4028 void
4029 evhttp_free(struct evhttp* http)
4030 {
4031         struct evhttp_cb *http_cb;
4032         struct evhttp_connection *evcon;
4033         struct evws_connection *evws;
4034         struct evhttp_bound_socket *bound;
4035         struct evhttp* vhost;
4036         struct evhttp_server_alias *alias;
4037
4038         /* Remove the accepting part */
4039         while ((bound = TAILQ_FIRST(&http->sockets)) != NULL) {
4040                 TAILQ_REMOVE(&http->sockets, bound, next);
4041
4042                 evconnlistener_free(bound->listener);
4043
4044                 mm_free(bound);
4045         }
4046
4047         while ((evcon = TAILQ_FIRST(&http->connections)) != NULL) {
4048                 /* evhttp_connection_free removes the connection */
4049                 evhttp_connection_free(evcon);
4050         }
4051
4052         while ((evws = TAILQ_FIRST(&http->ws_sessions)) != NULL) {
4053                 evws_connection_free(evws);
4054         }
4055
4056         while ((http_cb = TAILQ_FIRST(&http->callbacks)) != NULL) {
4057                 TAILQ_REMOVE(&http->callbacks, http_cb, next);
4058                 mm_free(http_cb->what);
4059                 mm_free(http_cb);
4060         }
4061
4062         while ((vhost = TAILQ_FIRST(&http->virtualhosts)) != NULL) {
4063                 TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
4064
4065                 evhttp_free(vhost);
4066         }
4067
4068         if (http->vhost_pattern != NULL)
4069                 mm_free(http->vhost_pattern);
4070
4071         while ((alias = TAILQ_FIRST(&http->aliases)) != NULL) {
4072                 TAILQ_REMOVE(&http->aliases, alias, next);
4073                 mm_free(alias->alias);
4074                 mm_free(alias);
4075         }
4076
4077         mm_free(http);
4078 }
4079
4080 int
4081 evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
4082     struct evhttp* vhost)
4083 {
4084         /* a vhost can only be a vhost once and should not have bound sockets */
4085         if (vhost->vhost_pattern != NULL ||
4086             TAILQ_FIRST(&vhost->sockets) != NULL)
4087                 return (-1);
4088
4089         vhost->vhost_pattern = mm_strdup(pattern);
4090         if (vhost->vhost_pattern == NULL)
4091                 return (-1);
4092
4093         TAILQ_INSERT_TAIL(&http->virtualhosts, vhost, next_vhost);
4094
4095         return (0);
4096 }
4097
4098 int
4099 evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost)
4100 {
4101         if (vhost->vhost_pattern == NULL)
4102                 return (-1);
4103
4104         TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
4105
4106         mm_free(vhost->vhost_pattern);
4107         vhost->vhost_pattern = NULL;
4108
4109         return (0);
4110 }
4111
4112 int
4113 evhttp_add_server_alias(struct evhttp *http, const char *alias)
4114 {
4115         struct evhttp_server_alias *evalias;
4116
4117         evalias = mm_calloc(1, sizeof(*evalias));
4118         if (!evalias)
4119                 return -1;
4120
4121         evalias->alias = mm_strdup(alias);
4122         if (!evalias->alias) {
4123                 mm_free(evalias);
4124                 return -1;
4125         }
4126
4127         TAILQ_INSERT_TAIL(&http->aliases, evalias, next);
4128
4129         return 0;
4130 }
4131
4132 int
4133 evhttp_remove_server_alias(struct evhttp *http, const char *alias)
4134 {
4135         struct evhttp_server_alias *evalias;
4136
4137         TAILQ_FOREACH(evalias, &http->aliases, next) {
4138                 if (evutil_ascii_strcasecmp(evalias->alias, alias) == 0) {
4139                         TAILQ_REMOVE(&http->aliases, evalias, next);
4140                         mm_free(evalias->alias);
4141                         mm_free(evalias);
4142                         return 0;
4143                 }
4144         }
4145
4146         return -1;
4147 }
4148
4149 void
4150 evhttp_set_timeout(struct evhttp* http, int timeout)
4151 {
4152         evhttp_set_timeout_(&http->timeout_read,  timeout, -1);
4153         evhttp_set_timeout_(&http->timeout_write, timeout, -1);
4154 }
4155 void
4156 evhttp_set_timeout_tv(struct evhttp* http, const struct timeval* tv)
4157 {
4158         evhttp_set_timeout_tv_(&http->timeout_read, tv, -1);
4159         evhttp_set_timeout_tv_(&http->timeout_write, tv, -1);
4160 }
4161 void
4162 evhttp_set_read_timeout_tv(struct evhttp* http, const struct timeval* tv)
4163 {
4164         evhttp_set_timeout_tv_(&http->timeout_read, tv, -1);
4165 }
4166 void
4167 evhttp_set_write_timeout_tv(struct evhttp* http, const struct timeval* tv)
4168 {
4169         evhttp_set_timeout_tv_(&http->timeout_write, tv, -1);
4170 }
4171
4172 int evhttp_set_flags(struct evhttp *http, int flags)
4173 {
4174         int avail_flags = 0;
4175         avail_flags |= EVHTTP_SERVER_LINGERING_CLOSE;
4176
4177         if (flags & ~avail_flags)
4178                 return 1;
4179         http->flags &= ~avail_flags;
4180
4181         http->flags |= flags;
4182
4183         return 0;
4184 }
4185
4186 void
4187 evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size)
4188 {
4189         if (max_headers_size < 0)
4190                 http->default_max_headers_size = EV_SIZE_MAX;
4191         else
4192                 http->default_max_headers_size = max_headers_size;
4193 }
4194
4195 void
4196 evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size)
4197 {
4198         if (max_body_size < 0)
4199                 http->default_max_body_size = EV_UINT64_MAX;
4200         else
4201                 http->default_max_body_size = max_body_size;
4202 }
4203
4204 void
4205 evhttp_set_max_connections(struct evhttp* http, int max_connections)
4206 {
4207         if (max_connections < 0)
4208                 http->connection_max = 0;
4209         else
4210                 http->connection_max = max_connections;
4211 }
4212
4213 int
4214 evhttp_get_connection_count(struct evhttp* http)
4215 {
4216         return http->connection_cnt;
4217 }
4218
4219 void
4220 evhttp_set_default_content_type(struct evhttp *http,
4221         const char *content_type) {
4222         http->default_content_type = content_type;
4223 }
4224
4225 void
4226 evhttp_set_allowed_methods(struct evhttp* http, ev_uint32_t methods)
4227 {
4228         http->allowed_methods = methods;
4229 }
4230
4231 void
4232 evhttp_set_ext_method_cmp(struct evhttp *http, evhttp_ext_method_cb cmp)
4233 {
4234         http->ext_method_cmp = cmp;
4235 }
4236
4237 int
4238 evhttp_set_cb(struct evhttp *http, const char *uri,
4239     void (*cb)(struct evhttp_request *, void *), void *cbarg)
4240 {
4241         struct evhttp_cb *http_cb;
4242
4243         TAILQ_FOREACH(http_cb, &http->callbacks, next) {
4244                 if (strcmp(http_cb->what, uri) == 0)
4245                         return (-1);
4246         }
4247
4248         if ((http_cb = mm_calloc(1, sizeof(struct evhttp_cb))) == NULL) {
4249                 event_warn("%s: calloc", __func__);
4250                 return (-2);
4251         }
4252
4253         http_cb->what = mm_strdup(uri);
4254         if (http_cb->what == NULL) {
4255                 event_warn("%s: strdup", __func__);
4256                 mm_free(http_cb);
4257                 return (-3);
4258         }
4259         http_cb->cb = cb;
4260         http_cb->cbarg = cbarg;
4261
4262         TAILQ_INSERT_TAIL(&http->callbacks, http_cb, next);
4263
4264         return (0);
4265 }
4266
4267 int
4268 evhttp_del_cb(struct evhttp *http, const char *uri)
4269 {
4270         struct evhttp_cb *http_cb;
4271
4272         TAILQ_FOREACH(http_cb, &http->callbacks, next) {
4273                 if (strcmp(http_cb->what, uri) == 0)
4274                         break;
4275         }
4276         if (http_cb == NULL)
4277                 return (-1);
4278
4279         TAILQ_REMOVE(&http->callbacks, http_cb, next);
4280         mm_free(http_cb->what);
4281         mm_free(http_cb);
4282
4283         return (0);
4284 }
4285
4286 void
4287 evhttp_set_gencb(struct evhttp *http,
4288     void (*cb)(struct evhttp_request *, void *), void *cbarg)
4289 {
4290         http->gencb = cb;
4291         http->gencbarg = cbarg;
4292 }
4293
4294 void
4295 evhttp_set_bevcb(struct evhttp *http,
4296     struct bufferevent* (*cb)(struct event_base *, void *), void *cbarg)
4297 {
4298         http->bevcb = cb;
4299         http->bevcbarg = cbarg;
4300 }
4301
4302 void
4303 evhttp_set_newreqcb(struct evhttp *http,
4304     int (*cb)(struct evhttp_request *, void *), void *cbarg)
4305 {
4306         http->newreqcb = cb;
4307         http->newreqcbarg = cbarg;
4308 }
4309 void
4310 evhttp_set_errorcb(struct evhttp *http,
4311     int (*cb)(struct evhttp_request *, struct evbuffer *, int, const char *, void *),
4312     void *cbarg)
4313 {
4314         http->errorcb = cb;
4315         http->errorcbarg = cbarg;
4316 }
4317
4318 /*
4319  * Request related functions
4320  */
4321
4322 struct evhttp_request *
4323 evhttp_request_new(void (*cb)(struct evhttp_request *, void *), void *arg)
4324 {
4325         struct evhttp_request *req = NULL;
4326
4327         /* Allocate request structure */
4328         if ((req = mm_calloc(1, sizeof(struct evhttp_request))) == NULL) {
4329                 event_warn("%s: calloc", __func__);
4330                 goto error;
4331         }
4332
4333         req->headers_size = 0;
4334         req->body_size = 0;
4335
4336         req->kind = EVHTTP_RESPONSE;
4337         req->input_headers = mm_calloc(1, sizeof(struct evkeyvalq));
4338         if (req->input_headers == NULL) {
4339                 event_warn("%s: calloc", __func__);
4340                 goto error;
4341         }
4342         TAILQ_INIT(req->input_headers);
4343
4344         req->output_headers = mm_calloc(1, sizeof(struct evkeyvalq));
4345         if (req->output_headers == NULL) {
4346                 event_warn("%s: calloc", __func__);
4347                 goto error;
4348         }
4349         TAILQ_INIT(req->output_headers);
4350
4351         if ((req->input_buffer = evbuffer_new()) == NULL) {
4352                 event_warn("%s: evbuffer_new", __func__);
4353                 goto error;
4354         }
4355
4356         if ((req->output_buffer = evbuffer_new()) == NULL) {
4357                 event_warn("%s: evbuffer_new", __func__);
4358                 goto error;
4359         }
4360
4361         req->cb = cb;
4362         req->cb_arg = arg;
4363
4364         return (req);
4365
4366  error:
4367         if (req != NULL)
4368                 evhttp_request_free(req);
4369         return (NULL);
4370 }
4371
4372 void
4373 evhttp_request_free(struct evhttp_request *req)
4374 {
4375         if ((req->flags & EVHTTP_REQ_DEFER_FREE) != 0) {
4376                 req->flags |= EVHTTP_REQ_NEEDS_FREE;
4377                 return;
4378         }
4379
4380         if (req->remote_host != NULL)
4381                 mm_free(req->remote_host);
4382         if (req->uri != NULL)
4383                 mm_free(req->uri);
4384         if (req->uri_elems != NULL)
4385                 evhttp_uri_free(req->uri_elems);
4386         if (req->response_code_line != NULL)
4387                 mm_free(req->response_code_line);
4388         if (req->host_cache != NULL)
4389                 mm_free(req->host_cache);
4390
4391         evhttp_clear_headers(req->input_headers);
4392         mm_free(req->input_headers);
4393
4394         evhttp_clear_headers(req->output_headers);
4395         mm_free(req->output_headers);
4396
4397         if (req->input_buffer != NULL)
4398                 evbuffer_free(req->input_buffer);
4399
4400         if (req->output_buffer != NULL)
4401                 evbuffer_free(req->output_buffer);
4402
4403         mm_free(req);
4404 }
4405
4406 void
4407 evhttp_request_own(struct evhttp_request *req)
4408 {
4409         req->flags |= EVHTTP_USER_OWNED;
4410 }
4411
4412 int
4413 evhttp_request_is_owned(struct evhttp_request *req)
4414 {
4415         return (req->flags & EVHTTP_USER_OWNED) != 0;
4416 }
4417
4418 struct evhttp_connection *
4419 evhttp_request_get_connection(struct evhttp_request *req)
4420 {
4421         return req->evcon;
4422 }
4423
4424 struct event_base *
4425 evhttp_connection_get_base(struct evhttp_connection *conn)
4426 {
4427         return conn->base;
4428 }
4429
4430 void
4431 evhttp_request_set_chunked_cb(struct evhttp_request *req,
4432     void (*cb)(struct evhttp_request *, void *))
4433 {
4434         req->chunk_cb = cb;
4435 }
4436
4437 void
4438 evhttp_request_set_header_cb(struct evhttp_request *req,
4439     int (*cb)(struct evhttp_request *, void *))
4440 {
4441         req->header_cb = cb;
4442 }
4443
4444 void
4445 evhttp_request_set_error_cb(struct evhttp_request *req,
4446     void (*cb)(enum evhttp_request_error, void *))
4447 {
4448         req->error_cb = cb;
4449 }
4450
4451 void
4452 evhttp_request_set_on_complete_cb(struct evhttp_request *req,
4453     void (*cb)(struct evhttp_request *, void *), void *cb_arg)
4454 {
4455         req->on_complete_cb = cb;
4456         req->on_complete_cb_arg = cb_arg;
4457 }
4458
4459 /*
4460  * Allows for inspection of the request URI
4461  */
4462
4463 const char *
4464 evhttp_request_get_uri(const struct evhttp_request *req) {
4465         if (req->uri == NULL)
4466                 event_debug(("%s: request %p has no uri\n", __func__, (void *)req));
4467         return (req->uri);
4468 }
4469
4470 const struct evhttp_uri *
4471 evhttp_request_get_evhttp_uri(const struct evhttp_request *req) {
4472         if (req->uri_elems == NULL)
4473                 event_debug(("%s: request %p has no uri elems\n",
4474                             __func__, (void *)req));
4475         return (req->uri_elems);
4476 }
4477
4478 const char *
4479 evhttp_request_get_host(struct evhttp_request *req)
4480 {
4481         const char *host = NULL;
4482
4483         if (req->host_cache)
4484                 return req->host_cache;
4485
4486         if (req->uri_elems)
4487                 host = evhttp_uri_get_host(req->uri_elems);
4488         if (!host && req->input_headers) {
4489                 const char *p;
4490                 size_t len;
4491
4492                 host = evhttp_find_header(req->input_headers, "Host");
4493                 /* The Host: header may include a port. Remove it here
4494                    to be consistent with uri_elems case above. */
4495                 if (host) {
4496                         p = host + strlen(host) - 1;
4497                         while (p > host && EVUTIL_ISDIGIT_(*p))
4498                                 --p;
4499                         if (p > host && *p == ':') {
4500                                 len = p - host;
4501                                 req->host_cache = mm_malloc(len + 1);
4502                                 if (!req->host_cache) {
4503                                         event_warn("%s: malloc", __func__);
4504                                         return NULL;
4505                                 }
4506                                 memcpy(req->host_cache, host, len);
4507                                 req->host_cache[len] = '\0';
4508                                 host = req->host_cache;
4509                         }
4510                 }
4511         }
4512
4513         return host;
4514 }
4515
4516 enum evhttp_cmd_type
4517 evhttp_request_get_command(const struct evhttp_request *req) {
4518         return (req->type);
4519 }
4520
4521 int
4522 evhttp_request_get_response_code(const struct evhttp_request *req)
4523 {
4524         return req->response_code;
4525 }
4526
4527 const char *
4528 evhttp_request_get_response_code_line(const struct evhttp_request *req)
4529 {
4530         return req->response_code_line;
4531 }
4532
4533 /** Returns the input headers */
4534 struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req)
4535 {
4536         return (req->input_headers);
4537 }
4538
4539 /** Returns the output headers */
4540 struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req)
4541 {
4542         return (req->output_headers);
4543 }
4544
4545 /** Returns the input buffer */
4546 struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req)
4547 {
4548         return (req->input_buffer);
4549 }
4550
4551 /** Returns the output buffer */
4552 struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req)
4553 {
4554         return (req->output_buffer);
4555 }
4556
4557
4558 /*
4559  * Takes a file descriptor to read a request from.
4560  * The callback is executed once the whole request has been read.
4561  */
4562
4563 static struct evhttp_connection*
4564 evhttp_get_request_connection(
4565         struct evhttp* http,
4566         evutil_socket_t fd, struct sockaddr *sa, ev_socklen_t salen,
4567         struct bufferevent* bev)
4568 {
4569         struct evhttp_connection *evcon;
4570
4571 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
4572         if (sa->sa_family == AF_UNIX) {
4573                 struct sockaddr_un *sa_un = (struct sockaddr_un *)sa;
4574                 sa_un->sun_path[0] = '\0';
4575         }
4576 #endif
4577
4578 #ifndef _WIN32
4579         if (sa->sa_family == AF_UNIX) {
4580                 struct sockaddr_un *sockaddr = (struct sockaddr_un *)sa;
4581
4582                 event_debug(("%s: new request from unix socket on "
4583                         EV_SOCK_FMT"\n", __func__, EV_SOCK_ARG(fd)));
4584
4585                 /* we need a connection object to put the http request on */
4586                 if (!bev && http->bevcb != NULL) {
4587                         bev = (*http->bevcb)(http->base, http->bevcbarg);
4588                 }
4589
4590                 evcon = evhttp_connection_base_bufferevent_unix_new(http->base,
4591                         bev, sockaddr->sun_path);
4592         }
4593         else
4594 #endif
4595         {
4596                 char *hostname = NULL, *portname = NULL;
4597
4598                 name_from_addr(sa, salen, &hostname, &portname);
4599                 if (hostname == NULL || portname == NULL) {
4600                         if (hostname) mm_free(hostname);
4601                         if (portname) mm_free(portname);
4602                         return (NULL);
4603                 }
4604
4605                 event_debug(("%s: new request from %s:%s on "EV_SOCK_FMT"\n",
4606                         __func__, hostname, portname, EV_SOCK_ARG(fd)));
4607
4608                 /* we need a connection object to put the http request on */
4609                 if (!bev && http->bevcb != NULL) {
4610                         bev = (*http->bevcb)(http->base, http->bevcbarg);
4611                 }
4612                 evcon = evhttp_connection_base_bufferevent_new(
4613                         http->base, NULL, bev, hostname, atoi(portname));
4614                 mm_free(hostname);
4615                 mm_free(portname);
4616         }
4617         if (evcon == NULL)
4618                 return (NULL);
4619
4620         evcon->max_headers_size = http->default_max_headers_size;
4621         evcon->max_body_size = http->default_max_body_size;
4622         if (http->flags & EVHTTP_SERVER_LINGERING_CLOSE)
4623                 evcon->flags |= EVHTTP_CON_LINGERING_CLOSE;
4624
4625         evcon->flags |= EVHTTP_CON_INCOMING;
4626         evcon->state = EVCON_READING_FIRSTLINE;
4627
4628         if (bufferevent_replacefd(evcon->bufev, fd))
4629                 goto err;
4630         if (bufferevent_enable(evcon->bufev, EV_READ))
4631                 goto err;
4632         if (bufferevent_disable(evcon->bufev, EV_WRITE))
4633                 goto err;
4634         bufferevent_socket_set_conn_address_(evcon->bufev, sa, salen);
4635
4636         return (evcon);
4637
4638 err:
4639         evhttp_connection_free(evcon);
4640         return (NULL);
4641 }
4642
4643 static int
4644 evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
4645 {
4646         struct evhttp *http = evcon->http_server;
4647         struct evhttp_request *req;
4648         if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL)
4649                 return (-1);
4650
4651         if (evcon->address != NULL) {
4652                 if ((req->remote_host = mm_strdup(evcon->address)) == NULL) {
4653                         event_warn("%s: strdup", __func__);
4654                         evhttp_request_free(req);
4655                         return (-1);
4656                 }
4657         }
4658         req->remote_port = evcon->port;
4659
4660         req->evcon = evcon;     /* the request ends up owning the connection */
4661         req->flags |= EVHTTP_REQ_OWN_CONNECTION;
4662
4663         /* We did not present the request to the user yet, so treat it
4664          * as if the user was done with the request.  This allows us
4665          * to free the request on a persistent connection if the
4666          * client drops it without sending a request.
4667          */
4668         req->userdone = 1;
4669         req->kind = EVHTTP_REQUEST;
4670
4671         if (http->newreqcb && http->newreqcb(req, http->newreqcbarg) == -1) {
4672                 evhttp_request_free(req);
4673                 return (-1);
4674         }
4675
4676         TAILQ_INSERT_TAIL(&evcon->requests, req, next);
4677
4678         evhttp_start_read_(evcon);
4679
4680         return (0);
4681 }
4682
4683 static void
4684 evhttp_get_request(struct evhttp *http, evutil_socket_t fd,
4685     struct sockaddr *sa, ev_socklen_t salen,
4686     struct bufferevent *bev)
4687 {
4688         struct evhttp_connection *evcon;
4689
4690         evcon = evhttp_get_request_connection(http, fd, sa, salen, bev);
4691         if (evcon == NULL) {
4692                 event_sock_warn(fd, "%s: cannot get connection on "EV_SOCK_FMT,
4693                     __func__, EV_SOCK_ARG(fd));
4694                 evutil_closesocket(fd);
4695                 return;
4696         }
4697
4698         /* the timeout can be used by the server to close idle connections */
4699         if (evutil_timerisset(&http->timeout_read))
4700                 evhttp_connection_set_read_timeout_tv(evcon,  &http->timeout_read);
4701         if (evutil_timerisset(&http->timeout_write))
4702                 evhttp_connection_set_write_timeout_tv(evcon, &http->timeout_write);
4703
4704         /*
4705          * if we want to accept more than one request on a connection,
4706          * we need to know which http server it belongs to.
4707          */
4708         evcon->http_server = http;
4709         evcon->ext_method_cmp = http->ext_method_cmp;
4710         TAILQ_INSERT_TAIL(&http->connections, evcon, next);
4711         http->connection_cnt++;
4712
4713         /* send "service unavailable" if we've reached the connection limit */
4714         if (http->connection_max && http->connection_max < http->connection_cnt) {
4715                 struct evhttp_request *req;
4716
4717                 if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL) {
4718                         evhttp_connection_free(evcon);
4719                         return;
4720                 }
4721
4722                 req->evcon = evcon;     /* the request owns the connection */
4723                 req->flags |= EVHTTP_REQ_OWN_CONNECTION;
4724                 req->kind = EVHTTP_REQUEST;
4725                 /* note, req->remote_host not needed since we don't read */
4726
4727                 TAILQ_INSERT_TAIL(&evcon->requests, req, next);
4728
4729                 /* send error to client */
4730                 evcon->state = EVCON_WRITING;
4731                 bufferevent_enable(evcon->bufev, EV_READ); /* enable close events */
4732                 evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
4733
4734         } else if (evhttp_associate_new_request_with_connection(evcon) == -1)
4735                 evhttp_connection_free(evcon);
4736 }
4737
4738
4739 /*
4740  * Network helper functions that we do not want to export to the rest of
4741  * the world.
4742  */
4743
4744 static void
4745 name_from_addr(struct sockaddr *sa, ev_socklen_t salen,
4746     char **phost, char **pport)
4747 {
4748         char ntop[NI_MAXHOST];
4749         char strport[NI_MAXSERV];
4750         int ni_result;
4751
4752 #ifdef EVENT__HAVE_GETNAMEINFO
4753         ni_result = getnameinfo(sa, salen,
4754                 ntop, sizeof(ntop), strport, sizeof(strport),
4755                 NI_NUMERICHOST|NI_NUMERICSERV);
4756
4757         if (ni_result != 0) {
4758 #ifdef EAI_SYSTEM
4759                 /* Windows doesn't have an EAI_SYSTEM. */
4760                 if (ni_result == EAI_SYSTEM)
4761                         event_err(1, "getnameinfo failed");
4762                 else
4763 #endif
4764                         event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
4765                 return;
4766         }
4767 #else
4768         ni_result = fake_getnameinfo(sa, salen,
4769                 ntop, sizeof(ntop), strport, sizeof(strport),
4770                 NI_NUMERICHOST|NI_NUMERICSERV);
4771         if (ni_result != 0)
4772                         return;
4773 #endif
4774
4775         *phost = mm_strdup(ntop);
4776         *pport = mm_strdup(strport);
4777 }
4778
4779 /* Create a non-blocking socket and bind it */
4780 static evutil_socket_t
4781 create_bind_socket_nonblock(struct evutil_addrinfo *ai, int reuse)
4782 {
4783         evutil_socket_t fd;
4784
4785         int on = 1, r;
4786         int serrno;
4787
4788         /* Create listen socket */
4789         fd = evutil_socket_(ai ? ai->ai_family : AF_INET,
4790             SOCK_STREAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
4791         if (fd == -1) {
4792                         event_sock_warn(-1, "socket");
4793                         return (-1);
4794         }
4795
4796         if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on))<0)
4797                 goto out;
4798         if (reuse) {
4799                 if (evutil_make_listen_socket_reuseable(fd) < 0)
4800                         goto out;
4801         }
4802
4803         if (ai != NULL) {
4804                 r = bind(fd, ai->ai_addr, (ev_socklen_t)ai->ai_addrlen);
4805                 if (r == -1)
4806                         goto out;
4807         }
4808
4809         return (fd);
4810
4811  out:
4812         serrno = EVUTIL_SOCKET_ERROR();
4813         evutil_closesocket(fd);
4814         EVUTIL_SET_SOCKET_ERROR(serrno);
4815         return (-1);
4816 }
4817
4818 static struct evutil_addrinfo *
4819 make_addrinfo(const char *address, ev_uint16_t port)
4820 {
4821         struct evutil_addrinfo *ai = NULL;
4822
4823         struct evutil_addrinfo hints;
4824         char strport[NI_MAXSERV];
4825         int ai_result;
4826
4827         memset(&hints, 0, sizeof(hints));
4828         hints.ai_family = AF_UNSPEC;
4829         hints.ai_socktype = SOCK_STREAM;
4830         /* turn NULL hostname into INADDR_ANY, and skip looking up any address
4831          * types we don't have an interface to connect to. */
4832         hints.ai_flags = EVUTIL_AI_PASSIVE|EVUTIL_AI_ADDRCONFIG;
4833         evutil_snprintf(strport, sizeof(strport), "%d", port);
4834         if ((ai_result = evutil_getaddrinfo(address, strport, &hints, &ai))
4835             != 0) {
4836                 if (ai_result == EVUTIL_EAI_SYSTEM)
4837                         event_warn("getaddrinfo");
4838                 else
4839                         event_warnx("getaddrinfo: %s",
4840                             evutil_gai_strerror(ai_result));
4841                 return (NULL);
4842         }
4843
4844         return (ai);
4845 }
4846
4847 static evutil_socket_t
4848 bind_socket(const char *address, ev_uint16_t port, int reuse)
4849 {
4850         evutil_socket_t fd;
4851         struct evutil_addrinfo *aitop = NULL;
4852
4853         /* just create an unbound socket */
4854         if (address == NULL && port == 0)
4855                 return create_bind_socket_nonblock(NULL, 0);
4856
4857         aitop = make_addrinfo(address, port);
4858
4859         if (aitop == NULL)
4860                 return (-1);
4861
4862         fd = create_bind_socket_nonblock(aitop, reuse);
4863
4864         evutil_freeaddrinfo(aitop);
4865
4866         return (fd);
4867 }
4868
4869 struct evhttp_uri {
4870         unsigned flags;
4871         char *scheme; /* scheme; e.g http, ftp etc */
4872         char *userinfo; /* userinfo (typically username:pass), or NULL */
4873         char *host; /* hostname, IP address, or NULL */
4874         int port; /* port, or zero */
4875 #ifndef _WIN32
4876         char *unixsocket; /* unix domain socket or NULL */
4877 #endif
4878         char *path; /* path, or "". */
4879         char *query; /* query, or NULL */
4880         char *fragment; /* fragment or NULL */
4881 };
4882
4883 struct evhttp_uri *
4884 evhttp_uri_new(void)
4885 {
4886         struct evhttp_uri *uri = mm_calloc(sizeof(struct evhttp_uri), 1);
4887         if (uri)
4888                 uri->port = -1;
4889         return uri;
4890 }
4891
4892 void
4893 evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags)
4894 {
4895         uri->flags = flags;
4896 }
4897
4898 /* Return true if the string starting at s and ending immediately before eos
4899  * is a valid URI scheme according to RFC3986
4900  */
4901 static int
4902 scheme_ok(const char *s, const char *eos)
4903 {
4904         /* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
4905         EVUTIL_ASSERT(eos >= s);
4906         if (s == eos)
4907                 return 0;
4908         if (!EVUTIL_ISALPHA_(*s))
4909                 return 0;
4910         while (++s < eos) {
4911                 if (! EVUTIL_ISALNUM_(*s) &&
4912                     *s != '+' && *s != '-' && *s != '.')
4913                         return 0;
4914         }
4915         return 1;
4916 }
4917
4918 #define SUBDELIMS "!$&'()*+,;="
4919
4920 /* Return true iff [s..eos) is a valid userinfo */
4921 static int
4922 userinfo_ok(const char *s, const char *eos)
4923 {
4924         while (s < eos) {
4925                 if (CHAR_IS_UNRESERVED(*s) ||
4926                     strchr(SUBDELIMS, *s) ||
4927                     *s == ':')
4928                         ++s;
4929                 else if (*s == '%' && s+2 < eos &&
4930                     EVUTIL_ISXDIGIT_(s[1]) &&
4931                     EVUTIL_ISXDIGIT_(s[2]))
4932                         s += 3;
4933                 else
4934                         return 0;
4935         }
4936         return 1;
4937 }
4938
4939 static int
4940 regname_ok(const char *s, const char *eos)
4941 {
4942         while (s && s<eos) {
4943                 if (CHAR_IS_UNRESERVED(*s) ||
4944                     strchr(SUBDELIMS, *s))
4945                         ++s;
4946                 else if (*s == '%' &&
4947                     EVUTIL_ISXDIGIT_(s[1]) &&
4948                     EVUTIL_ISXDIGIT_(s[2]))
4949                         s += 3;
4950                 else
4951                         return 0;
4952         }
4953         return 1;
4954 }
4955
4956 static int
4957 parse_port(const char *s, const char *eos)
4958 {
4959         int portnum = 0;
4960         while (s < eos) {
4961                 if (! EVUTIL_ISDIGIT_(*s))
4962                         return -1;
4963                 portnum = (portnum * 10) + (*s - '0');
4964                 if (portnum < 0)
4965                         return -1;
4966                 if (portnum > 65535)
4967                         return -1;
4968                 ++s;
4969         }
4970         return portnum;
4971 }
4972
4973 /* returns 0 for bad, 1 for ipv6, 2 for IPvFuture */
4974 static int
4975 bracket_addr_ok(const char *s, const char *eos)
4976 {
4977         if (s + 3 > eos || *s != '[' || *(eos-1) != ']')
4978                 return 0;
4979         if (s[1] == 'v') {
4980                 /* IPvFuture, or junk.
4981                    "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
4982                  */
4983                 s += 2; /* skip [v */
4984                 --eos;
4985                 if (!EVUTIL_ISXDIGIT_(*s)) /*require at least one*/
4986                         return 0;
4987                 while (s < eos && *s != '.') {
4988                         if (EVUTIL_ISXDIGIT_(*s))
4989                                 ++s;
4990                         else
4991                                 return 0;
4992                 }
4993                 if (*s != '.')
4994                         return 0;
4995                 ++s;
4996                 while (s < eos) {
4997                         if (CHAR_IS_UNRESERVED(*s) ||
4998                             strchr(SUBDELIMS, *s) ||
4999                             *s == ':')
5000                                 ++s;
5001                         else
5002                                 return 0;
5003                 }
5004                 return 2;
5005         } else {
5006                 /* IPv6, or junk */
5007                 char buf[64];
5008                 ev_ssize_t n_chars = eos-s-2;
5009                 struct in6_addr in6;
5010                 if (n_chars >= 64) /* way too long */
5011                         return 0;
5012                 memcpy(buf, s+1, n_chars);
5013                 buf[n_chars]='\0';
5014                 return (evutil_inet_pton(AF_INET6,buf,&in6)==1) ? 1 : 0;
5015         }
5016 }
5017
5018 static int
5019 parse_authority(struct evhttp_uri *uri, char *s, char *eos, unsigned *flags)
5020 {
5021         size_t len;
5022         char *cp, *port;
5023
5024         EVUTIL_ASSERT(eos);
5025         if (eos == s) {
5026                 uri->host = mm_strdup("");
5027                 if (uri->host == NULL) {
5028                         event_warn("%s: strdup", __func__);
5029                         return -1;
5030                 }
5031                 return 0;
5032         }
5033
5034         /* Optionally, we start with "userinfo@" */
5035
5036         cp = strchr(s, '@');
5037         if (cp && cp < eos) {
5038                 if (! userinfo_ok(s,cp))
5039                         return -1;
5040                 *cp++ = '\0';
5041                 uri->userinfo = mm_strdup(s);
5042                 if (uri->userinfo == NULL) {
5043                         event_warn("%s: strdup", __func__);
5044                         return -1;
5045                 }
5046         } else {
5047                 cp = s;
5048         }
5049
5050 #ifndef _WIN32
5051         if (*flags & EVHTTP_URI_UNIX_SOCKET && !strncmp(cp, "unix:", 5)) {
5052                 char *e = strchr(cp + 5, ':');
5053                 if (e) {
5054                         *e = '\0';
5055                         uri->unixsocket = mm_strdup(cp + 5);
5056                         return 0;
5057                 } else {
5058                         return -1;
5059                 }
5060         }
5061 #endif
5062
5063         /* Optionally, we end with ":port" */
5064         for (port=eos-1; port >= cp && EVUTIL_ISDIGIT_(*port); --port)
5065                 ;
5066         if (port >= cp && *port == ':') {
5067                 if (port+1 == eos) /* Leave port unspecified; the RFC allows a
5068                                     * nil port */
5069                         uri->port = -1;
5070                 else if ((uri->port = parse_port(port+1, eos))<0)
5071                         return -1;
5072                 eos = port;
5073         }
5074         /* Now, cp..eos holds the "host" port, which can be an IPv4Address,
5075          * an IP-Literal, or a reg-name */
5076         EVUTIL_ASSERT(eos >= cp);
5077         len = eos-cp;
5078         if (*cp == '[' && eos >= cp+2 && *(eos-1) == ']') {
5079                 /* IPv6address, IP-Literal, or junk. */
5080                 if (! bracket_addr_ok(cp, eos))
5081                         return -1;
5082                 if (*flags & EVHTTP_URI_HOST_STRIP_BRACKETS)
5083                         len = eos-cp-2;
5084         } else {
5085                 /* Make sure the host part is ok. */
5086                 if (! regname_ok(cp,eos)) /* Match IPv4Address or reg-name */
5087                         return -1;
5088         }
5089
5090         uri->host = mm_malloc(len+1);
5091         if (uri->host == NULL) {
5092                 event_warn("%s: malloc", __func__);
5093                 return -1;
5094         }
5095         if (*cp == '[' && *flags & EVHTTP_URI_HOST_STRIP_BRACKETS) {
5096                 memcpy(uri->host, cp+1, len);
5097                 *flags |= _EVHTTP_URI_HOST_HAS_BRACKETS;
5098         } else {
5099                 memcpy(uri->host, cp, len);
5100         }
5101         uri->host[len] = '\0';
5102         return 0;
5103
5104 }
5105
5106 static char *
5107 end_of_authority(char *cp)
5108 {
5109         while (*cp) {
5110                 if (*cp == '?' || *cp == '#' || *cp == '/')
5111                         return cp;
5112                 ++cp;
5113         }
5114         return cp;
5115 }
5116
5117 enum uri_part {
5118         PART_PATH,
5119         PART_QUERY,
5120         PART_FRAGMENT
5121 };
5122
5123 /* Return the character after the longest prefix of 'cp' that matches...
5124  *   *pchar / "/" if allow_qchars is false, or
5125  *   *(pchar / "/" / "?") if allow_qchars is true.
5126  */
5127 static char *
5128 end_of_path(char *cp, enum uri_part part, unsigned flags)
5129 {
5130         if (flags & EVHTTP_URI_NONCONFORMANT) {
5131                 /* If NONCONFORMANT:
5132                  *   Path is everything up to a # or ? or nul.
5133                  *   Query is everything up a # or nul
5134                  *   Fragment is everything up to a nul.
5135                  */
5136                 switch (part) {
5137                 case PART_PATH:
5138                         while (*cp && *cp != '#' && *cp != '?')
5139                                 ++cp;
5140                         break;
5141                 case PART_QUERY:
5142                         while (*cp && *cp != '#')
5143                                 ++cp;
5144                         break;
5145                 case PART_FRAGMENT:
5146                         cp += strlen(cp);
5147                         break;
5148                 };
5149                 return cp;
5150         }
5151
5152         while (*cp) {
5153                 if (CHAR_IS_UNRESERVED(*cp) ||
5154                     strchr(SUBDELIMS, *cp) ||
5155                     *cp == ':' || *cp == '@' || *cp == '/')
5156                         ++cp;
5157                 else if (*cp == '%' && EVUTIL_ISXDIGIT_(cp[1]) &&
5158                     EVUTIL_ISXDIGIT_(cp[2]))
5159                         cp += 3;
5160                 else if (*cp == '?' && part != PART_PATH)
5161                         ++cp;
5162                 else
5163                         return cp;
5164         }
5165         return cp;
5166 }
5167
5168 static int
5169 path_matches_noscheme(const char *cp)
5170 {
5171         while (*cp) {
5172                 if (*cp == ':')
5173                         return 0;
5174                 else if (*cp == '/')
5175                         return 1;
5176                 ++cp;
5177         }
5178         return 1;
5179 }
5180
5181 struct evhttp_uri *
5182 evhttp_uri_parse(const char *source_uri)
5183 {
5184         return evhttp_uri_parse_with_flags(source_uri, 0);
5185 }
5186
5187 struct evhttp_uri *
5188 evhttp_uri_parse_with_flags(const char *source_uri, unsigned flags)
5189 {
5190         char *readbuf = NULL, *readp = NULL, *token = NULL, *query = NULL;
5191         char *path = NULL, *fragment = NULL;
5192         int got_authority = 0;
5193
5194         struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
5195         if (uri == NULL) {
5196                 event_warn("%s: calloc", __func__);
5197                 goto err;
5198         }
5199         uri->port = -1;
5200         uri->flags = flags;
5201
5202         readbuf = mm_strdup(source_uri);
5203         if (readbuf == NULL) {
5204                 event_warn("%s: strdup", __func__);
5205                 goto err;
5206         }
5207
5208         readp = readbuf;
5209         token = NULL;
5210
5211         /* We try to follow RFC3986 here as much as we can, and match
5212            the productions
5213
5214               URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
5215
5216               relative-ref  = relative-part [ "?" query ] [ "#" fragment ]
5217          */
5218
5219         /* 1. scheme: */
5220         token = strchr(readp, ':');
5221         if (token && scheme_ok(readp,token)) {
5222                 *token = '\0';
5223                 uri->scheme = mm_strdup(readp);
5224                 if (uri->scheme == NULL) {
5225                         event_warn("%s: strdup", __func__);
5226                         goto err;
5227                 }
5228                 readp = token+1; /* eat : */
5229         }
5230
5231         /* 2. Optionally, "//" then an 'authority' part. */
5232         if (readp[0]=='/' && readp[1] == '/') {
5233                 char *authority;
5234                 readp += 2;
5235                 authority = readp;
5236                 path = end_of_authority(readp);
5237                 if (parse_authority(uri, authority, path, &uri->flags) < 0)
5238                         goto err;
5239                 readp = path;
5240                 got_authority = 1;
5241         }
5242
5243         /* 3. Query: path-abempty, path-absolute, path-rootless, or path-empty
5244          */
5245         path = readp;
5246         readp = end_of_path(path, PART_PATH, flags);
5247
5248         /* Query */
5249         if (*readp == '?') {
5250                 *readp = '\0';
5251                 ++readp;
5252                 query = readp;
5253                 readp = end_of_path(readp, PART_QUERY, flags);
5254         }
5255         /* fragment */
5256         if (*readp == '#') {
5257                 *readp = '\0';
5258                 ++readp;
5259                 fragment = readp;
5260                 readp = end_of_path(readp, PART_FRAGMENT, flags);
5261         }
5262         if (*readp != '\0') {
5263                 goto err;
5264         }
5265
5266         /* These next two cases may be unreachable; I'm leaving them
5267          * in to be defensive. */
5268         /* If you didn't get an authority, the path can't begin with "//" */
5269         if (!got_authority && path[0]=='/' && path[1]=='/')
5270                 goto err;
5271         /* If you did get an authority, the path must begin with "/" or be
5272          * empty. */
5273         if (got_authority && path[0] != '/' && path[0] != '\0')
5274                 goto err;
5275         /* (End of maybe-unreachable cases) */
5276
5277         /* If there was no scheme, the first part of the path (if any) must
5278          * have no colon in it. */
5279         if (! uri->scheme && !path_matches_noscheme(path))
5280                 goto err;
5281
5282         EVUTIL_ASSERT(path);
5283         uri->path = mm_strdup(path);
5284         if (uri->path == NULL) {
5285                 event_warn("%s: strdup", __func__);
5286                 goto err;
5287         }
5288
5289         if (query) {
5290                 uri->query = mm_strdup(query);
5291                 if (uri->query == NULL) {
5292                         event_warn("%s: strdup", __func__);
5293                         goto err;
5294                 }
5295         }
5296         if (fragment) {
5297                 uri->fragment = mm_strdup(fragment);
5298                 if (uri->fragment == NULL) {
5299                         event_warn("%s: strdup", __func__);
5300                         goto err;
5301                 }
5302         }
5303
5304         mm_free(readbuf);
5305
5306         return uri;
5307 err:
5308         if (uri)
5309                 evhttp_uri_free(uri);
5310         if (readbuf)
5311                 mm_free(readbuf);
5312         return NULL;
5313 }
5314
5315 static struct evhttp_uri *
5316 evhttp_uri_parse_authority(char *source_uri, unsigned flags)
5317 {
5318         struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
5319         char *end;
5320
5321         if (uri == NULL) {
5322                 event_warn("%s: calloc", __func__);
5323                 goto err;
5324         }
5325         uri->port = -1;
5326         uri->flags = flags;
5327
5328         end = end_of_authority(source_uri);
5329         if (parse_authority(uri, source_uri, end, &uri->flags) < 0)
5330                 goto err;
5331
5332         uri->path = mm_strdup("");
5333         if (uri->path == NULL) {
5334                 event_warn("%s: strdup", __func__);
5335                 goto err;
5336         }
5337
5338         return uri;
5339 err:
5340         if (uri)
5341                 evhttp_uri_free(uri);
5342         return NULL;
5343 }
5344
5345 void
5346 evhttp_uri_free(struct evhttp_uri *uri)
5347 {
5348 #define URI_FREE_STR_(f)                \
5349         if (uri->f) {                   \
5350                 mm_free(uri->f);                \
5351         }
5352
5353         URI_FREE_STR_(scheme);
5354         URI_FREE_STR_(userinfo);
5355         URI_FREE_STR_(host);
5356 #ifndef _WIN32
5357         URI_FREE_STR_(unixsocket);
5358 #endif
5359         URI_FREE_STR_(path);
5360         URI_FREE_STR_(query);
5361         URI_FREE_STR_(fragment);
5362
5363         mm_free(uri);
5364 #undef URI_FREE_STR_
5365 }
5366
5367 char *
5368 evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
5369 {
5370         struct evbuffer *tmp = 0;
5371         size_t joined_size = 0;
5372         char *output = NULL;
5373
5374 #define URI_ADD_(f)     evbuffer_add(tmp, uri->f, strlen(uri->f))
5375
5376         if (!uri || !buf || !limit)
5377                 return NULL;
5378
5379         tmp = evbuffer_new();
5380         if (!tmp)
5381                 return NULL;
5382
5383         if (uri->scheme) {
5384                 URI_ADD_(scheme);
5385                 evbuffer_add(tmp, ":", 1);
5386         }
5387 #ifndef _WIN32
5388         if (uri->unixsocket) {
5389                 evbuffer_add(tmp, "//", 2);
5390                 if (uri->userinfo)
5391                         evbuffer_add_printf(tmp, "%s@", uri->userinfo);
5392                 evbuffer_add_printf(tmp, "unix:%s:", uri->unixsocket);
5393         }
5394         else
5395 #endif
5396         if (uri->host) {
5397                 evbuffer_add(tmp, "//", 2);
5398                 if (uri->userinfo)
5399                         evbuffer_add_printf(tmp,"%s@", uri->userinfo);
5400                 if (uri->flags & _EVHTTP_URI_HOST_HAS_BRACKETS) {
5401                         evbuffer_add(tmp, "[", 1);
5402                         URI_ADD_(host);
5403                         evbuffer_add(tmp, "]", 1);
5404                 } else {
5405                         URI_ADD_(host);
5406                 }
5407                 if (uri->port >= 0)
5408                         evbuffer_add_printf(tmp,":%d", uri->port);
5409
5410                 if (uri->path && uri->path[0] != '/' && uri->path[0] != '\0')
5411                         goto err;
5412         }
5413
5414         if (uri->path)
5415                 URI_ADD_(path);
5416
5417         if (uri->query) {
5418                 evbuffer_add(tmp, "?", 1);
5419                 URI_ADD_(query);
5420         }
5421
5422         if (uri->fragment) {
5423                 evbuffer_add(tmp, "#", 1);
5424                 URI_ADD_(fragment);
5425         }
5426
5427         evbuffer_add(tmp, "\0", 1); /* NUL */
5428
5429         joined_size = evbuffer_get_length(tmp);
5430
5431         if (joined_size > limit) {
5432                 /* It doesn't fit. */
5433                 evbuffer_free(tmp);
5434                 return NULL;
5435         }
5436         evbuffer_remove(tmp, buf, joined_size);
5437
5438         output = buf;
5439 err:
5440         evbuffer_free(tmp);
5441
5442         return output;
5443 #undef URI_ADD_
5444 }
5445
5446 const char *
5447 evhttp_uri_get_scheme(const struct evhttp_uri *uri)
5448 {
5449         return uri->scheme;
5450 }
5451 const char *
5452 evhttp_uri_get_userinfo(const struct evhttp_uri *uri)
5453 {
5454         return uri->userinfo;
5455 }
5456 const char *
5457 evhttp_uri_get_host(const struct evhttp_uri *uri)
5458 {
5459         return uri->host;
5460 }
5461 #ifndef _WIN32
5462 const char *
5463 evhttp_uri_get_unixsocket(const struct evhttp_uri *uri)
5464 {
5465         return uri->unixsocket;
5466 }
5467 #endif
5468 int
5469 evhttp_uri_get_port(const struct evhttp_uri *uri)
5470 {
5471         return uri->port;
5472 }
5473 const char *
5474 evhttp_uri_get_path(const struct evhttp_uri *uri)
5475 {
5476         return uri->path;
5477 }
5478 const char *
5479 evhttp_uri_get_query(const struct evhttp_uri *uri)
5480 {
5481         return uri->query;
5482 }
5483 const char *
5484 evhttp_uri_get_fragment(const struct evhttp_uri *uri)
5485 {
5486         return uri->fragment;
5487 }
5488
5489 #define URI_SET_STR_(f) do {                                    \
5490         if (uri->f)                                             \
5491                 mm_free(uri->f);                                \
5492         if (f) {                                                \
5493                 if ((uri->f = mm_strdup(f)) == NULL) {          \
5494                         event_warn("%s: strdup()", __func__);   \
5495                         return -1;                              \
5496                 }                                               \
5497         } else {                                                \
5498                 uri->f = NULL;                                  \
5499         }                                                       \
5500         } while(0)
5501
5502 int
5503 evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme)
5504 {
5505         if (scheme && !scheme_ok(scheme, scheme+strlen(scheme)))
5506                 return -1;
5507
5508         URI_SET_STR_(scheme);
5509         return 0;
5510 }
5511 int
5512 evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo)
5513 {
5514         if (userinfo && !userinfo_ok(userinfo, userinfo+strlen(userinfo)))
5515                 return -1;
5516         URI_SET_STR_(userinfo);
5517         return 0;
5518 }
5519 int
5520 evhttp_uri_set_host(struct evhttp_uri *uri, const char *host)
5521 {
5522         size_t len = 0;
5523
5524         if (host) {
5525                 len = strlen(host);
5526
5527                 if (host[0] == '[') {
5528                         if (! bracket_addr_ok(host, host+len))
5529                                 return -1;
5530                 } else {
5531                         if (! regname_ok(host, host+len))
5532                                 return -1;
5533                 }
5534         }
5535
5536         if (host && host[0] == '[' && uri->flags & EVHTTP_URI_HOST_STRIP_BRACKETS) {
5537                 char *new_host;
5538
5539                 len -= 2;
5540                 new_host = mm_realloc(uri->host, len+1);
5541                 if (!new_host) {
5542                         free(uri->host);
5543                         uri->host = NULL;
5544                 } else {
5545                         memcpy(new_host, host+1, len);
5546                         new_host[len] = '\0';
5547                         uri->host = new_host;
5548                 }
5549                 uri->flags |= _EVHTTP_URI_HOST_HAS_BRACKETS;
5550         } else {
5551                 URI_SET_STR_(host);
5552                 uri->flags &= ~_EVHTTP_URI_HOST_HAS_BRACKETS;
5553         }
5554
5555         return 0;
5556 }
5557 #ifndef _WIN32
5558 int
5559 evhttp_uri_set_unixsocket(struct evhttp_uri *uri, const char *unixsocket)
5560 {
5561         URI_SET_STR_(unixsocket);
5562         return 0;
5563 }
5564 #endif
5565 int
5566 evhttp_uri_set_port(struct evhttp_uri *uri, int port)
5567 {
5568         if (port < -1)
5569                 return -1;
5570         uri->port = port;
5571         return 0;
5572 }
5573 #define end_of_cpath(cp,p,f) \
5574         ((const char*)(end_of_path(((char*)(cp)), (p), (f))))
5575
5576 int
5577 evhttp_uri_set_path(struct evhttp_uri *uri, const char *path)
5578 {
5579         if (path && end_of_cpath(path, PART_PATH, uri->flags) != path+strlen(path))
5580                 return -1;
5581
5582         URI_SET_STR_(path);
5583         return 0;
5584 }
5585 int
5586 evhttp_uri_set_query(struct evhttp_uri *uri, const char *query)
5587 {
5588         if (query && end_of_cpath(query, PART_QUERY, uri->flags) != query+strlen(query))
5589                 return -1;
5590         URI_SET_STR_(query);
5591         return 0;
5592 }
5593 int
5594 evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment)
5595 {
5596         if (fragment && end_of_cpath(fragment, PART_FRAGMENT, uri->flags) != fragment+strlen(fragment))
5597                 return -1;
5598         URI_SET_STR_(fragment);
5599         return 0;
5600 }