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