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