Committing a fix that was introduced a long time
[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, "Nothing to see here.  Move along.");
232
233 out403:
234         return ast_http_error((*status = 403),
235                               (*title = ast_strdup("Access Denied")),
236                               NULL, "Sorry, I cannot let you do that, Dave.");
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 }
395
396 /*
397  * Decode special characters in http uri.
398  * We have ast_uri_decode to handle %XX sequences, but spaces
399  * are encoded as a '+' so we need to replace them beforehand.
400  */
401 static void http_decode(char *s)
402 {
403         char *t;
404         
405         for (t = s; *t; t++) {
406                 if (*t == '+')
407                         *t = ' ';
408         }
409
410         ast_uri_decode(s);
411 }
412
413 static struct ast_str *handle_uri(struct ast_tcptls_session_instance *ser, char *uri, enum ast_http_method method,
414                                   int *status, char **title, int *contentlength, struct ast_variable **cookies, struct ast_variable *headers, 
415                                   unsigned int *static_content)
416 {
417         char *c;
418         struct ast_str *out = NULL;
419         char *params = uri;
420         struct ast_http_uri *urih = NULL;
421         int l;
422         struct ast_variable *vars = NULL, *v, *prev = NULL;
423         struct http_uri_redirect *redirect;
424         int saw_method = 0;
425
426         /* preserve previous behavior of only support URI parameters on GET requests */
427         if (method == AST_HTTP_GET) {
428                 strsep(&params, "?");
429                 
430                 /* Extract arguments from the request and store them in variables.
431                  * Note that a request can have multiple arguments with the same
432                  * name, and we store them all in the list of variables.
433                  * It is up to the application to handle multiple values.
434                  */
435                 if (params) {
436                         char *var, *val;
437                         
438                         while ((val = strsep(&params, "&"))) {
439                                 var = strsep(&val, "=");
440                                 if (val) {
441                                         http_decode(val);
442                                 } else {
443                                         val = "";
444                                 }
445                                 http_decode(var);
446                                 if ((v = ast_variable_new(var, val, ""))) {
447                                         if (vars) {
448                                                 prev->next = v;
449                                         } else {
450                                                 vars = v;
451                                         }
452                                         prev = v;
453                                 }
454                         }
455                 }
456         }
457
458         /*
459          * Append the cookies to the list of variables.
460          * This saves a pass in the cookies list, but has the side effect
461          * that a variable might mask a cookie with the same name if the
462          * application stops at the first match.
463          * Note that this is the same behaviour as $_REQUEST variables in PHP.
464          */
465         if (prev) {
466                 prev->next = *cookies;
467         } else {
468                 vars = *cookies;
469         }
470         *cookies = NULL;
471
472         http_decode(uri);
473
474         AST_RWLIST_RDLOCK(&uri_redirects);
475         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
476                 if (!strcasecmp(uri, redirect->target)) {
477                         char buf[512];
478
479                         snprintf(buf, sizeof(buf), "Location: %s\r\n", redirect->dest);
480                         out = ast_http_error((*status = 302),
481                                              (*title = ast_strdup("Moved Temporarily")),
482                                              buf, "There is no spoon...");
483
484                         break;
485                 }
486         }
487         AST_RWLIST_UNLOCK(&uri_redirects);
488
489         if (redirect) {
490                 goto cleanup;
491         }
492
493         /* We want requests to start with the (optional) prefix and '/' */
494         l = strlen(prefix);
495         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
496                 uri += l + 1;
497                 /* scan registered uris to see if we match one. */
498                 AST_RWLIST_RDLOCK(&uris);
499                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
500                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
501                         if (!saw_method) {
502                                 switch (method) {
503                                 case AST_HTTP_GET:
504                                         if (urih->supports_get) {
505                                                 saw_method = 1;
506                                         }
507                                         break;
508                                 case AST_HTTP_POST:
509                                         if (urih->supports_post) {
510                                                 saw_method = 1;
511                                         }
512                                         break;
513                                 }
514                         }
515
516                         l = strlen(urih->uri);
517                         c = uri + l;    /* candidate */
518
519                         if (strncasecmp(urih->uri, uri, l) || /* no match */
520                             (*c && *c != '/')) { /* substring */
521                                 continue;
522                         }
523
524                         if (*c == '/') {
525                                 c++;
526                         }
527
528                         if (!*c || urih->has_subtree) {
529                                 if (((method == AST_HTTP_GET) && urih->supports_get) ||
530                                     ((method == AST_HTTP_POST) && urih->supports_post)) {
531                                         uri = c;
532
533                                         break;
534                                 }
535                         }
536                 }
537
538                 if (!urih) {
539                         AST_RWLIST_UNLOCK(&uris);
540                 }
541         }
542
543         if (method == AST_HTTP_POST && !astman_is_authed(manid_from_vars(vars))) {
544                 out = ast_http_error((*status = 403),
545                               (*title = ast_strdup("Access Denied")),
546                               NULL, "Sorry, I cannot let you do that, Dave.");
547         } else if (urih) {
548                 *static_content = urih->static_content;
549                 out = urih->callback(ser, urih, uri, method, vars, headers, status, title, contentlength);
550                 AST_RWLIST_UNLOCK(&uris);
551         } else if (saw_method) {
552                 out = ast_http_error((*status = 404),
553                                      (*title = ast_strdup("Not Found")), NULL,
554                                      "The requested URL was not found on this server.");
555         } else {
556                 out = ast_http_error((*status = 501),
557                                      (*title = ast_strdup("Not Implemented")), NULL,
558                                      "Attempt to use unimplemented / unsupported method");
559         }
560
561 cleanup:
562         ast_variables_destroy(vars);
563
564         return out;
565 }
566
567 #ifdef DO_SSL
568 #if defined(HAVE_FUNOPEN)
569 #define HOOK_T int
570 #define LEN_T int
571 #else
572 #define HOOK_T ssize_t
573 #define LEN_T size_t
574 #endif
575
576 /*!
577  * replacement read/write functions for SSL support.
578  * We use wrappers rather than SSL_read/SSL_write directly so
579  * we can put in some debugging.
580  */
581 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
582 {
583         int i = SSL_read(cookie, buf, len-1);
584 #if 0
585         if (i >= 0)
586                 buf[i] = '\0';
587         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
588 #endif
589         return i;
590 }
591
592 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
593 {
594 #if 0
595         char *s = alloca(len+1);
596         strncpy(s, buf, len);
597         s[len] = '\0';
598         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
599 #endif
600         return SSL_write(cookie, buf, len);
601 }
602
603 static int ssl_close(void *cookie)
604 {
605         close(SSL_get_fd(cookie));
606         SSL_shutdown(cookie);
607         SSL_free(cookie);
608         return 0;
609 }*/
610 #endif  /* DO_SSL */
611
612 static struct ast_variable *parse_cookies(char *cookies)
613 {
614         char *cur;
615         struct ast_variable *vars = NULL, *var;
616
617         /* Skip Cookie: */
618         cookies += 8;
619
620         while ((cur = strsep(&cookies, ";"))) {
621                 char *name, *val;
622                 
623                 name = val = cur;
624                 strsep(&val, "=");
625
626                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
627                         continue;
628                 }
629
630                 name = ast_strip(name);
631                 val = ast_strip_quoted(val, "\"", "\"");
632
633                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
634                         continue;
635                 }
636
637                 if (option_debug) {
638                         ast_log(LOG_DEBUG, "mmm ... cookie!  Name: '%s'  Value: '%s'\n", name, val);
639                 }
640
641                 var = ast_variable_new(name, val, __FILE__);
642                 var->next = vars;
643                 vars = var;
644         }
645
646         return vars;
647 }
648
649 static void *httpd_helper_thread(void *data)
650 {
651         char buf[4096];
652         char cookie[4096];
653         struct ast_tcptls_session_instance *ser = data;
654         struct ast_variable *vars=NULL, *headers = NULL;
655         char *uri, *title=NULL;
656         int status = 200, contentlength = 0;
657         struct ast_str *out = NULL;
658         unsigned int static_content = 0;
659
660         if (!fgets(buf, sizeof(buf), ser->f)) {
661                 goto done;
662         }
663
664         uri = ast_skip_nonblanks(buf);  /* Skip method */
665         if (*uri) {
666                 *uri++ = '\0';
667         }
668
669         uri = ast_skip_blanks(uri);     /* Skip white space */
670
671         if (*uri) {                     /* terminate at the first blank */
672                 char *c = ast_skip_nonblanks(uri);
673
674                 if (*c) {
675                         *c = '\0';
676                 }
677         }
678
679         /* process "Cookie: " lines */
680         while (fgets(cookie, sizeof(cookie), ser->f)) {
681                 /* Trim trailing characters */
682                 ast_trim_blanks(cookie);
683                 if (ast_strlen_zero(cookie)) {
684                         break;
685                 }
686                 if (!strncasecmp(cookie, "Cookie: ", 8)) {
687                         vars = parse_cookies(cookie);
688                 }
689         }
690
691         if (!*uri) {
692                 out = ast_http_error(400, "Bad Request", NULL, "Invalid Request");
693         } else if (strcasecmp(buf, "post") && strcasecmp(buf, "get")) {
694                 out = ast_http_error(501, "Not Implemented", NULL,
695                                      "Attempt to use unimplemented / unsupported method");
696         } else {        /* try to serve it */
697                 out = handle_uri(ser, uri, (!strcasecmp(buf, "get")) ? AST_HTTP_GET : AST_HTTP_POST,
698                                  &status, &title, &contentlength, &vars, headers, &static_content);
699         }
700
701         /* If they aren't mopped up already, clean up the cookies */
702         if (vars) {
703                 ast_variables_destroy(vars);
704         }
705         /* Clean up all the header information pulled as well */
706         if (headers) {
707                 ast_variables_destroy(headers);
708         }
709
710         if (out) {
711                 struct timeval tv = ast_tvnow();
712                 char timebuf[256];
713                 struct ast_tm tm;
714
715                 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S %Z", ast_localtime(&tv, &tm, "GMT"));
716                 fprintf(ser->f,
717                         "HTTP/1.1 %d %s\r\n"
718                         "Server: Asterisk/%s\r\n"
719                         "Date: %s\r\n"
720                         "Connection: close\r\n"
721                         "%s",
722                         status, title ? title : "OK", ast_get_version(), timebuf,
723                         static_content ? "" : "Cache-Control: no-cache, no-store\r\n");
724                         /* We set the no-cache headers only for dynamic content.
725                         * If you want to make sure the static file you requested is not from cache,
726                         * append a random variable to your GET request.  Ex: 'something.html?r=109987734'
727                         */
728                 if (!contentlength) {   /* opaque body ? just dump it hoping it is properly formatted */
729                         fprintf(ser->f, "%s", out->str);
730                 } else {
731                         char *tmp = strstr(out->str, "\r\n\r\n");
732
733                         if (tmp) {
734                                 fprintf(ser->f, "Content-length: %d\r\n", contentlength);
735                                 /* first write the header, then the body */
736                                 fwrite(out->str, 1, (tmp + 4 - out->str), ser->f);
737                                 fwrite(tmp + 4, 1, contentlength, ser->f);
738                         }
739                 }
740                 ast_free(out);
741         }
742
743         if (title) {
744                 ast_free(title);
745         }
746
747 done:
748         fclose(ser->f);
749         ao2_ref(ser, -1);
750         ser = NULL;
751
752         return NULL;
753 }
754
755 /*!
756  * \brief Add a new URI redirect
757  * The entries in the redirect list are sorted by length, just like the list
758  * of URI handlers.
759  */
760 static void add_redirect(const char *value)
761 {
762         char *target, *dest;
763         struct http_uri_redirect *redirect, *cur;
764         unsigned int target_len;
765         unsigned int total_len;
766
767         dest = ast_strdupa(value);
768         dest = ast_skip_blanks(dest);
769         target = strsep(&dest, " ");
770         target = ast_skip_blanks(target);
771         target = strsep(&target, " "); /* trim trailing whitespace */
772
773         if (!dest) {
774                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
775                 return;
776         }
777
778         target_len = strlen(target) + 1;
779         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
780
781         if (!(redirect = ast_calloc(1, total_len))) {
782                 return;
783         }
784
785         redirect->dest = redirect->target + target_len;
786         strcpy(redirect->target, target);
787         strcpy(redirect->dest, dest);
788
789         AST_RWLIST_WRLOCK(&uri_redirects);
790
791         target_len--; /* So we can compare directly with strlen() */
792         if (AST_RWLIST_EMPTY(&uri_redirects) 
793             || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len) {
794                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
795                 AST_RWLIST_UNLOCK(&uri_redirects);
796
797                 return;
798         }
799
800         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
801                 if (AST_RWLIST_NEXT(cur, entry) 
802                     && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len) {
803                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
804                         AST_RWLIST_UNLOCK(&uri_redirects); 
805
806                         return;
807                 }
808         }
809
810         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
811
812         AST_RWLIST_UNLOCK(&uri_redirects);
813 }
814
815 static int __ast_http_load(int reload)
816 {
817         struct ast_config *cfg;
818         struct ast_variable *v;
819         int enabled=0;
820         int newenablestatic=0;
821         struct hostent *hp;
822         struct ast_hostent ahp;
823         char newprefix[MAX_PREFIX] = "";
824         int have_sslbindaddr = 0;
825         struct http_uri_redirect *redirect;
826         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
827
828         if ((cfg = ast_config_load2("http.conf", "http", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
829                 return 0;
830         }
831
832         /* default values */
833         memset(&http_desc.sin, 0, sizeof(http_desc.sin));
834         http_desc.sin.sin_port = htons(8088);
835
836         memset(&https_desc.sin, 0, sizeof(https_desc.sin));
837         https_desc.sin.sin_port = htons(8089);
838
839         http_tls_cfg.enabled = 0;
840         if (http_tls_cfg.certfile) {
841                 ast_free(http_tls_cfg.certfile);
842         }
843         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
844         if (http_tls_cfg.cipher) {
845                 ast_free(http_tls_cfg.cipher);
846         }
847         http_tls_cfg.cipher = ast_strdup("");
848
849         AST_RWLIST_WRLOCK(&uri_redirects);
850         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
851                 ast_free(redirect);
852         }
853         AST_RWLIST_UNLOCK(&uri_redirects);
854
855         if (cfg) {
856                 v = ast_variable_browse(cfg, "general");
857                 for (; v; v = v->next) {
858                         if (!strcasecmp(v->name, "enabled")) {
859                                 enabled = ast_true(v->value);
860                         } else if (!strcasecmp(v->name, "sslenable")) {
861                                 http_tls_cfg.enabled = ast_true(v->value);
862                         } else if (!strcasecmp(v->name, "sslbindport")) {
863                                 https_desc.sin.sin_port = htons(atoi(v->value));
864                         } else if (!strcasecmp(v->name, "sslcert")) {
865                                 ast_free(http_tls_cfg.certfile);
866                                 http_tls_cfg.certfile = ast_strdup(v->value);
867                         } else if (!strcasecmp(v->name, "sslcipher")) {
868                                 ast_free(http_tls_cfg.cipher);
869                                 http_tls_cfg.cipher = ast_strdup(v->value);
870                         } else if (!strcasecmp(v->name, "enablestatic")) {
871                                 newenablestatic = ast_true(v->value);
872                         } else if (!strcasecmp(v->name, "bindport")) {
873                                 http_desc.sin.sin_port = htons(atoi(v->value));
874                         } else if (!strcasecmp(v->name, "sslbindaddr")) {
875                                 if ((hp = ast_gethostbyname(v->value, &ahp))) {
876                                         memcpy(&https_desc.sin.sin_addr, hp->h_addr, sizeof(https_desc.sin.sin_addr));
877                                         have_sslbindaddr = 1;
878                                 } else {
879                                         ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
880                                 }
881                         } else if (!strcasecmp(v->name, "bindaddr")) {
882                                 if ((hp = ast_gethostbyname(v->value, &ahp))) {
883                                         memcpy(&http_desc.sin.sin_addr, hp->h_addr, sizeof(http_desc.sin.sin_addr));
884                                 } else {
885                                         ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
886                                 }
887                         } else if (!strcasecmp(v->name, "prefix")) {
888                                 if (!ast_strlen_zero(v->value)) {
889                                         newprefix[0] = '/';
890                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
891                                 } else {
892                                         newprefix[0] = '\0';
893                                 }
894                         } else if (!strcasecmp(v->name, "redirect")) {
895                                 add_redirect(v->value);
896                         } else {
897                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
898                         }
899                 }
900
901                 ast_config_destroy(cfg);
902         }
903
904         if (!have_sslbindaddr) {
905                 https_desc.sin.sin_addr = http_desc.sin.sin_addr;
906         }
907         if (enabled) {
908                 http_desc.sin.sin_family = https_desc.sin.sin_family = AF_INET;
909         }
910         if (strcmp(prefix, newprefix)) {
911                 ast_copy_string(prefix, newprefix, sizeof(prefix));
912         }
913         enablestatic = newenablestatic;
914         ast_tcptls_server_start(&http_desc);
915         if (ast_ssl_setup(https_desc.tls_cfg)) {
916                 ast_tcptls_server_start(&https_desc);
917         }
918
919         return 0;
920 }
921
922 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
923 {
924         struct ast_http_uri *urih;
925         struct http_uri_redirect *redirect;
926
927         switch (cmd) {
928         case CLI_INIT:
929                 e->command = "http show status";
930                 e->usage = 
931                         "Usage: http show status\n"
932                         "       Lists status of internal HTTP engine\n";
933                 return NULL;
934         case CLI_GENERATE:
935                 return NULL;
936         }
937         
938         if (a->argc != 3) {
939                 return CLI_SHOWUSAGE;
940         }
941         ast_cli(a->fd, "HTTP Server Status:\n");
942         ast_cli(a->fd, "Prefix: %s\n", prefix);
943         if (!http_desc.oldsin.sin_family) {
944                 ast_cli(a->fd, "Server Disabled\n\n");
945         } else {
946                 ast_cli(a->fd, "Server Enabled and Bound to %s:%d\n\n",
947                         ast_inet_ntoa(http_desc.oldsin.sin_addr),
948                         ntohs(http_desc.oldsin.sin_port));
949                 if (http_tls_cfg.enabled) {
950                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s:%d\n\n",
951                                 ast_inet_ntoa(https_desc.oldsin.sin_addr),
952                                 ntohs(https_desc.oldsin.sin_port));
953                 }
954         }
955
956         ast_cli(a->fd, "Enabled URI's:\n");
957         AST_RWLIST_RDLOCK(&uris);
958         if (AST_RWLIST_EMPTY(&uris)) {
959                 ast_cli(a->fd, "None.\n");
960         } else {
961                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
962                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : ""), urih->description);
963                 }
964         }
965         AST_RWLIST_UNLOCK(&uris);
966
967         ast_cli(a->fd, "\nEnabled Redirects:\n");
968         AST_RWLIST_RDLOCK(&uri_redirects);
969         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
970                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
971         }
972         if (AST_RWLIST_EMPTY(&uri_redirects)) {
973                 ast_cli(a->fd, "  None.\n");
974         }
975         AST_RWLIST_UNLOCK(&uri_redirects);
976
977         return CLI_SUCCESS;
978 }
979
980 int ast_http_reload(void)
981 {
982         return __ast_http_load(1);
983 }
984
985 static struct ast_cli_entry cli_http[] = {
986         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
987 };
988
989 int ast_http_init(void)
990 {
991         ast_http_uri_link(&statusuri);
992         ast_http_uri_link(&staticuri);
993         ast_cli_register_multiple(cli_http, sizeof(cli_http) / sizeof(struct ast_cli_entry));
994
995         return __ast_http_load(0);
996 }