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