http.c: Reduce log spam
[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         }
533
534         /* send content */
535         if (!close_connection && send_content && fd) {
536                 while ((len = read(fd, buf, sizeof(buf))) > 0) {
537                         if (ast_iostream_write(ser->stream, buf, len) != len) {
538                                 ast_debug(1, "ast_iostream_write() failed: %s\n", strerror(errno));
539                                 close_connection = 1;
540                                 break;
541                         }
542                 }
543         }
544
545         ast_free(http_header);
546         ast_free(out);
547         ast_free(server_header_field);
548
549         if (close_connection) {
550                 ast_debug(1, "HTTP closing session.  status_code:%d\n", status_code);
551                 ast_tcptls_close_session_file(ser);
552         } else {
553                 ast_debug(1, "HTTP keeping session open.  status_code:%d\n", status_code);
554         }
555 }
556
557 void ast_http_create_response(struct ast_tcptls_session_instance *ser, int status_code,
558         const char *status_title, struct ast_str *http_header_data, const char *text)
559 {
560         char server_name[MAX_SERVER_NAME_LENGTH];
561         struct ast_str *server_address = ast_str_create(MAX_SERVER_NAME_LENGTH);
562         struct ast_str *out = ast_str_create(MAX_CONTENT_LENGTH);
563
564         if (!http_header_data || !server_address || !out) {
565                 ast_free(http_header_data);
566                 ast_free(server_address);
567                 ast_free(out);
568                 if (ser) {
569                         ast_debug(1, "HTTP closing session. OOM.\n");
570                         ast_tcptls_close_session_file(ser);
571                 }
572                 return;
573         }
574
575         if(!ast_strlen_zero(http_server_name)) {
576                 ast_xml_escape(http_server_name, server_name, sizeof(server_name));
577                 ast_str_set(&server_address,
578                         0,
579                         "<address>%s</address>\r\n",
580                         server_name);
581         }
582
583         ast_str_set(&out,
584                     0,
585                     "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
586                     "<html><head>\r\n"
587                     "<title>%d %s</title>\r\n"
588                     "</head><body>\r\n"
589                     "<h1>%s</h1>\r\n"
590                     "<p>%s</p>\r\n"
591                     "<hr />\r\n"
592                     "%s"
593                     "</body></html>\r\n",
594                     status_code,
595                     status_title,
596                     status_title,
597                     text ? text : "",
598                     ast_str_buffer(server_address));
599
600         ast_free(server_address);
601
602         ast_http_send(ser,
603                       AST_HTTP_UNKNOWN,
604                       status_code,
605                       status_title,
606                       http_header_data,
607                       out,
608                       0,
609                       0);
610 }
611
612 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
613         const unsigned long nonce, const unsigned long opaque, int stale,
614         const char *text)
615 {
616         int status_code = 401;
617         char *status_title = "Unauthorized";
618         struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
619
620         if (http_header_data) {
621                 ast_str_set(&http_header_data,
622                             0,
623                             "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
624                             "Content-type: text/html\r\n",
625                             realm ? realm : "Asterisk",
626                             nonce,
627                             opaque,
628                             stale ? ", stale=true" : "");
629         }
630
631         ast_http_create_response(ser,
632                                  status_code,
633                                  status_title,
634                                  http_header_data,
635                                  text);
636 }
637
638 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code,
639         const char *status_title, const char *text)
640 {
641         struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
642
643         if (http_header_data) {
644                 ast_str_set(&http_header_data, 0, "Content-type: text/html\r\n");
645         }
646
647         ast_http_create_response(ser,
648                                  status_code,
649                                  status_title,
650                                  http_header_data,
651                                  text);
652 }
653
654 /*!
655  * \brief Link the new uri into the list.
656  *
657  * They are sorted by length of
658  * the string, not alphabetically. Duplicate entries are not replaced,
659  * but the insertion order (using <= and not just <) makes sure that
660  * more recent insertions hide older ones.
661  * On a lookup, we just scan the list and stop at the first matching entry.
662  */
663 int ast_http_uri_link(struct ast_http_uri *urih)
664 {
665         struct ast_http_uri *uri;
666         int len = strlen(urih->uri);
667
668         AST_RWLIST_WRLOCK(&uris);
669
670         urih->prefix = prefix;
671
672         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
673                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
674                 AST_RWLIST_UNLOCK(&uris);
675                 return 0;
676         }
677
678         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
679                 if (AST_RWLIST_NEXT(uri, entry) &&
680                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
681                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
682                         AST_RWLIST_UNLOCK(&uris);
683
684                         return 0;
685                 }
686         }
687
688         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
689
690         AST_RWLIST_UNLOCK(&uris);
691
692         return 0;
693 }
694
695 void ast_http_uri_unlink(struct ast_http_uri *urih)
696 {
697         AST_RWLIST_WRLOCK(&uris);
698         AST_RWLIST_REMOVE(&uris, urih, entry);
699         AST_RWLIST_UNLOCK(&uris);
700 }
701
702 void ast_http_uri_unlink_all_with_key(const char *key)
703 {
704         struct ast_http_uri *urih;
705         AST_RWLIST_WRLOCK(&uris);
706         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
707                 if (!strcmp(urih->key, key)) {
708                         AST_RWLIST_REMOVE_CURRENT(entry);
709                         if (urih->dmallocd) {
710                                 ast_free(urih->data);
711                         }
712                         if (urih->mallocd) {
713                                 ast_free(urih);
714                         }
715                 }
716         }
717         AST_RWLIST_TRAVERSE_SAFE_END;
718         AST_RWLIST_UNLOCK(&uris);
719 }
720
721 /*!
722  * \brief Retrieves the header with the given field name.
723  *
724  * \param headers Headers to search.
725  * \param field_name Name of the header to find.
726  * \return Associated header value.
727  * \return \c NULL if header is not present.
728  */
729 static const char *get_header(struct ast_variable *headers, const char *field_name)
730 {
731         struct ast_variable *v;
732
733         for (v = headers; v; v = v->next) {
734                 if (!strcasecmp(v->name, field_name)) {
735                         return v->value;
736                 }
737         }
738         return NULL;
739 }
740
741 /*!
742  * \brief Retrieves the content type specified in the "Content-Type" header.
743  *
744  * This function only returns the "type/subtype" and any trailing parameter is
745  * not included.
746  *
747  * \note the return value is an allocated string that needs to be freed.
748  *
749  * \retval the content type/subtype or NULL if the header is not found.
750  */
751 static char *get_content_type(struct ast_variable *headers)
752 {
753         const char *content_type = get_header(headers, "Content-Type");
754         const char *param;
755         size_t size;
756
757         if (!content_type) {
758                 return NULL;
759         }
760
761         param = strchr(content_type, ';');
762         size = param ? param - content_type : strlen(content_type);
763
764         return ast_strndup(content_type, size);
765 }
766
767 /*!
768  * \brief Returns the value of the Content-Length header.
769  *
770  * \param headers HTTP headers.
771  *
772  * \retval length Value of the Content-Length header.
773  * \retval 0 if header is not present.
774  * \retval -1 if header is invalid.
775  */
776 static int get_content_length(struct ast_variable *headers)
777 {
778         const char *content_length = get_header(headers, "Content-Length");
779         int length;
780
781         if (!content_length) {
782                 /* Missing content length; assume zero */
783                 return 0;
784         }
785
786         length = 0;
787         if (sscanf(content_length, "%30d", &length) != 1) {
788                 /* Invalid Content-Length value */
789                 length = -1;
790         }
791         return length;
792 }
793
794 /*!
795  * \brief Returns the value of the Transfer-Encoding header.
796  *
797  * \param headers HTTP headers.
798  * \retval string Value of the Transfer-Encoding header.
799  * \retval NULL if header is not present.
800  */
801 static const char *get_transfer_encoding(struct ast_variable *headers)
802 {
803         return get_header(headers, "Transfer-Encoding");
804 }
805
806 /*!
807  * \internal
808  * \brief Determine if the HTTP peer wants the connection closed.
809  *
810  * \param headers List of HTTP headers
811  *
812  * \retval 0 keep connection open.
813  * \retval -1 close connection.
814  */
815 static int http_check_connection_close(struct ast_variable *headers)
816 {
817         const char *connection = get_header(headers, "Connection");
818         int close_connection = 0;
819
820         if (connection && !strcasecmp(connection, "close")) {
821                 close_connection = -1;
822         }
823         return close_connection;
824 }
825
826 void ast_http_request_close_on_completion(struct ast_tcptls_session_instance *ser)
827 {
828         struct http_worker_private_data *request = ser->private_data;
829
830         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
831 }
832
833 /*!
834  * \internal
835  * \brief Initialize the request tracking information in case of early failure.
836  * \since 12.4.0
837  *
838  * \param request Request tracking information.
839  *
840  * \return Nothing
841  */
842 static void http_request_tracking_init(struct http_worker_private_data *request)
843 {
844         ast_set_flags_to(&request->flags,
845                 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
846                 /* Assume close in case request fails early */
847                 HTTP_FLAG_CLOSE_ON_COMPLETION);
848 }
849
850 /*!
851  * \internal
852  * \brief Setup the HTTP request tracking information.
853  * \since 12.4.0
854  *
855  * \param ser HTTP TCP/TLS session object.
856  * \param headers List of HTTP headers.
857  *
858  * \retval 0 on success.
859  * \retval -1 on error.
860  */
861 static int http_request_tracking_setup(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
862 {
863         struct http_worker_private_data *request = ser->private_data;
864         const char *transfer_encoding;
865
866         ast_set_flags_to(&request->flags,
867                 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
868                 http_check_connection_close(headers) ? HTTP_FLAG_CLOSE_ON_COMPLETION : 0);
869
870         transfer_encoding = get_transfer_encoding(headers);
871         if (transfer_encoding && !strcasecmp(transfer_encoding, "chunked")) {
872                 request->body_length = -1;
873                 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
874                 return 0;
875         }
876
877         request->body_length = get_content_length(headers);
878         if (0 < request->body_length) {
879                 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
880         } else if (request->body_length < 0) {
881                 /* Invalid Content-Length */
882                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
883                 ast_http_error(ser, 400, "Bad Request", "Invalid Content-Length in request!");
884                 return -1;
885         }
886         return 0;
887 }
888
889 void ast_http_body_read_status(struct ast_tcptls_session_instance *ser, int read_success)
890 {
891         struct http_worker_private_data *request;
892
893         request = ser->private_data;
894         if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
895                 || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
896                 /* No body to read. */
897                 return;
898         }
899         ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
900         if (!read_success) {
901                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
902         }
903 }
904
905 /*!
906  * \internal
907  * \brief Read the next length bytes from the HTTP body.
908  * \since 12.4.0
909  *
910  * \param ser HTTP TCP/TLS session object.
911  * \param buf Where to put the contents reading.
912  * \param length How much contents to read.
913  * \param what_getting Name of the contents reading.
914  *
915  * \retval 0 on success.
916  * \retval -1 on error.
917  */
918 static int http_body_read_contents(struct ast_tcptls_session_instance *ser, char *buf, int length, const char *what_getting)
919 {
920         int res;
921
922         /* Stream is in exclusive mode so we get it all if possible. */
923         res = ast_iostream_read(ser->stream, buf, length);
924         if (res < length) {
925                 ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d)\n",
926                         what_getting, length);
927                 return -1;
928         }
929         return 0;
930 }
931
932 /*!
933  * \internal
934  * \brief Read and discard the next length bytes from the HTTP body.
935  * \since 12.4.0
936  *
937  * \param ser HTTP TCP/TLS session object.
938  * \param length How much contents to discard
939  * \param what_getting Name of the contents discarding.
940  *
941  * \retval 0 on success.
942  * \retval -1 on error.
943  */
944 static int http_body_discard_contents(struct ast_tcptls_session_instance *ser, int length, const char *what_getting)
945 {
946         ssize_t res;
947
948         res = ast_iostream_discard(ser->stream, length);
949         if (res < length) {
950                 ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d but got %zd)\n",
951                         what_getting, length, res);
952                 return -1;
953         }
954         return 0;
955 }
956
957 /*!
958  * \internal
959  * \brief decode chunked mode hexadecimal value
960  *
961  * \param s string to decode
962  * \param len length of string
963  *
964  * \retval length on success.
965  * \retval -1 on error.
966  */
967 static int chunked_atoh(const char *s, int len)
968 {
969         int value = 0;
970         char c;
971
972         if (*s < '0') {
973                 /* zero value must be 0\n not just \n */
974                 return -1;
975         }
976
977         while (len--) {
978                 c = *s++;
979                 if (c == '\x0D') {
980                         return value;
981                 }
982                 if (c == ';') {
983                         /* We have a chunk-extension that we don't care about. */
984                         while (len--) {
985                                 if (*s++ == '\x0D') {
986                                         return value;
987                                 }
988                         }
989                         break;
990                 }
991                 value <<= 4;
992                 if (c >= '0' && c <= '9') {
993                         value += c - '0';
994                         continue;
995                 }
996                 if (c >= 'a' && c <= 'f') {
997                         value += 10 + c - 'a';
998                         continue;
999                 }
1000                 if (c >= 'A' && c <= 'F') {
1001                         value += 10 + c - 'A';
1002                         continue;
1003                 }
1004                 /* invalid character */
1005                 return -1;
1006         }
1007         /* end of string */
1008         return -1;
1009 }
1010
1011 /*!
1012  * \internal
1013  * \brief Read and convert the chunked body header length.
1014  * \since 12.4.0
1015  *
1016  * \param ser HTTP TCP/TLS session object.
1017  *
1018  * \retval length Size of chunk to expect.
1019  * \retval -1 on error.
1020  */
1021 static int http_body_get_chunk_length(struct ast_tcptls_session_instance *ser)
1022 {
1023         int length;
1024         char header_line[MAX_HTTP_LINE_LENGTH];
1025
1026         /* get the line of hexadecimal giving chunk-size w/ optional chunk-extension */
1027         if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1028                 ast_log(LOG_WARNING, "Short HTTP read of chunked header\n");
1029                 return -1;
1030         }
1031         length = chunked_atoh(header_line, strlen(header_line));
1032         if (length < 0) {
1033                 ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
1034                 return -1;
1035         }
1036         return length;
1037 }
1038
1039 /*!
1040  * \internal
1041  * \brief Read and check the chunk contents line termination.
1042  * \since 12.4.0
1043  *
1044  * \param ser HTTP TCP/TLS session object.
1045  *
1046  * \retval 0 on success.
1047  * \retval -1 on error.
1048  */
1049 static int http_body_check_chunk_sync(struct ast_tcptls_session_instance *ser)
1050 {
1051         int res;
1052         char chunk_sync[2];
1053
1054         /* Stay in fread until get the expected CRLF or timeout. */
1055         res = ast_iostream_read(ser->stream, chunk_sync, sizeof(chunk_sync));
1056         if (res < sizeof(chunk_sync)) {
1057                 ast_log(LOG_WARNING, "Short HTTP chunk sync read (Wanted %zu)\n",
1058                         sizeof(chunk_sync));
1059                 return -1;
1060         }
1061         if (chunk_sync[0] != 0x0D || chunk_sync[1] != 0x0A) {
1062                 ast_log(LOG_WARNING, "HTTP chunk sync bytes wrong (0x%02hhX, 0x%02hhX)\n",
1063                         (unsigned char) chunk_sync[0], (unsigned char) chunk_sync[1]);
1064                 return -1;
1065         }
1066
1067         return 0;
1068 }
1069
1070 /*!
1071  * \internal
1072  * \brief Read and discard any chunked trailer entity-header lines.
1073  * \since 12.4.0
1074  *
1075  * \param ser HTTP TCP/TLS session object.
1076  *
1077  * \retval 0 on success.
1078  * \retval -1 on error.
1079  */
1080 static int http_body_discard_chunk_trailer_headers(struct ast_tcptls_session_instance *ser)
1081 {
1082         char header_line[MAX_HTTP_LINE_LENGTH];
1083
1084         for (;;) {
1085                 if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1086                         ast_log(LOG_WARNING, "Short HTTP read of chunked trailer header\n");
1087                         return -1;
1088                 }
1089
1090                 /* Trim trailing whitespace */
1091                 ast_trim_blanks(header_line);
1092                 if (ast_strlen_zero(header_line)) {
1093                         /* A blank line ends the chunked-body */
1094                         break;
1095                 }
1096         }
1097         return 0;
1098 }
1099
1100 int ast_http_body_discard(struct ast_tcptls_session_instance *ser)
1101 {
1102         struct http_worker_private_data *request;
1103
1104         request = ser->private_data;
1105         if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
1106                 || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
1107                 /* No body to read or it has already been read. */
1108                 return 0;
1109         }
1110         ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
1111
1112         ast_debug(1, "HTTP discarding unused request body\n");
1113
1114         ast_assert(request->body_length != 0);
1115         if (0 < request->body_length) {
1116                 if (http_body_discard_contents(ser, request->body_length, "body")) {
1117                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1118                         return -1;
1119                 }
1120                 return 0;
1121         }
1122
1123         /* parse chunked-body */
1124         for (;;) {
1125                 int length;
1126
1127                 length = http_body_get_chunk_length(ser);
1128                 if (length < 0) {
1129                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1130                         return -1;
1131                 }
1132                 if (length == 0) {
1133                         /* parsed last-chunk */
1134                         break;
1135                 }
1136
1137                 if (http_body_discard_contents(ser, length, "chunk-data")
1138                         || http_body_check_chunk_sync(ser)) {
1139                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1140                         return -1;
1141                 }
1142         }
1143
1144         /* Read and discard any trailer entity-header lines. */
1145         if (http_body_discard_chunk_trailer_headers(ser)) {
1146                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1147                 return -1;
1148         }
1149         return 0;
1150 }
1151
1152 /*!
1153  * \brief Returns the contents (body) of the HTTP request
1154  *
1155  * \param return_length ptr to int that returns content length
1156  * \param ser HTTP TCP/TLS session object
1157  * \param headers List of HTTP headers
1158  * \return ptr to content (zero terminated) or NULL on failure
1159  * \note Since returned ptr is malloc'd, it should be free'd by caller
1160  */
1161 static char *ast_http_get_contents(int *return_length,
1162         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1163 {
1164         struct http_worker_private_data *request;
1165         int content_length;
1166         int bufsize;
1167         char *buf;
1168
1169         request = ser->private_data;
1170         if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)) {
1171                 /* no content - not an error */
1172                 return NULL;
1173         }
1174         if (ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
1175                 /* Already read the body.  Cannot read again.  Assume no content. */
1176                 ast_assert(0);
1177                 return NULL;
1178         }
1179         ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
1180
1181         ast_debug(2, "HTTP consuming request body\n");
1182
1183         ast_assert(request->body_length != 0);
1184         if (0 < request->body_length) {
1185                 /* handle regular non-chunked content */
1186                 content_length = request->body_length;
1187                 if (content_length > MAX_CONTENT_LENGTH) {
1188                         ast_log(LOG_WARNING, "Excessively long HTTP content. (%d > %d)\n",
1189                                 content_length, MAX_CONTENT_LENGTH);
1190                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1191                         errno = EFBIG;
1192                         return NULL;
1193                 }
1194                 buf = ast_malloc(content_length + 1);
1195                 if (!buf) {
1196                         /* Malloc sets ENOMEM */
1197                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1198                         return NULL;
1199                 }
1200
1201                 if (http_body_read_contents(ser, buf, content_length, "body")) {
1202                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1203                         errno = EIO;
1204                         ast_free(buf);
1205                         return NULL;
1206                 }
1207
1208                 buf[content_length] = 0;
1209                 *return_length = content_length;
1210                 return buf;
1211         }
1212
1213         /* pre-allocate buffer */
1214         bufsize = 250;
1215         buf = ast_malloc(bufsize);
1216         if (!buf) {
1217                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1218                 return NULL;
1219         }
1220
1221         /* parse chunked-body */
1222         content_length = 0;
1223         for (;;) {
1224                 int chunk_length;
1225
1226                 chunk_length = http_body_get_chunk_length(ser);
1227                 if (chunk_length < 0) {
1228                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1229                         errno = EIO;
1230                         ast_free(buf);
1231                         return NULL;
1232                 }
1233                 if (chunk_length == 0) {
1234                         /* parsed last-chunk */
1235                         break;
1236                 }
1237                 if (content_length + chunk_length > MAX_CONTENT_LENGTH) {
1238                         ast_log(LOG_WARNING,
1239                                 "Excessively long HTTP accumulated chunked body. (%d + %d > %d)\n",
1240                                 content_length, chunk_length, MAX_CONTENT_LENGTH);
1241                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1242                         errno = EFBIG;
1243                         ast_free(buf);
1244                         return NULL;
1245                 }
1246
1247                 /* insure buffer is large enough +1 */
1248                 if (content_length + chunk_length >= bufsize) {
1249                         char *new_buf;
1250
1251                         /* Increase bufsize until it can handle the expected data. */
1252                         do {
1253                                 bufsize *= 2;
1254                         } while (content_length + chunk_length >= bufsize);
1255
1256                         new_buf = ast_realloc(buf, bufsize);
1257                         if (!new_buf) {
1258                                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1259                                 ast_free(buf);
1260                                 return NULL;
1261                         }
1262                         buf = new_buf;
1263                 }
1264
1265                 if (http_body_read_contents(ser, buf + content_length, chunk_length, "chunk-data")
1266                         || http_body_check_chunk_sync(ser)) {
1267                         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1268                         errno = EIO;
1269                         ast_free(buf);
1270                         return NULL;
1271                 }
1272                 content_length += chunk_length;
1273         }
1274
1275         /*
1276          * Read and discard any trailer entity-header lines
1277          * which we don't care about.
1278          *
1279          * XXX In the future we may need to add the trailer headers
1280          * to the passed in headers list rather than discarding them.
1281          */
1282         if (http_body_discard_chunk_trailer_headers(ser)) {
1283                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1284                 errno = EIO;
1285                 ast_free(buf);
1286                 return NULL;
1287         }
1288
1289         buf[content_length] = 0;
1290         *return_length = content_length;
1291         return buf;
1292 }
1293
1294 struct ast_json *ast_http_get_json(
1295         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1296 {
1297         int content_length = 0;
1298         struct ast_json *body;
1299         RAII_VAR(char *, buf, NULL, ast_free);
1300         RAII_VAR(char *, type, get_content_type(headers), ast_free);
1301
1302         /* Use errno to distinguish errors from no body */
1303         errno = 0;
1304
1305         if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
1306                 /* Content type is not JSON.  Don't read the body. */
1307                 return NULL;
1308         }
1309
1310         buf = ast_http_get_contents(&content_length, ser, headers);
1311         if (!buf || !content_length) {
1312                 /*
1313                  * errno already set
1314                  * or it is not an error to have zero content
1315                  */
1316                 return NULL;
1317         }
1318
1319         body = ast_json_load_buf(buf, content_length, NULL);
1320         if (!body) {
1321                 /* Failed to parse JSON; treat as an I/O error */
1322                 errno = EIO;
1323                 return NULL;
1324         }
1325
1326         return body;
1327 }
1328
1329 /*
1330  * get post variables from client Request Entity-Body, if content type is
1331  * application/x-www-form-urlencoded
1332  */
1333 struct ast_variable *ast_http_get_post_vars(
1334         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1335 {
1336         int content_length = 0;
1337         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
1338         char *var, *val;
1339         RAII_VAR(char *, buf, NULL, ast_free);
1340         RAII_VAR(char *, type, get_content_type(headers), ast_free);
1341
1342         /* Use errno to distinguish errors from no params */
1343         errno = 0;
1344
1345         if (ast_strlen_zero(type) ||
1346             strcasecmp(type, "application/x-www-form-urlencoded")) {
1347                 /* Content type is not form data.  Don't read the body. */
1348                 return NULL;
1349         }
1350
1351         buf = ast_http_get_contents(&content_length, ser, headers);
1352         if (!buf || !content_length) {
1353                 /*
1354                  * errno already set
1355                  * or it is not an error to have zero content
1356                  */
1357                 return NULL;
1358         }
1359
1360         while ((val = strsep(&buf, "&"))) {
1361                 var = strsep(&val, "=");
1362                 if (val) {
1363                         ast_uri_decode(val, ast_uri_http_legacy);
1364                 } else  {
1365                         val = "";
1366                 }
1367                 ast_uri_decode(var, ast_uri_http_legacy);
1368                 if ((v = ast_variable_new(var, val, ""))) {
1369                         if (post_vars) {
1370                                 prev->next = v;
1371                         } else {
1372                                 post_vars = v;
1373                         }
1374                         prev = v;
1375                 }
1376         }
1377
1378         return post_vars;
1379 }
1380
1381 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
1382         enum ast_http_method method, struct ast_variable *headers)
1383 {
1384         char *c;
1385         int res = 0;
1386         char *params = uri;
1387         struct ast_http_uri *urih = NULL;
1388         int l;
1389         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
1390         struct http_uri_redirect *redirect;
1391
1392         ast_debug(2, "HTTP Request URI is %s \n", uri);
1393
1394         strsep(&params, "?");
1395         /* Extract arguments from the request and store them in variables. */
1396         if (params) {
1397                 char *var, *val;
1398
1399                 while ((val = strsep(&params, "&"))) {
1400                         var = strsep(&val, "=");
1401                         if (val) {
1402                                 ast_uri_decode(val, ast_uri_http_legacy);
1403                         } else  {
1404                                 val = "";
1405                         }
1406                         ast_uri_decode(var, ast_uri_http_legacy);
1407                         if ((v = ast_variable_new(var, val, ""))) {
1408                                 if (get_vars) {
1409                                         prev->next = v;
1410                                 } else {
1411                                         get_vars = v;
1412                                 }
1413                                 prev = v;
1414                         }
1415                 }
1416         }
1417
1418         AST_RWLIST_RDLOCK(&uri_redirects);
1419         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
1420                 if (!strcasecmp(uri, redirect->target)) {
1421                         struct ast_str *http_header = ast_str_create(128);
1422
1423                         if (!http_header) {
1424                                 ast_http_request_close_on_completion(ser);
1425                                 ast_http_error(ser, 500, "Server Error", "Out of memory");
1426                                 break;
1427                         }
1428                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
1429                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
1430                         break;
1431                 }
1432         }
1433         AST_RWLIST_UNLOCK(&uri_redirects);
1434         if (redirect) {
1435                 goto cleanup;
1436         }
1437
1438         /* We want requests to start with the (optional) prefix and '/' */
1439         l = strlen(prefix);
1440         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
1441                 uri += l + 1;
1442                 /* scan registered uris to see if we match one. */
1443                 AST_RWLIST_RDLOCK(&uris);
1444                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
1445                         l = strlen(urih->uri);
1446                         c = uri + l;    /* candidate */
1447                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
1448                         if (strncasecmp(urih->uri, uri, l) /* no match */
1449                             || (*c && *c != '/')) { /* substring */
1450                                 continue;
1451                         }
1452                         if (*c == '/') {
1453                                 c++;
1454                         }
1455                         if (!*c || urih->has_subtree) {
1456                                 uri = c;
1457                                 break;
1458                         }
1459                 }
1460                 AST_RWLIST_UNLOCK(&uris);
1461         }
1462         if (urih) {
1463                 ast_debug(1, "Match made with [%s]\n", urih->uri);
1464                 if (!urih->no_decode_uri) {
1465                         ast_uri_decode(uri, ast_uri_http_legacy);
1466                 }
1467                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
1468         } else {
1469                 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
1470                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
1471         }
1472
1473 cleanup:
1474         ast_variables_destroy(get_vars);
1475         return res;
1476 }
1477
1478 static struct ast_variable *parse_cookies(const char *cookies)
1479 {
1480         char *parse = ast_strdupa(cookies);
1481         char *cur;
1482         struct ast_variable *vars = NULL, *var;
1483
1484         while ((cur = strsep(&parse, ";"))) {
1485                 char *name, *val;
1486
1487                 name = val = cur;
1488                 strsep(&val, "=");
1489
1490                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1491                         continue;
1492                 }
1493
1494                 name = ast_strip(name);
1495                 val = ast_strip_quoted(val, "\"", "\"");
1496
1497                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1498                         continue;
1499                 }
1500
1501                 ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
1502
1503                 var = ast_variable_new(name, val, __FILE__);
1504                 var->next = vars;
1505                 vars = var;
1506         }
1507
1508         return vars;
1509 }
1510
1511 /* get cookie from Request headers */
1512 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
1513 {
1514         struct ast_variable *v, *cookies = NULL;
1515
1516         for (v = headers; v; v = v->next) {
1517                 if (!strcasecmp(v->name, "Cookie")) {
1518                         ast_variables_destroy(cookies);
1519                         cookies = parse_cookies(v->value);
1520                 }
1521         }
1522         return cookies;
1523 }
1524
1525 static struct ast_http_auth *auth_create(const char *userid, const char *password)
1526 {
1527         struct ast_http_auth *auth;
1528         size_t userid_len;
1529         size_t password_len;
1530
1531         if (!userid || !password) {
1532                 ast_log(LOG_ERROR, "Invalid userid/password\n");
1533                 return NULL;
1534         }
1535
1536         userid_len = strlen(userid) + 1;
1537         password_len = strlen(password) + 1;
1538
1539         /* Allocate enough room to store everything in one memory block */
1540         auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
1541         if (!auth) {
1542                 return NULL;
1543         }
1544
1545         /* Put the userid right after the struct */
1546         auth->userid = (char *)(auth + 1);
1547         strcpy(auth->userid, userid);
1548
1549         /* Put the password right after the userid */
1550         auth->password = auth->userid + userid_len;
1551         strcpy(auth->password, password);
1552
1553         return auth;
1554 }
1555
1556 #define BASIC_PREFIX "Basic "
1557 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
1558
1559 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
1560 {
1561         struct ast_variable *v;
1562
1563         for (v = headers; v; v = v->next) {
1564                 const char *base64;
1565                 char decoded[256] = {};
1566                 char *username;
1567                 char *password;
1568 #ifdef AST_DEVMODE
1569                 int cnt;
1570 #endif /* AST_DEVMODE */
1571
1572                 if (strcasecmp("Authorization", v->name) != 0) {
1573                         continue;
1574                 }
1575
1576                 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1577                         ast_log(LOG_DEBUG,
1578                                 "Unsupported Authorization scheme\n");
1579                         continue;
1580                 }
1581
1582                 /* Basic auth header parsing. RFC 2617, section 2.
1583                  *   credentials = "Basic" basic-credentials
1584                  *   basic-credentials = base64-user-pass
1585                  *   base64-user-pass  = <base64 encoding of user-pass,
1586                  *                        except not limited to 76 char/line>
1587                  *   user-pass   = userid ":" password
1588                  */
1589
1590                 base64 = v->value + BASIC_LEN;
1591
1592                 /* This will truncate "userid:password" lines to
1593                  * sizeof(decoded). The array is long enough that this shouldn't
1594                  * be a problem */
1595 #ifdef AST_DEVMODE
1596                 cnt =
1597 #endif /* AST_DEVMODE */
1598                 ast_base64decode((unsigned char*)decoded, base64,
1599                         sizeof(decoded) - 1);
1600                 ast_assert(cnt < sizeof(decoded));
1601
1602                 /* Split the string at the colon */
1603                 password = decoded;
1604                 username = strsep(&password, ":");
1605                 if (!password) {
1606                         ast_log(LOG_WARNING, "Invalid Authorization header\n");
1607                         return NULL;
1608                 }
1609
1610                 return auth_create(username, password);
1611         }
1612
1613         return NULL;
1614 }
1615
1616 int ast_http_response_status_line(const char *buf, const char *version, int code)
1617 {
1618         int status_code;
1619         size_t size = strlen(version);
1620
1621         if (strncmp(buf, version, size) || buf[size] != ' ') {
1622                 ast_log(LOG_ERROR, "HTTP version not supported - "
1623                         "expected %s\n", version);
1624                 return -1;
1625         }
1626
1627         /* skip to status code (version + space) */
1628         buf += size + 1;
1629
1630         if (sscanf(buf, "%d", &status_code) != 1) {
1631                 ast_log(LOG_ERROR, "Could not read HTTP status code - "
1632                         "%s\n", buf);
1633                 return -1;
1634         }
1635
1636         return status_code;
1637 }
1638
1639 static void remove_excess_lws(char *s)
1640 {
1641         char *p, *res = s;
1642         char *buf = ast_malloc(strlen(s) + 1);
1643         char *buf_end;
1644
1645         if (!buf) {
1646                 return;
1647         }
1648
1649         buf_end = buf;
1650
1651         while (*s && *(s = ast_skip_blanks(s))) {
1652                 p = s;
1653                 s = ast_skip_nonblanks(s);
1654
1655                 if (buf_end != buf) {
1656                         *buf_end++ = ' ';
1657                 }
1658
1659                 memcpy(buf_end, p, s - p);
1660                 buf_end += s - p;
1661         }
1662         *buf_end = '\0';
1663         /* safe since buf will always be less than or equal to res */
1664         strcpy(res, buf);
1665         ast_free(buf);
1666 }
1667
1668 int ast_http_header_parse(char *buf, char **name, char **value)
1669 {
1670         ast_trim_blanks(buf);
1671         if (ast_strlen_zero(buf)) {
1672                 return -1;
1673         }
1674
1675         *value = buf;
1676         *name = strsep(value, ":");
1677         if (!*value) {
1678                 return 1;
1679         }
1680
1681         *value = ast_skip_blanks(*value);
1682         if (ast_strlen_zero(*value) || ast_strlen_zero(*name)) {
1683                 return 1;
1684         }
1685
1686         remove_excess_lws(*value);
1687         return 0;
1688 }
1689
1690 int ast_http_header_match(const char *name, const char *expected_name,
1691                           const char *value, const char *expected_value)
1692 {
1693         if (strcasecmp(name, expected_name)) {
1694                 /* no value to validate if names don't match */
1695                 return 0;
1696         }
1697
1698         if (strcasecmp(value, expected_value)) {
1699                 ast_log(LOG_ERROR, "Invalid header value - expected %s "
1700                         "received %s", value, expected_value);
1701                 return -1;
1702         }
1703         return 1;
1704 }
1705
1706 int ast_http_header_match_in(const char *name, const char *expected_name,
1707                              const char *value, const char *expected_value)
1708 {
1709         if (strcasecmp(name, expected_name)) {
1710                 /* no value to validate if names don't match */
1711                 return 0;
1712         }
1713
1714         if (!strcasestr(expected_value, value)) {
1715                 ast_log(LOG_ERROR, "Header '%s' - could not locate '%s' "
1716                         "in '%s'\n", name, value, expected_value);
1717                 return -1;
1718
1719         }
1720         return 1;
1721 }
1722
1723 /*! Limit the number of request headers in case the sender is being ridiculous. */
1724 #define MAX_HTTP_REQUEST_HEADERS        100
1725
1726 /*!
1727  * \internal
1728  * \brief Read the request headers.
1729  * \since 12.4.0
1730  *
1731  * \param ser HTTP TCP/TLS session object.
1732  * \param headers Where to put the request headers list pointer.
1733  *
1734  * \retval 0 on success.
1735  * \retval -1 on error.
1736  */
1737 static int http_request_headers_get(struct ast_tcptls_session_instance *ser, struct ast_variable **headers)
1738 {
1739         struct ast_variable *tail = *headers;
1740         int remaining_headers;
1741         char header_line[MAX_HTTP_LINE_LENGTH];
1742
1743         remaining_headers = MAX_HTTP_REQUEST_HEADERS;
1744         for (;;) {
1745                 char *name;
1746                 char *value;
1747
1748                 if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1749                         ast_http_error(ser, 400, "Bad Request", "Timeout");
1750                         return -1;
1751                 }
1752
1753                 /* Trim trailing characters */
1754                 ast_trim_blanks(header_line);
1755                 if (ast_strlen_zero(header_line)) {
1756                         /* A blank line ends the request header section. */
1757                         break;
1758                 }
1759
1760                 value = header_line;
1761                 name = strsep(&value, ":");
1762                 if (!value) {
1763                         continue;
1764                 }
1765
1766                 value = ast_skip_blanks(value);
1767                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1768                         continue;
1769                 }
1770
1771                 ast_trim_blanks(name);
1772
1773                 if (!remaining_headers--) {
1774                         /* Too many headers. */
1775                         ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
1776                         return -1;
1777                 }
1778                 if (!*headers) {
1779                         *headers = ast_variable_new(name, value, __FILE__);
1780                         tail = *headers;
1781                 } else {
1782                         tail->next = ast_variable_new(name, value, __FILE__);
1783                         tail = tail->next;
1784                 }
1785                 if (!tail) {
1786                         /*
1787                          * Variable allocation failure.
1788                          * Try to make some room.
1789                          */
1790                         ast_variables_destroy(*headers);
1791                         *headers = NULL;
1792
1793                         ast_http_error(ser, 500, "Server Error", "Out of memory");
1794                         return -1;
1795                 }
1796         }
1797
1798         return 0;
1799 }
1800
1801 /*!
1802  * \internal
1803  * \brief Process a HTTP request.
1804  * \since 12.4.0
1805  *
1806  * \param ser HTTP TCP/TLS session object.
1807  *
1808  * \retval 0 Continue and process the next HTTP request.
1809  * \retval -1 Fatal HTTP connection error.  Force the HTTP connection closed.
1810  */
1811 static int httpd_process_request(struct ast_tcptls_session_instance *ser)
1812 {
1813         RAII_VAR(struct ast_variable *, headers, NULL, ast_variables_destroy);
1814         char *uri;
1815         char *method;
1816         const char *transfer_encoding;
1817         struct http_worker_private_data *request;
1818         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1819         int res;
1820         char request_line[MAX_HTTP_LINE_LENGTH];
1821
1822         if (ast_iostream_gets(ser->stream, request_line, sizeof(request_line)) <= 0) {
1823                 return -1;
1824         }
1825
1826         /* Re-initialize the request body tracking data. */
1827         request = ser->private_data;
1828         http_request_tracking_init(request);
1829
1830         /* Get method */
1831         method = ast_skip_blanks(request_line);
1832         uri = ast_skip_nonblanks(method);
1833         if (*uri) {
1834                 *uri++ = '\0';
1835         }
1836
1837         if (!strcasecmp(method,"GET")) {
1838                 http_method = AST_HTTP_GET;
1839         } else if (!strcasecmp(method,"POST")) {
1840                 http_method = AST_HTTP_POST;
1841         } else if (!strcasecmp(method,"HEAD")) {
1842                 http_method = AST_HTTP_HEAD;
1843         } else if (!strcasecmp(method,"PUT")) {
1844                 http_method = AST_HTTP_PUT;
1845         } else if (!strcasecmp(method,"DELETE")) {
1846                 http_method = AST_HTTP_DELETE;
1847         } else if (!strcasecmp(method,"OPTIONS")) {
1848                 http_method = AST_HTTP_OPTIONS;
1849         }
1850
1851         uri = ast_skip_blanks(uri);     /* Skip white space */
1852         if (*uri) {                     /* terminate at the first blank */
1853                 char *c = ast_skip_nonblanks(uri);
1854
1855                 if (*c) {
1856                         *c = '\0';
1857                 }
1858         } else {
1859                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1860                 return -1;
1861         }
1862
1863         if (ast_shutdown_final()) {
1864                 ast_http_error(ser, 503, "Service Unavailable", "Shutdown in progress");
1865                 return -1;
1866         }
1867
1868         /* process "Request Headers" lines */
1869         if (http_request_headers_get(ser, &headers)) {
1870                 return -1;
1871         }
1872
1873         transfer_encoding = get_transfer_encoding(headers);
1874         /* Transfer encoding defaults to identity */
1875         if (!transfer_encoding) {
1876                 transfer_encoding = "identity";
1877         }
1878
1879         /*
1880          * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
1881          * codings we don't understand.
1882          */
1883         if (strcasecmp(transfer_encoding, "identity") != 0 &&
1884                 strcasecmp(transfer_encoding, "chunked") != 0) {
1885                 /* Transfer encodings not supported */
1886                 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
1887                 return -1;
1888         }
1889
1890         if (http_request_tracking_setup(ser, headers)
1891                 || handle_uri(ser, uri, http_method, headers)
1892                 || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)) {
1893                 res = -1;
1894         } else {
1895                 res = 0;
1896         }
1897         return res;
1898 }
1899
1900 static void *httpd_helper_thread(void *data)
1901 {
1902         struct ast_tcptls_session_instance *ser = data;
1903         int timeout;
1904         int arg = 1;
1905
1906         if (!ser) {
1907                 ao2_cleanup(ser);
1908                 return NULL;
1909         }
1910
1911         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1912                 ast_log(LOG_WARNING, "HTTP session count exceeded %d sessions.\n",
1913                         session_limit);
1914                 goto done;
1915         }
1916         ast_debug(1, "HTTP opening session.  Top level\n");
1917
1918         /*
1919          * Here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
1920          * This is necessary to prevent delays (caused by buffering) as we
1921          * write to the socket in bits and pieces.
1922          */
1923         if (setsockopt(ast_iostream_get_fd(ser->stream), IPPROTO_TCP, TCP_NODELAY, (char *) &arg, sizeof(arg)) < 0) {
1924                 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
1925         }
1926         ast_iostream_nonblock(ser->stream);
1927
1928         /* Setup HTTP worker private data to keep track of request body reading. */
1929         ao2_cleanup(ser->private_data);
1930         ser->private_data = ao2_alloc_options(sizeof(struct http_worker_private_data), NULL,
1931                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1932         if (!ser->private_data) {
1933                 ast_http_error(ser, 500, "Server Error", "Out of memory");
1934                 goto done;
1935         }
1936         http_request_tracking_init(ser->private_data);
1937
1938         /* Determine initial HTTP request wait timeout. */
1939         timeout = session_keep_alive;
1940         if (timeout <= 0) {
1941                 /* Persistent connections not enabled. */
1942                 timeout = session_inactivity;
1943         }
1944         if (timeout < MIN_INITIAL_REQUEST_TIMEOUT) {
1945                 timeout = MIN_INITIAL_REQUEST_TIMEOUT;
1946         }
1947
1948         /* We can let the stream wait for data to arrive. */
1949         ast_iostream_set_exclusive_input(ser->stream, 1);
1950
1951         for (;;) {
1952                 /* Wait for next potential HTTP request message. */
1953                 ast_iostream_set_timeout_idle_inactivity(ser->stream, timeout, session_inactivity);
1954                 if (httpd_process_request(ser)) {
1955                         /* Break the connection or the connection closed */
1956                         break;
1957                 }
1958                 if (!ser->stream) {
1959                         /* Web-socket or similar that took the connection */
1960                         break;
1961                 }
1962
1963                 timeout = session_keep_alive;
1964                 if (timeout <= 0) {
1965                         /* Persistent connections not enabled. */
1966                         break;
1967                 }
1968         }
1969
1970 done:
1971         ast_atomic_fetchadd_int(&session_count, -1);
1972
1973         ast_debug(1, "HTTP closing session.  Top level\n");
1974         ast_tcptls_close_session_file(ser);
1975
1976         ao2_ref(ser, -1);
1977         return NULL;
1978 }
1979
1980 /*!
1981  * \brief Add a new URI redirect
1982  * The entries in the redirect list are sorted by length, just like the list
1983  * of URI handlers.
1984  */
1985 static void add_redirect(const char *value)
1986 {
1987         char *target, *dest;
1988         struct http_uri_redirect *redirect, *cur;
1989         unsigned int target_len;
1990         unsigned int total_len;
1991
1992         dest = ast_strdupa(value);
1993         dest = ast_skip_blanks(dest);
1994         target = strsep(&dest, " ");
1995         target = ast_skip_blanks(target);
1996         target = strsep(&target, " "); /* trim trailing whitespace */
1997
1998         if (!dest) {
1999                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
2000                 return;
2001         }
2002
2003         target_len = strlen(target) + 1;
2004         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
2005
2006         if (!(redirect = ast_calloc(1, total_len))) {
2007                 return;
2008         }
2009         redirect->dest = redirect->target + target_len;
2010         strcpy(redirect->target, target);
2011         strcpy(redirect->dest, dest);
2012
2013         AST_RWLIST_WRLOCK(&uri_redirects);
2014
2015         target_len--; /* So we can compare directly with strlen() */
2016         if (AST_RWLIST_EMPTY(&uri_redirects)
2017                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
2018                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
2019                 AST_RWLIST_UNLOCK(&uri_redirects);
2020
2021                 return;
2022         }
2023
2024         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
2025                 if (AST_RWLIST_NEXT(cur, entry)
2026                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
2027                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
2028                         AST_RWLIST_UNLOCK(&uri_redirects);
2029                         return;
2030                 }
2031         }
2032
2033         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
2034
2035         AST_RWLIST_UNLOCK(&uri_redirects);
2036 }
2037
2038 static int __ast_http_load(int reload)
2039 {
2040         struct ast_config *cfg;
2041         struct ast_variable *v;
2042         int enabled=0;
2043         int newenablestatic=0;
2044         char newprefix[MAX_PREFIX] = "";
2045         char server_name[MAX_SERVER_NAME_LENGTH];
2046         struct http_uri_redirect *redirect;
2047         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2048         uint32_t bindport = DEFAULT_PORT;
2049         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
2050         int num_addrs = 0;
2051         int http_tls_was_enabled = 0;
2052
2053         cfg = ast_config_load2("http.conf", "http", config_flags);
2054         if (!cfg || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
2055                 return 0;
2056         }
2057
2058         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
2059
2060         http_tls_cfg.enabled = 0;
2061
2062         ast_free(http_tls_cfg.certfile);
2063         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
2064
2065         ast_free(http_tls_cfg.capath);
2066         http_tls_cfg.capath = ast_strdup("");
2067
2068         ast_free(http_tls_cfg.pvtfile);
2069         http_tls_cfg.pvtfile = ast_strdup("");
2070
2071         /* Apply modern intermediate settings according to the Mozilla OpSec team as of July 30th, 2015 but disable TLSv1 */
2072         ast_set_flag(&http_tls_cfg.flags, AST_SSL_DISABLE_TLSV1 | AST_SSL_SERVER_CIPHER_ORDER);
2073
2074         ast_free(http_tls_cfg.cipher);
2075         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");
2076
2077         AST_RWLIST_WRLOCK(&uri_redirects);
2078         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2079                 ast_free(redirect);
2080         }
2081         AST_RWLIST_UNLOCK(&uri_redirects);
2082
2083         ast_sockaddr_setnull(&https_desc.local_address);
2084
2085         session_limit = DEFAULT_SESSION_LIMIT;
2086         session_inactivity = DEFAULT_SESSION_INACTIVITY;
2087         session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2088
2089         snprintf(server_name, sizeof(server_name), "Asterisk/%s", ast_get_version());
2090
2091         v = ast_variable_browse(cfg, "general");
2092         for (; v; v = v->next) {
2093                 /* read tls config options while preventing unsupported options from being set */
2094                 if (strcasecmp(v->name, "tlscafile")
2095                         && strcasecmp(v->name, "tlscapath")
2096                         && strcasecmp(v->name, "tlscadir")
2097                         && strcasecmp(v->name, "tlsverifyclient")
2098                         && strcasecmp(v->name, "tlsdontverifyserver")
2099                         && strcasecmp(v->name, "tlsclientmethod")
2100                         && strcasecmp(v->name, "sslclientmethod")
2101                         && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
2102                         continue;
2103                 }
2104
2105                 if (!strcasecmp(v->name, "servername")) {
2106                         if (!ast_strlen_zero(v->value)) {
2107                                 ast_copy_string(server_name, v->value, sizeof(server_name));
2108                         } else {
2109                                 server_name[0] = '\0';
2110                         }
2111                 } else if (!strcasecmp(v->name, "enabled")) {
2112                         enabled = ast_true(v->value);
2113                 } else if (!strcasecmp(v->name, "enablestatic")) {
2114                         newenablestatic = ast_true(v->value);
2115                 } else if (!strcasecmp(v->name, "bindport")) {
2116                         if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT,
2117                                 &bindport, DEFAULT_PORT, 0, 65535)) {
2118                                 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %" PRId32 "\n",
2119                                         v->value, DEFAULT_PORT);
2120                         }
2121                 } else if (!strcasecmp(v->name, "bindaddr")) {
2122                         if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
2123                                 ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
2124                         }
2125                 } else if (!strcasecmp(v->name, "prefix")) {
2126                         if (!ast_strlen_zero(v->value)) {
2127                                 newprefix[0] = '/';
2128                                 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
2129                         } else {
2130                                 newprefix[0] = '\0';
2131                         }
2132                 } else if (!strcasecmp(v->name, "redirect")) {
2133                         add_redirect(v->value);
2134                 } else if (!strcasecmp(v->name, "sessionlimit")) {
2135                         if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2136                                 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
2137                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2138                                         v->name, v->value, v->lineno);
2139                         }
2140                 } else if (!strcasecmp(v->name, "session_inactivity")) {
2141                         if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2142                                 &session_inactivity, DEFAULT_SESSION_INACTIVITY, 1, INT_MAX)) {
2143                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2144                                         v->name, v->value, v->lineno);
2145                         }
2146                 } else if (!strcasecmp(v->name, "session_keep_alive")) {
2147                         if (sscanf(v->value, "%30d", &session_keep_alive) != 1
2148                                 || session_keep_alive < 0) {
2149                                 session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2150                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2151                                         v->name, v->value, v->lineno);
2152                         }
2153                 } else {
2154                         ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
2155                 }
2156         }
2157
2158         ast_config_destroy(cfg);
2159
2160         if (strcmp(prefix, newprefix)) {
2161                 ast_copy_string(prefix, newprefix, sizeof(prefix));
2162         }
2163
2164         ast_copy_string(http_server_name, server_name, sizeof(http_server_name));
2165         enablestatic = newenablestatic;
2166
2167         if (num_addrs && enabled) {
2168                 int i;
2169                 for (i = 0; i < num_addrs; ++i) {
2170                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
2171                         if (!ast_sockaddr_port(&http_desc.local_address)) {
2172                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
2173                         }
2174                         ast_tcptls_server_start(&http_desc);
2175                         if (http_desc.accept_fd == -1) {
2176                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
2177                                 ast_sockaddr_setnull(&http_desc.local_address);
2178                         } else {
2179                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
2180                                 break;
2181                         }
2182                 }
2183                 /* When no specific TLS bindaddr is specified, we just use
2184                  * the non-TLS bindaddress here.
2185                  */
2186                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
2187                         ast_sockaddr_copy(&https_desc.local_address, &http_desc.local_address);
2188                         /* Of course, we can't use the same port though.
2189                          * Since no bind address was specified, we just use the
2190                          * default TLS port
2191                          */
2192                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2193                 }
2194         }
2195         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
2196                 ast_tcptls_server_stop(&https_desc);
2197         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
2198                 /* We can get here either because a TLS-specific address was specified
2199                  * or because we copied the non-TLS address here. In the case where
2200                  * we read an explicit address from the config, there may have been
2201                  * no port specified, so we'll just use the default TLS port.
2202                  */
2203                 if (!ast_sockaddr_port(&https_desc.local_address)) {
2204                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2205                 }
2206                 if (ast_ssl_setup(https_desc.tls_cfg)) {
2207                         ast_tcptls_server_start(&https_desc);
2208                 }
2209         }
2210
2211         return 0;
2212 }
2213
2214 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2215 {
2216         struct ast_http_uri *urih;
2217         struct http_uri_redirect *redirect;
2218
2219         switch (cmd) {
2220         case CLI_INIT:
2221                 e->command = "http show status";
2222                 e->usage =
2223                         "Usage: http show status\n"
2224                         "       Lists status of internal HTTP engine\n";
2225                 return NULL;
2226         case CLI_GENERATE:
2227                 return NULL;
2228         }
2229
2230         if (a->argc != 3) {
2231                 return CLI_SHOWUSAGE;
2232         }
2233         ast_cli(a->fd, "HTTP Server Status:\n");
2234         ast_cli(a->fd, "Prefix: %s\n", prefix);
2235         ast_cli(a->fd, "Server: %s\n", http_server_name);
2236         if (ast_sockaddr_isnull(&http_desc.old_address)) {
2237                 ast_cli(a->fd, "Server Disabled\n\n");
2238         } else {
2239                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
2240                         ast_sockaddr_stringify(&http_desc.old_address));
2241                 if (http_tls_cfg.enabled) {
2242                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
2243                                 ast_sockaddr_stringify(&https_desc.old_address));
2244                 }
2245         }
2246
2247         ast_cli(a->fd, "Enabled URI's:\n");
2248         AST_RWLIST_RDLOCK(&uris);
2249         if (AST_RWLIST_EMPTY(&uris)) {
2250                 ast_cli(a->fd, "None.\n");
2251         } else {
2252                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
2253                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
2254         }
2255         AST_RWLIST_UNLOCK(&uris);
2256
2257         ast_cli(a->fd, "\nEnabled Redirects:\n");
2258         AST_RWLIST_RDLOCK(&uri_redirects);
2259         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
2260                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
2261         if (AST_RWLIST_EMPTY(&uri_redirects)) {
2262                 ast_cli(a->fd, "  None.\n");
2263         }
2264         AST_RWLIST_UNLOCK(&uri_redirects);
2265
2266         return CLI_SUCCESS;
2267 }
2268
2269 int ast_http_reload(void)
2270 {
2271         return __ast_http_load(1);
2272 }
2273
2274 static struct ast_cli_entry cli_http[] = {
2275         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
2276 };
2277
2278 static void http_shutdown(void)
2279 {
2280         struct http_uri_redirect *redirect;
2281         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
2282
2283         ast_tcptls_server_stop(&http_desc);
2284         if (http_tls_cfg.enabled) {
2285                 ast_tcptls_server_stop(&https_desc);
2286         }
2287         ast_free(http_tls_cfg.certfile);
2288         ast_free(http_tls_cfg.capath);
2289         ast_free(http_tls_cfg.pvtfile);
2290         ast_free(http_tls_cfg.cipher);
2291
2292         ast_http_uri_unlink(&statusuri);
2293         ast_http_uri_unlink(&staticuri);
2294
2295         AST_RWLIST_WRLOCK(&uri_redirects);
2296         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2297                 ast_free(redirect);
2298         }
2299         AST_RWLIST_UNLOCK(&uri_redirects);
2300 }
2301
2302 int ast_http_init(void)
2303 {
2304         ast_http_uri_link(&statusuri);
2305         ast_http_uri_link(&staticuri);
2306         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
2307         ast_register_cleanup(http_shutdown);
2308
2309         return __ast_http_load(0);
2310 }