MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
http.c
1 /*
2  * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  * derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31 
32 #ifdef HAVE_SYS_PARAM_H
33 #include <sys/param.h>
34 #endif
35 #ifdef HAVE_SYS_TYPES_H
36 #include <sys/types.h>
37 #endif
38 
39 #ifdef HAVE_SYS_TIME_H
40 #include <sys/time.h>
41 #endif
42 #ifdef HAVE_SYS_IOCCOM_H
43 #include <sys/ioccom.h>
44 #endif
45 
46 #ifndef WIN32
47 #include <sys/resource.h>
48 #include <sys/socket.h>
49 #include <sys/stat.h>
50 #include <sys/wait.h>
51 #endif
52 
53 #include <sys/queue.h>
54 
55 #ifndef HAVE_TAILQFOREACH
56 #include <event-internal.h>
57 #endif
58 
59 #ifndef WIN32
60 #include <netinet/in.h>
61 #include <netdb.h>
62 #endif
63 
64 #ifdef WIN32
65 #include <winsock2.h>
66 #endif
67 
68 #include <assert.h>
69 #include <ctype.h>
70 #include <errno.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #ifndef WIN32
75 #include <syslog.h>
76 #endif
77 #include <signal.h>
78 #include <time.h>
79 #ifdef HAVE_UNISTD_H
80 #include <unistd.h>
81 #endif
82 #ifdef HAVE_FCNTL_H
83 #include <fcntl.h>
84 #endif
85 
86 #undef timeout_pending
87 #undef timeout_initialized
88 
89 #include "strlcpy-internal.h"
90 #include "event.h"
91 #include "evhttp.h"
92 #include "evutil.h"
93 #include "log.h"
94 #include "http-internal.h"
95 
96 #ifdef WIN32
97 #define strcasecmp _stricmp
98 #define strncasecmp _strnicmp
99 #define strdup _strdup
100 #endif
101 
102 #ifndef HAVE_GETNAMEINFO
103 #define NI_MAXSERV 32
104 #define NI_MAXHOST 1025
105 
106 #define NI_NUMERICHOST 1
107 #define NI_NUMERICSERV 2
108 
109 static int
110 fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
111  size_t hostlen, char *serv, size_t servlen, int flags)
112 {
113  struct sockaddr_in *sin = (struct sockaddr_in *)sa;
114 
115  if (serv != NULL) {
116  char tmpserv[16];
117  evutil_snprintf(tmpserv, sizeof(tmpserv),
118  "%d", ntohs(sin->sin_port));
119  if (strlcpy(serv, tmpserv, servlen) >= servlen)
120  return (-1);
121  }
122 
123  if (host != NULL) {
124  if (flags & NI_NUMERICHOST) {
125  if (strlcpy(host, inet_ntoa(sin->sin_addr),
126  hostlen) >= hostlen)
127  return (-1);
128  else
129  return (0);
130  } else {
131  struct hostent *hp;
132  hp = gethostbyaddr((char *)&sin->sin_addr,
133  sizeof(struct in_addr), AF_INET);
134  if (hp == NULL)
135  return (-2);
136 
137  if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
138  return (-1);
139  else
140  return (0);
141  }
142  }
143  return (0);
144 }
145 
146 #endif
147 
148 #ifndef HAVE_GETADDRINFO
149 struct addrinfo {
150  int ai_family;
151  int ai_socktype;
152  int ai_protocol;
153  size_t ai_addrlen;
154  struct sockaddr *ai_addr;
155  struct addrinfo *ai_next;
156 };
157 static int
158 fake_getaddrinfo(const char *hostname, struct addrinfo *ai)
159 {
160  struct hostent *he = NULL;
161  struct sockaddr_in *sa;
162  if (hostname) {
163  he = gethostbyname(hostname);
164  if (!he)
165  return (-1);
166  }
167  ai->ai_family = he ? he->h_addrtype : AF_INET;
168  ai->ai_socktype = SOCK_STREAM;
169  ai->ai_protocol = 0;
170  ai->ai_addrlen = sizeof(struct sockaddr_in);
171  if (NULL == (ai->ai_addr = malloc(ai->ai_addrlen)))
172  return (-1);
173  sa = (struct sockaddr_in*)ai->ai_addr;
174  memset(sa, 0, ai->ai_addrlen);
175  if (he) {
176  sa->sin_family = he->h_addrtype;
177  memcpy(&sa->sin_addr, he->h_addr_list[0], he->h_length);
178  } else {
179  sa->sin_family = AF_INET;
180  sa->sin_addr.s_addr = INADDR_ANY;
181  }
182  ai->ai_next = NULL;
183  return (0);
184 }
185 static void
186 fake_freeaddrinfo(struct addrinfo *ai)
187 {
188  free(ai->ai_addr);
189 }
190 #endif
191 
192 #ifndef MIN
193 #define MIN(a,b) (((a)<(b))?(a):(b))
194 #endif
195 
196 /* wrapper for setting the base from the http server */
197 #define EVHTTP_BASE_SET(x, y) do { \
198  if ((x)->base != NULL) event_base_set((x)->base, y); \
199 } while (0)
200 
201 extern int debug;
202 
203 static int socket_connect(int fd, const char *address, unsigned short port);
204 static int bind_socket_ai(struct addrinfo *, int reuse);
205 static int bind_socket(const char *, u_short, int reuse);
206 static void name_from_addr(struct sockaddr *, socklen_t, char **, char **);
207 static int evhttp_associate_new_request_with_connection(
208  struct evhttp_connection *evcon);
209 static void evhttp_connection_start_detectclose(
210  struct evhttp_connection *evcon);
211 static void evhttp_connection_stop_detectclose(
212  struct evhttp_connection *evcon);
213 static void evhttp_request_dispatch(struct evhttp_connection* evcon);
214 static void evhttp_read_firstline(struct evhttp_connection *evcon,
215  struct evhttp_request *req);
216 static void evhttp_read_header(struct evhttp_connection *evcon,
217  struct evhttp_request *req);
218 static int evhttp_add_header_internal(struct evkeyvalq *headers,
219  const char *key, const char *value);
220 static int evhttp_decode_uri_internal(const char *uri, size_t length,
221  char *ret, int always_decode_plus);
222 
223 void evhttp_read(int, short, void *);
224 void evhttp_write(int, short, void *);
225 
226 #ifndef HAVE_STRSEP
227 /* strsep replacement for platforms that lack it. Only works if
228  * del is one character long. */
229 static char *
230 strsep(char **s, const char *del)
231 {
232  char *d, *tok;
233  assert(strlen(del) == 1);
234  if (!s || !*s)
235  return NULL;
236  tok = *s;
237  d = strstr(tok, del);
238  if (d) {
239  *d = '\0';
240  *s = d + 1;
241  } else
242  *s = NULL;
243  return tok;
244 }
245 #endif
246 
247 static const char *
248 html_replace(char ch, char *buf)
249 {
250  switch (ch) {
251  case '<':
252  return "&lt;";
253  case '>':
254  return "&gt;";
255  case '"':
256  return "&quot;";
257  case '\'':
258  return "&#039;";
259  case '&':
260  return "&amp;";
261  default:
262  break;
263  }
264 
265  /* Echo the character back */
266  buf[0] = ch;
267  buf[1] = '\0';
268 
269  return buf;
270 }
271 
272 /*
273  * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
274  * &#039; and &amp; correspondingly.
275  *
276  * The returned string needs to be freed by the caller.
277  */
278 
279 char *
280 evhttp_htmlescape(const char *html)
281 {
282  int i, new_size = 0, old_size = strlen(html);
283  char *escaped_html, *p;
284  char scratch_space[2];
285 
286  for (i = 0; i < old_size; ++i)
287  new_size += strlen(html_replace(html[i], scratch_space));
288 
289  p = escaped_html = malloc(new_size + 1);
290  if (escaped_html == NULL)
291  event_err(1, "%s: malloc(%d)", __func__, new_size + 1);
292  for (i = 0; i < old_size; ++i) {
293  const char *replaced = html_replace(html[i], scratch_space);
294  /* this is length checked */
295  strcpy(p, replaced);
296  p += strlen(replaced);
297  }
298 
299  *p = '\0';
300 
301  return (escaped_html);
302 }
303 
304 static const char *
305 evhttp_method(enum evhttp_cmd_type type)
306 {
307  const char *method;
308 
309  switch (type) {
310  case EVHTTP_REQ_GET:
311  method = "GET";
312  break;
313  case EVHTTP_REQ_POST:
314  method = "POST";
315  break;
316  case EVHTTP_REQ_HEAD:
317  method = "HEAD";
318  break;
319  default:
320  method = NULL;
321  break;
322  }
323 
324  return (method);
325 }
326 
327 static void
328 evhttp_add_event(struct event *ev, int timeout, int default_timeout)
329 {
330  if (timeout != 0) {
331  struct timeval tv;
332 
333  evutil_timerclear(&tv);
334  tv.tv_sec = timeout != -1 ? timeout : default_timeout;
335  event_add(ev, &tv);
336  } else {
337  event_add(ev, NULL);
338  }
339 }
340 
341 void
342 evhttp_write_buffer(struct evhttp_connection *evcon,
343  void (*cb)(struct evhttp_connection *, void *), void *arg)
344 {
345  event_debug(("%s: preparing to write buffer\n", __func__));
346 
347  /* Set call back */
348  evcon->cb = cb;
349  evcon->cb_arg = arg;
350 
351  /* check if the event is already pending */
352  if (event_pending(&evcon->ev, EV_WRITE|EV_TIMEOUT, NULL))
353  event_del(&evcon->ev);
354 
355  event_set(&evcon->ev, evcon->fd, EV_WRITE, evhttp_write, evcon);
356  EVHTTP_BASE_SET(evcon, &evcon->ev);
357  evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_WRITE_TIMEOUT);
358 }
359 
360 static int
361 evhttp_connected(struct evhttp_connection *evcon)
362 {
363  switch (evcon->state) {
364  case EVCON_DISCONNECTED:
365  case EVCON_CONNECTING:
366  return (0);
367  case EVCON_IDLE:
368  case EVCON_READING_FIRSTLINE:
369  case EVCON_READING_HEADERS:
370  case EVCON_READING_BODY:
371  case EVCON_READING_TRAILER:
372  case EVCON_WRITING:
373  default:
374  return (1);
375  }
376 }
377 
378 /*
379  * Create the headers needed for an HTTP request
380  */
381 static void
382 evhttp_make_header_request(struct evhttp_connection *evcon,
383  struct evhttp_request *req)
384 {
385  const char *method;
386 
387  evhttp_remove_header(req->output_headers, "Proxy-Connection");
388 
389  /* Generate request line */
390  method = evhttp_method(req->type);
391  evbuffer_add_printf(evcon->output_buffer, "%s %s HTTP/%d.%d\r\n",
392  method, req->uri, req->major, req->minor);
393 
394  /* Add the content length on a post request if missing */
395  if (req->type == EVHTTP_REQ_POST &&
396  evhttp_find_header(req->output_headers, "Content-Length") == NULL){
397  char size[12];
398  evutil_snprintf(size, sizeof(size), "%ld",
399  (long)EVBUFFER_LENGTH(req->output_buffer));
400  evhttp_add_header(req->output_headers, "Content-Length", size);
401  }
402 }
403 
404 static int
405 evhttp_is_connection_close(int flags, struct evkeyvalq* headers)
406 {
407  if (flags & EVHTTP_PROXY_REQUEST) {
408  /* proxy connection */
409  const char *connection = evhttp_find_header(headers, "Proxy-Connection");
410  return (connection == NULL || strcasecmp(connection, "keep-alive") != 0);
411  } else {
412  const char *connection = evhttp_find_header(headers, "Connection");
413  return (connection != NULL && strcasecmp(connection, "close") == 0);
414  }
415 }
416 
417 static int
418 evhttp_is_connection_keepalive(struct evkeyvalq* headers)
419 {
420  const char *connection = evhttp_find_header(headers, "Connection");
421  return (connection != NULL
422  && strncasecmp(connection, "keep-alive", 10) == 0);
423 }
424 
425 static void
426 evhttp_maybe_add_date_header(struct evkeyvalq *headers)
427 {
428  if (evhttp_find_header(headers, "Date") == NULL) {
429  char date[50];
430 #ifndef WIN32
431  struct tm cur;
432 #endif
433  struct tm *cur_p;
434  time_t t = time(NULL);
435 #ifdef WIN32
436  cur_p = gmtime(&t);
437 #else
438  gmtime_r(&t, &cur);
439  cur_p = &cur;
440 #endif
441  if (strftime(date, sizeof(date),
442  "%a, %d %b %Y %H:%M:%S GMT", cur_p) != 0) {
443  evhttp_add_header(headers, "Date", date);
444  }
445  }
446 }
447 
448 static void
449 evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
450  long content_length)
451 {
452  if (evhttp_find_header(headers, "Transfer-Encoding") == NULL &&
453  evhttp_find_header(headers, "Content-Length") == NULL) {
454  char len[12];
455  evutil_snprintf(len, sizeof(len), "%ld", content_length);
456  evhttp_add_header(headers, "Content-Length", len);
457  }
458 }
459 
460 /*
461  * Create the headers needed for an HTTP reply
462  */
463 
464 static void
465 evhttp_make_header_response(struct evhttp_connection *evcon,
466  struct evhttp_request *req)
467 {
468  int is_keepalive = evhttp_is_connection_keepalive(req->input_headers);
469  evbuffer_add_printf(evcon->output_buffer, "HTTP/%d.%d %d %s\r\n",
470  req->major, req->minor, req->response_code,
471  req->response_code_line);
472 
473  if (req->major == 1) {
474  if (req->minor == 1)
475  evhttp_maybe_add_date_header(req->output_headers);
476 
477  /*
478  * if the protocol is 1.0; and the connection was keep-alive
479  * we need to add a keep-alive header, too.
480  */
481  if (req->minor == 0 && is_keepalive)
482  evhttp_add_header(req->output_headers,
483  "Connection", "keep-alive");
484 
485  if (req->minor == 1 || is_keepalive) {
486  /*
487  * we need to add the content length if the
488  * user did not give it, this is required for
489  * persistent connections to work.
490  */
491  evhttp_maybe_add_content_length_header(
492  req->output_headers,
493  (long)EVBUFFER_LENGTH(req->output_buffer));
494  }
495  }
496 
497  /* Potentially add headers for unidentified content. */
498  if (EVBUFFER_LENGTH(req->output_buffer)) {
499  if (evhttp_find_header(req->output_headers,
500  "Content-Type") == NULL) {
501  evhttp_add_header(req->output_headers,
502  "Content-Type", "text/html; charset=ISO-8859-1");
503  }
504  }
505 
506  /* if the request asked for a close, we send a close, too */
507  if (evhttp_is_connection_close(req->flags, req->input_headers)) {
508  evhttp_remove_header(req->output_headers, "Connection");
509  if (!(req->flags & EVHTTP_PROXY_REQUEST))
510  evhttp_add_header(req->output_headers, "Connection", "close");
511  evhttp_remove_header(req->output_headers, "Proxy-Connection");
512  }
513 }
514 
515 void
516 evhttp_make_header(struct evhttp_connection *evcon, struct evhttp_request *req)
517 {
518  struct evkeyval *header;
519 
520  /*
521  * Depending if this is a HTTP request or response, we might need to
522  * add some new headers or remove existing headers.
523  */
524  if (req->kind == EVHTTP_REQUEST) {
525  evhttp_make_header_request(evcon, req);
526  } else {
527  evhttp_make_header_response(evcon, req);
528  }
529 
530  TAILQ_FOREACH(header, req->output_headers, next) {
531  evbuffer_add_printf(evcon->output_buffer, "%s: %s\r\n",
532  header->key, header->value);
533  }
534  evbuffer_add(evcon->output_buffer, "\r\n", 2);
535 
536  if (EVBUFFER_LENGTH(req->output_buffer) > 0) {
537  /*
538  * For a request, we add the POST data, for a reply, this
539  * is the regular data.
540  */
541  evbuffer_add_buffer(evcon->output_buffer, req->output_buffer);
542  }
543 }
544 
545 /* Separated host, port and file from URI */
546 
547 int
548 evhttp_hostportfile(char *url, char **phost, u_short *pport, char **pfile)
549 {
550  /* XXX not threadsafe. */
551  static char host[1024];
552  static char file[1024];
553  char *p;
554  const char *p2;
555  int len;
556  u_short port;
557 
558  len = strlen(HTTP_PREFIX);
559  if (strncasecmp(url, HTTP_PREFIX, len))
560  return (-1);
561 
562  url += len;
563 
564  /* We might overrun */
565  if (strlcpy(host, url, sizeof (host)) >= sizeof(host))
566  return (-1);
567 
568  p = strchr(host, '/');
569  if (p != NULL) {
570  *p = '\0';
571  p2 = p + 1;
572  } else
573  p2 = NULL;
574 
575  if (pfile != NULL) {
576  /* Generate request file */
577  if (p2 == NULL)
578  p2 = "";
579  evutil_snprintf(file, sizeof(file), "/%s", p2);
580  }
581 
582  p = strchr(host, ':');
583  if (p != NULL) {
584  *p = '\0';
585  port = atoi(p + 1);
586 
587  if (port == 0)
588  return (-1);
589  } else
590  port = HTTP_DEFAULTPORT;
591 
592  if (phost != NULL)
593  *phost = host;
594  if (pport != NULL)
595  *pport = port;
596  if (pfile != NULL)
597  *pfile = file;
598 
599  return (0);
600 }
601 
602 static int
603 evhttp_connection_incoming_fail(struct evhttp_request *req,
604  enum evhttp_connection_error error)
605 {
606  switch (error) {
607  case EVCON_HTTP_TIMEOUT:
608  case EVCON_HTTP_EOF:
609  /*
610  * these are cases in which we probably should just
611  * close the connection and not send a reply. this
612  * case may happen when a browser keeps a persistent
613  * connection open and we timeout on the read.
614  */
615  return (-1);
616  case EVCON_HTTP_INVALID_HEADER:
617  default: /* xxx: probably should just error on default */
618  /* the callback looks at the uri to determine errors */
619  if (req->uri) {
620  free(req->uri);
621  req->uri = NULL;
622  }
623 
624  /*
625  * the callback needs to send a reply, once the reply has
626  * been send, the connection should get freed.
627  */
628  (*req->cb)(req, req->cb_arg);
629  }
630 
631  return (0);
632 }
633 
634 void
635 evhttp_connection_fail(struct evhttp_connection *evcon,
636  enum evhttp_connection_error error)
637 {
638  struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
639  void (*cb)(struct evhttp_request *, void *);
640  void *cb_arg;
641  assert(req != NULL);
642 
643  if (evcon->flags & EVHTTP_CON_INCOMING) {
644  /*
645  * for incoming requests, there are two different
646  * failure cases. it's either a network level error
647  * or an http layer error. for problems on the network
648  * layer like timeouts we just drop the connections.
649  * For HTTP problems, we might have to send back a
650  * reply before the connection can be freed.
651  */
652  if (evhttp_connection_incoming_fail(req, error) == -1)
653  evhttp_connection_free(evcon);
654  return;
655  }
656 
657  /* save the callback for later; the cb might free our object */
658  cb = req->cb;
659  cb_arg = req->cb_arg;
660 
661  TAILQ_REMOVE(&evcon->requests, req, next);
662  evhttp_request_free(req);
663 
664  /* xxx: maybe we should fail all requests??? */
665 
666  /* reset the connection */
667  evhttp_connection_reset(evcon);
668 
669  /* We are trying the next request that was queued on us */
670  if (TAILQ_FIRST(&evcon->requests) != NULL)
671  evhttp_connection_connect(evcon);
672 
673  /* inform the user */
674  if (cb != NULL)
675  (*cb)(NULL, cb_arg);
676 }
677 
678 void
679 evhttp_write(int fd, short what, void *arg)
680 {
681  struct evhttp_connection *evcon = arg;
682  int n;
683 
684  if (what == EV_TIMEOUT) {
685  evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
686  return;
687  }
688 
689  n = evbuffer_write(evcon->output_buffer, fd);
690  if (n == -1) {
691  event_debug(("%s: evbuffer_write", __func__));
692  evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
693  return;
694  }
695 
696  if (n == 0) {
697  event_debug(("%s: write nothing", __func__));
698  evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
699  return;
700  }
701 
702  if (EVBUFFER_LENGTH(evcon->output_buffer) != 0) {
703  evhttp_add_event(&evcon->ev,
704  evcon->timeout, HTTP_WRITE_TIMEOUT);
705  return;
706  }
707 
708  /* Activate our call back */
709  if (evcon->cb != NULL)
710  (*evcon->cb)(evcon, evcon->cb_arg);
711 }
712 
720 static void
721 evhttp_connection_done(struct evhttp_connection *evcon)
722 {
723  struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
724  int con_outgoing = evcon->flags & EVHTTP_CON_OUTGOING;
725 
726  if (con_outgoing) {
727  /* idle or close the connection */
728  int need_close;
729  TAILQ_REMOVE(&evcon->requests, req, next);
730  req->evcon = NULL;
731 
732  evcon->state = EVCON_IDLE;
733 
734  need_close =
735  evhttp_is_connection_close(req->flags, req->input_headers)||
736  evhttp_is_connection_close(req->flags, req->output_headers);
737 
738  /* check if we got asked to close the connection */
739  if (need_close)
740  evhttp_connection_reset(evcon);
741 
742  if (TAILQ_FIRST(&evcon->requests) != NULL) {
743  /*
744  * We have more requests; reset the connection
745  * and deal with the next request.
746  */
747  if (!evhttp_connected(evcon))
748  evhttp_connection_connect(evcon);
749  else
750  evhttp_request_dispatch(evcon);
751  } else if (!need_close) {
752  /*
753  * The connection is going to be persistent, but we
754  * need to detect if the other side closes it.
755  */
756  evhttp_connection_start_detectclose(evcon);
757  }
758  } else {
759  /*
760  * incoming connection - we need to leave the request on the
761  * connection so that we can reply to it.
762  */
763  evcon->state = EVCON_WRITING;
764  }
765 
766  /* notify the user of the request */
767  (*req->cb)(req, req->cb_arg);
768 
769  /* if this was an outgoing request, we own and it's done. so free it */
770  if (con_outgoing) {
771  evhttp_request_free(req);
772  }
773 }
774 
775 /*
776  * Handles reading from a chunked request.
777  * return ALL_DATA_READ:
778  * all data has been read
779  * return MORE_DATA_EXPECTED:
780  * more data is expected
781  * return DATA_CORRUPTED:
782  * data is corrupted
783  * return REQUEST_CANCLED:
784  * request was canceled by the user calling evhttp_cancel_request
785  */
786 
787 static enum message_read_status
788 evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
789 {
790  int len;
791 
792  while ((len = EVBUFFER_LENGTH(buf)) > 0) {
793  if (req->ntoread < 0) {
794  /* Read chunk size */
795  ev_int64_t ntoread;
796  char *p = evbuffer_readline(buf);
797  char *endp;
798  int error;
799  if (p == NULL)
800  break;
801  /* the last chunk is on a new line? */
802  if (strlen(p) == 0) {
803  free(p);
804  continue;
805  }
806  ntoread = evutil_strtoll(p, &endp, 16);
807  error = (*p == '\0' ||
808  (*endp != '\0' && *endp != ' ') ||
809  ntoread < 0);
810  free(p);
811  if (error) {
812  /* could not get chunk size */
813  return (DATA_CORRUPTED);
814  }
815  req->ntoread = ntoread;
816  if (req->ntoread == 0) {
817  /* Last chunk */
818  return (ALL_DATA_READ);
819  }
820  continue;
821  }
822 
823  /* don't have enough to complete a chunk; wait for more */
824  if (len < req->ntoread)
825  return (MORE_DATA_EXPECTED);
826 
827  /* Completed chunk */
828  evbuffer_add(req->input_buffer,
829  EVBUFFER_DATA(buf), (size_t)req->ntoread);
830  evbuffer_drain(buf, (size_t)req->ntoread);
831  req->ntoread = -1;
832  if (req->chunk_cb != NULL) {
833  (*req->chunk_cb)(req, req->cb_arg);
834  evbuffer_drain(req->input_buffer,
835  EVBUFFER_LENGTH(req->input_buffer));
836  }
837  }
838 
839  return (MORE_DATA_EXPECTED);
840 }
841 
842 static void
843 evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
844 {
845  struct evbuffer *buf = evcon->input_buffer;
846 
847  switch (evhttp_parse_headers(req, buf)) {
848  case DATA_CORRUPTED:
849  evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
850  break;
851  case ALL_DATA_READ:
852  event_del(&evcon->ev);
853  evhttp_connection_done(evcon);
854  break;
855  case MORE_DATA_EXPECTED:
856  default:
857  evhttp_add_event(&evcon->ev, evcon->timeout,
858  HTTP_READ_TIMEOUT);
859  break;
860  }
861 }
862 
863 static void
864 evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
865 {
866  struct evbuffer *buf = evcon->input_buffer;
867 
868  if (req->chunked) {
869  switch (evhttp_handle_chunked_read(req, buf)) {
870  case ALL_DATA_READ:
871  /* finished last chunk */
872  evcon->state = EVCON_READING_TRAILER;
873  evhttp_read_trailer(evcon, req);
874  return;
875  case DATA_CORRUPTED:
876  /* corrupted data */
877  evhttp_connection_fail(evcon,
878  EVCON_HTTP_INVALID_HEADER);
879  return;
880  case REQUEST_CANCELED:
881  /* request canceled */
882  evhttp_request_free(req);
883  return;
884  case MORE_DATA_EXPECTED:
885  default:
886  break;
887  }
888  } else if (req->ntoread < 0) {
889  /* Read until connection close. */
890  evbuffer_add_buffer(req->input_buffer, buf);
891  } else if (EVBUFFER_LENGTH(buf) >= req->ntoread) {
892  /* Completed content length */
893  evbuffer_add(req->input_buffer, EVBUFFER_DATA(buf),
894  (size_t)req->ntoread);
895  evbuffer_drain(buf, (size_t)req->ntoread);
896  req->ntoread = 0;
897  evhttp_connection_done(evcon);
898  return;
899  }
900  /* Read more! */
901  event_set(&evcon->ev, evcon->fd, EV_READ, evhttp_read, evcon);
902  EVHTTP_BASE_SET(evcon, &evcon->ev);
903  evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_READ_TIMEOUT);
904 }
905 
906 /*
907  * Reads data into a buffer structure until no more data
908  * can be read on the file descriptor or we have read all
909  * the data that we wanted to read.
910  * Execute callback when done.
911  */
912 
913 void
914 evhttp_read(int fd, short what, void *arg)
915 {
916  struct evhttp_connection *evcon = arg;
917  struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
918  struct evbuffer *buf = evcon->input_buffer;
919  int n, len;
920 
921  if (what == EV_TIMEOUT) {
922  evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
923  return;
924  }
925  n = evbuffer_read(buf, fd, -1);
926  len = EVBUFFER_LENGTH(buf);
927  event_debug(("%s: got %d on %d\n", __func__, n, fd));
928 
929  if (n == -1) {
930  if (errno != EINTR && errno != EAGAIN) {
931  event_debug(("%s: evbuffer_read", __func__));
932  evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
933  } else {
934  evhttp_add_event(&evcon->ev, evcon->timeout,
935  HTTP_READ_TIMEOUT);
936  }
937  return;
938  } else if (n == 0) {
939  /* Connection closed */
940  evhttp_connection_done(evcon);
941  return;
942  }
943 
944  switch (evcon->state) {
945  case EVCON_READING_FIRSTLINE:
946  evhttp_read_firstline(evcon, req);
947  break;
948  case EVCON_READING_HEADERS:
949  evhttp_read_header(evcon, req);
950  break;
951  case EVCON_READING_BODY:
952  evhttp_read_body(evcon, req);
953  break;
954  case EVCON_READING_TRAILER:
955  evhttp_read_trailer(evcon, req);
956  break;
957  case EVCON_DISCONNECTED:
958  case EVCON_CONNECTING:
959  case EVCON_IDLE:
960  case EVCON_WRITING:
961  default:
962  event_errx(1, "%s: illegal connection state %d",
963  __func__, evcon->state);
964  }
965 }
966 
967 static void
968 evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
969 {
970  /* This is after writing the request to the server */
971  struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
972  assert(req != NULL);
973 
974  assert(evcon->state == EVCON_WRITING);
975 
976  /* We are done writing our header and are now expecting the response */
977  req->kind = EVHTTP_RESPONSE;
978 
979  evhttp_start_read(evcon);
980 }
981 
982 /*
983  * Clean up a connection object
984  */
985 
986 void
988 {
989  struct evhttp_request *req;
990 
991  /* notify interested parties that this connection is going down */
992  if (evcon->fd != -1) {
993  if (evhttp_connected(evcon) && evcon->closecb != NULL)
994  (*evcon->closecb)(evcon, evcon->closecb_arg);
995  }
996 
997  /* remove all requests that might be queued on this connection */
998  while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
999  TAILQ_REMOVE(&evcon->requests, req, next);
1000  evhttp_request_free(req);
1001  }
1002 
1003  if (evcon->http_server != NULL) {
1004  struct evhttp *http = evcon->http_server;
1005  TAILQ_REMOVE(&http->connections, evcon, next);
1006  }
1007 
1008  if (event_initialized(&evcon->close_ev))
1009  event_del(&evcon->close_ev);
1010 
1011  if (event_initialized(&evcon->ev))
1012  event_del(&evcon->ev);
1013 
1014  if (evcon->fd != -1)
1015  EVUTIL_CLOSESOCKET(evcon->fd);
1016 
1017  if (evcon->bind_address != NULL)
1018  free(evcon->bind_address);
1019 
1020  if (evcon->address != NULL)
1021  free(evcon->address);
1022 
1023  if (evcon->input_buffer != NULL)
1024  evbuffer_free(evcon->input_buffer);
1025 
1026  if (evcon->output_buffer != NULL)
1027  evbuffer_free(evcon->output_buffer);
1028 
1029  free(evcon);
1030 }
1031 
1032 void
1034  const char *address)
1035 {
1036  assert(evcon->state == EVCON_DISCONNECTED);
1037  if (evcon->bind_address)
1038  free(evcon->bind_address);
1039  if ((evcon->bind_address = strdup(address)) == NULL)
1040  event_err(1, "%s: strdup", __func__);
1041 }
1042 
1043 void
1045  unsigned short port)
1046 {
1047  assert(evcon->state == EVCON_DISCONNECTED);
1048  evcon->bind_port = port;
1049 }
1050 
1051 static void
1052 evhttp_request_dispatch(struct evhttp_connection* evcon)
1053 {
1054  struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
1055 
1056  /* this should not usually happy but it's possible */
1057  if (req == NULL)
1058  return;
1059 
1060  /* delete possible close detection events */
1061  evhttp_connection_stop_detectclose(evcon);
1062 
1063  /* we assume that the connection is connected already */
1064  assert(evcon->state == EVCON_IDLE);
1065 
1066  evcon->state = EVCON_WRITING;
1067 
1068  /* Create the header from the store arguments */
1069  evhttp_make_header(evcon, req);
1070 
1071  evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
1072 }
1073 
1074 /* Reset our connection state */
1075 void
1076 evhttp_connection_reset(struct evhttp_connection *evcon)
1077 {
1078  if (event_initialized(&evcon->ev))
1079  event_del(&evcon->ev);
1080 
1081  if (evcon->fd != -1) {
1082  /* inform interested parties about connection close */
1083  if (evhttp_connected(evcon) && evcon->closecb != NULL)
1084  (*evcon->closecb)(evcon, evcon->closecb_arg);
1085 
1086  EVUTIL_CLOSESOCKET(evcon->fd);
1087  evcon->fd = -1;
1088  }
1089  evcon->state = EVCON_DISCONNECTED;
1090 
1091  evbuffer_drain(evcon->input_buffer,
1092  EVBUFFER_LENGTH(evcon->input_buffer));
1093  evbuffer_drain(evcon->output_buffer,
1094  EVBUFFER_LENGTH(evcon->output_buffer));
1095 }
1096 
1097 static void
1098 evhttp_detect_close_cb(int fd, short what, void *arg)
1099 {
1100  struct evhttp_connection *evcon = arg;
1101  evhttp_connection_reset(evcon);
1102 }
1103 
1104 static void
1105 evhttp_connection_start_detectclose(struct evhttp_connection *evcon)
1106 {
1107  evcon->flags |= EVHTTP_CON_CLOSEDETECT;
1108 
1109  if (event_initialized(&evcon->close_ev))
1110  event_del(&evcon->close_ev);
1111  event_set(&evcon->close_ev, evcon->fd, EV_READ,
1112  evhttp_detect_close_cb, evcon);
1113  EVHTTP_BASE_SET(evcon, &evcon->close_ev);
1114  event_add(&evcon->close_ev, NULL);
1115 }
1116 
1117 static void
1118 evhttp_connection_stop_detectclose(struct evhttp_connection *evcon)
1119 {
1120  evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
1121  event_del(&evcon->close_ev);
1122 }
1123 
1124 static void
1125 evhttp_connection_retry(int fd, short what, void *arg)
1126 {
1127  struct evhttp_connection *evcon = arg;
1128 
1129  evcon->state = EVCON_DISCONNECTED;
1130  evhttp_connection_connect(evcon);
1131 }
1132 
1133 /*
1134  * Call back for asynchronous connection attempt.
1135  */
1136 
1137 static void
1138 evhttp_connectioncb(int fd, short what, void *arg)
1139 {
1140  struct evhttp_connection *evcon = arg;
1141  int error;
1142  socklen_t errsz = sizeof(error);
1143 
1144  if (what == EV_TIMEOUT) {
1145  event_debug(("%s: connection timeout for \"%s:%d\" on %d",
1146  __func__, evcon->address, evcon->port, evcon->fd));
1147  goto cleanup;
1148  }
1149 
1150  /* Check if the connection completed */
1151  if (getsockopt(evcon->fd, SOL_SOCKET, SO_ERROR, (void*)&error,
1152  &errsz) == -1) {
1153  event_debug(("%s: getsockopt for \"%s:%d\" on %d",
1154  __func__, evcon->address, evcon->port, evcon->fd));
1155  goto cleanup;
1156  }
1157 
1158  if (error) {
1159  event_debug(("%s: connect failed for \"%s:%d\" on %d: %s",
1160  __func__, evcon->address, evcon->port, evcon->fd,
1161  strerror(error)));
1162  goto cleanup;
1163  }
1164 
1165  /* We are connected to the server now */
1166  event_debug(("%s: connected to \"%s:%d\" on %d\n",
1167  __func__, evcon->address, evcon->port, evcon->fd));
1168 
1169  /* Reset the retry count as we were successful in connecting */
1170  evcon->retry_cnt = 0;
1171  evcon->state = EVCON_IDLE;
1172 
1173  /* try to start requests that have queued up on this connection */
1174  evhttp_request_dispatch(evcon);
1175  return;
1176 
1177  cleanup:
1178  if (evcon->retry_max < 0 || evcon->retry_cnt < evcon->retry_max) {
1179  evtimer_set(&evcon->ev, evhttp_connection_retry, evcon);
1180  EVHTTP_BASE_SET(evcon, &evcon->ev);
1181  evhttp_add_event(&evcon->ev, MIN(3600, 2 << evcon->retry_cnt),
1182  HTTP_CONNECT_TIMEOUT);
1183  evcon->retry_cnt++;
1184  return;
1185  }
1186  evhttp_connection_reset(evcon);
1187 
1188  /* for now, we just signal all requests by executing their callbacks */
1189  while (TAILQ_FIRST(&evcon->requests) != NULL) {
1190  struct evhttp_request *request = TAILQ_FIRST(&evcon->requests);
1191  TAILQ_REMOVE(&evcon->requests, request, next);
1192  request->evcon = NULL;
1193 
1194  /* we might want to set an error here */
1195  request->cb(request, request->cb_arg);
1196  evhttp_request_free(request);
1197  }
1198 }
1199 
1200 /*
1201  * Check if we got a valid response code.
1202  */
1203 
1204 static int
1205 evhttp_valid_response_code(int code)
1206 {
1207  if (code == 0)
1208  return (0);
1209 
1210  return (1);
1211 }
1212 
1213 /* Parses the status line of a web server */
1214 
1215 static int
1216 evhttp_parse_response_line(struct evhttp_request *req, char *line)
1217 {
1218  char *protocol;
1219  char *number;
1220  char *readable;
1221 
1222  protocol = strsep(&line, " ");
1223  if (line == NULL)
1224  return (-1);
1225  number = strsep(&line, " ");
1226  if (line == NULL)
1227  return (-1);
1228  readable = line;
1229 
1230  if (strcmp(protocol, "HTTP/1.0") == 0) {
1231  req->major = 1;
1232  req->minor = 0;
1233  } else if (strcmp(protocol, "HTTP/1.1") == 0) {
1234  req->major = 1;
1235  req->minor = 1;
1236  } else {
1237  event_debug(("%s: bad protocol \"%s\"",
1238  __func__, protocol));
1239  return (-1);
1240  }
1241 
1242  req->response_code = atoi(number);
1243  if (!evhttp_valid_response_code(req->response_code)) {
1244  event_debug(("%s: bad response code \"%s\"",
1245  __func__, number));
1246  return (-1);
1247  }
1248 
1249  if ((req->response_code_line = strdup(readable)) == NULL)
1250  event_err(1, "%s: strdup", __func__);
1251 
1252  return (0);
1253 }
1254 
1255 /* Parse the first line of a HTTP request */
1256 
1257 static int
1258 evhttp_parse_request_line(struct evhttp_request *req, char *line)
1259 {
1260  char *method;
1261  char *uri;
1262  char *version;
1263 
1264  /* Parse the request line */
1265  method = strsep(&line, " ");
1266  if (line == NULL)
1267  return (-1);
1268  uri = strsep(&line, " ");
1269  if (line == NULL)
1270  return (-1);
1271  version = strsep(&line, " ");
1272  if (line != NULL)
1273  return (-1);
1274 
1275  /* First line */
1276  if (strcmp(method, "GET") == 0) {
1277  req->type = EVHTTP_REQ_GET;
1278  } else if (strcmp(method, "POST") == 0) {
1279  req->type = EVHTTP_REQ_POST;
1280  } else if (strcmp(method, "HEAD") == 0) {
1281  req->type = EVHTTP_REQ_HEAD;
1282  } else {
1283  event_debug(("%s: bad method %s on request %p from %s",
1284  __func__, method, req, req->remote_host));
1285  return (-1);
1286  }
1287 
1288  if (strcmp(version, "HTTP/1.0") == 0) {
1289  req->major = 1;
1290  req->minor = 0;
1291  } else if (strcmp(version, "HTTP/1.1") == 0) {
1292  req->major = 1;
1293  req->minor = 1;
1294  } else {
1295  event_debug(("%s: bad version %s on request %p from %s",
1296  __func__, version, req, req->remote_host));
1297  return (-1);
1298  }
1299 
1300  if ((req->uri = strdup(uri)) == NULL) {
1301  event_debug(("%s: evhttp_decode_uri", __func__));
1302  return (-1);
1303  }
1304 
1305  /* determine if it's a proxy request */
1306  if (strlen(req->uri) > 0 && req->uri[0] != '/')
1307  req->flags |= EVHTTP_PROXY_REQUEST;
1308 
1309  return (0);
1310 }
1311 
1312 const char *
1313 evhttp_find_header(const struct evkeyvalq *headers, const char *key)
1314 {
1315  struct evkeyval *header;
1316 
1317  TAILQ_FOREACH(header, headers, next) {
1318  if (strcasecmp(header->key, key) == 0)
1319  return (header->value);
1320  }
1321 
1322  return (NULL);
1323 }
1324 
1325 void
1326 evhttp_clear_headers(struct evkeyvalq *headers)
1327 {
1328  struct evkeyval *header;
1329 
1330  for (header = TAILQ_FIRST(headers);
1331  header != NULL;
1332  header = TAILQ_FIRST(headers)) {
1333  TAILQ_REMOVE(headers, header, next);
1334  free(header->key);
1335  free(header->value);
1336  free(header);
1337  }
1338 }
1339 
1340 /*
1341  * Returns 0, if the header was successfully removed.
1342  * Returns -1, if the header could not be found.
1343  */
1344 
1345 int
1346 evhttp_remove_header(struct evkeyvalq *headers, const char *key)
1347 {
1348  struct evkeyval *header;
1349 
1350  TAILQ_FOREACH(header, headers, next) {
1351  if (strcasecmp(header->key, key) == 0)
1352  break;
1353  }
1354 
1355  if (header == NULL)
1356  return (-1);
1357 
1358  /* Free and remove the header that we found */
1359  TAILQ_REMOVE(headers, header, next);
1360  free(header->key);
1361  free(header->value);
1362  free(header);
1363 
1364  return (0);
1365 }
1366 
1367 static int
1368 evhttp_header_is_valid_value(const char *value)
1369 {
1370  const char *p = value;
1371 
1372  while ((p = strpbrk(p, "\r\n")) != NULL) {
1373  /* we really expect only one new line */
1374  p += strspn(p, "\r\n");
1375  /* we expect a space or tab for continuation */
1376  if (*p != ' ' && *p != '\t')
1377  return (0);
1378  }
1379  return (1);
1380 }
1381 
1382 int
1383 evhttp_add_header(struct evkeyvalq *headers,
1384  const char *key, const char *value)
1385 {
1386  event_debug(("%s: key: %s val: %s\n", __func__, key, value));
1387 
1388  if (strchr(key, '\r') != NULL || strchr(key, '\n') != NULL) {
1389  /* drop illegal headers */
1390  event_debug(("%s: dropping illegal header key\n", __func__));
1391  return (-1);
1392  }
1393 
1394  if (!evhttp_header_is_valid_value(value)) {
1395  event_debug(("%s: dropping illegal header value\n", __func__));
1396  return (-1);
1397  }
1398 
1399  return (evhttp_add_header_internal(headers, key, value));
1400 }
1401 
1402 static int
1403 evhttp_add_header_internal(struct evkeyvalq *headers,
1404  const char *key, const char *value)
1405 {
1406  struct evkeyval *header = calloc(1, sizeof(struct evkeyval));
1407  if (header == NULL) {
1408  event_warn("%s: calloc", __func__);
1409  return (-1);
1410  }
1411  if ((header->key = strdup(key)) == NULL) {
1412  free(header);
1413  event_warn("%s: strdup", __func__);
1414  return (-1);
1415  }
1416  if ((header->value = strdup(value)) == NULL) {
1417  free(header->key);
1418  free(header);
1419  event_warn("%s: strdup", __func__);
1420  return (-1);
1421  }
1422 
1423  TAILQ_INSERT_TAIL(headers, header, next);
1424 
1425  return (0);
1426 }
1427 
1428 /*
1429  * Parses header lines from a request or a response into the specified
1430  * request object given an event buffer.
1431  *
1432  * Returns
1433  * DATA_CORRUPTED on error
1434  * MORE_DATA_EXPECTED when we need to read more headers
1435  * ALL_DATA_READ when all headers have been read.
1436  */
1437 
1438 enum message_read_status
1439 evhttp_parse_firstline(struct evhttp_request *req, struct evbuffer *buffer)
1440 {
1441  char *line;
1442  enum message_read_status status = ALL_DATA_READ;
1443 
1444  line = evbuffer_readline(buffer);
1445  if (line == NULL)
1446  return (MORE_DATA_EXPECTED);
1447 
1448  switch (req->kind) {
1449  case EVHTTP_REQUEST:
1450  if (evhttp_parse_request_line(req, line) == -1)
1451  status = DATA_CORRUPTED;
1452  break;
1453  case EVHTTP_RESPONSE:
1454  if (evhttp_parse_response_line(req, line) == -1)
1455  status = DATA_CORRUPTED;
1456  break;
1457  default:
1458  status = DATA_CORRUPTED;
1459  }
1460 
1461  free(line);
1462  return (status);
1463 }
1464 
1465 static int
1466 evhttp_append_to_last_header(struct evkeyvalq *headers, const char *line)
1467 {
1468  struct evkeyval *header = TAILQ_LAST(headers, evkeyvalq);
1469  char *newval;
1470  size_t old_len, line_len;
1471 
1472  if (header == NULL)
1473  return (-1);
1474 
1475  old_len = strlen(header->value);
1476  line_len = strlen(line);
1477 
1478  newval = realloc(header->value, old_len + line_len + 1);
1479  if (newval == NULL)
1480  return (-1);
1481 
1482  memcpy(newval + old_len, line, line_len + 1);
1483  header->value = newval;
1484 
1485  return (0);
1486 }
1487 
1488 enum message_read_status
1489 evhttp_parse_headers(struct evhttp_request *req, struct evbuffer* buffer)
1490 {
1491  char *line;
1492  enum message_read_status status = MORE_DATA_EXPECTED;
1493 
1494  struct evkeyvalq* headers = req->input_headers;
1495  while ((line = evbuffer_readline(buffer))
1496  != NULL) {
1497  char *skey, *svalue;
1498 
1499  if (*line == '\0') { /* Last header - Done */
1500  status = ALL_DATA_READ;
1501  free(line);
1502  break;
1503  }
1504 
1505  /* Check if this is a continuation line */
1506  if (*line == ' ' || *line == '\t') {
1507  if (evhttp_append_to_last_header(headers, line) == -1)
1508  goto error;
1509  free(line);
1510  continue;
1511  }
1512 
1513  /* Processing of header lines */
1514  svalue = line;
1515  skey = strsep(&svalue, ":");
1516  if (svalue == NULL)
1517  goto error;
1518 
1519  svalue += strspn(svalue, " ");
1520 
1521  if (evhttp_add_header(headers, skey, svalue) == -1)
1522  goto error;
1523 
1524  free(line);
1525  }
1526 
1527  return (status);
1528 
1529  error:
1530  free(line);
1531  return (DATA_CORRUPTED);
1532 }
1533 
1534 static int
1535 evhttp_get_body_length(struct evhttp_request *req)
1536 {
1537  struct evkeyvalq *headers = req->input_headers;
1538  const char *content_length;
1539  const char *connection;
1540 
1541  content_length = evhttp_find_header(headers, "Content-Length");
1542  connection = evhttp_find_header(headers, "Connection");
1543 
1544  if (content_length == NULL && connection == NULL)
1545  req->ntoread = -1;
1546  else if (content_length == NULL &&
1547  strcasecmp(connection, "Close") != 0) {
1548  /* Bad combination, we don't know when it will end */
1549  event_warnx("%s: we got no content length, but the "
1550  "server wants to keep the connection open: %s.",
1551  __func__, connection);
1552  return (-1);
1553  } else if (content_length == NULL) {
1554  req->ntoread = -1;
1555  } else {
1556  char *endp;
1557  ev_int64_t ntoread = evutil_strtoll(content_length, &endp, 10);
1558  if (*content_length == '\0' || *endp != '\0' || ntoread < 0) {
1559  event_debug(("%s: illegal content length: %s",
1560  __func__, content_length));
1561  return (-1);
1562  }
1563  req->ntoread = ntoread;
1564  }
1565 
1566  event_debug(("%s: bytes to read: %lld (in buffer %ld)\n",
1567  __func__, req->ntoread,
1568  EVBUFFER_LENGTH(req->evcon->input_buffer)));
1569 
1570  return (0);
1571 }
1572 
1573 static void
1574 evhttp_get_body(struct evhttp_connection *evcon, struct evhttp_request *req)
1575 {
1576  const char *xfer_enc;
1577 
1578  /* If this is a request without a body, then we are done */
1579  if (req->kind == EVHTTP_REQUEST && req->type != EVHTTP_REQ_POST) {
1580  evhttp_connection_done(evcon);
1581  return;
1582  }
1583  evcon->state = EVCON_READING_BODY;
1584  xfer_enc = evhttp_find_header(req->input_headers, "Transfer-Encoding");
1585  if (xfer_enc != NULL && strcasecmp(xfer_enc, "chunked") == 0) {
1586  req->chunked = 1;
1587  req->ntoread = -1;
1588  } else {
1589  if (evhttp_get_body_length(req) == -1) {
1590  evhttp_connection_fail(evcon,
1591  EVCON_HTTP_INVALID_HEADER);
1592  return;
1593  }
1594  }
1595  evhttp_read_body(evcon, req);
1596 }
1597 
1598 static void
1599 evhttp_read_firstline(struct evhttp_connection *evcon,
1600  struct evhttp_request *req)
1601 {
1602  enum message_read_status res;
1603 
1604  res = evhttp_parse_firstline(req, evcon->input_buffer);
1605  if (res == DATA_CORRUPTED) {
1606  /* Error while reading, terminate */
1607  event_debug(("%s: bad header lines on %d\n",
1608  __func__, evcon->fd));
1609  evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
1610  return;
1611  } else if (res == MORE_DATA_EXPECTED) {
1612  /* Need more header lines */
1613  evhttp_add_event(&evcon->ev,
1614  evcon->timeout, HTTP_READ_TIMEOUT);
1615  return;
1616  }
1617 
1618  evcon->state = EVCON_READING_HEADERS;
1619  evhttp_read_header(evcon, req);
1620 }
1621 
1622 static void
1623 evhttp_read_header(struct evhttp_connection *evcon, struct evhttp_request *req)
1624 {
1625  enum message_read_status res;
1626  int fd = evcon->fd;
1627 
1628  res = evhttp_parse_headers(req, evcon->input_buffer);
1629  if (res == DATA_CORRUPTED) {
1630  /* Error while reading, terminate */
1631  event_debug(("%s: bad header lines on %d\n", __func__, fd));
1632  evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
1633  return;
1634  } else if (res == MORE_DATA_EXPECTED) {
1635  /* Need more header lines */
1636  evhttp_add_event(&evcon->ev,
1637  evcon->timeout, HTTP_READ_TIMEOUT);
1638  return;
1639  }
1640 
1641  /* Done reading headers, do the real work */
1642  switch (req->kind) {
1643  case EVHTTP_REQUEST:
1644  event_debug(("%s: checking for post data on %d\n",
1645  __func__, fd));
1646  evhttp_get_body(evcon, req);
1647  break;
1648 
1649  case EVHTTP_RESPONSE:
1650  if (req->response_code == HTTP_NOCONTENT ||
1651  req->response_code == HTTP_NOTMODIFIED ||
1652  (req->response_code >= 100 && req->response_code < 200)) {
1653  event_debug(("%s: skipping body for code %d\n",
1654  __func__, req->response_code));
1655  evhttp_connection_done(evcon);
1656  } else {
1657  event_debug(("%s: start of read body for %s on %d\n",
1658  __func__, req->remote_host, fd));
1659  evhttp_get_body(evcon, req);
1660  }
1661  break;
1662 
1663  default:
1664  event_warnx("%s: bad header on %d", __func__, fd);
1665  evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
1666  break;
1667  }
1668 }
1669 
1670 /*
1671  * Creates a TCP connection to the specified port and executes a callback
1672  * when finished. Failure or sucess is indicate by the passed connection
1673  * object.
1674  *
1675  * Although this interface accepts a hostname, it is intended to take
1676  * only numeric hostnames so that non-blocking DNS resolution can
1677  * happen elsewhere.
1678  */
1679 
1680 struct evhttp_connection *
1681 evhttp_connection_new(const char *address, unsigned short port)
1682 {
1683  struct evhttp_connection *evcon = NULL;
1684 
1685  event_debug(("Attempting connection to %s:%d\n", address, port));
1686 
1687  if ((evcon = calloc(1, sizeof(struct evhttp_connection))) == NULL) {
1688  event_warn("%s: calloc failed", __func__);
1689  goto error;
1690  }
1691 
1692  evcon->fd = -1;
1693  evcon->port = port;
1694 
1695  evcon->timeout = -1;
1696  evcon->retry_cnt = evcon->retry_max = 0;
1697 
1698  if ((evcon->address = strdup(address)) == NULL) {
1699  event_warn("%s: strdup failed", __func__);
1700  goto error;
1701  }
1702 
1703  if ((evcon->input_buffer = evbuffer_new()) == NULL) {
1704  event_warn("%s: evbuffer_new failed", __func__);
1705  goto error;
1706  }
1707 
1708  if ((evcon->output_buffer = evbuffer_new()) == NULL) {
1709  event_warn("%s: evbuffer_new failed", __func__);
1710  goto error;
1711  }
1712 
1713  evcon->state = EVCON_DISCONNECTED;
1714  TAILQ_INIT(&evcon->requests);
1715 
1716  return (evcon);
1717 
1718  error:
1719  if (evcon != NULL)
1720  evhttp_connection_free(evcon);
1721  return (NULL);
1722 }
1723 
1725  struct event_base *base)
1726 {
1727  assert(evcon->base == NULL);
1728  assert(evcon->state == EVCON_DISCONNECTED);
1729  evcon->base = base;
1730 }
1731 
1732 void
1734  int timeout_in_secs)
1735 {
1736  evcon->timeout = timeout_in_secs;
1737 }
1738 
1739 void
1741  int retry_max)
1742 {
1743  evcon->retry_max = retry_max;
1744 }
1745 
1746 void
1748  void (*cb)(struct evhttp_connection *, void *), void *cbarg)
1749 {
1750  evcon->closecb = cb;
1751  evcon->closecb_arg = cbarg;
1752 }
1753 
1754 void
1756  char **address, u_short *port)
1757 {
1758  *address = evcon->address;
1759  *port = evcon->port;
1760 }
1761 
1762 int
1763 evhttp_connection_connect(struct evhttp_connection *evcon)
1764 {
1765  if (evcon->state == EVCON_CONNECTING)
1766  return (0);
1767 
1768  evhttp_connection_reset(evcon);
1769 
1770  assert(!(evcon->flags & EVHTTP_CON_INCOMING));
1771  evcon->flags |= EVHTTP_CON_OUTGOING;
1772 
1773  evcon->fd = bind_socket(
1774  evcon->bind_address, evcon->bind_port, 0 /*reuse*/);
1775  if (evcon->fd == -1) {
1776  event_debug(("%s: failed to bind to \"%s\"",
1777  __func__, evcon->bind_address));
1778  return (-1);
1779  }
1780 
1781  if (socket_connect(evcon->fd, evcon->address, evcon->port) == -1) {
1782  EVUTIL_CLOSESOCKET(evcon->fd); evcon->fd = -1;
1783  return (-1);
1784  }
1785 
1786  /* Set up a callback for successful connection setup */
1787  event_set(&evcon->ev, evcon->fd, EV_WRITE, evhttp_connectioncb, evcon);
1788  EVHTTP_BASE_SET(evcon, &evcon->ev);
1789  evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_CONNECT_TIMEOUT);
1790 
1791  evcon->state = EVCON_CONNECTING;
1792 
1793  return (0);
1794 }
1795 
1796 /*
1797  * Starts an HTTP request on the provided evhttp_connection object.
1798  * If the connection object is not connected to the web server already,
1799  * this will start the connection.
1800  */
1801 
1802 int
1804  struct evhttp_request *req,
1805  enum evhttp_cmd_type type, const char *uri)
1806 {
1807  /* We are making a request */
1808  req->kind = EVHTTP_REQUEST;
1809  req->type = type;
1810  if (req->uri != NULL)
1811  free(req->uri);
1812  if ((req->uri = strdup(uri)) == NULL)
1813  event_err(1, "%s: strdup", __func__);
1814 
1815  /* Set the protocol version if it is not supplied */
1816  if (!req->major && !req->minor) {
1817  req->major = 1;
1818  req->minor = 1;
1819  }
1820 
1821  assert(req->evcon == NULL);
1822  req->evcon = evcon;
1823  assert(!(req->flags & EVHTTP_REQ_OWN_CONNECTION));
1824 
1825  TAILQ_INSERT_TAIL(&evcon->requests, req, next);
1826 
1827  /* If the connection object is not connected; make it so */
1828  if (!evhttp_connected(evcon))
1829  return (evhttp_connection_connect(evcon));
1830 
1831  /*
1832  * If it's connected already and we are the first in the queue,
1833  * then we can dispatch this request immediately. Otherwise, it
1834  * will be dispatched once the pending requests are completed.
1835  */
1836  if (TAILQ_FIRST(&evcon->requests) == req)
1837  evhttp_request_dispatch(evcon);
1838 
1839  return (0);
1840 }
1841 
1842 /*
1843  * Reads data from file descriptor into request structure
1844  * Request structure needs to be set up correctly.
1845  */
1846 
1847 void
1848 evhttp_start_read(struct evhttp_connection *evcon)
1849 {
1850  /* Set up an event to read the headers */
1851  if (event_initialized(&evcon->ev))
1852  event_del(&evcon->ev);
1853  event_set(&evcon->ev, evcon->fd, EV_READ, evhttp_read, evcon);
1854  EVHTTP_BASE_SET(evcon, &evcon->ev);
1855 
1856  evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_READ_TIMEOUT);
1857  evcon->state = EVCON_READING_FIRSTLINE;
1858 }
1859 
1860 static void
1861 evhttp_send_done(struct evhttp_connection *evcon, void *arg)
1862 {
1863  int need_close;
1864  struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
1865  TAILQ_REMOVE(&evcon->requests, req, next);
1866 
1867  /* delete possible close detection events */
1868  evhttp_connection_stop_detectclose(evcon);
1869 
1870  need_close =
1871  (req->minor == 0 &&
1872  !evhttp_is_connection_keepalive(req->input_headers))||
1873  evhttp_is_connection_close(req->flags, req->input_headers) ||
1874  evhttp_is_connection_close(req->flags, req->output_headers);
1875 
1876  assert(req->flags & EVHTTP_REQ_OWN_CONNECTION);
1877  evhttp_request_free(req);
1878 
1879  if (need_close) {
1880  evhttp_connection_free(evcon);
1881  return;
1882  }
1883 
1884  /* we have a persistent connection; try to accept another request. */
1885  if (evhttp_associate_new_request_with_connection(evcon) == -1)
1886  evhttp_connection_free(evcon);
1887 }
1888 
1889 /*
1890  * Returns an error page.
1891  */
1892 
1893 void
1894 evhttp_send_error(struct evhttp_request *req, int error, const char *reason)
1895 {
1896 #define ERR_FORMAT "<HTML><HEAD>\n" \
1897  "<TITLE>%d %s</TITLE>\n" \
1898  "</HEAD><BODY>\n" \
1899  "<H1>Method Not Implemented</H1>\n" \
1900  "Invalid method in request<P>\n" \
1901  "</BODY></HTML>\n"
1902 
1903  struct evbuffer *buf = evbuffer_new();
1904 
1905  /* close the connection on error */
1906  evhttp_add_header(req->output_headers, "Connection", "close");
1907 
1908  evhttp_response_code(req, error, reason);
1909 
1910  evbuffer_add_printf(buf, ERR_FORMAT, error, reason);
1911 
1912  evhttp_send_page(req, buf);
1913 
1914  evbuffer_free(buf);
1915 #undef ERR_FORMAT
1916 }
1917 
1918 /* Requires that headers and response code are already set up */
1919 
1920 static inline void
1921 evhttp_send(struct evhttp_request *req, struct evbuffer *databuf)
1922 {
1923  struct evhttp_connection *evcon = req->evcon;
1924 
1925  assert(TAILQ_FIRST(&evcon->requests) == req);
1926 
1927  /* xxx: not sure if we really should expose the data buffer this way */
1928  if (databuf != NULL)
1929  evbuffer_add_buffer(req->output_buffer, databuf);
1930 
1931  /* Adds headers to the response */
1932  evhttp_make_header(evcon, req);
1933 
1934  evhttp_write_buffer(evcon, evhttp_send_done, NULL);
1935 }
1936 
1937 void
1938 evhttp_send_reply(struct evhttp_request *req, int code, const char *reason,
1939  struct evbuffer *databuf)
1940 {
1941  evhttp_response_code(req, code, reason);
1942 
1943  evhttp_send(req, databuf);
1944 }
1945 
1946 void
1947 evhttp_send_reply_start(struct evhttp_request *req, int code,
1948  const char *reason)
1949 {
1950  evhttp_response_code(req, code, reason);
1951  if (req->major == 1 && req->minor == 1) {
1952  /* use chunked encoding for HTTP/1.1 */
1953  evhttp_add_header(req->output_headers, "Transfer-Encoding",
1954  "chunked");
1955  req->chunked = 1;
1956  }
1957  evhttp_make_header(req->evcon, req);
1958  evhttp_write_buffer(req->evcon, NULL, NULL);
1959 }
1960 
1961 void
1962 evhttp_send_reply_chunk(struct evhttp_request *req, struct evbuffer *databuf)
1963 {
1964  if (req->chunked) {
1965  evbuffer_add_printf(req->evcon->output_buffer, "%x\r\n",
1966  (unsigned)EVBUFFER_LENGTH(databuf));
1967  }
1968  evbuffer_add_buffer(req->evcon->output_buffer, databuf);
1969  if (req->chunked) {
1970  evbuffer_add(req->evcon->output_buffer, "\r\n", 2);
1971  }
1972  evhttp_write_buffer(req->evcon, NULL, NULL);
1973 }
1974 
1975 void
1976 evhttp_send_reply_end(struct evhttp_request *req)
1977 {
1978  struct evhttp_connection *evcon = req->evcon;
1979 
1980  if (req->chunked) {
1981  evbuffer_add(req->evcon->output_buffer, "0\r\n\r\n", 5);
1982  evhttp_write_buffer(req->evcon, evhttp_send_done, NULL);
1983  req->chunked = 0;
1984  } else if (!event_pending(&evcon->ev, EV_WRITE|EV_TIMEOUT, NULL)) {
1985  /* let the connection know that we are done with the request */
1986  evhttp_send_done(evcon, NULL);
1987  } else {
1988  /* make the callback execute after all data has been written */
1989  evcon->cb = evhttp_send_done;
1990  evcon->cb_arg = NULL;
1991  }
1992 }
1993 
1994 void
1995 evhttp_response_code(struct evhttp_request *req, int code, const char *reason)
1996 {
1997  req->kind = EVHTTP_RESPONSE;
1998  req->response_code = code;
1999  if (req->response_code_line != NULL)
2000  free(req->response_code_line);
2001  req->response_code_line = strdup(reason);
2002 }
2003 
2004 void
2005 evhttp_send_page(struct evhttp_request *req, struct evbuffer *databuf)
2006 {
2007  if (!req->major || !req->minor) {
2008  req->major = 1;
2009  req->minor = 1;
2010  }
2011 
2012  if (req->kind != EVHTTP_RESPONSE)
2013  evhttp_response_code(req, 200, "OK");
2014 
2015  evhttp_clear_headers(req->output_headers);
2016  evhttp_add_header(req->output_headers, "Content-Type", "text/html");
2017  evhttp_add_header(req->output_headers, "Connection", "close");
2018 
2019  evhttp_send(req, databuf);
2020 }
2021 
2022 static const char uri_chars[256] = {
2023  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2024  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2025  0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2026  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0,
2027  /* 64 */
2028  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2029  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
2030  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2031  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0,
2032  /* 128 */
2033  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2034  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2035  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2036  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2037  /* 192 */
2038  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2039  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2040  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2041  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2042 };
2043 
2044 /*
2045  * Helper functions to encode/decode a URI.
2046  * The returned string must be freed by the caller.
2047  */
2048 char *
2049 evhttp_encode_uri(const char *uri)
2050 {
2051  struct evbuffer *buf = evbuffer_new();
2052  char *p;
2053 
2054  for (p = (char *)uri; *p != '\0'; p++) {
2055  if (uri_chars[(u_char)(*p)]) {
2056  evbuffer_add(buf, p, 1);
2057  } else {
2058  evbuffer_add_printf(buf, "%%%02X", (u_char)(*p));
2059  }
2060  }
2061  evbuffer_add(buf, "", 1);
2062  p = strdup((char *)EVBUFFER_DATA(buf));
2063  evbuffer_free(buf);
2064 
2065  return (p);
2066 }
2067 
2068 /*
2069  * @param always_decode_plus: when true we transform plus to space even
2070  * if we have not seen a ?.
2071  */
2072 static int
2073 evhttp_decode_uri_internal(
2074  const char *uri, size_t length, char *ret, int always_decode_plus)
2075 {
2076  char c;
2077  int i, j, in_query = always_decode_plus;
2078 
2079  for (i = j = 0; uri[i] != '\0'; i++) {
2080  c = uri[i];
2081  if (c == '?') {
2082  in_query = 1;
2083  } else if (c == '+' && in_query) {
2084  c = ' ';
2085  } else if (c == '%' && isxdigit((unsigned char)uri[i+1]) &&
2086  isxdigit((unsigned char)uri[i+2])) {
2087  char tmp[] = { uri[i+1], uri[i+2], '\0' };
2088  c = (char)strtol(tmp, NULL, 16);
2089  i += 2;
2090  }
2091  ret[j++] = c;
2092  }
2093  ret[j] = '\0';
2094 
2095  return (j);
2096 }
2097 
2098 char *
2099 evhttp_decode_uri(const char *uri)
2100 {
2101  char *ret;
2102 
2103  if ((ret = malloc(strlen(uri) + 1)) == NULL)
2104  event_err(1, "%s: malloc(%lu)", __func__,
2105  (unsigned long)(strlen(uri) + 1));
2106 
2107  evhttp_decode_uri_internal(uri, strlen(uri),
2108  ret, 0 /*always_decode_plus*/);
2109 
2110  return (ret);
2111 }
2112 
2113 /*
2114  * Helper function to parse out arguments in a query.
2115  * The arguments are separated by key and value.
2116  */
2117 
2118 void
2119 evhttp_parse_query(const char *uri, struct evkeyvalq *headers)
2120 {
2121  char *line;
2122  char *argument;
2123  char *p;
2124 
2125  TAILQ_INIT(headers);
2126 
2127  /* No arguments - we are done */
2128  if (strchr(uri, '?') == NULL)
2129  return;
2130 
2131  if ((line = strdup(uri)) == NULL)
2132  event_err(1, "%s: strdup", __func__);
2133 
2134 
2135  argument = line;
2136 
2137  /* We already know that there has to be a ? */
2138  strsep(&argument, "?");
2139 
2140  p = argument;
2141  while (p != NULL && *p != '\0') {
2142  char *key, *value, *decoded_value;
2143  argument = strsep(&p, "&");
2144 
2145  value = argument;
2146  key = strsep(&value, "=");
2147  if (value == NULL)
2148  goto error;
2149 
2150  if ((decoded_value = malloc(strlen(value) + 1)) == NULL)
2151  event_err(1, "%s: malloc", __func__);
2152 
2153  evhttp_decode_uri_internal(value, strlen(value),
2154  decoded_value, 1 /*always_decode_plus*/);
2155  event_debug(("Query Param: %s -> %s\n", key, decoded_value));
2156  evhttp_add_header_internal(headers, key, decoded_value);
2157  free(decoded_value);
2158  }
2159 
2160  error:
2161  free(line);
2162 }
2163 
2164 static struct evhttp_cb *
2165 evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req)
2166 {
2167  struct evhttp_cb *cb;
2168  size_t offset = 0;
2169 
2170  /* Test for different URLs */
2171  char *p = strchr(req->uri, '?');
2172  if (p != NULL)
2173  offset = (size_t)(p - req->uri);
2174 
2175  TAILQ_FOREACH(cb, callbacks, next) {
2176  int res = 0;
2177  if (p == NULL) {
2178  res = strcmp(cb->what, req->uri) == 0;
2179  } else {
2180  res = ((strncmp(cb->what, req->uri, offset) == 0) &&
2181  (cb->what[offset] == '\0'));
2182  }
2183 
2184  if (res)
2185  return (cb);
2186  }
2187 
2188  return (NULL);
2189 }
2190 
2191 static void
2192 evhttp_handle_request(struct evhttp_request *req, void *arg)
2193 {
2194  struct evhttp *http = arg;
2195  struct evhttp_cb *cb = NULL;
2196 
2197  if (req->uri == NULL) {
2198  evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request");
2199  return;
2200  }
2201 
2202  if ((cb = evhttp_dispatch_callback(&http->callbacks, req)) != NULL) {
2203  (*cb->cb)(req, cb->cbarg);
2204  return;
2205  }
2206 
2207  /* Generic call back */
2208  if (http->gencb) {
2209  (*http->gencb)(req, http->gencbarg);
2210  return;
2211  } else {
2212  /* We need to send a 404 here */
2213 #define ERR_FORMAT "<html><head>" \
2214  "<title>404 Not Found</title>" \
2215  "</head><body>" \
2216  "<h1>Not Found</h1>" \
2217  "<p>The requested URL %s was not found on this server.</p>"\
2218  "</body></html>\n"
2219 
2220  char *escaped_html = evhttp_htmlescape(req->uri);
2221  struct evbuffer *buf = evbuffer_new();
2222 
2223  evhttp_response_code(req, HTTP_NOTFOUND, "Not Found");
2224 
2225  evbuffer_add_printf(buf, ERR_FORMAT, escaped_html);
2226 
2227  free(escaped_html);
2228 
2229  evhttp_send_page(req, buf);
2230 
2231  evbuffer_free(buf);
2232 #undef ERR_FORMAT
2233  }
2234 }
2235 
2236 static void
2237 accept_socket(int fd, short what, void *arg)
2238 {
2239  struct evhttp *http = arg;
2240  struct sockaddr_storage ss;
2241  socklen_t addrlen = sizeof(ss);
2242  int nfd;
2243 
2244  if ((nfd = accept(fd, (struct sockaddr *)&ss, &addrlen)) == -1) {
2245  if (errno != EAGAIN && errno != EINTR)
2246  event_warn("%s: bad accept", __func__);
2247  return;
2248  }
2249  if (evutil_make_socket_nonblocking(nfd) < 0)
2250  return;
2251 
2252  evhttp_get_request(http, nfd, (struct sockaddr *)&ss, addrlen);
2253 }
2254 
2255 int
2256 evhttp_bind_socket(struct evhttp *http, const char *address, u_short port)
2257 {
2258  int fd;
2259  int res;
2260 
2261  if ((fd = bind_socket(address, port, 1 /*reuse*/)) == -1)
2262  return (-1);
2263 
2264  if (listen(fd, 128) == -1) {
2265  event_warn("%s: listen", __func__);
2266  EVUTIL_CLOSESOCKET(fd);
2267  return (-1);
2268  }
2269 
2270  res = evhttp_accept_socket(http, fd);
2271 
2272  if (res != -1)
2273  event_debug(("Bound to port %d - Awaiting connections ... ",
2274  port));
2275 
2276  return (res);
2277 }
2278 
2279 int
2280 evhttp_accept_socket(struct evhttp *http, int fd)
2281 {
2282  struct evhttp_bound_socket *bound;
2283  struct event *ev;
2284  int res;
2285 
2286  bound = malloc(sizeof(struct evhttp_bound_socket));
2287  if (bound == NULL)
2288  return (-1);
2289 
2290  ev = &bound->bind_ev;
2291 
2292  /* Schedule the socket for accepting */
2293  event_set(ev, fd, EV_READ | EV_PERSIST, accept_socket, http);
2294  EVHTTP_BASE_SET(http, ev);
2295 
2296  res = event_add(ev, NULL);
2297 
2298  if (res == -1) {
2299  free(bound);
2300  return (-1);
2301  }
2302 
2303  TAILQ_INSERT_TAIL(&http->sockets, bound, next);
2304 
2305  return (0);
2306 }
2307 
2308 static struct evhttp*
2309 evhttp_new_object(void)
2310 {
2311  struct evhttp *http = NULL;
2312 
2313  if ((http = calloc(1, sizeof(struct evhttp))) == NULL) {
2314  event_warn("%s: calloc", __func__);
2315  return (NULL);
2316  }
2317 
2318  http->timeout = -1;
2319 
2320  TAILQ_INIT(&http->sockets);
2321  TAILQ_INIT(&http->callbacks);
2322  TAILQ_INIT(&http->connections);
2323 
2324  return (http);
2325 }
2326 
2327 struct evhttp *
2328 evhttp_new(struct event_base *base)
2329 {
2330  struct evhttp *http = evhttp_new_object();
2331 
2332  http->base = base;
2333 
2334  return (http);
2335 }
2336 
2337 /*
2338  * Start a web server on the specified address and port.
2339  */
2340 
2341 struct evhttp *
2342 evhttp_start(const char *address, u_short port)
2343 {
2344  struct evhttp *http = evhttp_new_object();
2345 
2346  if (evhttp_bind_socket(http, address, port) == -1) {
2347  free(http);
2348  return (NULL);
2349  }
2350 
2351  return (http);
2352 }
2353 
2354 void
2355 evhttp_free(struct evhttp* http)
2356 {
2357  struct evhttp_cb *http_cb;
2358  struct evhttp_connection *evcon;
2359  struct evhttp_bound_socket *bound;
2360  int fd;
2361 
2362  /* Remove the accepting part */
2363  while ((bound = TAILQ_FIRST(&http->sockets)) != NULL) {
2364  TAILQ_REMOVE(&http->sockets, bound, next);
2365 
2366  fd = bound->bind_ev.ev_fd;
2367  event_del(&bound->bind_ev);
2368  EVUTIL_CLOSESOCKET(fd);
2369 
2370  free(bound);
2371  }
2372 
2373  while ((evcon = TAILQ_FIRST(&http->connections)) != NULL) {
2374  /* evhttp_connection_free removes the connection */
2375  evhttp_connection_free(evcon);
2376  }
2377 
2378  while ((http_cb = TAILQ_FIRST(&http->callbacks)) != NULL) {
2379  TAILQ_REMOVE(&http->callbacks, http_cb, next);
2380  free(http_cb->what);
2381  free(http_cb);
2382  }
2383 
2384  free(http);
2385 }
2386 
2387 void
2388 evhttp_set_timeout(struct evhttp* http, int timeout_in_secs)
2389 {
2390  http->timeout = timeout_in_secs;
2391 }
2392 
2393 void
2394 evhttp_set_cb(struct evhttp *http, const char *uri,
2395  void (*cb)(struct evhttp_request *, void *), void *cbarg)
2396 {
2397  struct evhttp_cb *http_cb;
2398 
2399  if ((http_cb = calloc(1, sizeof(struct evhttp_cb))) == NULL)
2400  event_err(1, "%s: calloc", __func__);
2401 
2402  http_cb->what = strdup(uri);
2403  http_cb->cb = cb;
2404  http_cb->cbarg = cbarg;
2405 
2406  TAILQ_INSERT_TAIL(&http->callbacks, http_cb, next);
2407 }
2408 
2409 int
2410 evhttp_del_cb(struct evhttp *http, const char *uri)
2411 {
2412  struct evhttp_cb *http_cb;
2413 
2414  TAILQ_FOREACH(http_cb, &http->callbacks, next) {
2415  if (strcmp(http_cb->what, uri) == 0)
2416  break;
2417  }
2418  if (http_cb == NULL)
2419  return (-1);
2420 
2421  TAILQ_REMOVE(&http->callbacks, http_cb, next);
2422  free(http_cb->what);
2423  free(http_cb);
2424 
2425  return (0);
2426 }
2427 
2428 void
2430  void (*cb)(struct evhttp_request *, void *), void *cbarg)
2431 {
2432  http->gencb = cb;
2433  http->gencbarg = cbarg;
2434 }
2435 
2436 /*
2437  * Request related functions
2438  */
2439 
2440 struct evhttp_request *
2441 evhttp_request_new(void (*cb)(struct evhttp_request *, void *), void *arg)
2442 {
2443  struct evhttp_request *req = NULL;
2444 
2445  /* Allocate request structure */
2446  if ((req = calloc(1, sizeof(struct evhttp_request))) == NULL) {
2447  event_warn("%s: calloc", __func__);
2448  goto error;
2449  }
2450 
2451  req->kind = EVHTTP_RESPONSE;
2452  req->input_headers = calloc(1, sizeof(struct evkeyvalq));
2453  if (req->input_headers == NULL) {
2454  event_warn("%s: calloc", __func__);
2455  goto error;
2456  }
2457  TAILQ_INIT(req->input_headers);
2458 
2459  req->output_headers = calloc(1, sizeof(struct evkeyvalq));
2460  if (req->output_headers == NULL) {
2461  event_warn("%s: calloc", __func__);
2462  goto error;
2463  }
2464  TAILQ_INIT(req->output_headers);
2465 
2466  if ((req->input_buffer = evbuffer_new()) == NULL) {
2467  event_warn("%s: evbuffer_new", __func__);
2468  goto error;
2469  }
2470 
2471  if ((req->output_buffer = evbuffer_new()) == NULL) {
2472  event_warn("%s: evbuffer_new", __func__);
2473  goto error;
2474  }
2475 
2476  req->cb = cb;
2477  req->cb_arg = arg;
2478 
2479  return (req);
2480 
2481  error:
2482  if (req != NULL)
2483  evhttp_request_free(req);
2484  return (NULL);
2485 }
2486 
2487 void
2489 {
2490  if (req->remote_host != NULL)
2491  free(req->remote_host);
2492  if (req->uri != NULL)
2493  free(req->uri);
2494  if (req->response_code_line != NULL)
2495  free(req->response_code_line);
2496 
2497  evhttp_clear_headers(req->input_headers);
2498  free(req->input_headers);
2499 
2500  evhttp_clear_headers(req->output_headers);
2501  free(req->output_headers);
2502 
2503  if (req->input_buffer != NULL)
2504  evbuffer_free(req->input_buffer);
2505 
2506  if (req->output_buffer != NULL)
2507  evbuffer_free(req->output_buffer);
2508 
2509  free(req);
2510 }
2511 
2512 void
2514  void (*cb)(struct evhttp_request *, void *))
2515 {
2516  req->chunk_cb = cb;
2517 }
2518 
2519 /*
2520  * Allows for inspection of the request URI
2521  */
2522 
2523 const char *
2524 evhttp_request_uri(struct evhttp_request *req) {
2525  if (req->uri == NULL)
2526  event_debug(("%s: request %p has no uri\n", __func__, req));
2527  return (req->uri);
2528 }
2529 
2530 /*
2531  * Takes a file descriptor to read a request from.
2532  * The callback is executed once the whole request has been read.
2533  */
2534 
2535 static struct evhttp_connection*
2536 evhttp_get_request_connection(
2537  struct evhttp* http,
2538  int fd, struct sockaddr *sa, socklen_t salen)
2539 {
2540  struct evhttp_connection *evcon;
2541  char *hostname = NULL, *portname = NULL;
2542 
2543  name_from_addr(sa, salen, &hostname, &portname);
2544  if (hostname == NULL || portname == NULL) {
2545  if (hostname) free(hostname);
2546  if (portname) free(portname);
2547  return (NULL);
2548  }
2549 
2550  event_debug(("%s: new request from %s:%s on %d\n",
2551  __func__, hostname, portname, fd));
2552 
2553  /* we need a connection object to put the http request on */
2554  evcon = evhttp_connection_new(hostname, atoi(portname));
2555  free(hostname);
2556  free(portname);
2557  if (evcon == NULL)
2558  return (NULL);
2559 
2560  /* associate the base if we have one*/
2561  evhttp_connection_set_base(evcon, http->base);
2562 
2563  evcon->flags |= EVHTTP_CON_INCOMING;
2564  evcon->state = EVCON_READING_FIRSTLINE;
2565 
2566  evcon->fd = fd;
2567 
2568  return (evcon);
2569 }
2570 
2571 static int
2572 evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
2573 {
2574  struct evhttp *http = evcon->http_server;
2575  struct evhttp_request *req;
2576  if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL)
2577  return (-1);
2578 
2579  req->evcon = evcon; /* the request ends up owning the connection */
2580  req->flags |= EVHTTP_REQ_OWN_CONNECTION;
2581 
2582  TAILQ_INSERT_TAIL(&evcon->requests, req, next);
2583 
2584  req->kind = EVHTTP_REQUEST;
2585 
2586  if ((req->remote_host = strdup(evcon->address)) == NULL)
2587  event_err(1, "%s: strdup", __func__);
2588  req->remote_port = evcon->port;
2589 
2590  evhttp_start_read(evcon);
2591 
2592  return (0);
2593 }
2594 
2595 void
2596 evhttp_get_request(struct evhttp *http, int fd,
2597  struct sockaddr *sa, socklen_t salen)
2598 {
2599  struct evhttp_connection *evcon;
2600 
2601  evcon = evhttp_get_request_connection(http, fd, sa, salen);
2602  if (evcon == NULL)
2603  return;
2604 
2605  /* the timeout can be used by the server to close idle connections */
2606  if (http->timeout != -1)
2607  evhttp_connection_set_timeout(evcon, http->timeout);
2608 
2609  /*
2610  * if we want to accept more than one request on a connection,
2611  * we need to know which http server it belongs to.
2612  */
2613  evcon->http_server = http;
2614  TAILQ_INSERT_TAIL(&http->connections, evcon, next);
2615 
2616  if (evhttp_associate_new_request_with_connection(evcon) == -1)
2617  evhttp_connection_free(evcon);
2618 }
2619 
2620 
2621 /*
2622  * Network helper functions that we do not want to export to the rest of
2623  * the world.
2624  */
2625 #if 0 /* Unused */
2626 static struct addrinfo *
2627 addr_from_name(char *address)
2628 {
2629 #ifdef HAVE_GETADDRINFO
2630  struct addrinfo ai, *aitop;
2631  int ai_result;
2632 
2633  memset(&ai, 0, sizeof(ai));
2634  ai.ai_family = AF_INET;
2635  ai.ai_socktype = SOCK_RAW;
2636  ai.ai_flags = 0;
2637  if ((ai_result = getaddrinfo(address, NULL, &ai, &aitop)) != 0) {
2638  if ( ai_result == EAI_SYSTEM )
2639  event_warn("getaddrinfo");
2640  else
2641  event_warnx("getaddrinfo: %s", gai_strerror(ai_result));
2642  }
2643 
2644  return (aitop);
2645 #else
2646  assert(0);
2647  return NULL; /* XXXXX Use gethostbyname, if this function is ever used. */
2648 #endif
2649 }
2650 #endif
2651 
2652 static void
2653 name_from_addr(struct sockaddr *sa, socklen_t salen,
2654  char **phost, char **pport)
2655 {
2656  char ntop[NI_MAXHOST];
2657  char strport[NI_MAXSERV];
2658  int ni_result;
2659 
2660 #ifdef HAVE_GETNAMEINFO
2661  ni_result = getnameinfo(sa, salen,
2662  ntop, sizeof(ntop), strport, sizeof(strport),
2663  NI_NUMERICHOST|NI_NUMERICSERV);
2664 
2665  if (ni_result != 0) {
2666  if (ni_result == EAI_SYSTEM)
2667  event_err(1, "getnameinfo failed");
2668  else
2669  event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
2670  return;
2671  }
2672 #else
2673  ni_result = fake_getnameinfo(sa, salen,
2674  ntop, sizeof(ntop), strport, sizeof(strport),
2675  NI_NUMERICHOST|NI_NUMERICSERV);
2676  if (ni_result != 0)
2677  return;
2678 #endif
2679  *phost = strdup(ntop);
2680  *pport = strdup(strport);
2681 }
2682 
2683 /* Create a non-blocking socket and bind it */
2684 /* todo: rename this function */
2685 static int
2686 bind_socket_ai(struct addrinfo *ai, int reuse)
2687 {
2688  int fd, on = 1, r;
2689  int serrno;
2690 
2691  /* Create listen socket */
2692  fd = socket(AF_INET, SOCK_STREAM, 0);
2693  if (fd == -1) {
2694  event_warn("socket");
2695  return (-1);
2696  }
2697 
2698  if (evutil_make_socket_nonblocking(fd) < 0)
2699  goto out;
2700 
2701 #ifndef WIN32
2702  if (fcntl(fd, F_SETFD, 1) == -1) {
2703  event_warn("fcntl(F_SETFD)");
2704  goto out;
2705  }
2706 #endif
2707 
2708  setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
2709  if (reuse) {
2710  setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2711  (void *)&on, sizeof(on));
2712  }
2713 
2714  if (ai != NULL) {
2715  r = bind(fd, ai->ai_addr, ai->ai_addrlen);
2716  if (r == -1)
2717  goto out;
2718  }
2719 
2720  return (fd);
2721 
2722  out:
2723  serrno = EVUTIL_SOCKET_ERROR();
2724  EVUTIL_CLOSESOCKET(fd);
2725  EVUTIL_SET_SOCKET_ERROR(serrno);
2726  return (-1);
2727 }
2728 
2729 static struct addrinfo *
2730 make_addrinfo(const char *address, u_short port)
2731 {
2732  struct addrinfo *aitop = NULL;
2733 
2734 #ifdef HAVE_GETADDRINFO
2735  struct addrinfo ai;
2736  char strport[NI_MAXSERV];
2737  int ai_result;
2738 
2739  memset(&ai, 0, sizeof(ai));
2740  ai.ai_family = AF_INET;
2741  ai.ai_socktype = SOCK_STREAM;
2742  ai.ai_flags = AI_PASSIVE; /* turn NULL host name into INADDR_ANY */
2743  evutil_snprintf(strport, sizeof(strport), "%d", port);
2744  if ((ai_result = getaddrinfo(address, strport, &ai, &aitop)) != 0) {
2745  if ( ai_result == EAI_SYSTEM )
2746  event_warn("getaddrinfo");
2747  else
2748  event_warnx("getaddrinfo: %s", gai_strerror(ai_result));
2749  return (NULL);
2750  }
2751 #else
2752  static int cur;
2753  static struct addrinfo ai[2]; /* We will be returning the address of some of this memory so it has to last even after this call. */
2754  if (++cur == 2) cur = 0; /* allow calling this function twice */
2755 
2756  if (fake_getaddrinfo(address, &ai[cur]) < 0) {
2757  event_warn("fake_getaddrinfo");
2758  return (NULL);
2759  }
2760  aitop = &ai[cur];
2761  ((struct sockaddr_in *) aitop->ai_addr)->sin_port = htons(port);
2762 #endif
2763 
2764  return (aitop);
2765 }
2766 
2767 static int
2768 bind_socket(const char *address, u_short port, int reuse)
2769 {
2770  int fd;
2771  struct addrinfo *aitop = NULL;
2772 
2773  /* just create an unbound socket */
2774  if (address == NULL && port == 0)
2775  return bind_socket_ai(NULL, 0);
2776 
2777  aitop = make_addrinfo(address, port);
2778 
2779  if (aitop == NULL)
2780  return (-1);
2781 
2782  fd = bind_socket_ai(aitop, reuse);
2783 
2784 #ifdef HAVE_GETADDRINFO
2785  freeaddrinfo(aitop);
2786 #else
2787  fake_freeaddrinfo(aitop);
2788 #endif
2789 
2790  return (fd);
2791 }
2792 
2793 static int
2794 socket_connect(int fd, const char *address, unsigned short port)
2795 {
2796  struct addrinfo *ai = make_addrinfo(address, port);
2797  int res = -1;
2798 
2799  if (ai == NULL) {
2800  event_debug(("%s: make_addrinfo: \"%s:%d\"",
2801  __func__, address, port));
2802  return (-1);
2803  }
2804 
2805  if (connect(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
2806 #ifdef WIN32
2807  int tmp_error = WSAGetLastError();
2808  if (tmp_error != WSAEWOULDBLOCK && tmp_error != WSAEINVAL &&
2809  tmp_error != WSAEINPROGRESS) {
2810  goto out;
2811  }
2812 #else
2813  if (errno != EINPROGRESS) {
2814  goto out;
2815  }
2816 #endif
2817  }
2818 
2819  /* everything is fine */
2820  res = 0;
2821 
2822 out:
2823 #ifdef HAVE_GETADDRINFO
2824  freeaddrinfo(ai);
2825 #else
2826  fake_freeaddrinfo(ai);
2827 #endif
2828 
2829  return (res);
2830 }