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