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