Merged revisions 135473 via svnmerge from
[asterisk/asterisk.git] / main / http.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file 
21  * \brief http server for AMI access
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * This program implements a tiny http server
26  * and was inspired by micro-httpd by Jef Poskanzer 
27  * 
28  * \ref AstHTTP - AMI over the http protocol
29  */
30
31 #include "asterisk.h"
32
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34
35 #include <time.h>
36 #include <sys/time.h>
37 #include <sys/stat.h>
38 #include <sys/signal.h>
39 #include <fcntl.h>
40
41 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
42 #include "asterisk/network.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/tcptls.h"
45 #include "asterisk/http.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/strings.h"
48 #include "asterisk/config.h"
49 #include "asterisk/stringfields.h"
50 #include "asterisk/ast_version.h"
51 #include "asterisk/manager.h"
52 #include "asterisk/_private.h"
53
54 #define MAX_PREFIX 80
55
56 /* See http.h for more information about the SSL implementation */
57 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
58 #define DO_SSL  /* comment in/out if you want to support ssl */
59 #endif
60
61 static struct ast_tls_config http_tls_cfg;
62
63 static void *httpd_helper_thread(void *arg);
64
65 /*!
66  * we have up to two accepting threads, one for http, one for https
67  */
68 static struct server_args http_desc = {
69         .accept_fd = -1,
70         .master = AST_PTHREADT_NULL,
71         .tls_cfg = NULL,
72         .poll_timeout = -1,
73         .name = "http server",
74         .accept_fn = ast_tcptls_server_root,
75         .worker_fn = httpd_helper_thread,
76 };
77
78 static struct server_args https_desc = {
79         .accept_fd = -1,
80         .master = AST_PTHREADT_NULL,
81         .tls_cfg = &http_tls_cfg,
82         .poll_timeout = -1,
83         .name = "https server",
84         .accept_fn = ast_tcptls_server_root,
85         .worker_fn = httpd_helper_thread,
86 };
87
88 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri);      /*!< list of supported handlers */
89
90 /* all valid URIs must be prepended by the string in prefix. */
91 static char prefix[MAX_PREFIX];
92 static int enablestatic;
93
94 /*! \brief Limit the kinds of files we're willing to serve up */
95 static struct {
96         const char *ext;
97         const char *mtype;
98 } mimetypes[] = {
99         { "png", "image/png" },
100         { "jpg", "image/jpeg" },
101         { "js", "application/x-javascript" },
102         { "wav", "audio/x-wav" },
103         { "mp3", "audio/mpeg" },
104         { "svg", "image/svg+xml" },
105         { "svgz", "image/svg+xml" },
106         { "gif", "image/gif" },
107 };
108
109 struct http_uri_redirect {
110         AST_LIST_ENTRY(http_uri_redirect) entry;
111         char *dest;
112         char target[0];
113 };
114
115 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
116
117 static const char *ftype2mtype(const char *ftype, char *wkspace, int wkspacelen)
118 {
119         int x;
120
121         if (ftype) {
122                 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
123                         if (!strcasecmp(ftype, mimetypes[x].ext)) {
124                                 return mimetypes[x].mtype;
125                         }
126                 }
127         }
128
129         snprintf(wkspace, wkspacelen, "text/%s", S_OR(ftype, "plain"));
130
131         return wkspace;
132 }
133
134 static uint32_t manid_from_vars(struct ast_variable *sid) {
135         uint32_t mngid;
136
137         while (sid && strcmp(sid->name, "mansession_id"))
138                 sid = sid->next;
139         
140         if (!sid || sscanf(sid->value, "%x", &mngid) != 1)
141                 return 0;
142         
143         return mngid;
144 }
145
146 void ast_http_prefix(char *buf, int len)
147 {
148         if (buf) {
149                 ast_copy_string(buf, prefix, len);
150         }
151 }
152
153 static struct ast_str *static_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *vars, struct ast_variable *headers, int *status, char **title, int *contentlength)
154 {
155         char *path;
156         char *ftype;
157         const char *mtype;
158         char wkspace[80];
159         struct stat st;
160         int len;
161         int fd;
162         struct timeval tv = ast_tvnow();
163         char buf[256];
164         struct ast_tm tm;
165
166         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration 
167            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
168         if (!enablestatic || ast_strlen_zero(uri)) {
169                 goto out403;
170         }
171
172         /* Disallow any funny filenames at all */
173         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
174                 goto out403;
175         }
176
177         if (strstr(uri, "/..")) {
178                 goto out403;
179         }
180                 
181         if ((ftype = strrchr(uri, '.'))) {
182                 ftype++;
183         }
184
185         mtype = ftype2mtype(ftype, wkspace, sizeof(wkspace));
186         
187         /* Cap maximum length */
188         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
189                 goto out403;
190         }
191                 
192         path = alloca(len);
193         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
194         if (stat(path, &st)) {
195                 goto out404;
196         }
197
198         if (S_ISDIR(st.st_mode)) {
199                 goto out404;
200         }       
201
202         if ((fd = open(path, O_RDONLY)) < 0) {
203                 goto out403;
204         }
205
206         if (strstr(path, "/private/") && !astman_is_authed(manid_from_vars(vars))) {
207                 goto out403;
208         }
209
210         ast_strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S %Z", ast_localtime(&tv, &tm, "GMT"));
211         fprintf(ser->f, "HTTP/1.1 200 OK\r\n"
212                 "Server: Asterisk/%s\r\n"
213                 "Date: %s\r\n"
214                 "Connection: close\r\n"
215                 "Cache-Control: no-cache, no-store\r\n"
216                 "Content-Length: %d\r\n"
217                 "Content-type: %s\r\n\r\n",
218                 ast_get_version(), buf, (int) st.st_size, mtype);
219
220         while ((len = read(fd, buf, sizeof(buf))) > 0) {
221                 fwrite(buf, 1, len, ser->f);
222         }
223
224         close(fd);
225
226         return NULL;
227
228 out404:
229         return ast_http_error((*status = 404),
230                               (*title = ast_strdup("Not Found")),
231                                NULL, "The requested URL was not found on this server.");
232
233 out403:
234         return ast_http_error((*status = 403),
235                               (*title = ast_strdup("Access Denied")),
236                               NULL, "You do not have permission to access the requested URL.");
237 }
238
239
240 static struct ast_str *httpstatus_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *vars, struct ast_variable *headers, int *status, char **title, int *contentlength)
241 {
242         struct ast_str *out = ast_str_create(512);
243         struct ast_variable *v;
244
245         if (out == NULL) {
246                 return out;
247         }
248
249         ast_str_append(&out, 0,
250                        "\r\n"
251                        "<title>Asterisk HTTP Status</title>\r\n"
252                        "<body bgcolor=\"#ffffff\">\r\n"
253                        "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
254                        "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
255         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
256         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
257                        ast_inet_ntoa(http_desc.oldsin.sin_addr));
258         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%d</b></td></tr>\r\n",
259                        ntohs(http_desc.oldsin.sin_port));
260
261         if (http_tls_cfg.enabled) {
262                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%d</b></td></tr>\r\n",
263                                ntohs(https_desc.oldsin.sin_port));
264         }
265
266         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
267
268         for (v = vars; v; v = v->next) {
269                 if (strncasecmp(v->name, "cookie_", 7)) {
270                         ast_str_append(&out, 0, "<tr><td><i>Submitted Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
271                 }
272         }
273
274         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
275
276         for (v = vars; v; v = v->next) {
277                 if (!strncasecmp(v->name, "cookie_", 7)) {
278                         ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
279                 }
280         }
281
282         ast_str_append(&out, 0, "</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body>\r\n");
283         return out;
284 }
285
286 static struct ast_http_uri statusuri = {
287         .callback = httpstatus_callback,
288         .description = "Asterisk HTTP General Status",
289         .uri = "httpstatus",
290         .supports_get = 1,
291         .data = NULL,
292         .key = __FILE__,
293 };
294         
295 static struct ast_http_uri staticuri = {
296         .callback = static_callback,
297         .description = "Asterisk HTTP Static Delivery",
298         .uri = "static",
299         .has_subtree = 1,
300         .static_content = 1,
301         .supports_get = 1,
302         .data = NULL,
303         .key= __FILE__,
304 };
305         
306 struct ast_str *ast_http_error(int status, const char *title, const char *extra_header, const char *text)
307 {
308         struct ast_str *out = ast_str_create(512);
309
310         if (out == NULL) {
311                 return out;
312         }
313
314         ast_str_set(&out, 0,
315                     "Content-type: text/html\r\n"
316                     "%s"
317                     "\r\n"
318                     "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
319                     "<html><head>\r\n"
320                     "<title>%d %s</title>\r\n"
321                     "</head><body>\r\n"
322                     "<h1>%s</h1>\r\n"
323                     "<p>%s</p>\r\n"
324                     "<hr />\r\n"
325                     "<address>Asterisk Server</address>\r\n"
326                     "</body></html>\r\n",
327                     (extra_header ? extra_header : ""), status, title, title, text);
328
329         return out;
330 }
331
332 /*! \brief 
333  * Link the new uri into the list. 
334  *
335  * They are sorted by length of
336  * the string, not alphabetically. Duplicate entries are not replaced,
337  * but the insertion order (using <= and not just <) makes sure that
338  * more recent insertions hide older ones.
339  * On a lookup, we just scan the list and stop at the first matching entry.
340  */
341 int ast_http_uri_link(struct ast_http_uri *urih)
342 {
343         struct ast_http_uri *uri;
344         int len = strlen(urih->uri);
345
346         if (!(urih->supports_get || urih->supports_post)) {
347                 ast_log(LOG_WARNING, "URI handler does not provide either GET or POST method: %s (%s)\n", urih->uri, urih->description);
348                 return -1;
349         }
350
351         AST_RWLIST_WRLOCK(&uris);
352
353         if (AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len) {
354                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
355                 AST_RWLIST_UNLOCK(&uris);
356
357                 return 0;
358         }
359
360         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
361                 if (AST_RWLIST_NEXT(uri, entry) &&
362                     strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
363                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
364                         AST_RWLIST_UNLOCK(&uris); 
365
366                         return 0;
367                 }
368         }
369
370         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
371
372         AST_RWLIST_UNLOCK(&uris);
373         
374         return 0;
375 }       
376
377 void ast_http_uri_unlink(struct ast_http_uri *urih)
378 {
379         AST_RWLIST_WRLOCK(&uris);
380         AST_RWLIST_REMOVE(&uris, urih, entry);
381         AST_RWLIST_UNLOCK(&uris);
382 }
383
384 void ast_http_uri_unlink_all_with_key(const char *key)
385 {
386         struct ast_http_uri *urih;
387         AST_RWLIST_WRLOCK(&uris);
388         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
389                 if (!strcmp(urih->key, key)) {
390                         AST_RWLIST_REMOVE_CURRENT(entry);
391                 }
392         }
393         AST_RWLIST_TRAVERSE_SAFE_END
394         AST_RWLIST_UNLOCK(&uris);
395 }
396
397 /*
398  * Decode special characters in http uri.
399  * We have ast_uri_decode to handle %XX sequences, but spaces
400  * are encoded as a '+' so we need to replace them beforehand.
401  */
402 static void http_decode(char *s)
403 {
404         char *t;
405         
406         for (t = s; *t; t++) {
407                 if (*t == '+')
408                         *t = ' ';
409         }
410
411         ast_uri_decode(s);
412 }
413
414 static struct ast_str *handle_uri(struct ast_tcptls_session_instance *ser, char *uri, enum ast_http_method method,
415                                   int *status, char **title, int *contentlength, struct ast_variable **cookies, struct ast_variable *headers, 
416                                   unsigned int *static_content)
417 {
418         char *c;
419         struct ast_str *out = NULL;
420         char *params = uri;
421         struct ast_http_uri *urih = NULL;
422         int l;
423         struct ast_variable *vars = NULL, *v, *prev = NULL;
424         struct http_uri_redirect *redirect;
425         int saw_method = 0;
426
427         /* preserve previous behavior of only support URI parameters on GET requests */
428         if (method == AST_HTTP_GET) {
429                 strsep(&params, "?");
430                 
431                 /* Extract arguments from the request and store them in variables.
432                  * Note that a request can have multiple arguments with the same
433                  * name, and we store them all in the list of variables.
434                  * It is up to the application to handle multiple values.
435                  */
436                 if (params) {
437                         char *var, *val;
438                         
439                         while ((val = strsep(&params, "&"))) {
440                                 var = strsep(&val, "=");
441                                 if (val) {
442                                         http_decode(val);
443                                 } else {
444                                         val = "";
445                                 }
446                                 http_decode(var);
447                                 if ((v = ast_variable_new(var, val, ""))) {
448                                         if (vars) {
449                                                 prev->next = v;
450                                         } else {
451                                                 vars = v;
452                                         }
453                                         prev = v;
454                                 }
455                         }
456                 }
457         }
458
459         /*
460          * Append the cookies to the list of variables.
461          * This saves a pass in the cookies list, but has the side effect
462          * that a variable might mask a cookie with the same name if the
463          * application stops at the first match.
464          * Note that this is the same behaviour as $_REQUEST variables in PHP.
465          */
466         if (prev) {
467                 prev->next = *cookies;
468         } else {
469                 vars = *cookies;
470         }
471         *cookies = NULL;
472
473         http_decode(uri);
474
475         AST_RWLIST_RDLOCK(&uri_redirects);
476         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
477                 if (!strcasecmp(uri, redirect->target)) {
478                         char buf[512];
479
480                         snprintf(buf, sizeof(buf), "Location: %s\r\n", redirect->dest);
481                         out = ast_http_error((*status = 302),
482                                              (*title = ast_strdup("Moved Temporarily")),
483                                              buf, "Redirecting...");
484
485                         break;
486                 }
487         }
488         AST_RWLIST_UNLOCK(&uri_redirects);
489
490         if (redirect) {
491                 goto cleanup;
492         }
493
494         /* We want requests to start with the (optional) prefix and '/' */
495         l = strlen(prefix);
496         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
497                 uri += l + 1;
498                 /* scan registered uris to see if we match one. */
499                 AST_RWLIST_RDLOCK(&uris);
500                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
501                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
502                         if (!saw_method) {
503                                 switch (method) {
504                                 case AST_HTTP_GET:
505                                         if (urih->supports_get) {
506                                                 saw_method = 1;
507                                         }
508                                         break;
509                                 case AST_HTTP_POST:
510                                         if (urih->supports_post) {
511                                                 saw_method = 1;
512                                         }
513                                         break;
514                                 }
515                         }
516
517                         l = strlen(urih->uri);
518                         c = uri + l;    /* candidate */
519
520                         if (strncasecmp(urih->uri, uri, l) || /* no match */
521                             (*c && *c != '/')) { /* substring */
522                                 continue;
523                         }
524
525                         if (*c == '/') {
526                                 c++;
527                         }
528
529                         if (!*c || urih->has_subtree) {
530                                 if (((method == AST_HTTP_GET) && urih->supports_get) ||
531                                     ((method == AST_HTTP_POST) && urih->supports_post)) {
532                                         uri = c;
533
534                                         break;
535                                 }
536                         }
537                 }
538
539                 if (!urih) {
540                         AST_RWLIST_UNLOCK(&uris);
541                 }
542         }
543
544         if (method == AST_HTTP_POST && !astman_is_authed(manid_from_vars(vars))) {
545                 out = ast_http_error((*status = 403),
546                               (*title = ast_strdup("Access Denied")),
547                               NULL, "You do not have permission to access the requested URL.");
548         } else if (urih) {
549                 *static_content = urih->static_content;
550                 out = urih->callback(ser, urih, uri, method, vars, headers, status, title, contentlength);
551                 AST_RWLIST_UNLOCK(&uris);
552         } else if (saw_method) {
553                 out = ast_http_error((*status = 404),
554                                      (*title = ast_strdup("Not Found")), NULL,
555                                      "The requested URL was not found on this server.");
556         } else {
557                 out = ast_http_error((*status = 501),
558                                      (*title = ast_strdup("Not Implemented")), NULL,
559                                      "Attempt to use unimplemented / unsupported method");
560         }
561
562 cleanup:
563         ast_variables_destroy(vars);
564
565         return out;
566 }
567
568 #ifdef DO_SSL
569 #if defined(HAVE_FUNOPEN)
570 #define HOOK_T int
571 #define LEN_T int
572 #else
573 #define HOOK_T ssize_t
574 #define LEN_T size_t
575 #endif
576
577 /*!
578  * replacement read/write functions for SSL support.
579  * We use wrappers rather than SSL_read/SSL_write directly so
580  * we can put in some debugging.
581  */
582 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
583 {
584         int i = SSL_read(cookie, buf, len-1);
585 #if 0
586         if (i >= 0)
587                 buf[i] = '\0';
588         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
589 #endif
590         return i;
591 }
592
593 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
594 {
595 #if 0
596         char *s = alloca(len+1);
597         strncpy(s, buf, len);
598         s[len] = '\0';
599         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
600 #endif
601         return SSL_write(cookie, buf, len);
602 }
603
604 static int ssl_close(void *cookie)
605 {
606         close(SSL_get_fd(cookie));
607         SSL_shutdown(cookie);
608         SSL_free(cookie);
609         return 0;
610 }*/
611 #endif  /* DO_SSL */
612
613 static struct ast_variable *parse_cookies(char *cookies)
614 {
615         char *cur;
616         struct ast_variable *vars = NULL, *var;
617
618         /* Skip Cookie: */
619         cookies += 8;
620
621         while ((cur = strsep(&cookies, ";"))) {
622                 char *name, *val;
623                 
624                 name = val = cur;
625                 strsep(&val, "=");
626
627                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
628                         continue;
629                 }
630
631                 name = ast_strip(name);
632                 val = ast_strip_quoted(val, "\"", "\"");
633
634                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
635                         continue;
636                 }
637
638                 if (option_debug) {
639                         ast_log(LOG_DEBUG, "mmm ... cookie!  Name: '%s'  Value: '%s'\n", name, val);
640                 }
641
642                 var = ast_variable_new(name, val, __FILE__);
643                 var->next = vars;
644                 vars = var;
645         }
646
647         return vars;
648 }
649
650 static void *httpd_helper_thread(void *data)
651 {
652         char buf[4096];
653         char cookie[4096];
654         struct ast_tcptls_session_instance *ser = data;
655         struct ast_variable *vars=NULL, *headers = NULL;
656         char *uri, *title=NULL;
657         int status = 200, contentlength = 0;
658         struct ast_str *out = NULL;
659         unsigned int static_content = 0;
660         struct ast_variable *tail = headers;
661
662         if (!fgets(buf, sizeof(buf), ser->f)) {
663                 goto done;
664         }
665
666         uri = ast_skip_nonblanks(buf);  /* Skip method */
667         if (*uri) {
668                 *uri++ = '\0';
669         }
670
671         uri = ast_skip_blanks(uri);     /* Skip white space */
672
673         if (*uri) {                     /* terminate at the first blank */
674                 char *c = ast_skip_nonblanks(uri);
675
676                 if (*c) {
677                         *c = '\0';
678                 }
679         }
680
681         /* process "Cookie: " lines */
682         while (fgets(cookie, sizeof(cookie), ser->f)) {
683                 /* Trim trailing characters */
684                 ast_trim_blanks(cookie);
685                 if (ast_strlen_zero(cookie)) {
686                         break;
687                 }
688                 if (!strncasecmp(cookie, "Cookie: ", 8)) {
689                         vars = parse_cookies(cookie);
690                 } else {
691                         char *name, *val;
692
693                         val = cookie;
694                         name = strsep(&val, ":");
695                         if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
696                                 continue;
697                         }
698                         ast_trim_blanks(name);
699                         val = ast_skip_blanks(val);
700
701                         if (!headers) {
702                                 headers = ast_variable_new(name, val, __FILE__);
703                                 tail = headers;
704                         } else {
705                                 tail->next = ast_variable_new(name, val, __FILE__);
706                                 tail = tail->next;
707                         }
708                 }
709         }
710
711         if (!*uri) {
712                 out = ast_http_error(400, "Bad Request", NULL, "Invalid Request");
713         } else if (strcasecmp(buf, "post") && strcasecmp(buf, "get")) {
714                 out = ast_http_error(501, "Not Implemented", NULL,
715                                      "Attempt to use unimplemented / unsupported method");
716         } else {        /* try to serve it */
717                 out = handle_uri(ser, uri, (!strcasecmp(buf, "get")) ? AST_HTTP_GET : AST_HTTP_POST,
718                                  &status, &title, &contentlength, &vars, headers, &static_content);
719         }
720
721         /* If they aren't mopped up already, clean up the cookies */
722         if (vars) {
723                 ast_variables_destroy(vars);
724         }
725         /* Clean up all the header information pulled as well */
726         if (headers) {
727                 ast_variables_destroy(headers);
728         }
729
730         if (out) {
731                 struct timeval tv = ast_tvnow();
732                 char timebuf[256];
733                 struct ast_tm tm;
734
735                 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S %Z", ast_localtime(&tv, &tm, "GMT"));
736                 fprintf(ser->f,
737                         "HTTP/1.1 %d %s\r\n"
738                         "Server: Asterisk/%s\r\n"
739                         "Date: %s\r\n"
740                         "Connection: close\r\n"
741                         "%s",
742                         status, title ? title : "OK", ast_get_version(), timebuf,
743                         static_content ? "" : "Cache-Control: no-cache, no-store\r\n");
744                         /* We set the no-cache headers only for dynamic content.
745                         * If you want to make sure the static file you requested is not from cache,
746                         * append a random variable to your GET request.  Ex: 'something.html?r=109987734'
747                         */
748                 if (!contentlength) {   /* opaque body ? just dump it hoping it is properly formatted */
749                         fprintf(ser->f, "%s", out->str);
750                 } else {
751                         char *tmp = strstr(out->str, "\r\n\r\n");
752
753                         if (tmp) {
754                                 fprintf(ser->f, "Content-length: %d\r\n", contentlength);
755                                 /* first write the header, then the body */
756                                 fwrite(out->str, 1, (tmp + 4 - out->str), ser->f);
757                                 fwrite(tmp + 4, 1, contentlength, ser->f);
758                         }
759                 }
760                 ast_free(out);
761         }
762
763         if (title) {
764                 ast_free(title);
765         }
766
767 done:
768         fclose(ser->f);
769         ao2_ref(ser, -1);
770         ser = NULL;
771
772         return NULL;
773 }
774
775 /*!
776  * \brief Add a new URI redirect
777  * The entries in the redirect list are sorted by length, just like the list
778  * of URI handlers.
779  */
780 static void add_redirect(const char *value)
781 {
782         char *target, *dest;
783         struct http_uri_redirect *redirect, *cur;
784         unsigned int target_len;
785         unsigned int total_len;
786
787         dest = ast_strdupa(value);
788         dest = ast_skip_blanks(dest);
789         target = strsep(&dest, " ");
790         target = ast_skip_blanks(target);
791         target = strsep(&target, " "); /* trim trailing whitespace */
792
793         if (!dest) {
794                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
795                 return;
796         }
797
798         target_len = strlen(target) + 1;
799         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
800
801         if (!(redirect = ast_calloc(1, total_len))) {
802                 return;
803         }
804
805         redirect->dest = redirect->target + target_len;
806         strcpy(redirect->target, target);
807         strcpy(redirect->dest, dest);
808
809         AST_RWLIST_WRLOCK(&uri_redirects);
810
811         target_len--; /* So we can compare directly with strlen() */
812         if (AST_RWLIST_EMPTY(&uri_redirects) 
813             || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len) {
814                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
815                 AST_RWLIST_UNLOCK(&uri_redirects);
816
817                 return;
818         }
819
820         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
821                 if (AST_RWLIST_NEXT(cur, entry) 
822                     && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len) {
823                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
824                         AST_RWLIST_UNLOCK(&uri_redirects); 
825
826                         return;
827                 }
828         }
829
830         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
831
832         AST_RWLIST_UNLOCK(&uri_redirects);
833 }
834
835 static int __ast_http_load(int reload)
836 {
837         struct ast_config *cfg;
838         struct ast_variable *v;
839         int enabled=0;
840         int newenablestatic=0;
841         struct hostent *hp;
842         struct ast_hostent ahp;
843         char newprefix[MAX_PREFIX] = "";
844         int have_sslbindaddr = 0;
845         struct http_uri_redirect *redirect;
846         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
847
848         if ((cfg = ast_config_load2("http.conf", "http", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
849                 return 0;
850         }
851
852         /* default values */
853         memset(&http_desc.sin, 0, sizeof(http_desc.sin));
854         http_desc.sin.sin_port = htons(8088);
855
856         memset(&https_desc.sin, 0, sizeof(https_desc.sin));
857         https_desc.sin.sin_port = htons(8089);
858
859         http_tls_cfg.enabled = 0;
860         if (http_tls_cfg.certfile) {
861                 ast_free(http_tls_cfg.certfile);
862         }
863         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
864         if (http_tls_cfg.cipher) {
865                 ast_free(http_tls_cfg.cipher);
866         }
867         http_tls_cfg.cipher = ast_strdup("");
868
869         AST_RWLIST_WRLOCK(&uri_redirects);
870         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
871                 ast_free(redirect);
872         }
873         AST_RWLIST_UNLOCK(&uri_redirects);
874
875         if (cfg) {
876                 v = ast_variable_browse(cfg, "general");
877                 for (; v; v = v->next) {
878                         if (!strcasecmp(v->name, "enabled")) {
879                                 enabled = ast_true(v->value);
880                         } else if (!strcasecmp(v->name, "sslenable")) {
881                                 http_tls_cfg.enabled = ast_true(v->value);
882                         } else if (!strcasecmp(v->name, "sslbindport")) {
883                                 https_desc.sin.sin_port = htons(atoi(v->value));
884                         } else if (!strcasecmp(v->name, "sslcert")) {
885                                 ast_free(http_tls_cfg.certfile);
886                                 http_tls_cfg.certfile = ast_strdup(v->value);
887                         } else if (!strcasecmp(v->name, "sslcipher")) {
888                                 ast_free(http_tls_cfg.cipher);
889                                 http_tls_cfg.cipher = ast_strdup(v->value);
890                         } else if (!strcasecmp(v->name, "enablestatic")) {
891                                 newenablestatic = ast_true(v->value);
892                         } else if (!strcasecmp(v->name, "bindport")) {
893                                 http_desc.sin.sin_port = htons(atoi(v->value));
894                         } else if (!strcasecmp(v->name, "sslbindaddr")) {
895                                 if ((hp = ast_gethostbyname(v->value, &ahp))) {
896                                         memcpy(&https_desc.sin.sin_addr, hp->h_addr, sizeof(https_desc.sin.sin_addr));
897                                         have_sslbindaddr = 1;
898                                 } else {
899                                         ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
900                                 }
901                         } else if (!strcasecmp(v->name, "bindaddr")) {
902                                 if ((hp = ast_gethostbyname(v->value, &ahp))) {
903                                         memcpy(&http_desc.sin.sin_addr, hp->h_addr, sizeof(http_desc.sin.sin_addr));
904                                 } else {
905                                         ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
906                                 }
907                         } else if (!strcasecmp(v->name, "prefix")) {
908                                 if (!ast_strlen_zero(v->value)) {
909                                         newprefix[0] = '/';
910                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
911                                 } else {
912                                         newprefix[0] = '\0';
913                                 }
914                         } else if (!strcasecmp(v->name, "redirect")) {
915                                 add_redirect(v->value);
916                         } else {
917                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
918                         }
919                 }
920
921                 ast_config_destroy(cfg);
922         }
923
924         if (!have_sslbindaddr) {
925                 https_desc.sin.sin_addr = http_desc.sin.sin_addr;
926         }
927         if (enabled) {
928                 http_desc.sin.sin_family = https_desc.sin.sin_family = AF_INET;
929         }
930         if (strcmp(prefix, newprefix)) {
931                 ast_copy_string(prefix, newprefix, sizeof(prefix));
932         }
933         enablestatic = newenablestatic;
934         ast_tcptls_server_start(&http_desc);
935         if (ast_ssl_setup(https_desc.tls_cfg)) {
936                 ast_tcptls_server_start(&https_desc);
937         }
938
939         return 0;
940 }
941
942 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
943 {
944         struct ast_http_uri *urih;
945         struct http_uri_redirect *redirect;
946
947         switch (cmd) {
948         case CLI_INIT:
949                 e->command = "http show status";
950                 e->usage = 
951                         "Usage: http show status\n"
952                         "       Lists status of internal HTTP engine\n";
953                 return NULL;
954         case CLI_GENERATE:
955                 return NULL;
956         }
957         
958         if (a->argc != 3) {
959                 return CLI_SHOWUSAGE;
960         }
961         ast_cli(a->fd, "HTTP Server Status:\n");
962         ast_cli(a->fd, "Prefix: %s\n", prefix);
963         if (!http_desc.oldsin.sin_family) {
964                 ast_cli(a->fd, "Server Disabled\n\n");
965         } else {
966                 ast_cli(a->fd, "Server Enabled and Bound to %s:%d\n\n",
967                         ast_inet_ntoa(http_desc.oldsin.sin_addr),
968                         ntohs(http_desc.oldsin.sin_port));
969                 if (http_tls_cfg.enabled) {
970                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s:%d\n\n",
971                                 ast_inet_ntoa(https_desc.oldsin.sin_addr),
972                                 ntohs(https_desc.oldsin.sin_port));
973                 }
974         }
975
976         ast_cli(a->fd, "Enabled URI's:\n");
977         AST_RWLIST_RDLOCK(&uris);
978         if (AST_RWLIST_EMPTY(&uris)) {
979                 ast_cli(a->fd, "None.\n");
980         } else {
981                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
982                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : ""), urih->description);
983                 }
984         }
985         AST_RWLIST_UNLOCK(&uris);
986
987         ast_cli(a->fd, "\nEnabled Redirects:\n");
988         AST_RWLIST_RDLOCK(&uri_redirects);
989         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
990                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
991         }
992         if (AST_RWLIST_EMPTY(&uri_redirects)) {
993                 ast_cli(a->fd, "  None.\n");
994         }
995         AST_RWLIST_UNLOCK(&uri_redirects);
996
997         return CLI_SUCCESS;
998 }
999
1000 int ast_http_reload(void)
1001 {
1002         return __ast_http_load(1);
1003 }
1004
1005 static struct ast_cli_entry cli_http[] = {
1006         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1007 };
1008
1009 int ast_http_init(void)
1010 {
1011         ast_http_uri_link(&statusuri);
1012         ast_http_uri_link(&staticuri);
1013         ast_cli_register_multiple(cli_http, sizeof(cli_http) / sizeof(struct ast_cli_entry));
1014
1015         return __ast_http_load(0);
1016 }