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