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