Merge "res_calendar: Specialized calendars depend on symbols of general calendar."
[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 #include <time.h>
48 #include <sys/time.h>
49 #include <sys/stat.h>
50 #include <signal.h>
51 #include <fcntl.h>
52
53 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
54 #include "asterisk/cli.h"
55 #include "asterisk/tcptls.h"
56 #include "asterisk/http.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/strings.h"
59 #include "asterisk/config.h"
60 #include "asterisk/stringfields.h"
61 #include "asterisk/ast_version.h"
62 #include "asterisk/manager.h"
63 #include "asterisk/_private.h"
64 #include "asterisk/astobj2.h"
65 #include "asterisk/netsock2.h"
66 #include "asterisk/json.h"
67
68 #define MAX_PREFIX 80
69 #define DEFAULT_PORT 8088
70 #define DEFAULT_TLS_PORT 8089
71 #define DEFAULT_SESSION_LIMIT 100
72 /*! (ms) Idle time waiting for data. */
73 #define DEFAULT_SESSION_INACTIVITY 30000
74 /*! (ms) Min timeout for initial HTTP request to start coming in. */
75 #define MIN_INITIAL_REQUEST_TIMEOUT     10000
76 /*! (ms) Idle time between HTTP requests */
77 #define DEFAULT_SESSION_KEEP_ALIVE 15000
78 /*! Max size for the http server name */
79 #define MAX_SERVER_NAME_LENGTH 128
80 /*! Max size for the http response header */
81 #define DEFAULT_RESPONSE_HEADER_LENGTH 512
82
83 /*! Maximum application/json or application/x-www-form-urlencoded body content length. */
84 #if !defined(LOW_MEMORY)
85 #define MAX_CONTENT_LENGTH 4096
86 #else
87 #define MAX_CONTENT_LENGTH 1024
88 #endif  /* !defined(LOW_MEMORY) */
89
90 /*! Maximum line length for HTTP requests. */
91 #if !defined(LOW_MEMORY)
92 #define MAX_HTTP_LINE_LENGTH 4096
93 #else
94 #define MAX_HTTP_LINE_LENGTH 1024
95 #endif  /* !defined(LOW_MEMORY) */
96
97 static char http_server_name[MAX_SERVER_NAME_LENGTH];
98
99 static int session_limit = DEFAULT_SESSION_LIMIT;
100 static int session_inactivity = DEFAULT_SESSION_INACTIVITY;
101 static int session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
102 static int session_count = 0;
103
104 static struct ast_tls_config http_tls_cfg;
105
106 static void *httpd_helper_thread(void *arg);
107
108 /*!
109  * we have up to two accepting threads, one for http, one for https
110  */
111 static struct ast_tcptls_session_args http_desc = {
112         .accept_fd = -1,
113         .master = AST_PTHREADT_NULL,
114         .tls_cfg = NULL,
115         .poll_timeout = -1,
116         .name = "http server",
117         .accept_fn = ast_tcptls_server_root,
118         .worker_fn = httpd_helper_thread,
119 };
120
121 static struct ast_tcptls_session_args https_desc = {
122         .accept_fd = -1,
123         .master = AST_PTHREADT_NULL,
124         .tls_cfg = &http_tls_cfg,
125         .poll_timeout = -1,
126         .name = "https server",
127         .accept_fn = ast_tcptls_server_root,
128         .worker_fn = httpd_helper_thread,
129 };
130
131 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri);      /*!< list of supported handlers */
132
133 /* all valid URIs must be prepended by the string in prefix. */
134 static char prefix[MAX_PREFIX];
135 static int enablestatic;
136
137 /*! \brief Limit the kinds of files we're willing to serve up */
138 static struct {
139         const char *ext;
140         const char *mtype;
141 } mimetypes[] = {
142         { "png", "image/png" },
143         { "xml", "text/xml" },
144         { "jpg", "image/jpeg" },
145         { "js", "application/x-javascript" },
146         { "wav", "audio/x-wav" },
147         { "mp3", "audio/mpeg" },
148         { "svg", "image/svg+xml" },
149         { "svgz", "image/svg+xml" },
150         { "gif", "image/gif" },
151         { "html", "text/html" },
152         { "htm", "text/html" },
153         { "css", "text/css" },
154         { "cnf", "text/plain" },
155         { "cfg", "text/plain" },
156         { "bin", "application/octet-stream" },
157         { "sbn", "application/octet-stream" },
158         { "ld", "application/octet-stream" },
159 };
160
161 struct http_uri_redirect {
162         AST_LIST_ENTRY(http_uri_redirect) entry;
163         char *dest;
164         char target[0];
165 };
166
167 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
168
169 static const struct ast_cfhttp_methods_text {
170         enum ast_http_method method;
171         const char *text;
172 } ast_http_methods_text[] = {
173         { AST_HTTP_UNKNOWN,     "UNKNOWN" },
174         { AST_HTTP_GET,         "GET" },
175         { AST_HTTP_POST,        "POST" },
176         { AST_HTTP_HEAD,        "HEAD" },
177         { AST_HTTP_PUT,         "PUT" },
178         { AST_HTTP_DELETE,      "DELETE" },
179         { AST_HTTP_OPTIONS,     "OPTIONS" },
180 };
181
182 const char *ast_get_http_method(enum ast_http_method method)
183 {
184         int x;
185
186         for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
187                 if (ast_http_methods_text[x].method == method) {
188                         return ast_http_methods_text[x].text;
189                 }
190         }
191
192         return NULL;
193 }
194
195 const char *ast_http_ftype2mtype(const char *ftype)
196 {
197         int x;
198
199         if (ftype) {
200                 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
201                         if (!strcasecmp(ftype, mimetypes[x].ext)) {
202                                 return mimetypes[x].mtype;
203                         }
204                 }
205         }
206         return NULL;
207 }
208
209 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
210 {
211         uint32_t mngid = 0;
212         struct ast_variable *v, *cookies;
213
214         cookies = ast_http_get_cookies(headers);
215         for (v = cookies; v; v = v->next) {
216                 if (!strcasecmp(v->name, "mansession_id")) {
217                         sscanf(v->value, "%30x", &mngid);
218                         break;
219                 }
220         }
221         ast_variables_destroy(cookies);
222         return mngid;
223 }
224
225 void ast_http_prefix(char *buf, int len)
226 {
227         if (buf) {
228                 ast_copy_string(buf, prefix, len);
229         }
230 }
231
232 static int static_callback(struct ast_tcptls_session_instance *ser,
233         const struct ast_http_uri *urih, const char *uri,
234         enum ast_http_method method, struct ast_variable *get_vars,
235         struct ast_variable *headers)
236 {
237         char *path;
238         const char *ftype;
239         const char *mtype;
240         char wkspace[80];
241         struct stat st;
242         int len;
243         int fd;
244         struct ast_str *http_header;
245         struct timeval tv;
246         struct ast_tm tm;
247         char timebuf[80], etag[23];
248         struct ast_variable *v;
249         int not_modified = 0;
250
251         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
252                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
253                 return 0;
254         }
255
256         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
257            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
258         if (!enablestatic || ast_strlen_zero(uri)) {
259                 goto out403;
260         }
261
262         /* Disallow any funny filenames at all (checking first character only??) */
263         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
264                 goto out403;
265         }
266
267         if (strstr(uri, "/..")) {
268                 goto out403;
269         }
270
271         if ((ftype = strrchr(uri, '.'))) {
272                 ftype++;
273         }
274
275         if (!(mtype = ast_http_ftype2mtype(ftype))) {
276                 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
277                 mtype = wkspace;
278         }
279
280         /* Cap maximum length */
281         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
282                 goto out403;
283         }
284
285         path = ast_alloca(len);
286         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
287         if (stat(path, &st)) {
288                 goto out404;
289         }
290
291         if (S_ISDIR(st.st_mode)) {
292                 goto out404;
293         }
294
295         if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
296                 goto out403;
297         }
298
299         fd = open(path, O_RDONLY);
300         if (fd < 0) {
301                 goto out403;
302         }
303
304         /* make "Etag:" http header value */
305         snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
306
307         /* make "Last-Modified:" http header value */
308         tv.tv_sec = st.st_mtime;
309         tv.tv_usec = 0;
310         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
311
312         /* check received "If-None-Match" request header and Etag value for file */
313         for (v = headers; v; v = v->next) {
314                 if (!strcasecmp(v->name, "If-None-Match")) {
315                         if (!strcasecmp(v->value, etag)) {
316                                 not_modified = 1;
317                         }
318                         break;
319                 }
320         }
321
322         http_header = ast_str_create(255);
323         if (!http_header) {
324                 ast_http_request_close_on_completion(ser);
325                 ast_http_error(ser, 500, "Server Error", "Out of memory");
326                 close(fd);
327                 return 0;
328         }
329
330         ast_str_set(&http_header, 0, "Content-type: %s\r\n"
331                 "ETag: %s\r\n"
332                 "Last-Modified: %s\r\n",
333                 mtype,
334                 etag,
335                 timebuf);
336
337         /* ast_http_send() frees http_header, so we don't need to do it before returning */
338         if (not_modified) {
339                 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
340         } else {
341                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
342         }
343         close(fd);
344         return 0;
345
346 out404:
347         ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
348         return 0;
349
350 out403:
351         ast_http_request_close_on_completion(ser);
352         ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
353         return 0;
354 }
355
356 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
357         const struct ast_http_uri *urih, const char *uri,
358         enum ast_http_method method, struct ast_variable *get_vars,
359         struct ast_variable *headers)
360 {
361         struct ast_str *out;
362         struct ast_variable *v, *cookies = NULL;
363
364         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
365                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
366                 return 0;
367         }
368
369         out = ast_str_create(512);
370         if (!out) {
371                 ast_http_request_close_on_completion(ser);
372                 ast_http_error(ser, 500, "Server Error", "Out of memory");
373                 return 0;
374         }
375
376         ast_str_append(&out, 0,
377                 "<html><title>Asterisk HTTP Status</title>\r\n"
378                 "<body bgcolor=\"#ffffff\">\r\n"
379                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
380                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
381
382         ast_str_append(&out, 0, "<tr><td><i>Server</i></td><td><b>%s</b></td></tr>\r\n", http_server_name);
383         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
384         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
385                        ast_sockaddr_stringify_addr(&http_desc.old_address));
386         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
387                        ast_sockaddr_stringify_port(&http_desc.old_address));
388         if (http_tls_cfg.enabled) {
389                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
390                                ast_sockaddr_stringify_port(&https_desc.old_address));
391         }
392         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
393         for (v = get_vars; v; v = v->next) {
394                 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
395         }
396         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
397
398         cookies = ast_http_get_cookies(headers);
399         for (v = cookies; v; v = v->next) {
400                 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
401         }
402         ast_variables_destroy(cookies);
403
404         ast_str_append(&out, 0, "</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body></html>\r\n");
405         ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
406         return 0;
407 }
408
409 static struct ast_http_uri statusuri = {
410         .callback = httpstatus_callback,
411         .description = "Asterisk HTTP General Status",
412         .uri = "httpstatus",
413         .has_subtree = 0,
414         .data = NULL,
415         .key = __FILE__,
416 };
417
418 static struct ast_http_uri staticuri = {
419         .callback = static_callback,
420         .description = "Asterisk HTTP Static Delivery",
421         .uri = "static",
422         .has_subtree = 1,
423         .data = NULL,
424         .key= __FILE__,
425 };
426
427 enum http_private_flags {
428         /*! TRUE if the HTTP request has a body. */
429         HTTP_FLAG_HAS_BODY = (1 << 0),
430         /*! TRUE if the HTTP request body has been read. */
431         HTTP_FLAG_BODY_READ = (1 << 1),
432         /*! TRUE if the HTTP request must close when completed. */
433         HTTP_FLAG_CLOSE_ON_COMPLETION = (1 << 2),
434 };
435
436 /*! HTTP tcptls worker_fn private data. */
437 struct http_worker_private_data {
438         /*! Body length or -1 if chunked.  Valid if HTTP_FLAG_HAS_BODY is TRUE. */
439         int body_length;
440         /*! HTTP body tracking flags */
441         struct ast_flags flags;
442 };
443
444 void ast_http_send(struct ast_tcptls_session_instance *ser,
445         enum ast_http_method method, int status_code, const char *status_title,
446         struct ast_str *http_header, struct ast_str *out, int fd,
447         unsigned int static_content)
448 {
449         struct timeval now = ast_tvnow();
450         struct ast_tm tm;
451         char timebuf[80];
452         char buf[256];
453         int len;
454         int content_length = 0;
455         int close_connection;
456         struct ast_str *server_header_field = ast_str_create(MAX_SERVER_NAME_LENGTH);
457         int send_content;
458
459         if (!ser || !server_header_field) {
460                 /* The connection is not open. */
461                 ast_free(http_header);
462                 ast_free(out);
463                 ast_free(server_header_field);
464                 return;
465         }
466
467         if(!ast_strlen_zero(http_server_name)) {
468                 ast_str_set(&server_header_field,
469                         0,
470                         "Server: %s\r\n",
471                         http_server_name);
472         }
473
474         /*
475          * We shouldn't be sending non-final status codes to this
476          * function because we may close the connection before
477          * returning.
478          */
479         ast_assert(200 <= status_code);
480
481         if (session_keep_alive <= 0) {
482                 close_connection = 1;
483         } else {
484                 struct http_worker_private_data *request;
485
486                 request = ser->private_data;
487                 if (!request
488                         || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)
489                         || ast_http_body_discard(ser)) {
490                         close_connection = 1;
491                 } else {
492                         close_connection = 0;
493                 }
494         }
495
496         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
497
498         /* calc content length */
499         if (out) {
500                 content_length += ast_str_strlen(out);
501         }
502
503         if (fd) {
504                 content_length += lseek(fd, 0, SEEK_END);
505                 lseek(fd, 0, SEEK_SET);
506         }
507
508         send_content = method != AST_HTTP_HEAD || status_code >= 400;
509
510         /* send http header */
511         if (ast_iostream_printf(ser->stream,
512                 "HTTP/1.1 %d %s\r\n"
513                 "%s"
514                 "Date: %s\r\n"
515                 "%s"
516                 "%s"
517                 "%s"
518                 "Content-Length: %d\r\n"
519                 "\r\n"
520                 "%s",
521                 status_code, status_title ? status_title : "OK",
522                 ast_str_buffer(server_header_field),
523                 timebuf,
524                 close_connection ? "Connection: close\r\n" : "",
525                 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
526                 http_header ? ast_str_buffer(http_header) : "",
527                 content_length,
528                 send_content && out && ast_str_strlen(out) ? ast_str_buffer(out) : ""
529                 ) <= 0) {
530                 ast_debug(1, "ast_iostream_printf() failed: %s\n", strerror(errno));
531                 close_connection = 1;
532         } else if (send_content && fd) {
533                 /* send file content */
534                 while ((len = read(fd, buf, sizeof(buf))) > 0) {
535                         if (ast_iostream_write(ser->stream, buf, len) != len) {
536                                 ast_debug(1, "ast_iostream_write() failed: %s\n", strerror(errno));
537                                 close_connection = 1;
538                                 break;
539                         }
540                 }
541         }
542
543         ast_free(http_header);
544         ast_free(out);
545         ast_free(server_header_field);
546
547         if (close_connection) {
548                 ast_debug(1, "HTTP closing session.  status_code:%d\n", status_code);
549                 ast_tcptls_close_session_file(ser);
550         } else {
551                 ast_debug(1, "HTTP keeping session open.  status_code:%d\n", status_code);
552         }
553 }
554
555 void ast_http_create_response(struct ast_tcptls_session_instance *ser, int status_code,
556         const char *status_title, struct ast_str *http_header_data, const char *text)
557 {
558         char server_name[MAX_SERVER_NAME_LENGTH];
559         struct ast_str *server_address = ast_str_create(MAX_SERVER_NAME_LENGTH);
560         struct ast_str *out = ast_str_create(MAX_CONTENT_LENGTH);
561
562         if (!http_header_data || !server_address || !out) {
563                 ast_free(http_header_data);
564                 ast_free(server_address);
565                 ast_free(out);
566                 if (ser) {
567                         ast_debug(1, "HTTP closing session. OOM.\n");
568                         ast_tcptls_close_session_file(ser);
569                 }
570                 return;
571         }
572
573         if(!ast_strlen_zero(http_server_name)) {
574                 ast_xml_escape(http_server_name, server_name, sizeof(server_name));
575                 ast_str_set(&server_address,
576                         0,
577                         "<address>%s</address>\r\n",
578                         server_name);
579         }
580
581         ast_str_set(&out,
582                     0,
583                     "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
584                     "<html><head>\r\n"
585                     "<title>%d %s</title>\r\n"
586                     "</head><body>\r\n"
587                     "<h1>%s</h1>\r\n"
588                     "<p>%s</p>\r\n"
589                     "<hr />\r\n"
590                     "%s"
591                     "</body></html>\r\n",
592                     status_code,
593                     status_title,
594                     status_title,
595                     text ? text : "",
596                     ast_str_buffer(server_address));
597
598         ast_free(server_address);
599
600         ast_http_send(ser,
601                       AST_HTTP_UNKNOWN,
602                       status_code,
603                       status_title,
604                       http_header_data,
605                       out,
606                       0,
607                       0);
608 }
609
610 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
611         const unsigned long nonce, const unsigned long opaque, int stale,
612         const char *text)
613 {
614         int status_code = 401;
615         char *status_title = "Unauthorized";
616         struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
617
618         if (http_header_data) {
619                 ast_str_set(&http_header_data,
620                             0,
621                             "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
622                             "Content-type: text/html\r\n",
623                             realm ? realm : "Asterisk",
624                             nonce,
625                             opaque,
626                             stale ? ", stale=true" : "");
627         }
628
629         ast_http_create_response(ser,
630                                  status_code,
631                                  status_title,
632                                  http_header_data,
633                                  text);
634 }
635
636 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code,
637         const char *status_title, const char *text)
638 {
639         struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
640
641         if (http_header_data) {
642                 ast_str_set(&http_header_data, 0, "Content-type: text/html\r\n");
643         }
644
645         ast_http_create_response(ser,
646                                  status_code,
647                                  status_title,
648                                  http_header_data,
649                                  text);
650 }
651
652 /*!
653  * \brief Link the new uri into the list.
654  *
655  * They are sorted by length of
656  * the string, not alphabetically. Duplicate entries are not replaced,
657  * but the insertion order (using <= and not just <) makes sure that
658  * more recent insertions hide older ones.
659  * On a lookup, we just scan the list and stop at the first matching entry.
660  */
661 int ast_http_uri_link(struct ast_http_uri *urih)
662 {
663         struct ast_http_uri *uri;
664         int len = strlen(urih->uri);
665
666         AST_RWLIST_WRLOCK(&uris);
667
668         urih->prefix = prefix;
669
670         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
671                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
672                 AST_RWLIST_UNLOCK(&uris);
673                 return 0;
674         }
675
676         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
677                 if (AST_RWLIST_NEXT(uri, entry) &&
678                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
679                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
680                         AST_RWLIST_UNLOCK(&uris);
681
682                         return 0;
683                 }
684         }
685
686         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
687
688         AST_RWLIST_UNLOCK(&uris);
689
690         return 0;
691 }
692
693 void ast_http_uri_unlink(struct ast_http_uri *urih)
694 {
695         AST_RWLIST_WRLOCK(&uris);
696         AST_RWLIST_REMOVE(&uris, urih, entry);
697         AST_RWLIST_UNLOCK(&uris);
698 }
699
700 void ast_http_uri_unlink_all_with_key(const char *key)
701 {
702         struct ast_http_uri *urih;
703         AST_RWLIST_WRLOCK(&uris);
704         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
705                 if (!strcmp(urih->key, key)) {
706                         AST_RWLIST_REMOVE_CURRENT(entry);
707                         if (urih->dmallocd) {
708                                 ast_free(urih->data);
709                         }
710                         if (urih->mallocd) {
711                                 ast_free(urih);
712                         }
713                 }
714         }
715         AST_RWLIST_TRAVERSE_SAFE_END;
716         AST_RWLIST_UNLOCK(&uris);
717 }
718
719 /*!
720  * \brief Retrieves the header with the given field name.
721  *
722  * \param headers Headers to search.
723  * \param field_name Name of the header to find.
724  * \return Associated header value.
725  * \return \c NULL if header is not present.
726  */
727 static const char *get_header(struct ast_variable *headers, const char *field_name)
728 {
729         struct ast_variable *v;
730
731         for (v = headers; v; v = v->next) {
732                 if (!strcasecmp(v->name, field_name)) {
733                         return v->value;
734                 }
735         }
736         return NULL;
737 }
738
739 /*!
740  * \brief Retrieves the content type specified in the "Content-Type" header.
741  *
742  * This function only returns the "type/subtype" and any trailing parameter is
743  * not included.
744  *
745  * \note the return value is an allocated string that needs to be freed.
746  *
747  * \retval the content type/subtype or NULL if the header is not found.
748  */
749 static char *get_content_type(struct ast_variable *headers)
750 {
751         const char *content_type = get_header(headers, "Content-Type");
752         const char *param;
753         size_t size;
754
755         if (!content_type) {
756                 return NULL;
757         }
758
759         param = strchr(content_type, ';');
760         size = param ? param - content_type : strlen(content_type);
761
762         return ast_strndup(content_type, size);
763 }
764
765 /*!
766  * \brief Returns the value of the Content-Length header.
767  *
768  * \param headers HTTP headers.
769  *
770  * \retval length Value of the Content-Length header.
771  * \retval 0 if header is not present.
772  * \retval -1 if header is invalid.
773  */
774 static int get_content_length(struct ast_variable *headers)
775 {
776         const char *content_length = get_header(headers, "Content-Length");
777         int length;
778
779         if (!content_length) {
780                 /* Missing content length; assume zero */
781                 return 0;
782         }
783
784         length = 0;
785         if (sscanf(content_length, "%30d", &length) != 1) {
786                 /* Invalid Content-Length value */
787                 length = -1;
788         }
789         return length;
790 }
791
792 /*!
793  * \brief Returns the value of the Transfer-Encoding header.
794  *
795  * \param headers HTTP headers.
796  * \retval string Value of the Transfer-Encoding header.
797  * \retval NULL if header is not present.
798  */
799 static const char *get_transfer_encoding(struct ast_variable *headers)
800 {
801         return get_header(headers, "Transfer-Encoding");
802 }
803
804 /*!
805  * \internal
806  * \brief Determine if the HTTP peer wants the connection closed.
807  *
808  * \param headers List of HTTP headers
809  *
810  * \retval 0 keep connection open.
811  * \retval -1 close connection.
812  */
813 static int http_check_connection_close(struct ast_variable *headers)
814 {
815         const char *connection = get_header(headers, "Connection");
816         int close_connection = 0;
817
818         if (connection && !strcasecmp(connection, "close")) {
819                 close_connection = -1;
820         }
821         return close_connection;
822 }
823
824 void ast_http_request_close_on_completion(struct ast_tcptls_session_instance *ser)
825 {
826         struct http_worker_private_data *request = ser->private_data;
827
828         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
829 }
830
831 /*!
832  * \internal
833  * \brief Initialize the request tracking information in case of early failure.
834  * \since 12.4.0
835  *
836  * \param request Request tracking information.
837  *
838  * \return Nothing
839  */
840 static void http_request_tracking_init(struct http_worker_private_data *request)
841 {
842         ast_set_flags_to(&request->flags,
843                 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
844                 /* Assume close in case request fails early */
845                 HTTP_FLAG_CLOSE_ON_COMPLETION);
846 }
847
848 /*!
849  * \internal
850  * \brief Setup the HTTP request tracking information.
851  * \since 12.4.0
852  *
853  * \param ser HTTP TCP/TLS session object.
854  * \param headers List of HTTP headers.
855  *
856  * \retval 0 on success.
857  * \retval -1 on error.
858  */
859 static int http_request_tracking_setup(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
860 {
861         struct http_worker_private_data *request = ser->private_data;
862         const char *transfer_encoding;
863
864         ast_set_flags_to(&request->flags,
865                 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
866                 http_check_connection_close(headers) ? HTTP_FLAG_CLOSE_ON_COMPLETION : 0);
867
868         transfer_encoding = get_transfer_encoding(headers);
869         if (transfer_encoding && !strcasecmp(transfer_encoding, "chunked")) {
870                 request->body_length = -1;
871                 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
872                 return 0;
873         }
874
875         request->body_length = get_content_length(headers);
876         if (0 < request->body_length) {
877                 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
878         } else if (request->body_length < 0) {
879                 /* Invalid Content-Length */
880                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
881                 ast_http_error(ser, 400, "Bad Request", "Invalid Content-Length in request!");
882                 return -1;
883         }
884         return 0;
885 }
886
887 void ast_http_body_read_status(struct ast_tcptls_session_instance *ser, int read_success)
888 {
889         struct http_worker_private_data *request;
890
891         request = ser->private_data;
892         if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
893                 || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
894                 /* No body to read. */
895                 return;
896         }
897         ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
898         if (!read_success) {
899                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
900         }
901 }
902
903 /*!
904  * \internal
905  * \brief Read the next length bytes from the HTTP body.
906  * \since 12.4.0
907  *
908  * \param ser HTTP TCP/TLS session object.
909  * \param buf Where to put the contents reading.
910  * \param length How much contents to read.
911  * \param what_getting Name of the contents reading.
912  *
913  * \retval 0 on success.
914  * \retval -1 on error.
915  */
916 static int http_body_read_contents(struct ast_tcptls_session_instance *ser, char *buf, int length, const char *what_getting)
917 {
918         int res;
919
920         /* Stream is in exclusive mode so we get it all if possible. */
921         res = ast_iostream_read(ser->stream, buf, length);
922         if (res < length) {
923                 ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d)\n",
924                         what_getting, length);
925                 return -1;
926         }
927         return 0;
928 }
929
930 /*!
931  * \internal
932  * \brief Read and discard the next length bytes from the HTTP body.
933  * \since 12.4.0
934  *
935  * \param ser HTTP TCP/TLS session object.
936  * \param length How much contents to discard
937  * \param what_getting Name of the contents discarding.
938  *
939  * \retval 0 on success.
940  * \retval -1 on error.
941  */
942 static int http_body_discard_contents(struct ast_tcptls_session_instance *ser, int length, const char *what_getting)
943 {
944         ssize_t res;
945
946         res = ast_iostream_discard(ser->stream, length);
947         if (res < length) {
948                 ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d but got %zd)\n",
949                         what_getting, length, res);
950                 return -1;
951         }
952         return 0;
953 }
954
955 /*!
956  * \internal
957  * \brief decode chunked mode hexadecimal value
958  *
959  * \param s string to decode
960  * \param len length of string
961  *
962  * \retval length on success.
963  * \retval -1 on error.
964  */
965 static int chunked_atoh(const char *s, int len)
966 {
967         int value = 0;
968         char c;
969
970         if (*s < '0') {
971                 /* zero value must be 0\n not just \n */
972                 return -1;
973         }
974
975         while (len--) {
976                 c = *s++;
977                 if (c == '\x0D') {
978                         return value;
979                 }
980                 if (c == ';') {
981                         /* We have a chunk-extension that we don't care about. */
982                         while (len--) {
983                                 if (*s++ == '\x0D') {
984                                         return value;
985                                 }
986                         }
987                         break;
988                 }
989                 value <<= 4;
990                 if (c >= '0' && c <= '9') {
991                         value += c - '0';
992                         continue;
993                 }
994                 if (c >= 'a' && c <= 'f') {
995                         value += 10 + c - 'a';
996                         continue;
997                 }
998                 if (c >= 'A' && c <= 'F') {
999                         value += 10 + c - 'A';
1000                         continue;
1001                 }
1002                 /* invalid character */
1003                 return -1;
1004         }
1005         /* end of string */
1006         return -1;
1007 }
1008
1009 /*!
1010  * \internal
1011  * \brief Read and convert the chunked body header length.
1012  * \since 12.4.0
1013  *
1014  * \param ser HTTP TCP/TLS session object.
1015  *
1016  * \retval length Size of chunk to expect.
1017  * \retval -1 on error.
1018  */
1019 static int http_body_get_chunk_length(struct ast_tcptls_session_instance *ser)
1020 {
1021         int length;
1022         char header_line[MAX_HTTP_LINE_LENGTH];
1023
1024         /* get the line of hexadecimal giving chunk-size w/ optional chunk-extension */
1025         if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1026                 ast_log(LOG_WARNING, "Short HTTP read of chunked header\n");
1027                 return -1;
1028         }
1029         length = chunked_atoh(header_line, strlen(header_line));
1030         if (length < 0) {
1031                 ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
1032                 return -1;
1033         }
1034         return length;
1035 }
1036
1037 /*!
1038  * \internal
1039  * \brief Read and check the chunk contents line termination.
1040  * \since 12.4.0
1041  *
1042  * \param ser HTTP TCP/TLS session object.
1043  *
1044  * \retval 0 on success.
1045  * \retval -1 on error.
1046  */
1047 static int http_body_check_chunk_sync(struct ast_tcptls_session_instance *ser)
1048 {
1049         int res;
1050         char chunk_sync[2];
1051
1052         /* Stay in fread until get the expected CRLF or timeout. */
1053         res = ast_iostream_read(ser->stream, chunk_sync, sizeof(chunk_sync));
1054         if (res < sizeof(chunk_sync)) {
1055                 ast_log(LOG_WARNING, "Short HTTP chunk sync read (Wanted %zu)\n",
1056                         sizeof(chunk_sync));
1057                 return -1;
1058         }
1059         if (chunk_sync[0] != 0x0D || chunk_sync[1] != 0x0A) {
1060                 ast_log(LOG_WARNING, "HTTP chunk sync bytes wrong (0x%02hhX, 0x%02hhX)\n",
1061                         (unsigned char) chunk_sync[0], (unsigned char) chunk_sync[1]);
1062                 return -1;
1063         }
1064
1065         return 0;
1066 }
1067
1068 /*!
1069  * \internal
1070  * \brief Read and discard any chunked trailer entity-header lines.
1071  * \since 12.4.0
1072  *
1073  * \param ser HTTP TCP/TLS session object.
1074  *
1075  * \retval 0 on success.
1076  * \retval -1 on error.
1077  */
1078 static int http_body_discard_chunk_trailer_headers(struct ast_tcptls_session_instance *ser)
1079 {
1080         char header_line[MAX_HTTP_LINE_LENGTH];
1081
1082         for (;;) {
1083                 if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1084                         ast_log(LOG_WARNING, "Short HTTP read of chunked trailer header\n");
1085                         return -1;
1086                 }
1087
1088                 /* Trim trailing whitespace */
1089                 ast_trim_blanks(header_line);
1090                 if (ast_strlen_zero(header_line)) {
1091                         /* A blank line ends the chunked-body */
1092                         break;
1093                 }
1094         }
1095         return 0;
1096 }
1097
1098 int ast_http_body_discard(struct ast_tcptls_session_instance *ser)
1099 {
1100         struct http_worker_private_data *request;
1101
1102         request = ser->private_data;
1103         if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
1104                 || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
1105                 /* No body to read or it has already been read. */
1106                 return 0;
1107         }
1108         ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
1109
1110         ast_debug(1, "HTTP discarding unused request body\n");
1111
1112         ast_assert(request->body_length != 0);
1113         if (0 < request->body_length) {
1114                 if (http_body_discard_contents(ser, request->body_length, "body")) {
1115                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1116                         return -1;
1117                 }
1118                 return 0;
1119         }
1120
1121         /* parse chunked-body */
1122         for (;;) {
1123                 int length;
1124
1125                 length = http_body_get_chunk_length(ser);
1126                 if (length < 0) {
1127                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1128                         return -1;
1129                 }
1130                 if (length == 0) {
1131                         /* parsed last-chunk */
1132                         break;
1133                 }
1134
1135                 if (http_body_discard_contents(ser, length, "chunk-data")
1136                         || http_body_check_chunk_sync(ser)) {
1137                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1138                         return -1;
1139                 }
1140         }
1141
1142         /* Read and discard any trailer entity-header lines. */
1143         if (http_body_discard_chunk_trailer_headers(ser)) {
1144                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1145                 return -1;
1146         }
1147         return 0;
1148 }
1149
1150 /*!
1151  * \brief Returns the contents (body) of the HTTP request
1152  *
1153  * \param return_length ptr to int that returns content length
1154  * \param ser HTTP TCP/TLS session object
1155  * \param headers List of HTTP headers
1156  * \return ptr to content (zero terminated) or NULL on failure
1157  * \note Since returned ptr is malloc'd, it should be free'd by caller
1158  */
1159 static char *ast_http_get_contents(int *return_length,
1160         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1161 {
1162         struct http_worker_private_data *request;
1163         int content_length;
1164         int bufsize;
1165         char *buf;
1166
1167         request = ser->private_data;
1168         if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)) {
1169                 /* no content - not an error */
1170                 return NULL;
1171         }
1172         if (ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
1173                 /* Already read the body.  Cannot read again.  Assume no content. */
1174                 ast_assert(0);
1175                 return NULL;
1176         }
1177         ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
1178
1179         ast_debug(2, "HTTP consuming request body\n");
1180
1181         ast_assert(request->body_length != 0);
1182         if (0 < request->body_length) {
1183                 /* handle regular non-chunked content */
1184                 content_length = request->body_length;
1185                 if (content_length > MAX_CONTENT_LENGTH) {
1186                         ast_log(LOG_WARNING, "Excessively long HTTP content. (%d > %d)\n",
1187                                 content_length, MAX_CONTENT_LENGTH);
1188                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1189                         errno = EFBIG;
1190                         return NULL;
1191                 }
1192                 buf = ast_malloc(content_length + 1);
1193                 if (!buf) {
1194                         /* Malloc sets ENOMEM */
1195                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1196                         return NULL;
1197                 }
1198
1199                 if (http_body_read_contents(ser, buf, content_length, "body")) {
1200                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1201                         errno = EIO;
1202                         ast_free(buf);
1203                         return NULL;
1204                 }
1205
1206                 buf[content_length] = 0;
1207                 *return_length = content_length;
1208                 return buf;
1209         }
1210
1211         /* pre-allocate buffer */
1212         bufsize = 250;
1213         buf = ast_malloc(bufsize);
1214         if (!buf) {
1215                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1216                 return NULL;
1217         }
1218
1219         /* parse chunked-body */
1220         content_length = 0;
1221         for (;;) {
1222                 int chunk_length;
1223
1224                 chunk_length = http_body_get_chunk_length(ser);
1225                 if (chunk_length < 0) {
1226                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1227                         errno = EIO;
1228                         ast_free(buf);
1229                         return NULL;
1230                 }
1231                 if (chunk_length == 0) {
1232                         /* parsed last-chunk */
1233                         break;
1234                 }
1235                 if (content_length + chunk_length > MAX_CONTENT_LENGTH) {
1236                         ast_log(LOG_WARNING,
1237                                 "Excessively long HTTP accumulated chunked body. (%d + %d > %d)\n",
1238                                 content_length, chunk_length, MAX_CONTENT_LENGTH);
1239                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1240                         errno = EFBIG;
1241                         ast_free(buf);
1242                         return NULL;
1243                 }
1244
1245                 /* insure buffer is large enough +1 */
1246                 if (content_length + chunk_length >= bufsize) {
1247                         char *new_buf;
1248
1249                         /* Increase bufsize until it can handle the expected data. */
1250                         do {
1251                                 bufsize *= 2;
1252                         } while (content_length + chunk_length >= bufsize);
1253
1254                         new_buf = ast_realloc(buf, bufsize);
1255                         if (!new_buf) {
1256                                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1257                                 ast_free(buf);
1258                                 return NULL;
1259                         }
1260                         buf = new_buf;
1261                 }
1262
1263                 if (http_body_read_contents(ser, buf + content_length, chunk_length, "chunk-data")
1264                         || http_body_check_chunk_sync(ser)) {
1265                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1266                         errno = EIO;
1267                         ast_free(buf);
1268                         return NULL;
1269                 }
1270                 content_length += chunk_length;
1271         }
1272
1273         /*
1274          * Read and discard any trailer entity-header lines
1275          * which we don't care about.
1276          *
1277          * XXX In the future we may need to add the trailer headers
1278          * to the passed in headers list rather than discarding them.
1279          */
1280         if (http_body_discard_chunk_trailer_headers(ser)) {
1281                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1282                 errno = EIO;
1283                 ast_free(buf);
1284                 return NULL;
1285         }
1286
1287         buf[content_length] = 0;
1288         *return_length = content_length;
1289         return buf;
1290 }
1291
1292 struct ast_json *ast_http_get_json(
1293         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1294 {
1295         int content_length = 0;
1296         struct ast_json *body;
1297         RAII_VAR(char *, buf, NULL, ast_free);
1298         RAII_VAR(char *, type, get_content_type(headers), ast_free);
1299
1300         /* Use errno to distinguish errors from no body */
1301         errno = 0;
1302
1303         if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
1304                 /* Content type is not JSON.  Don't read the body. */
1305                 return NULL;
1306         }
1307
1308         buf = ast_http_get_contents(&content_length, ser, headers);
1309         if (!buf || !content_length) {
1310                 /*
1311                  * errno already set
1312                  * or it is not an error to have zero content
1313                  */
1314                 return NULL;
1315         }
1316
1317         body = ast_json_load_buf(buf, content_length, NULL);
1318         if (!body) {
1319                 /* Failed to parse JSON; treat as an I/O error */
1320                 errno = EIO;
1321                 return NULL;
1322         }
1323
1324         return body;
1325 }
1326
1327 /*
1328  * get post variables from client Request Entity-Body, if content type is
1329  * application/x-www-form-urlencoded
1330  */
1331 struct ast_variable *ast_http_get_post_vars(
1332         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1333 {
1334         int content_length = 0;
1335         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
1336         char *var, *val;
1337         RAII_VAR(char *, buf, NULL, ast_free);
1338         RAII_VAR(char *, type, get_content_type(headers), ast_free);
1339
1340         /* Use errno to distinguish errors from no params */
1341         errno = 0;
1342
1343         if (ast_strlen_zero(type) ||
1344             strcasecmp(type, "application/x-www-form-urlencoded")) {
1345                 /* Content type is not form data.  Don't read the body. */
1346                 return NULL;
1347         }
1348
1349         buf = ast_http_get_contents(&content_length, ser, headers);
1350         if (!buf || !content_length) {
1351                 /*
1352                  * errno already set
1353                  * or it is not an error to have zero content
1354                  */
1355                 return NULL;
1356         }
1357
1358         while ((val = strsep(&buf, "&"))) {
1359                 var = strsep(&val, "=");
1360                 if (val) {
1361                         ast_uri_decode(val, ast_uri_http_legacy);
1362                 } else  {
1363                         val = "";
1364                 }
1365                 ast_uri_decode(var, ast_uri_http_legacy);
1366                 if ((v = ast_variable_new(var, val, ""))) {
1367                         if (post_vars) {
1368                                 prev->next = v;
1369                         } else {
1370                                 post_vars = v;
1371                         }
1372                         prev = v;
1373                 }
1374         }
1375
1376         return post_vars;
1377 }
1378
1379 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
1380         enum ast_http_method method, struct ast_variable *headers)
1381 {
1382         char *c;
1383         int res = 0;
1384         char *params = uri;
1385         struct ast_http_uri *urih = NULL;
1386         int l;
1387         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
1388         struct http_uri_redirect *redirect;
1389
1390         ast_debug(2, "HTTP Request URI is %s \n", uri);
1391
1392         strsep(&params, "?");
1393         /* Extract arguments from the request and store them in variables. */
1394         if (params) {
1395                 char *var, *val;
1396
1397                 while ((val = strsep(&params, "&"))) {
1398                         var = strsep(&val, "=");
1399                         if (val) {
1400                                 ast_uri_decode(val, ast_uri_http_legacy);
1401                         } else  {
1402                                 val = "";
1403                         }
1404                         ast_uri_decode(var, ast_uri_http_legacy);
1405                         if ((v = ast_variable_new(var, val, ""))) {
1406                                 if (get_vars) {
1407                                         prev->next = v;
1408                                 } else {
1409                                         get_vars = v;
1410                                 }
1411                                 prev = v;
1412                         }
1413                 }
1414         }
1415
1416         AST_RWLIST_RDLOCK(&uri_redirects);
1417         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
1418                 if (!strcasecmp(uri, redirect->target)) {
1419                         struct ast_str *http_header = ast_str_create(128);
1420
1421                         if (!http_header) {
1422                                 ast_http_request_close_on_completion(ser);
1423                                 ast_http_error(ser, 500, "Server Error", "Out of memory");
1424                                 break;
1425                         }
1426                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
1427                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
1428                         break;
1429                 }
1430         }
1431         AST_RWLIST_UNLOCK(&uri_redirects);
1432         if (redirect) {
1433                 goto cleanup;
1434         }
1435
1436         /* We want requests to start with the (optional) prefix and '/' */
1437         l = strlen(prefix);
1438         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
1439                 uri += l + 1;
1440                 /* scan registered uris to see if we match one. */
1441                 AST_RWLIST_RDLOCK(&uris);
1442                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
1443                         l = strlen(urih->uri);
1444                         c = uri + l;    /* candidate */
1445                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
1446                         if (strncasecmp(urih->uri, uri, l) /* no match */
1447                             || (*c && *c != '/')) { /* substring */
1448                                 continue;
1449                         }
1450                         if (*c == '/') {
1451                                 c++;
1452                         }
1453                         if (!*c || urih->has_subtree) {
1454                                 uri = c;
1455                                 break;
1456                         }
1457                 }
1458                 AST_RWLIST_UNLOCK(&uris);
1459         }
1460         if (urih) {
1461                 ast_debug(1, "Match made with [%s]\n", urih->uri);
1462                 if (!urih->no_decode_uri) {
1463                         ast_uri_decode(uri, ast_uri_http_legacy);
1464                 }
1465                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
1466         } else {
1467                 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
1468                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
1469         }
1470
1471 cleanup:
1472         ast_variables_destroy(get_vars);
1473         return res;
1474 }
1475
1476 static struct ast_variable *parse_cookies(const char *cookies)
1477 {
1478         char *parse = ast_strdupa(cookies);
1479         char *cur;
1480         struct ast_variable *vars = NULL, *var;
1481
1482         while ((cur = strsep(&parse, ";"))) {
1483                 char *name, *val;
1484
1485                 name = val = cur;
1486                 strsep(&val, "=");
1487
1488                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1489                         continue;
1490                 }
1491
1492                 name = ast_strip(name);
1493                 val = ast_strip_quoted(val, "\"", "\"");
1494
1495                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1496                         continue;
1497                 }
1498
1499                 ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
1500
1501                 var = ast_variable_new(name, val, __FILE__);
1502                 var->next = vars;
1503                 vars = var;
1504         }
1505
1506         return vars;
1507 }
1508
1509 /* get cookie from Request headers */
1510 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
1511 {
1512         struct ast_variable *v, *cookies = NULL;
1513
1514         for (v = headers; v; v = v->next) {
1515                 if (!strcasecmp(v->name, "Cookie")) {
1516                         ast_variables_destroy(cookies);
1517                         cookies = parse_cookies(v->value);
1518                 }
1519         }
1520         return cookies;
1521 }
1522
1523 static struct ast_http_auth *auth_create(const char *userid, const char *password)
1524 {
1525         struct ast_http_auth *auth;
1526         size_t userid_len;
1527         size_t password_len;
1528
1529         if (!userid || !password) {
1530                 ast_log(LOG_ERROR, "Invalid userid/password\n");
1531                 return NULL;
1532         }
1533
1534         userid_len = strlen(userid) + 1;
1535         password_len = strlen(password) + 1;
1536
1537         /* Allocate enough room to store everything in one memory block */
1538         auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
1539         if (!auth) {
1540                 return NULL;
1541         }
1542
1543         /* Put the userid right after the struct */
1544         auth->userid = (char *)(auth + 1);
1545         strcpy(auth->userid, userid);
1546
1547         /* Put the password right after the userid */
1548         auth->password = auth->userid + userid_len;
1549         strcpy(auth->password, password);
1550
1551         return auth;
1552 }
1553
1554 #define BASIC_PREFIX "Basic "
1555 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
1556
1557 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
1558 {
1559         struct ast_variable *v;
1560
1561         for (v = headers; v; v = v->next) {
1562                 const char *base64;
1563                 char decoded[256] = {};
1564                 char *username;
1565                 char *password;
1566 #ifdef AST_DEVMODE
1567                 int cnt;
1568 #endif /* AST_DEVMODE */
1569
1570                 if (strcasecmp("Authorization", v->name) != 0) {
1571                         continue;
1572                 }
1573
1574                 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1575                         ast_log(LOG_DEBUG,
1576                                 "Unsupported Authorization scheme\n");
1577                         continue;
1578                 }
1579
1580                 /* Basic auth header parsing. RFC 2617, section 2.
1581                  *   credentials = "Basic" basic-credentials
1582                  *   basic-credentials = base64-user-pass
1583                  *   base64-user-pass  = <base64 encoding of user-pass,
1584                  *                        except not limited to 76 char/line>
1585                  *   user-pass   = userid ":" password
1586                  */
1587
1588                 base64 = v->value + BASIC_LEN;
1589
1590                 /* This will truncate "userid:password" lines to
1591                  * sizeof(decoded). The array is long enough that this shouldn't
1592                  * be a problem */
1593 #ifdef AST_DEVMODE
1594                 cnt =
1595 #endif /* AST_DEVMODE */
1596                 ast_base64decode((unsigned char*)decoded, base64,
1597                         sizeof(decoded) - 1);
1598                 ast_assert(cnt < sizeof(decoded));
1599
1600                 /* Split the string at the colon */
1601                 password = decoded;
1602                 username = strsep(&password, ":");
1603                 if (!password) {
1604                         ast_log(LOG_WARNING, "Invalid Authorization header\n");
1605                         return NULL;
1606                 }
1607
1608                 return auth_create(username, password);
1609         }
1610
1611         return NULL;
1612 }
1613
1614 int ast_http_response_status_line(const char *buf, const char *version, int code)
1615 {
1616         int status_code;
1617         size_t size = strlen(version);
1618
1619         if (strncmp(buf, version, size) || buf[size] != ' ') {
1620                 ast_log(LOG_ERROR, "HTTP version not supported - "
1621                         "expected %s\n", version);
1622                 return -1;
1623         }
1624
1625         /* skip to status code (version + space) */
1626         buf += size + 1;
1627
1628         if (sscanf(buf, "%d", &status_code) != 1) {
1629                 ast_log(LOG_ERROR, "Could not read HTTP status code - "
1630                         "%s\n", buf);
1631                 return -1;
1632         }
1633
1634         return status_code;
1635 }
1636
1637 static void remove_excess_lws(char *s)
1638 {
1639         char *p, *res = s;
1640         char *buf = ast_malloc(strlen(s) + 1);
1641         char *buf_end;
1642
1643         if (!buf) {
1644                 return;
1645         }
1646
1647         buf_end = buf;
1648
1649         while (*s && *(s = ast_skip_blanks(s))) {
1650                 p = s;
1651                 s = ast_skip_nonblanks(s);
1652
1653                 if (buf_end != buf) {
1654                         *buf_end++ = ' ';
1655                 }
1656
1657                 memcpy(buf_end, p, s - p);
1658                 buf_end += s - p;
1659         }
1660         *buf_end = '\0';
1661         /* safe since buf will always be less than or equal to res */
1662         strcpy(res, buf);
1663         ast_free(buf);
1664 }
1665
1666 int ast_http_header_parse(char *buf, char **name, char **value)
1667 {
1668         ast_trim_blanks(buf);
1669         if (ast_strlen_zero(buf)) {
1670                 return -1;
1671         }
1672
1673         *value = buf;
1674         *name = strsep(value, ":");
1675         if (!*value) {
1676                 return 1;
1677         }
1678
1679         *value = ast_skip_blanks(*value);
1680         if (ast_strlen_zero(*value) || ast_strlen_zero(*name)) {
1681                 return 1;
1682         }
1683
1684         remove_excess_lws(*value);
1685         return 0;
1686 }
1687
1688 int ast_http_header_match(const char *name, const char *expected_name,
1689                           const char *value, const char *expected_value)
1690 {
1691         if (strcasecmp(name, expected_name)) {
1692                 /* no value to validate if names don't match */
1693                 return 0;
1694         }
1695
1696         if (strcasecmp(value, expected_value)) {
1697                 ast_log(LOG_ERROR, "Invalid header value - expected %s "
1698                         "received %s", value, expected_value);
1699                 return -1;
1700         }
1701         return 1;
1702 }
1703
1704 int ast_http_header_match_in(const char *name, const char *expected_name,
1705                              const char *value, const char *expected_value)
1706 {
1707         if (strcasecmp(name, expected_name)) {
1708                 /* no value to validate if names don't match */
1709                 return 0;
1710         }
1711
1712         if (!strcasestr(expected_value, value)) {
1713                 ast_log(LOG_ERROR, "Header '%s' - could not locate '%s' "
1714                         "in '%s'\n", name, value, expected_value);
1715                 return -1;
1716
1717         }
1718         return 1;
1719 }
1720
1721 /*! Limit the number of request headers in case the sender is being ridiculous. */
1722 #define MAX_HTTP_REQUEST_HEADERS        100
1723
1724 /*!
1725  * \internal
1726  * \brief Read the request headers.
1727  * \since 12.4.0
1728  *
1729  * \param ser HTTP TCP/TLS session object.
1730  * \param headers Where to put the request headers list pointer.
1731  *
1732  * \retval 0 on success.
1733  * \retval -1 on error.
1734  */
1735 static int http_request_headers_get(struct ast_tcptls_session_instance *ser, struct ast_variable **headers)
1736 {
1737         struct ast_variable *tail = *headers;
1738         int remaining_headers;
1739         char header_line[MAX_HTTP_LINE_LENGTH];
1740
1741         remaining_headers = MAX_HTTP_REQUEST_HEADERS;
1742         for (;;) {
1743                 char *name;
1744                 char *value;
1745
1746                 if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1747                         ast_http_error(ser, 400, "Bad Request", "Timeout");
1748                         return -1;
1749                 }
1750
1751                 /* Trim trailing characters */
1752                 ast_trim_blanks(header_line);
1753                 if (ast_strlen_zero(header_line)) {
1754                         /* A blank line ends the request header section. */
1755                         break;
1756                 }
1757
1758                 value = header_line;
1759                 name = strsep(&value, ":");
1760                 if (!value) {
1761                         continue;
1762                 }
1763
1764                 value = ast_skip_blanks(value);
1765                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1766                         continue;
1767                 }
1768
1769                 ast_trim_blanks(name);
1770
1771                 if (!remaining_headers--) {
1772                         /* Too many headers. */
1773                         ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
1774                         return -1;
1775                 }
1776                 if (!*headers) {
1777                         *headers = ast_variable_new(name, value, __FILE__);
1778                         tail = *headers;
1779                 } else {
1780                         tail->next = ast_variable_new(name, value, __FILE__);
1781                         tail = tail->next;
1782                 }
1783                 if (!tail) {
1784                         /*
1785                          * Variable allocation failure.
1786                          * Try to make some room.
1787                          */
1788                         ast_variables_destroy(*headers);
1789                         *headers = NULL;
1790
1791                         ast_http_error(ser, 500, "Server Error", "Out of memory");
1792                         return -1;
1793                 }
1794         }
1795
1796         return 0;
1797 }
1798
1799 /*!
1800  * \internal
1801  * \brief Process a HTTP request.
1802  * \since 12.4.0
1803  *
1804  * \param ser HTTP TCP/TLS session object.
1805  *
1806  * \retval 0 Continue and process the next HTTP request.
1807  * \retval -1 Fatal HTTP connection error.  Force the HTTP connection closed.
1808  */
1809 static int httpd_process_request(struct ast_tcptls_session_instance *ser)
1810 {
1811         RAII_VAR(struct ast_variable *, headers, NULL, ast_variables_destroy);
1812         char *uri;
1813         char *method;
1814         const char *transfer_encoding;
1815         struct http_worker_private_data *request;
1816         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1817         int res;
1818         char request_line[MAX_HTTP_LINE_LENGTH];
1819
1820         if (ast_iostream_gets(ser->stream, request_line, sizeof(request_line)) <= 0) {
1821                 return -1;
1822         }
1823
1824         /* Re-initialize the request body tracking data. */
1825         request = ser->private_data;
1826         http_request_tracking_init(request);
1827
1828         /* Get method */
1829         method = ast_skip_blanks(request_line);
1830         uri = ast_skip_nonblanks(method);
1831         if (*uri) {
1832                 *uri++ = '\0';
1833         }
1834
1835         if (!strcasecmp(method,"GET")) {
1836                 http_method = AST_HTTP_GET;
1837         } else if (!strcasecmp(method,"POST")) {
1838                 http_method = AST_HTTP_POST;
1839         } else if (!strcasecmp(method,"HEAD")) {
1840                 http_method = AST_HTTP_HEAD;
1841         } else if (!strcasecmp(method,"PUT")) {
1842                 http_method = AST_HTTP_PUT;
1843         } else if (!strcasecmp(method,"DELETE")) {
1844                 http_method = AST_HTTP_DELETE;
1845         } else if (!strcasecmp(method,"OPTIONS")) {
1846                 http_method = AST_HTTP_OPTIONS;
1847         }
1848
1849         uri = ast_skip_blanks(uri);     /* Skip white space */
1850         if (*uri) {                     /* terminate at the first blank */
1851                 char *c = ast_skip_nonblanks(uri);
1852
1853                 if (*c) {
1854                         *c = '\0';
1855                 }
1856         } else {
1857                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1858                 return -1;
1859         }
1860
1861         if (ast_shutdown_final()) {
1862                 ast_http_error(ser, 503, "Service Unavailable", "Shutdown in progress");
1863                 return -1;
1864         }
1865
1866         /* process "Request Headers" lines */
1867         if (http_request_headers_get(ser, &headers)) {
1868                 return -1;
1869         }
1870
1871         transfer_encoding = get_transfer_encoding(headers);
1872         /* Transfer encoding defaults to identity */
1873         if (!transfer_encoding) {
1874                 transfer_encoding = "identity";
1875         }
1876
1877         /*
1878          * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
1879          * codings we don't understand.
1880          */
1881         if (strcasecmp(transfer_encoding, "identity") != 0 &&
1882                 strcasecmp(transfer_encoding, "chunked") != 0) {
1883                 /* Transfer encodings not supported */
1884                 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
1885                 return -1;
1886         }
1887
1888         if (http_request_tracking_setup(ser, headers)
1889                 || handle_uri(ser, uri, http_method, headers)
1890                 || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)) {
1891                 res = -1;
1892         } else {
1893                 res = 0;
1894         }
1895         return res;
1896 }
1897
1898 static void *httpd_helper_thread(void *data)
1899 {
1900         struct ast_tcptls_session_instance *ser = data;
1901         int timeout;
1902         int arg = 1;
1903
1904         if (!ser) {
1905                 ao2_cleanup(ser);
1906                 return NULL;
1907         }
1908
1909         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1910                 ast_log(LOG_WARNING, "HTTP session count exceeded %d sessions.\n",
1911                         session_limit);
1912                 goto done;
1913         }
1914         ast_debug(1, "HTTP opening session.  Top level\n");
1915
1916         /*
1917          * Here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
1918          * This is necessary to prevent delays (caused by buffering) as we
1919          * write to the socket in bits and pieces.
1920          */
1921         if (setsockopt(ast_iostream_get_fd(ser->stream), IPPROTO_TCP, TCP_NODELAY, (char *) &arg, sizeof(arg)) < 0) {
1922                 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
1923         }
1924         ast_iostream_nonblock(ser->stream);
1925
1926         /* Setup HTTP worker private data to keep track of request body reading. */
1927         ao2_cleanup(ser->private_data);
1928         ser->private_data = ao2_alloc_options(sizeof(struct http_worker_private_data), NULL,
1929                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1930         if (!ser->private_data) {
1931                 ast_http_error(ser, 500, "Server Error", "Out of memory");
1932                 goto done;
1933         }
1934         http_request_tracking_init(ser->private_data);
1935
1936         /* Determine initial HTTP request wait timeout. */
1937         timeout = session_keep_alive;
1938         if (timeout <= 0) {
1939                 /* Persistent connections not enabled. */
1940                 timeout = session_inactivity;
1941         }
1942         if (timeout < MIN_INITIAL_REQUEST_TIMEOUT) {
1943                 timeout = MIN_INITIAL_REQUEST_TIMEOUT;
1944         }
1945
1946         /* We can let the stream wait for data to arrive. */
1947         ast_iostream_set_exclusive_input(ser->stream, 1);
1948
1949         for (;;) {
1950                 /* Wait for next potential HTTP request message. */
1951                 ast_iostream_set_timeout_idle_inactivity(ser->stream, timeout, session_inactivity);
1952                 if (httpd_process_request(ser)) {
1953                         /* Break the connection or the connection closed */
1954                         break;
1955                 }
1956                 if (!ser->stream) {
1957                         /* Web-socket or similar that took the connection */
1958                         break;
1959                 }
1960
1961                 timeout = session_keep_alive;
1962                 if (timeout <= 0) {
1963                         /* Persistent connections not enabled. */
1964                         break;
1965                 }
1966         }
1967
1968 done:
1969         ast_atomic_fetchadd_int(&session_count, -1);
1970
1971         ast_debug(1, "HTTP closing session.  Top level\n");
1972         ast_tcptls_close_session_file(ser);
1973
1974         ao2_ref(ser, -1);
1975         return NULL;
1976 }
1977
1978 /*!
1979  * \brief Add a new URI redirect
1980  * The entries in the redirect list are sorted by length, just like the list
1981  * of URI handlers.
1982  */
1983 static void add_redirect(const char *value)
1984 {
1985         char *target, *dest;
1986         struct http_uri_redirect *redirect, *cur;
1987         unsigned int target_len;
1988         unsigned int total_len;
1989
1990         dest = ast_strdupa(value);
1991         dest = ast_skip_blanks(dest);
1992         target = strsep(&dest, " ");
1993         target = ast_skip_blanks(target);
1994         target = strsep(&target, " "); /* trim trailing whitespace */
1995
1996         if (!dest) {
1997                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
1998                 return;
1999         }
2000
2001         target_len = strlen(target) + 1;
2002         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
2003
2004         if (!(redirect = ast_calloc(1, total_len))) {
2005                 return;
2006         }
2007         redirect->dest = redirect->target + target_len;
2008         strcpy(redirect->target, target);
2009         strcpy(redirect->dest, dest);
2010
2011         AST_RWLIST_WRLOCK(&uri_redirects);
2012
2013         target_len--; /* So we can compare directly with strlen() */
2014         if (AST_RWLIST_EMPTY(&uri_redirects)
2015                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
2016                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
2017                 AST_RWLIST_UNLOCK(&uri_redirects);
2018
2019                 return;
2020         }
2021
2022         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
2023                 if (AST_RWLIST_NEXT(cur, entry)
2024                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
2025                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
2026                         AST_RWLIST_UNLOCK(&uri_redirects);
2027                         return;
2028                 }
2029         }
2030
2031         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
2032
2033         AST_RWLIST_UNLOCK(&uri_redirects);
2034 }
2035
2036 static int __ast_http_load(int reload)
2037 {
2038         struct ast_config *cfg;
2039         struct ast_variable *v;
2040         int enabled=0;
2041         int newenablestatic=0;
2042         char newprefix[MAX_PREFIX] = "";
2043         char server_name[MAX_SERVER_NAME_LENGTH];
2044         struct http_uri_redirect *redirect;
2045         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2046         uint32_t bindport = DEFAULT_PORT;
2047         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
2048         int num_addrs = 0;
2049         int http_tls_was_enabled = 0;
2050
2051         cfg = ast_config_load2("http.conf", "http", config_flags);
2052         if (!cfg || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
2053                 return 0;
2054         }
2055
2056         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
2057
2058         http_tls_cfg.enabled = 0;
2059
2060         ast_free(http_tls_cfg.certfile);
2061         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
2062
2063         ast_free(http_tls_cfg.capath);
2064         http_tls_cfg.capath = ast_strdup("");
2065
2066         ast_free(http_tls_cfg.pvtfile);
2067         http_tls_cfg.pvtfile = ast_strdup("");
2068
2069         /* Apply modern intermediate settings according to the Mozilla OpSec team as of July 30th, 2015 but disable TLSv1 */
2070         ast_set_flag(&http_tls_cfg.flags, AST_SSL_DISABLE_TLSV1 | AST_SSL_SERVER_CIPHER_ORDER);
2071
2072         ast_free(http_tls_cfg.cipher);
2073         http_tls_cfg.cipher = ast_strdup("ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA");
2074
2075         AST_RWLIST_WRLOCK(&uri_redirects);
2076         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2077                 ast_free(redirect);
2078         }
2079         AST_RWLIST_UNLOCK(&uri_redirects);
2080
2081         ast_sockaddr_setnull(&https_desc.local_address);
2082
2083         session_limit = DEFAULT_SESSION_LIMIT;
2084         session_inactivity = DEFAULT_SESSION_INACTIVITY;
2085         session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2086
2087         snprintf(server_name, sizeof(server_name), "Asterisk/%s", ast_get_version());
2088
2089         v = ast_variable_browse(cfg, "general");
2090         for (; v; v = v->next) {
2091                 /* read tls config options while preventing unsupported options from being set */
2092                 if (strcasecmp(v->name, "tlscafile")
2093                         && strcasecmp(v->name, "tlscapath")
2094                         && strcasecmp(v->name, "tlscadir")
2095                         && strcasecmp(v->name, "tlsverifyclient")
2096                         && strcasecmp(v->name, "tlsdontverifyserver")
2097                         && strcasecmp(v->name, "tlsclientmethod")
2098                         && strcasecmp(v->name, "sslclientmethod")
2099                         && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
2100                         continue;
2101                 }
2102
2103                 if (!strcasecmp(v->name, "servername")) {
2104                         if (!ast_strlen_zero(v->value)) {
2105                                 ast_copy_string(server_name, v->value, sizeof(server_name));
2106                         } else {
2107                                 server_name[0] = '\0';
2108                         }
2109                 } else if (!strcasecmp(v->name, "enabled")) {
2110                         enabled = ast_true(v->value);
2111                 } else if (!strcasecmp(v->name, "enablestatic")) {
2112                         newenablestatic = ast_true(v->value);
2113                 } else if (!strcasecmp(v->name, "bindport")) {
2114                         if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT,
2115                                 &bindport, DEFAULT_PORT, 0, 65535)) {
2116                                 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %" PRId32 "\n",
2117                                         v->value, DEFAULT_PORT);
2118                         }
2119                 } else if (!strcasecmp(v->name, "bindaddr")) {
2120                         if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
2121                                 ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
2122                         }
2123                 } else if (!strcasecmp(v->name, "prefix")) {
2124                         if (!ast_strlen_zero(v->value)) {
2125                                 newprefix[0] = '/';
2126                                 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
2127                         } else {
2128                                 newprefix[0] = '\0';
2129                         }
2130                 } else if (!strcasecmp(v->name, "redirect")) {
2131                         add_redirect(v->value);
2132                 } else if (!strcasecmp(v->name, "sessionlimit")) {
2133                         if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2134                                 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
2135                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2136                                         v->name, v->value, v->lineno);
2137                         }
2138                 } else if (!strcasecmp(v->name, "session_inactivity")) {
2139                         if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2140                                 &session_inactivity, DEFAULT_SESSION_INACTIVITY, 1, INT_MAX)) {
2141                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2142                                         v->name, v->value, v->lineno);
2143                         }
2144                 } else if (!strcasecmp(v->name, "session_keep_alive")) {
2145                         if (sscanf(v->value, "%30d", &session_keep_alive) != 1
2146                                 || session_keep_alive < 0) {
2147                                 session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2148                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2149                                         v->name, v->value, v->lineno);
2150                         }
2151                 } else {
2152                         ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
2153                 }
2154         }
2155
2156         ast_config_destroy(cfg);
2157
2158         if (strcmp(prefix, newprefix)) {
2159                 ast_copy_string(prefix, newprefix, sizeof(prefix));
2160         }
2161
2162         ast_copy_string(http_server_name, server_name, sizeof(http_server_name));
2163         enablestatic = newenablestatic;
2164
2165         if (num_addrs && enabled) {
2166                 int i;
2167                 for (i = 0; i < num_addrs; ++i) {
2168                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
2169                         if (!ast_sockaddr_port(&http_desc.local_address)) {
2170                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
2171                         }
2172                         ast_tcptls_server_start(&http_desc);
2173                         if (http_desc.accept_fd == -1) {
2174                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
2175                                 ast_sockaddr_setnull(&http_desc.local_address);
2176                         } else {
2177                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
2178                                 break;
2179                         }
2180                 }
2181                 /* When no specific TLS bindaddr is specified, we just use
2182                  * the non-TLS bindaddress here.
2183                  */
2184                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
2185                         ast_sockaddr_copy(&https_desc.local_address, &http_desc.local_address);
2186                         /* Of course, we can't use the same port though.
2187                          * Since no bind address was specified, we just use the
2188                          * default TLS port
2189                          */
2190                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2191                 }
2192         }
2193         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
2194                 ast_tcptls_server_stop(&https_desc);
2195         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
2196                 /* We can get here either because a TLS-specific address was specified
2197                  * or because we copied the non-TLS address here. In the case where
2198                  * we read an explicit address from the config, there may have been
2199                  * no port specified, so we'll just use the default TLS port.
2200                  */
2201                 if (!ast_sockaddr_port(&https_desc.local_address)) {
2202                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2203                 }
2204                 if (ast_ssl_setup(https_desc.tls_cfg)) {
2205                         ast_tcptls_server_start(&https_desc);
2206                 }
2207         }
2208
2209         return 0;
2210 }
2211
2212 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2213 {
2214         struct ast_http_uri *urih;
2215         struct http_uri_redirect *redirect;
2216
2217         switch (cmd) {
2218         case CLI_INIT:
2219                 e->command = "http show status";
2220                 e->usage =
2221                         "Usage: http show status\n"
2222                         "       Lists status of internal HTTP engine\n";
2223                 return NULL;
2224         case CLI_GENERATE:
2225                 return NULL;
2226         }
2227
2228         if (a->argc != 3) {
2229                 return CLI_SHOWUSAGE;
2230         }
2231         ast_cli(a->fd, "HTTP Server Status:\n");
2232         ast_cli(a->fd, "Prefix: %s\n", prefix);
2233         ast_cli(a->fd, "Server: %s\n", http_server_name);
2234         if (ast_sockaddr_isnull(&http_desc.old_address)) {
2235                 ast_cli(a->fd, "Server Disabled\n\n");
2236         } else {
2237                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
2238                         ast_sockaddr_stringify(&http_desc.old_address));
2239                 if (http_tls_cfg.enabled) {
2240                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
2241                                 ast_sockaddr_stringify(&https_desc.old_address));
2242                 }
2243         }
2244
2245         ast_cli(a->fd, "Enabled URI's:\n");
2246         AST_RWLIST_RDLOCK(&uris);
2247         if (AST_RWLIST_EMPTY(&uris)) {
2248                 ast_cli(a->fd, "None.\n");
2249         } else {
2250                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
2251                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
2252         }
2253         AST_RWLIST_UNLOCK(&uris);
2254
2255         ast_cli(a->fd, "\nEnabled Redirects:\n");
2256         AST_RWLIST_RDLOCK(&uri_redirects);
2257         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
2258                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
2259         if (AST_RWLIST_EMPTY(&uri_redirects)) {
2260                 ast_cli(a->fd, "  None.\n");
2261         }
2262         AST_RWLIST_UNLOCK(&uri_redirects);
2263
2264         return CLI_SUCCESS;
2265 }
2266
2267 int ast_http_reload(void)
2268 {
2269         return __ast_http_load(1);
2270 }
2271
2272 static struct ast_cli_entry cli_http[] = {
2273         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
2274 };
2275
2276 static void http_shutdown(void)
2277 {
2278         struct http_uri_redirect *redirect;
2279         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
2280
2281         ast_tcptls_server_stop(&http_desc);
2282         if (http_tls_cfg.enabled) {
2283                 ast_tcptls_server_stop(&https_desc);
2284         }
2285         ast_free(http_tls_cfg.certfile);
2286         ast_free(http_tls_cfg.capath);
2287         ast_free(http_tls_cfg.pvtfile);
2288         ast_free(http_tls_cfg.cipher);
2289
2290         ast_http_uri_unlink(&statusuri);
2291         ast_http_uri_unlink(&staticuri);
2292
2293         AST_RWLIST_WRLOCK(&uri_redirects);
2294         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2295                 ast_free(redirect);
2296         }
2297         AST_RWLIST_UNLOCK(&uri_redirects);
2298 }
2299
2300 int ast_http_init(void)
2301 {
2302         ast_http_uri_link(&statusuri);
2303         ast_http_uri_link(&staticuri);
2304         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
2305         ast_register_cleanup(http_shutdown);
2306
2307         return __ast_http_load(0);
2308 }