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