http: Properly reject requests with Transfer-Encoding set
[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  * GMime http://spruce.sourceforge.net/gmime/
29  *
30  * \ref AstHTTP - AMI over the http protocol
31  */
32
33 /*! \li \ref http.c uses the configuration file \ref http.conf
34  * \addtogroup configuration_file
35  */
36
37 /*! \page http.conf http.conf
38  * \verbinclude http.conf.sample
39  */
40
41 /*** MODULEINFO
42         <support_level>core</support_level>
43  ***/
44
45 #include "asterisk.h"
46
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48
49 #include <time.h>
50 #include <sys/time.h>
51 #include <sys/stat.h>
52 #include <sys/signal.h>
53 #include <fcntl.h>
54
55 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
56 #include "asterisk/cli.h"
57 #include "asterisk/tcptls.h"
58 #include "asterisk/http.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/strings.h"
61 #include "asterisk/config.h"
62 #include "asterisk/stringfields.h"
63 #include "asterisk/ast_version.h"
64 #include "asterisk/manager.h"
65 #include "asterisk/_private.h"
66 #include "asterisk/astobj2.h"
67 #include "asterisk/netsock2.h"
68 #include "asterisk/json.h"
69
70 #define MAX_PREFIX 80
71 #define DEFAULT_PORT 8088
72 #define DEFAULT_TLS_PORT 8089
73 #define DEFAULT_SESSION_LIMIT 100
74
75 /* See http.h for more information about the SSL implementation */
76 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
77 #define DO_SSL  /* comment in/out if you want to support ssl */
78 #endif
79
80 static int session_limit = DEFAULT_SESSION_LIMIT;
81 static int session_count = 0;
82
83 static struct ast_tls_config http_tls_cfg;
84
85 static void *httpd_helper_thread(void *arg);
86
87 /*!
88  * we have up to two accepting threads, one for http, one for https
89  */
90 static struct ast_tcptls_session_args http_desc = {
91         .accept_fd = -1,
92         .master = AST_PTHREADT_NULL,
93         .tls_cfg = NULL,
94         .poll_timeout = -1,
95         .name = "http server",
96         .accept_fn = ast_tcptls_server_root,
97         .worker_fn = httpd_helper_thread,
98 };
99
100 static struct ast_tcptls_session_args https_desc = {
101         .accept_fd = -1,
102         .master = AST_PTHREADT_NULL,
103         .tls_cfg = &http_tls_cfg,
104         .poll_timeout = -1,
105         .name = "https server",
106         .accept_fn = ast_tcptls_server_root,
107         .worker_fn = httpd_helper_thread,
108 };
109
110 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri);      /*!< list of supported handlers */
111
112 /* all valid URIs must be prepended by the string in prefix. */
113 static char prefix[MAX_PREFIX];
114 static int enablestatic;
115
116 /*! \brief Limit the kinds of files we're willing to serve up */
117 static struct {
118         const char *ext;
119         const char *mtype;
120 } mimetypes[] = {
121         { "png", "image/png" },
122         { "xml", "text/xml" },
123         { "jpg", "image/jpeg" },
124         { "js", "application/x-javascript" },
125         { "wav", "audio/x-wav" },
126         { "mp3", "audio/mpeg" },
127         { "svg", "image/svg+xml" },
128         { "svgz", "image/svg+xml" },
129         { "gif", "image/gif" },
130         { "html", "text/html" },
131         { "htm", "text/html" },
132         { "css", "text/css" },
133         { "cnf", "text/plain" },
134         { "cfg", "text/plain" },
135         { "bin", "application/octet-stream" },
136         { "sbn", "application/octet-stream" },
137         { "ld", "application/octet-stream" },
138 };
139
140 struct http_uri_redirect {
141         AST_LIST_ENTRY(http_uri_redirect) entry;
142         char *dest;
143         char target[0];
144 };
145
146 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
147
148 static const struct ast_cfhttp_methods_text {
149         enum ast_http_method method;
150         const char *text;
151 } ast_http_methods_text[] = {
152         { AST_HTTP_UNKNOWN,     "UNKNOWN" },
153         { AST_HTTP_GET,         "GET" },
154         { AST_HTTP_POST,        "POST" },
155         { AST_HTTP_HEAD,        "HEAD" },
156         { AST_HTTP_PUT,         "PUT" },
157         { AST_HTTP_DELETE,      "DELETE" },
158         { AST_HTTP_OPTIONS,     "OPTIONS" },
159 };
160
161 const char *ast_get_http_method(enum ast_http_method method)
162 {
163         int x;
164
165         for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
166                 if (ast_http_methods_text[x].method == method) {
167                         return ast_http_methods_text[x].text;
168                 }
169         }
170
171         return NULL;
172 }
173
174 const char *ast_http_ftype2mtype(const char *ftype)
175 {
176         int x;
177
178         if (ftype) {
179                 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
180                         if (!strcasecmp(ftype, mimetypes[x].ext)) {
181                                 return mimetypes[x].mtype;
182                         }
183                 }
184         }
185         return NULL;
186 }
187
188 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
189 {
190         uint32_t mngid = 0;
191         struct ast_variable *v, *cookies;
192
193         cookies = ast_http_get_cookies(headers);
194         for (v = cookies; v; v = v->next) {
195                 if (!strcasecmp(v->name, "mansession_id")) {
196                         sscanf(v->value, "%30x", &mngid);
197                         break;
198                 }
199         }
200         if (cookies) {
201                 ast_variables_destroy(cookies);
202         }
203         return mngid;
204 }
205
206 void ast_http_prefix(char *buf, int len)
207 {
208         if (buf) {
209                 ast_copy_string(buf, prefix, len);
210         }
211 }
212
213 static int static_callback(struct ast_tcptls_session_instance *ser,
214         const struct ast_http_uri *urih, const char *uri,
215         enum ast_http_method method, struct ast_variable *get_vars,
216         struct ast_variable *headers)
217 {
218         char *path;
219         const char *ftype;
220         const char *mtype;
221         char wkspace[80];
222         struct stat st;
223         int len;
224         int fd;
225         struct ast_str *http_header;
226         struct timeval tv;
227         struct ast_tm tm;
228         char timebuf[80], etag[23];
229         struct ast_variable *v;
230         int not_modified = 0;
231
232         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
233                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
234                 return -1;
235         }
236
237         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
238            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
239         if (!enablestatic || ast_strlen_zero(uri)) {
240                 goto out403;
241         }
242
243         /* Disallow any funny filenames at all (checking first character only??) */
244         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
245                 goto out403;
246         }
247
248         if (strstr(uri, "/..")) {
249                 goto out403;
250         }
251
252         if ((ftype = strrchr(uri, '.'))) {
253                 ftype++;
254         }
255
256         if (!(mtype = ast_http_ftype2mtype(ftype))) {
257                 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
258                 mtype = wkspace;
259         }
260
261         /* Cap maximum length */
262         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
263                 goto out403;
264         }
265
266         path = ast_alloca(len);
267         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
268         if (stat(path, &st)) {
269                 goto out404;
270         }
271
272         if (S_ISDIR(st.st_mode)) {
273                 goto out404;
274         }
275
276         if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
277                 goto out403;
278         }
279
280         fd = open(path, O_RDONLY);
281         if (fd < 0) {
282                 goto out403;
283         }
284
285         /* make "Etag:" http header value */
286         snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
287
288         /* make "Last-Modified:" http header value */
289         tv.tv_sec = st.st_mtime;
290         tv.tv_usec = 0;
291         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
292
293         /* check received "If-None-Match" request header and Etag value for file */
294         for (v = headers; v; v = v->next) {
295                 if (!strcasecmp(v->name, "If-None-Match")) {
296                         if (!strcasecmp(v->value, etag)) {
297                                 not_modified = 1;
298                         }
299                         break;
300                 }
301         }
302
303         if ( (http_header = ast_str_create(255)) == NULL) {
304                 close(fd);
305                 return -1;
306         }
307
308         ast_str_set(&http_header, 0, "Content-type: %s\r\n"
309                 "ETag: %s\r\n"
310                 "Last-Modified: %s\r\n",
311                 mtype,
312                 etag,
313                 timebuf);
314
315         /* ast_http_send() frees http_header, so we don't need to do it before returning */
316         if (not_modified) {
317                 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
318         } else {
319                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
320         }
321         close(fd);
322         return 0;
323
324 out404:
325         ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
326         return -1;
327
328 out403:
329         ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
330         return -1;
331 }
332
333 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
334         const struct ast_http_uri *urih, const char *uri,
335         enum ast_http_method method, struct ast_variable *get_vars,
336         struct ast_variable *headers)
337 {
338         struct ast_str *out;
339         struct ast_variable *v, *cookies = NULL;
340
341         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
342                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
343                 return -1;
344         }
345
346         if ( (out = ast_str_create(512)) == NULL) {
347                 return -1;
348         }
349
350         ast_str_append(&out, 0,
351                 "<title>Asterisk HTTP Status</title>\r\n"
352                 "<body bgcolor=\"#ffffff\">\r\n"
353                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
354                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
355
356         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
357         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
358                        ast_sockaddr_stringify_addr(&http_desc.old_address));
359         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
360                        ast_sockaddr_stringify_port(&http_desc.old_address));
361         if (http_tls_cfg.enabled) {
362                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
363                                ast_sockaddr_stringify_port(&https_desc.old_address));
364         }
365         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
366         for (v = get_vars; v; v = v->next) {
367                 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
368         }
369         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
370
371         cookies = ast_http_get_cookies(headers);
372         for (v = cookies; v; v = v->next) {
373                 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
374         }
375         ast_variables_destroy(cookies);
376
377         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");
378         ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
379         return 0;
380 }
381
382 static struct ast_http_uri statusuri = {
383         .callback = httpstatus_callback,
384         .description = "Asterisk HTTP General Status",
385         .uri = "httpstatus",
386         .has_subtree = 0,
387         .data = NULL,
388         .key = __FILE__,
389 };
390
391 static struct ast_http_uri staticuri = {
392         .callback = static_callback,
393         .description = "Asterisk HTTP Static Delivery",
394         .uri = "static",
395         .has_subtree = 1,
396         .data = NULL,
397         .key= __FILE__,
398 };
399
400
401 /* send http/1.1 response */
402 /* free content variable and close socket*/
403 void ast_http_send(struct ast_tcptls_session_instance *ser,
404         enum ast_http_method method, int status_code, const char *status_title,
405         struct ast_str *http_header, struct ast_str *out, const int fd,
406         unsigned int static_content)
407 {
408         struct timeval now = ast_tvnow();
409         struct ast_tm tm;
410         char timebuf[80];
411         int content_length = 0;
412
413         if (!ser || 0 == ser->f) {
414                 return;
415         }
416
417         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
418
419         /* calc content length */
420         if (out) {
421                 content_length += strlen(ast_str_buffer(out));
422         }
423
424         if (fd) {
425                 content_length += lseek(fd, 0, SEEK_END);
426                 lseek(fd, 0, SEEK_SET);
427         }
428
429         /* send http header */
430         fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
431                 "Server: Asterisk/%s\r\n"
432                 "Date: %s\r\n"
433                 "Connection: close\r\n"
434                 "%s"
435                 "Content-Length: %d\r\n"
436                 "%s"
437                 "\r\n",
438                 status_code, status_title ? status_title : "OK",
439                 ast_get_version(),
440                 timebuf,
441                 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
442                 content_length,
443                 http_header ? ast_str_buffer(http_header) : ""
444                 );
445
446         /* send content */
447         if (method != AST_HTTP_HEAD || status_code >= 400) {
448                 if (out) {
449                         fprintf(ser->f, "%s", ast_str_buffer(out));
450                 }
451
452                 if (fd) {
453                         char buf[256];
454                         int len;
455                         while ((len = read(fd, buf, sizeof(buf))) > 0) {
456                                 if (fwrite(buf, len, 1, ser->f) != 1) {
457                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
458                                         break;
459                                 }
460                         }
461                 }
462         }
463
464         if (http_header) {
465                 ast_free(http_header);
466         }
467         if (out) {
468                 ast_free(out);
469         }
470
471         fclose(ser->f);
472         ser->f = 0;
473         return;
474 }
475
476 /* Send http "401 Unauthorized" responce and close socket*/
477 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
478         const unsigned long nonce, const unsigned long opaque, int stale,
479         const char *text)
480 {
481         struct ast_str *http_headers = ast_str_create(128);
482         struct ast_str *out = ast_str_create(512);
483
484         if (!http_headers || !out) {
485                 ast_free(http_headers);
486                 ast_free(out);
487                 return;
488         }
489
490         ast_str_set(&http_headers, 0,
491                 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
492                 "Content-type: text/html\r\n",
493                 realm ? realm : "Asterisk",
494                 nonce,
495                 opaque,
496                 stale ? ", stale=true" : "");
497
498         ast_str_set(&out, 0,
499                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
500                 "<html><head>\r\n"
501                 "<title>401 Unauthorized</title>\r\n"
502                 "</head><body>\r\n"
503                 "<h1>401 Unauthorized</h1>\r\n"
504                 "<p>%s</p>\r\n"
505                 "<hr />\r\n"
506                 "<address>Asterisk Server</address>\r\n"
507                 "</body></html>\r\n",
508                 text ? text : "");
509
510         ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
511         return;
512 }
513
514 /* send http error response and close socket*/
515 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
516 {
517         struct ast_str *http_headers = ast_str_create(40);
518         struct ast_str *out = ast_str_create(256);
519
520         if (!http_headers || !out) {
521                 ast_free(http_headers);
522                 ast_free(out);
523                 return;
524         }
525
526         ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
527
528         ast_str_set(&out, 0,
529                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
530                 "<html><head>\r\n"
531                 "<title>%d %s</title>\r\n"
532                 "</head><body>\r\n"
533                 "<h1>%s</h1>\r\n"
534                 "<p>%s</p>\r\n"
535                 "<hr />\r\n"
536                 "<address>Asterisk Server</address>\r\n"
537                 "</body></html>\r\n",
538                         status_code, status_title, status_title, text);
539
540         ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
541         return;
542 }
543
544 /*! \brief
545  * Link the new uri into the list.
546  *
547  * They are sorted by length of
548  * the string, not alphabetically. Duplicate entries are not replaced,
549  * but the insertion order (using <= and not just <) makes sure that
550  * more recent insertions hide older ones.
551  * On a lookup, we just scan the list and stop at the first matching entry.
552  */
553 int ast_http_uri_link(struct ast_http_uri *urih)
554 {
555         struct ast_http_uri *uri;
556         int len = strlen(urih->uri);
557
558         AST_RWLIST_WRLOCK(&uris);
559
560         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
561                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
562                 AST_RWLIST_UNLOCK(&uris);
563                 return 0;
564         }
565
566         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
567                 if (AST_RWLIST_NEXT(uri, entry) &&
568                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
569                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
570                         AST_RWLIST_UNLOCK(&uris);
571
572                         return 0;
573                 }
574         }
575
576         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
577
578         AST_RWLIST_UNLOCK(&uris);
579
580         return 0;
581 }
582
583 void ast_http_uri_unlink(struct ast_http_uri *urih)
584 {
585         AST_RWLIST_WRLOCK(&uris);
586         AST_RWLIST_REMOVE(&uris, urih, entry);
587         AST_RWLIST_UNLOCK(&uris);
588 }
589
590 void ast_http_uri_unlink_all_with_key(const char *key)
591 {
592         struct ast_http_uri *urih;
593         AST_RWLIST_WRLOCK(&uris);
594         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
595                 if (!strcmp(urih->key, key)) {
596                         AST_RWLIST_REMOVE_CURRENT(entry);
597                         if (urih->dmallocd) {
598                                 ast_free(urih->data);
599                         }
600                         if (urih->mallocd) {
601                                 ast_free(urih);
602                         }
603                 }
604         }
605         AST_RWLIST_TRAVERSE_SAFE_END;
606         AST_RWLIST_UNLOCK(&uris);
607 }
608
609 #define MAX_POST_CONTENT 1025
610
611 /*!
612  * \brief Retrieves the header with the given field name.
613  *
614  * \param headers Headers to search.
615  * \param field_name Name of the header to find.
616  * \return Associated header value.
617  * \return \c NULL if header is not present.
618  */
619 static const char *get_header(struct ast_variable *headers,
620         const char *field_name)
621 {
622         struct ast_variable *v;
623
624         for (v = headers; v; v = v->next) {
625                 if (!strcasecmp(v->name, field_name)) {
626                         return v->value;
627                 }
628         }
629         return NULL;
630 }
631
632 /*!
633  * \brief Retrieves the content type specified in the "Content-Type" header.
634  *
635  * This function only returns the "type/subtype" and any trailing parameter is
636  * not included.
637  *
638  * \note the return value is an allocated string that needs to be freed.
639  *
640  * \retval the content type/subtype or NULL if the header is not found.
641  */
642 static char *get_content_type(struct ast_variable *headers)
643 {
644         const char *content_type = get_header(headers, "Content-Type");
645         const char *param;
646         size_t size;
647
648         if (!content_type) {
649                 return NULL;
650         }
651
652         param = strchr(content_type, ';');
653         size = param ? param - content_type : strlen(content_type);
654
655         return ast_strndup(content_type, size);
656 }
657
658 /*!
659  * \brief Returns the value of the Content-Length header.
660  *
661  * \param headers HTTP headers.
662  * \return Value of the Content-Length header.
663  * \return 0 if header is not present, or is invalid.
664  */
665 static int get_content_length(struct ast_variable *headers)
666 {
667         const char *content_length = get_header(headers, "Content-Length");
668
669         if (!content_length) {
670                 /* Missing content length; assume zero */
671                 return 0;
672         }
673
674         /* atoi() will return 0 for invalid inputs, which is good enough for
675          * the HTTP parsing. */
676         return atoi(content_length);
677 }
678
679 /*!
680  * \brief Returns the value of the Transfer-Encoding header.
681  *
682  * \param headers HTTP headers.
683  * \return Value of the Transfer-Encoding header.
684  * \return 0 if header is not present, or is invalid.
685  */
686 static const char *get_transfer_encoding(struct ast_variable *headers)
687 {
688         return get_header(headers, "Transfer-Encoding");
689 }
690
691 struct ast_json *ast_http_get_json(
692         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
693 {
694         int content_length = 0;
695         int res;
696         struct ast_json *body;
697         RAII_VAR(char *, buf, NULL, ast_free);
698         RAII_VAR(char *, type, get_content_type(headers), ast_free);
699
700         /* Use errno to distinguish errors from no body */
701         errno = 0;
702
703         if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
704                 /* Content type is not JSON */
705                 return NULL;
706         }
707
708         content_length = get_content_length(headers);
709
710         if (content_length <= 0) {
711                 /* No content (or streaming content). */
712                 return NULL;
713         }
714
715         if (content_length > MAX_POST_CONTENT - 1) {
716                 ast_log(LOG_WARNING,
717                         "Excessively long HTTP content. (%d > %d)\n",
718                         content_length, MAX_POST_CONTENT);
719                 errno = EFBIG;
720                 return NULL;
721         }
722
723         buf = ast_malloc(content_length);
724         if (!buf) {
725                 /* Malloc sets ENOMEM */
726                 return NULL;
727         }
728
729         res = fread(buf, 1, content_length, ser->f);
730         if (res < content_length) {
731                 /* Error, distinguishable by ferror() or feof(), but neither
732                  * is good. Treat either one as I/O error */
733                 ast_log(LOG_WARNING, "Short HTTP request body (%d < %d)\n",
734                         res, content_length);
735                 errno = EIO;
736                 return NULL;
737         }
738
739         body = ast_json_load_buf(buf, content_length, NULL);
740         if (body == NULL) {
741                 /* Failed to parse JSON; treat as an I/O error */
742                 errno = EIO;
743                 return NULL;
744         }
745
746         return body;
747 }
748
749 /*
750  * get post variables from client Request Entity-Body, if content type is
751  * application/x-www-form-urlencoded
752  */
753 struct ast_variable *ast_http_get_post_vars(
754         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
755 {
756         int content_length = 0;
757         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
758         char *var, *val;
759         RAII_VAR(char *, buf, NULL, ast_free_ptr);
760         RAII_VAR(char *, type, get_content_type(headers), ast_free);
761         int res;
762
763         /* Use errno to distinguish errors from no params */
764         errno = 0;
765
766         if (ast_strlen_zero(type) ||
767             strcasecmp(type, "application/x-www-form-urlencoded")) {
768                 /* Content type is not form data */
769                 return NULL;
770         }
771
772         content_length = get_content_length(headers);
773
774         if (content_length <= 0) {
775                 return NULL;
776         }
777
778         if (content_length > MAX_POST_CONTENT - 1) {
779                 ast_log(LOG_WARNING,
780                         "Excessively long HTTP content. (%d > %d)\n",
781                         content_length, MAX_POST_CONTENT);
782                 errno = EFBIG;
783                 return NULL;
784         }
785
786         buf = ast_malloc(content_length + 1);
787         if (!buf) {
788                 /* malloc sets errno to ENOMEM */
789                 return NULL;
790         }
791
792         res = fread(buf, 1, content_length, ser->f);
793         if (res < content_length) {
794                 /* Error, distinguishable by ferror() or feof(), but neither
795                  * is good. Treat either one as I/O error */
796                 errno = EIO;
797                 return NULL;
798         }
799         buf[content_length] = '\0';
800
801         while ((val = strsep(&buf, "&"))) {
802                 var = strsep(&val, "=");
803                 if (val) {
804                         ast_uri_decode(val, ast_uri_http_legacy);
805                 } else  {
806                         val = "";
807                 }
808                 ast_uri_decode(var, ast_uri_http_legacy);
809                 if ((v = ast_variable_new(var, val, ""))) {
810                         if (post_vars) {
811                                 prev->next = v;
812                         } else {
813                                 post_vars = v;
814                         }
815                         prev = v;
816                 }
817         }
818
819         return post_vars;
820 }
821
822 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
823         enum ast_http_method method, struct ast_variable *headers)
824 {
825         char *c;
826         int res = -1;
827         char *params = uri;
828         struct ast_http_uri *urih = NULL;
829         int l;
830         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
831         struct http_uri_redirect *redirect;
832
833         ast_debug(2, "HTTP Request URI is %s \n", uri);
834
835         strsep(&params, "?");
836         /* Extract arguments from the request and store them in variables. */
837         if (params) {
838                 char *var, *val;
839
840                 while ((val = strsep(&params, "&"))) {
841                         var = strsep(&val, "=");
842                         if (val) {
843                                 ast_uri_decode(val, ast_uri_http_legacy);
844                         } else  {
845                                 val = "";
846                         }
847                         ast_uri_decode(var, ast_uri_http_legacy);
848                         if ((v = ast_variable_new(var, val, ""))) {
849                                 if (get_vars) {
850                                         prev->next = v;
851                                 } else {
852                                         get_vars = v;
853                                 }
854                                 prev = v;
855                         }
856                 }
857         }
858
859         AST_RWLIST_RDLOCK(&uri_redirects);
860         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
861                 if (!strcasecmp(uri, redirect->target)) {
862                         struct ast_str *http_header = ast_str_create(128);
863                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
864                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
865
866                         break;
867                 }
868         }
869         AST_RWLIST_UNLOCK(&uri_redirects);
870         if (redirect) {
871                 goto cleanup;
872         }
873
874         /* We want requests to start with the (optional) prefix and '/' */
875         l = strlen(prefix);
876         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
877                 uri += l + 1;
878                 /* scan registered uris to see if we match one. */
879                 AST_RWLIST_RDLOCK(&uris);
880                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
881                         l = strlen(urih->uri);
882                         c = uri + l;    /* candidate */
883                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
884                         if (strncasecmp(urih->uri, uri, l) /* no match */
885                             || (*c && *c != '/')) { /* substring */
886                                 continue;
887                         }
888                         if (*c == '/') {
889                                 c++;
890                         }
891                         if (!*c || urih->has_subtree) {
892                                 uri = c;
893                                 break;
894                         }
895                 }
896                 AST_RWLIST_UNLOCK(&uris);
897         }
898         if (urih) {
899                 ast_debug(1, "Match made with [%s]\n", urih->uri);
900                 if (!urih->no_decode_uri) {
901                         ast_uri_decode(uri, ast_uri_http_legacy);
902                 }
903                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
904         } else {
905                 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
906                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
907         }
908
909 cleanup:
910         ast_variables_destroy(get_vars);
911         return res;
912 }
913
914 #ifdef DO_SSL
915 #if defined(HAVE_FUNOPEN)
916 #define HOOK_T int
917 #define LEN_T int
918 #else
919 #define HOOK_T ssize_t
920 #define LEN_T size_t
921 #endif
922
923 /*!
924  * replacement read/write functions for SSL support.
925  * We use wrappers rather than SSL_read/SSL_write directly so
926  * we can put in some debugging.
927  */
928 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
929 {
930         int i = SSL_read(cookie, buf, len-1);
931 #if 0
932         if (i >= 0)
933                 buf[i] = '\0';
934         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
935 #endif
936         return i;
937 }
938
939 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
940 {
941 #if 0
942         char *s = ast_alloca(len+1);
943         strncpy(s, buf, len);
944         s[len] = '\0';
945         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
946 #endif
947         return SSL_write(cookie, buf, len);
948 }
949
950 static int ssl_close(void *cookie)
951 {
952         close(SSL_get_fd(cookie));
953         SSL_shutdown(cookie);
954         SSL_free(cookie);
955         return 0;
956 }*/
957 #endif  /* DO_SSL */
958
959 static struct ast_variable *parse_cookies(char *cookies)
960 {
961         char *cur;
962         struct ast_variable *vars = NULL, *var;
963
964         while ((cur = strsep(&cookies, ";"))) {
965                 char *name, *val;
966
967                 name = val = cur;
968                 strsep(&val, "=");
969
970                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
971                         continue;
972                 }
973
974                 name = ast_strip(name);
975                 val = ast_strip_quoted(val, "\"", "\"");
976
977                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
978                         continue;
979                 }
980
981                 ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
982
983                 var = ast_variable_new(name, val, __FILE__);
984                 var->next = vars;
985                 vars = var;
986         }
987
988         return vars;
989 }
990
991 /* get cookie from Request headers */
992 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
993 {
994         struct ast_variable *v, *cookies=NULL;
995
996         for (v = headers; v; v = v->next) {
997                 if (!strcasecmp(v->name, "Cookie")) {
998                         char *tmp = ast_strdupa(v->value);
999                         if (cookies) {
1000                                 ast_variables_destroy(cookies);
1001                         }
1002
1003                         cookies = parse_cookies(tmp);
1004                 }
1005         }
1006         return cookies;
1007 }
1008
1009 static struct ast_http_auth *auth_create(const char *userid,
1010         const char *password)
1011 {
1012         RAII_VAR(struct ast_http_auth *, auth, NULL, ao2_cleanup);
1013         size_t userid_len;
1014         size_t password_len;
1015
1016         if (!userid || !password) {
1017                 ast_log(LOG_ERROR, "Invalid userid/password\n");
1018                 return NULL;
1019         }
1020
1021         userid_len = strlen(userid) + 1;
1022         password_len = strlen(password) + 1;
1023
1024         /* Allocate enough room to store everything in one memory block */
1025         auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
1026         if (!auth) {
1027                 return NULL;
1028         }
1029
1030         /* Put the userid right after the struct */
1031         auth->userid = (char *)(auth + 1);
1032         strcpy(auth->userid, userid);
1033
1034         /* Put the password right after the userid */
1035         auth->password = auth->userid + userid_len;
1036         strcpy(auth->password, password);
1037
1038         ao2_ref(auth, +1);
1039         return auth;
1040 }
1041
1042 #define BASIC_PREFIX "Basic "
1043 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
1044
1045 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
1046 {
1047         struct ast_variable *v;
1048
1049         for (v = headers; v; v = v->next) {
1050                 const char *base64;
1051                 char decoded[256] = {};
1052                 char *username;
1053                 char *password;
1054 #ifdef AST_DEVMODE
1055                 int cnt;
1056 #endif /* AST_DEVMODE */
1057
1058                 if (strcasecmp("Authorization", v->name) != 0) {
1059                         continue;
1060                 }
1061
1062                 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1063                         ast_log(LOG_DEBUG,
1064                                 "Unsupported Authorization scheme\n");
1065                         continue;
1066                 }
1067
1068                 /* Basic auth header parsing. RFC 2617, section 2.
1069                  *   credentials = "Basic" basic-credentials
1070                  *   basic-credentials = base64-user-pass
1071                  *   base64-user-pass  = <base64 encoding of user-pass,
1072                  *                        except not limited to 76 char/line>
1073                  *   user-pass   = userid ":" password
1074                  */
1075
1076                 base64 = v->value + BASIC_LEN;
1077
1078                 /* This will truncate "userid:password" lines to
1079                  * sizeof(decoded). The array is long enough that this shouldn't
1080                  * be a problem */
1081 #ifdef AST_DEVMODE
1082                 cnt =
1083 #endif /* AST_DEVMODE */
1084                 ast_base64decode((unsigned char*)decoded, base64,
1085                         sizeof(decoded) - 1);
1086                 ast_assert(cnt < sizeof(decoded));
1087
1088                 /* Split the string at the colon */
1089                 password = decoded;
1090                 username = strsep(&password, ":");
1091                 if (!password) {
1092                         ast_log(LOG_WARNING, "Invalid Authorization header\n");
1093                         return NULL;
1094                 }
1095
1096                 return auth_create(username, password);
1097         }
1098
1099         return NULL;
1100 }
1101
1102 static void *httpd_helper_thread(void *data)
1103 {
1104         char buf[4096];
1105         char header_line[4096];
1106         struct ast_tcptls_session_instance *ser = data;
1107         struct ast_variable *headers = NULL;
1108         struct ast_variable *tail = headers;
1109         char *uri, *method;
1110         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1111         const char *transfer_encoding;
1112
1113         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1114                 goto done;
1115         }
1116
1117         if (!fgets(buf, sizeof(buf), ser->f)) {
1118                 goto done;
1119         }
1120
1121         /* Get method */
1122         method = ast_skip_blanks(buf);
1123         uri = ast_skip_nonblanks(method);
1124         if (*uri) {
1125                 *uri++ = '\0';
1126         }
1127
1128         if (!strcasecmp(method,"GET")) {
1129                 http_method = AST_HTTP_GET;
1130         } else if (!strcasecmp(method,"POST")) {
1131                 http_method = AST_HTTP_POST;
1132         } else if (!strcasecmp(method,"HEAD")) {
1133                 http_method = AST_HTTP_HEAD;
1134         } else if (!strcasecmp(method,"PUT")) {
1135                 http_method = AST_HTTP_PUT;
1136         } else if (!strcasecmp(method,"DELETE")) {
1137                 http_method = AST_HTTP_DELETE;
1138         } else if (!strcasecmp(method,"OPTIONS")) {
1139                 http_method = AST_HTTP_OPTIONS;
1140         }
1141
1142         uri = ast_skip_blanks(uri);     /* Skip white space */
1143
1144         if (*uri) {                     /* terminate at the first blank */
1145                 char *c = ast_skip_nonblanks(uri);
1146
1147                 if (*c) {
1148                         *c = '\0';
1149                 }
1150         }
1151
1152         /* process "Request Headers" lines */
1153         while (fgets(header_line, sizeof(header_line), ser->f)) {
1154                 char *name, *value;
1155
1156                 /* Trim trailing characters */
1157                 ast_trim_blanks(header_line);
1158                 if (ast_strlen_zero(header_line)) {
1159                         break;
1160                 }
1161
1162                 value = header_line;
1163                 name = strsep(&value, ":");
1164                 if (!value) {
1165                         continue;
1166                 }
1167
1168                 value = ast_skip_blanks(value);
1169                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1170                         continue;
1171                 }
1172
1173                 ast_trim_blanks(name);
1174
1175                 if (!headers) {
1176                         headers = ast_variable_new(name, value, __FILE__);
1177                         tail = headers;
1178                 } else {
1179                         tail->next = ast_variable_new(name, value, __FILE__);
1180                         tail = tail->next;
1181                 }
1182         }
1183
1184         transfer_encoding = get_transfer_encoding(headers);
1185         /* Transfer encoding defaults to identity */
1186         if (!transfer_encoding) {
1187                 transfer_encoding = "identity";
1188         }
1189
1190         /*
1191          * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
1192          * codings we don't understand.
1193          */
1194         if (strcasecmp(transfer_encoding, "identity") != 0) {
1195                 /* Transfer encodings not supported */
1196                 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
1197                 goto done;
1198         }
1199
1200         if (!*uri) {
1201                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1202                 goto done;
1203         }
1204
1205         handle_uri(ser, uri, http_method, headers);
1206
1207 done:
1208         ast_atomic_fetchadd_int(&session_count, -1);
1209
1210         /* clean up all the header information */
1211         if (headers) {
1212                 ast_variables_destroy(headers);
1213         }
1214
1215         if (ser->f) {
1216                 fclose(ser->f);
1217         }
1218         ao2_ref(ser, -1);
1219         ser = NULL;
1220         return NULL;
1221 }
1222
1223 /*!
1224  * \brief Add a new URI redirect
1225  * The entries in the redirect list are sorted by length, just like the list
1226  * of URI handlers.
1227  */
1228 static void add_redirect(const char *value)
1229 {
1230         char *target, *dest;
1231         struct http_uri_redirect *redirect, *cur;
1232         unsigned int target_len;
1233         unsigned int total_len;
1234
1235         dest = ast_strdupa(value);
1236         dest = ast_skip_blanks(dest);
1237         target = strsep(&dest, " ");
1238         target = ast_skip_blanks(target);
1239         target = strsep(&target, " "); /* trim trailing whitespace */
1240
1241         if (!dest) {
1242                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
1243                 return;
1244         }
1245
1246         target_len = strlen(target) + 1;
1247         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
1248
1249         if (!(redirect = ast_calloc(1, total_len))) {
1250                 return;
1251         }
1252         redirect->dest = redirect->target + target_len;
1253         strcpy(redirect->target, target);
1254         strcpy(redirect->dest, dest);
1255
1256         AST_RWLIST_WRLOCK(&uri_redirects);
1257
1258         target_len--; /* So we can compare directly with strlen() */
1259         if (AST_RWLIST_EMPTY(&uri_redirects)
1260                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1261                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1262                 AST_RWLIST_UNLOCK(&uri_redirects);
1263
1264                 return;
1265         }
1266
1267         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1268                 if (AST_RWLIST_NEXT(cur, entry)
1269                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1270                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1271                         AST_RWLIST_UNLOCK(&uri_redirects);
1272                         return;
1273                 }
1274         }
1275
1276         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1277
1278         AST_RWLIST_UNLOCK(&uri_redirects);
1279 }
1280
1281 static int __ast_http_load(int reload)
1282 {
1283         struct ast_config *cfg;
1284         struct ast_variable *v;
1285         int enabled=0;
1286         int newenablestatic=0;
1287         char newprefix[MAX_PREFIX] = "";
1288         struct http_uri_redirect *redirect;
1289         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1290         uint32_t bindport = DEFAULT_PORT;
1291         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1292         int num_addrs = 0;
1293         int http_tls_was_enabled = 0;
1294
1295         cfg = ast_config_load2("http.conf", "http", config_flags);
1296         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1297                 return 0;
1298         }
1299
1300         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1301
1302         http_tls_cfg.enabled = 0;
1303         if (http_tls_cfg.certfile) {
1304                 ast_free(http_tls_cfg.certfile);
1305         }
1306         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1307
1308         if (http_tls_cfg.pvtfile) {
1309                 ast_free(http_tls_cfg.pvtfile);
1310         }
1311         http_tls_cfg.pvtfile = ast_strdup("");
1312
1313         if (http_tls_cfg.cipher) {
1314                 ast_free(http_tls_cfg.cipher);
1315         }
1316         http_tls_cfg.cipher = ast_strdup("");
1317
1318         AST_RWLIST_WRLOCK(&uri_redirects);
1319         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1320                 ast_free(redirect);
1321         }
1322         AST_RWLIST_UNLOCK(&uri_redirects);
1323
1324         ast_sockaddr_setnull(&https_desc.local_address);
1325
1326         if (cfg) {
1327                 v = ast_variable_browse(cfg, "general");
1328                 for (; v; v = v->next) {
1329
1330                         /* read tls config options while preventing unsupported options from being set */
1331                         if (strcasecmp(v->name, "tlscafile")
1332                                 && strcasecmp(v->name, "tlscapath")
1333                                 && strcasecmp(v->name, "tlscadir")
1334                                 && strcasecmp(v->name, "tlsverifyclient")
1335                                 && strcasecmp(v->name, "tlsdontverifyserver")
1336                                 && strcasecmp(v->name, "tlsclientmethod")
1337                                 && strcasecmp(v->name, "sslclientmethod")
1338                                 && strcasecmp(v->name, "tlscipher")
1339                                 && strcasecmp(v->name, "sslcipher")
1340                                 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1341                                 continue;
1342                         }
1343
1344                         if (!strcasecmp(v->name, "enabled")) {
1345                                 enabled = ast_true(v->value);
1346                         } else if (!strcasecmp(v->name, "enablestatic")) {
1347                                 newenablestatic = ast_true(v->value);
1348                         } else if (!strcasecmp(v->name, "bindport")) {
1349                                 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1350                                         ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1351                                 }
1352                         } else if (!strcasecmp(v->name, "bindaddr")) {
1353                                 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1354                                         ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1355                                 }
1356                         } else if (!strcasecmp(v->name, "prefix")) {
1357                                 if (!ast_strlen_zero(v->value)) {
1358                                         newprefix[0] = '/';
1359                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1360                                 } else {
1361                                         newprefix[0] = '\0';
1362                                 }
1363                         } else if (!strcasecmp(v->name, "redirect")) {
1364                                 add_redirect(v->value);
1365                         } else if (!strcasecmp(v->name, "sessionlimit")) {
1366                                 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1367                                                         &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1368                                         ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1369                                                         v->name, v->value, v->lineno);
1370                                 }
1371                         } else {
1372                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1373                         }
1374                 }
1375
1376                 ast_config_destroy(cfg);
1377         }
1378
1379         if (strcmp(prefix, newprefix)) {
1380                 ast_copy_string(prefix, newprefix, sizeof(prefix));
1381         }
1382         enablestatic = newenablestatic;
1383
1384         if (num_addrs && enabled) {
1385                 int i;
1386                 for (i = 0; i < num_addrs; ++i) {
1387                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1388                         if (!ast_sockaddr_port(&http_desc.local_address)) {
1389                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1390                         }
1391                         ast_tcptls_server_start(&http_desc);
1392                         if (http_desc.accept_fd == -1) {
1393                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1394                                 ast_sockaddr_setnull(&http_desc.local_address);
1395                         } else {
1396                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1397                                 break;
1398                         }
1399                 }
1400                 /* When no specific TLS bindaddr is specified, we just use
1401                  * the non-TLS bindaddress here.
1402                  */
1403                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1404                         ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1405                         /* Of course, we can't use the same port though.
1406                          * Since no bind address was specified, we just use the
1407                          * default TLS port
1408                          */
1409                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1410                 }
1411         }
1412         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1413                 ast_tcptls_server_stop(&https_desc);
1414         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1415                 /* We can get here either because a TLS-specific address was specified
1416                  * or because we copied the non-TLS address here. In the case where
1417                  * we read an explicit address from the config, there may have been
1418                  * no port specified, so we'll just use the default TLS port.
1419                  */
1420                 if (!ast_sockaddr_port(&https_desc.local_address)) {
1421                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1422                 }
1423                 if (ast_ssl_setup(https_desc.tls_cfg)) {
1424                         ast_tcptls_server_start(&https_desc);
1425                 }
1426         }
1427
1428         return 0;
1429 }
1430
1431 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1432 {
1433         struct ast_http_uri *urih;
1434         struct http_uri_redirect *redirect;
1435
1436         switch (cmd) {
1437         case CLI_INIT:
1438                 e->command = "http show status";
1439                 e->usage =
1440                         "Usage: http show status\n"
1441                         "       Lists status of internal HTTP engine\n";
1442                 return NULL;
1443         case CLI_GENERATE:
1444                 return NULL;
1445         }
1446
1447         if (a->argc != 3) {
1448                 return CLI_SHOWUSAGE;
1449         }
1450         ast_cli(a->fd, "HTTP Server Status:\n");
1451         ast_cli(a->fd, "Prefix: %s\n", prefix);
1452         if (ast_sockaddr_isnull(&http_desc.old_address)) {
1453                 ast_cli(a->fd, "Server Disabled\n\n");
1454         } else {
1455                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1456                         ast_sockaddr_stringify(&http_desc.old_address));
1457                 if (http_tls_cfg.enabled) {
1458                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1459                                 ast_sockaddr_stringify(&https_desc.old_address));
1460                 }
1461         }
1462
1463         ast_cli(a->fd, "Enabled URI's:\n");
1464         AST_RWLIST_RDLOCK(&uris);
1465         if (AST_RWLIST_EMPTY(&uris)) {
1466                 ast_cli(a->fd, "None.\n");
1467         } else {
1468                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1469                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1470         }
1471         AST_RWLIST_UNLOCK(&uris);
1472
1473         ast_cli(a->fd, "\nEnabled Redirects:\n");
1474         AST_RWLIST_RDLOCK(&uri_redirects);
1475         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1476                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
1477         if (AST_RWLIST_EMPTY(&uri_redirects)) {
1478                 ast_cli(a->fd, "  None.\n");
1479         }
1480         AST_RWLIST_UNLOCK(&uri_redirects);
1481
1482         return CLI_SUCCESS;
1483 }
1484
1485 int ast_http_reload(void)
1486 {
1487         return __ast_http_load(1);
1488 }
1489
1490 static struct ast_cli_entry cli_http[] = {
1491         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1492 };
1493
1494 static void http_shutdown(void)
1495 {
1496         struct http_uri_redirect *redirect;
1497         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1498
1499         ast_tcptls_server_stop(&http_desc);
1500         if (http_tls_cfg.enabled) {
1501                 ast_tcptls_server_stop(&https_desc);
1502         }
1503         ast_free(http_tls_cfg.certfile);
1504         ast_free(http_tls_cfg.pvtfile);
1505         ast_free(http_tls_cfg.cipher);
1506
1507         ast_http_uri_unlink(&statusuri);
1508         ast_http_uri_unlink(&staticuri);
1509
1510         AST_RWLIST_WRLOCK(&uri_redirects);
1511         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1512                 ast_free(redirect);
1513         }
1514         AST_RWLIST_UNLOCK(&uri_redirects);
1515 }
1516
1517 int ast_http_init(void)
1518 {
1519         ast_http_uri_link(&statusuri);
1520         ast_http_uri_link(&staticuri);
1521         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1522         ast_register_atexit(http_shutdown);
1523
1524         return __ast_http_load(0);
1525 }