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