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