Merge "Revert "PJSIP_CONTACT: add missing argument documentation""
[asterisk/asterisk.git] / main / http.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief http server for AMI access
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * This program implements a tiny http server
26  * and was inspired by micro-httpd by Jef Poskanzer
27  *
28  * GMime http://spruce.sourceforge.net/gmime/
29  *
30  * \ref AstHTTP - AMI over the http protocol
31  */
32
33 /*! \li \ref http.c uses the configuration file \ref http.conf
34  * \addtogroup configuration_file
35  */
36
37 /*! \page http.conf http.conf
38  * \verbinclude http.conf.sample
39  */
40
41 /*** MODULEINFO
42         <support_level>core</support_level>
43  ***/
44
45 #include "asterisk.h"
46
47 #include <time.h>
48 #include <sys/time.h>
49 #include <sys/stat.h>
50 #include <signal.h>
51 #include <fcntl.h>
52
53 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
54 #include "asterisk/cli.h"
55 #include "asterisk/tcptls.h"
56 #include "asterisk/http.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/strings.h"
59 #include "asterisk/config.h"
60 #include "asterisk/stringfields.h"
61 #include "asterisk/ast_version.h"
62 #include "asterisk/manager.h"
63 #include "asterisk/module.h"
64 #include "asterisk/astobj2.h"
65 #include "asterisk/netsock2.h"
66 #include "asterisk/json.h"
67
68 #define MAX_PREFIX 80
69 #define DEFAULT_PORT 8088
70 #define DEFAULT_TLS_PORT 8089
71 #define DEFAULT_SESSION_LIMIT 100
72 /*! (ms) Idle time waiting for data. */
73 #define DEFAULT_SESSION_INACTIVITY 30000
74 /*! (ms) Min timeout for initial HTTP request to start coming in. */
75 #define MIN_INITIAL_REQUEST_TIMEOUT     10000
76 /*! (ms) Idle time between HTTP requests */
77 #define DEFAULT_SESSION_KEEP_ALIVE 15000
78 /*! Max size for the http server name */
79 #define MAX_SERVER_NAME_LENGTH 128
80 /*! Max size for the http response header */
81 #define DEFAULT_RESPONSE_HEADER_LENGTH 512
82
83 /*! Maximum application/json or application/x-www-form-urlencoded body content length. */
84 #if !defined(LOW_MEMORY)
85 #define MAX_CONTENT_LENGTH 40960
86 #else
87 #define MAX_CONTENT_LENGTH 1024
88 #endif  /* !defined(LOW_MEMORY) */
89
90 /*! Initial response body length. */
91 #if !defined(LOW_MEMORY)
92 #define INITIAL_RESPONSE_BODY_BUFFER 1024
93 #else
94 #define INITIAL_RESPONSE_BODY_BUFFER 512
95 #endif  /* !defined(LOW_MEMORY) */
96
97 /*! Maximum line length for HTTP requests. */
98 #if !defined(LOW_MEMORY)
99 #define MAX_HTTP_LINE_LENGTH 4096
100 #else
101 #define MAX_HTTP_LINE_LENGTH 1024
102 #endif  /* !defined(LOW_MEMORY) */
103
104 static char http_server_name[MAX_SERVER_NAME_LENGTH];
105
106 static int session_limit = DEFAULT_SESSION_LIMIT;
107 static int session_inactivity = DEFAULT_SESSION_INACTIVITY;
108 static int session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
109 static int session_count = 0;
110
111 static struct ast_tls_config http_tls_cfg;
112
113 static void *httpd_helper_thread(void *arg);
114
115 /*!
116  * we have up to two accepting threads, one for http, one for https
117  */
118 static struct ast_tcptls_session_args http_desc = {
119         .accept_fd = -1,
120         .master = AST_PTHREADT_NULL,
121         .tls_cfg = NULL,
122         .poll_timeout = -1,
123         .name = "http server",
124         .accept_fn = ast_tcptls_server_root,
125         .worker_fn = httpd_helper_thread,
126 };
127
128 static struct ast_tcptls_session_args https_desc = {
129         .accept_fd = -1,
130         .master = AST_PTHREADT_NULL,
131         .tls_cfg = &http_tls_cfg,
132         .poll_timeout = -1,
133         .name = "https server",
134         .accept_fn = ast_tcptls_server_root,
135         .worker_fn = httpd_helper_thread,
136 };
137
138 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri);      /*!< list of supported handlers */
139
140 /* all valid URIs must be prepended by the string in prefix. */
141 static char prefix[MAX_PREFIX];
142 static int enablestatic;
143
144 /*! \brief Limit the kinds of files we're willing to serve up */
145 static struct {
146         const char *ext;
147         const char *mtype;
148 } mimetypes[] = {
149         { "png", "image/png" },
150         { "xml", "text/xml" },
151         { "jpg", "image/jpeg" },
152         { "js", "application/x-javascript" },
153         { "wav", "audio/x-wav" },
154         { "mp3", "audio/mpeg" },
155         { "svg", "image/svg+xml" },
156         { "svgz", "image/svg+xml" },
157         { "gif", "image/gif" },
158         { "html", "text/html" },
159         { "htm", "text/html" },
160         { "css", "text/css" },
161         { "cnf", "text/plain" },
162         { "cfg", "text/plain" },
163         { "bin", "application/octet-stream" },
164         { "sbn", "application/octet-stream" },
165         { "ld", "application/octet-stream" },
166 };
167
168 struct http_uri_redirect {
169         AST_LIST_ENTRY(http_uri_redirect) entry;
170         char *dest;
171         char target[0];
172 };
173
174 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
175
176 static const struct ast_cfhttp_methods_text {
177         enum ast_http_method method;
178         const char *text;
179 } ast_http_methods_text[] = {
180         { AST_HTTP_UNKNOWN,     "UNKNOWN" },
181         { AST_HTTP_GET,         "GET" },
182         { AST_HTTP_POST,        "POST" },
183         { AST_HTTP_HEAD,        "HEAD" },
184         { AST_HTTP_PUT,         "PUT" },
185         { AST_HTTP_DELETE,      "DELETE" },
186         { AST_HTTP_OPTIONS,     "OPTIONS" },
187 };
188
189 const char *ast_get_http_method(enum ast_http_method method)
190 {
191         int x;
192
193         for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
194                 if (ast_http_methods_text[x].method == method) {
195                         return ast_http_methods_text[x].text;
196                 }
197         }
198
199         return NULL;
200 }
201
202 const char *ast_http_ftype2mtype(const char *ftype)
203 {
204         int x;
205
206         if (ftype) {
207                 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
208                         if (!strcasecmp(ftype, mimetypes[x].ext)) {
209                                 return mimetypes[x].mtype;
210                         }
211                 }
212         }
213         return NULL;
214 }
215
216 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
217 {
218         uint32_t mngid = 0;
219         struct ast_variable *v, *cookies;
220
221         cookies = ast_http_get_cookies(headers);
222         for (v = cookies; v; v = v->next) {
223                 if (!strcasecmp(v->name, "mansession_id")) {
224                         sscanf(v->value, "%30x", &mngid);
225                         break;
226                 }
227         }
228         ast_variables_destroy(cookies);
229         return mngid;
230 }
231
232 void ast_http_prefix(char *buf, int len)
233 {
234         if (buf) {
235                 ast_copy_string(buf, prefix, len);
236         }
237 }
238
239 static int static_callback(struct ast_tcptls_session_instance *ser,
240         const struct ast_http_uri *urih, const char *uri,
241         enum ast_http_method method, struct ast_variable *get_vars,
242         struct ast_variable *headers)
243 {
244         char *path;
245         const char *ftype;
246         const char *mtype;
247         char wkspace[80];
248         struct stat st;
249         int len;
250         int fd;
251         struct ast_str *http_header;
252         struct timeval tv;
253         struct ast_tm tm;
254         char timebuf[80], etag[23];
255         struct ast_variable *v;
256         int not_modified = 0;
257
258         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
259                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
260                 return 0;
261         }
262
263         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
264            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
265         if (!enablestatic || ast_strlen_zero(uri)) {
266                 goto out403;
267         }
268
269         /* Disallow any funny filenames at all (checking first character only??) */
270         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
271                 goto out403;
272         }
273
274         if (strstr(uri, "/..")) {
275                 goto out403;
276         }
277
278         if ((ftype = strrchr(uri, '.'))) {
279                 ftype++;
280         }
281
282         if (!(mtype = ast_http_ftype2mtype(ftype))) {
283                 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
284                 mtype = wkspace;
285         }
286
287         /* Cap maximum length */
288         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
289                 goto out403;
290         }
291
292         path = ast_alloca(len);
293         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
294         if (stat(path, &st)) {
295                 goto out404;
296         }
297
298         if (S_ISDIR(st.st_mode)) {
299                 goto out404;
300         }
301
302         if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
303                 goto out403;
304         }
305
306         fd = open(path, O_RDONLY);
307         if (fd < 0) {
308                 goto out403;
309         }
310
311         /* make "Etag:" http header value */
312         snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
313
314         /* make "Last-Modified:" http header value */
315         tv.tv_sec = st.st_mtime;
316         tv.tv_usec = 0;
317         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
318
319         /* check received "If-None-Match" request header and Etag value for file */
320         for (v = headers; v; v = v->next) {
321                 if (!strcasecmp(v->name, "If-None-Match")) {
322                         if (!strcasecmp(v->value, etag)) {
323                                 not_modified = 1;
324                         }
325                         break;
326                 }
327         }
328
329         http_header = ast_str_create(255);
330         if (!http_header) {
331                 ast_http_request_close_on_completion(ser);
332                 ast_http_error(ser, 500, "Server Error", "Out of memory");
333                 close(fd);
334                 return 0;
335         }
336
337         ast_str_set(&http_header, 0, "Content-type: %s\r\n"
338                 "ETag: %s\r\n"
339                 "Last-Modified: %s\r\n",
340                 mtype,
341                 etag,
342                 timebuf);
343
344         /* ast_http_send() frees http_header, so we don't need to do it before returning */
345         if (not_modified) {
346                 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
347         } else {
348                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
349         }
350         close(fd);
351         return 0;
352
353 out404:
354         ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
355         return 0;
356
357 out403:
358         ast_http_request_close_on_completion(ser);
359         ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
360         return 0;
361 }
362
363 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
364         const struct ast_http_uri *urih, const char *uri,
365         enum ast_http_method method, struct ast_variable *get_vars,
366         struct ast_variable *headers)
367 {
368         struct ast_str *out;
369         struct ast_variable *v, *cookies = NULL;
370
371         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
372                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
373                 return 0;
374         }
375
376         out = ast_str_create(512);
377         if (!out) {
378                 ast_http_request_close_on_completion(ser);
379                 ast_http_error(ser, 500, "Server Error", "Out of memory");
380                 return 0;
381         }
382
383         ast_str_append(&out, 0,
384                 "<html><title>Asterisk HTTP Status</title>\r\n"
385                 "<body bgcolor=\"#ffffff\">\r\n"
386                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
387                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
388
389         ast_str_append(&out, 0, "<tr><td><i>Server</i></td><td><b>%s</b></td></tr>\r\n", http_server_name);
390         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
391         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
392                        ast_sockaddr_stringify_addr(&http_desc.old_address));
393         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
394                        ast_sockaddr_stringify_port(&http_desc.old_address));
395         if (http_tls_cfg.enabled) {
396                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
397                                ast_sockaddr_stringify_port(&https_desc.old_address));
398         }
399         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
400         for (v = get_vars; v; v = v->next) {
401                 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
402         }
403         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
404
405         cookies = ast_http_get_cookies(headers);
406         for (v = cookies; v; v = v->next) {
407                 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
408         }
409         ast_variables_destroy(cookies);
410
411         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");
412         ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
413         return 0;
414 }
415
416 static struct ast_http_uri statusuri = {
417         .callback = httpstatus_callback,
418         .description = "Asterisk HTTP General Status",
419         .uri = "httpstatus",
420         .has_subtree = 0,
421         .data = NULL,
422         .key = __FILE__,
423 };
424
425 static struct ast_http_uri staticuri = {
426         .callback = static_callback,
427         .description = "Asterisk HTTP Static Delivery",
428         .uri = "static",
429         .has_subtree = 1,
430         .data = NULL,
431         .key= __FILE__,
432 };
433
434 enum http_private_flags {
435         /*! TRUE if the HTTP request has a body. */
436         HTTP_FLAG_HAS_BODY = (1 << 0),
437         /*! TRUE if the HTTP request body has been read. */
438         HTTP_FLAG_BODY_READ = (1 << 1),
439         /*! TRUE if the HTTP request must close when completed. */
440         HTTP_FLAG_CLOSE_ON_COMPLETION = (1 << 2),
441 };
442
443 /*! HTTP tcptls worker_fn private data. */
444 struct http_worker_private_data {
445         /*! Body length or -1 if chunked.  Valid if HTTP_FLAG_HAS_BODY is TRUE. */
446         int body_length;
447         /*! HTTP body tracking flags */
448         struct ast_flags flags;
449 };
450
451 void ast_http_send(struct ast_tcptls_session_instance *ser,
452         enum ast_http_method method, int status_code, const char *status_title,
453         struct ast_str *http_header, struct ast_str *out, int fd,
454         unsigned int static_content)
455 {
456         struct timeval now = ast_tvnow();
457         struct ast_tm tm;
458         char timebuf[80];
459         char buf[256];
460         int len;
461         int content_length = 0;
462         int close_connection;
463         struct ast_str *server_header_field = ast_str_create(MAX_SERVER_NAME_LENGTH);
464         int send_content;
465
466         if (!ser || !server_header_field) {
467                 /* The connection is not open. */
468                 ast_free(http_header);
469                 ast_free(out);
470                 ast_free(server_header_field);
471                 return;
472         }
473
474         if(!ast_strlen_zero(http_server_name)) {
475                 ast_str_set(&server_header_field,
476                         0,
477                         "Server: %s\r\n",
478                         http_server_name);
479         }
480
481         /*
482          * We shouldn't be sending non-final status codes to this
483          * function because we may close the connection before
484          * returning.
485          */
486         ast_assert(200 <= status_code);
487
488         if (session_keep_alive <= 0) {
489                 close_connection = 1;
490         } else {
491                 struct http_worker_private_data *request;
492
493                 request = ser->private_data;
494                 if (!request
495                         || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)
496                         || ast_http_body_discard(ser)) {
497                         close_connection = 1;
498                 } else {
499                         close_connection = 0;
500                 }
501         }
502
503         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
504
505         /* calc content length */
506         if (out) {
507                 content_length += ast_str_strlen(out);
508         }
509
510         if (fd) {
511                 content_length += lseek(fd, 0, SEEK_END);
512                 lseek(fd, 0, SEEK_SET);
513         }
514
515         send_content = method != AST_HTTP_HEAD || status_code >= 400;
516
517         /* send http header */
518         if (ast_iostream_printf(ser->stream,
519                 "HTTP/1.1 %d %s\r\n"
520                 "%s"
521                 "Date: %s\r\n"
522                 "%s"
523                 "%s"
524                 "%s"
525                 "Content-Length: %d\r\n"
526                 "\r\n"
527                 "%s",
528                 status_code, status_title ? status_title : "OK",
529                 ast_str_buffer(server_header_field),
530                 timebuf,
531                 close_connection ? "Connection: close\r\n" : "",
532                 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
533                 http_header ? ast_str_buffer(http_header) : "",
534                 content_length,
535                 send_content && out && ast_str_strlen(out) ? ast_str_buffer(out) : ""
536                 ) <= 0) {
537                 ast_debug(1, "ast_iostream_printf() failed: %s\n", strerror(errno));
538                 close_connection = 1;
539         } else if (send_content && fd) {
540                 /* send file content */
541                 while ((len = read(fd, buf, sizeof(buf))) > 0) {
542                         if (ast_iostream_write(ser->stream, buf, len) != len) {
543                                 ast_debug(1, "ast_iostream_write() failed: %s\n", strerror(errno));
544                                 close_connection = 1;
545                                 break;
546                         }
547                 }
548         }
549
550         ast_free(http_header);
551         ast_free(out);
552         ast_free(server_header_field);
553
554         if (close_connection) {
555                 ast_debug(1, "HTTP closing session.  status_code:%d\n", status_code);
556                 ast_tcptls_close_session_file(ser);
557         } else {
558                 ast_debug(1, "HTTP keeping session open.  status_code:%d\n", status_code);
559         }
560 }
561
562 void ast_http_create_response(struct ast_tcptls_session_instance *ser, int status_code,
563         const char *status_title, struct ast_str *http_header_data, const char *text)
564 {
565         char server_name[MAX_SERVER_NAME_LENGTH];
566         struct ast_str *server_address = ast_str_create(MAX_SERVER_NAME_LENGTH);
567         struct ast_str *out = ast_str_create(INITIAL_RESPONSE_BODY_BUFFER);
568
569         if (!http_header_data || !server_address || !out) {
570                 ast_free(http_header_data);
571                 ast_free(server_address);
572                 ast_free(out);
573                 if (ser) {
574                         ast_debug(1, "HTTP closing session. OOM.\n");
575                         ast_tcptls_close_session_file(ser);
576                 }
577                 return;
578         }
579
580         if(!ast_strlen_zero(http_server_name)) {
581                 ast_xml_escape(http_server_name, server_name, sizeof(server_name));
582                 ast_str_set(&server_address,
583                         0,
584                         "<address>%s</address>\r\n",
585                         server_name);
586         }
587
588         ast_str_set(&out,
589                     0,
590                     "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
591                     "<html><head>\r\n"
592                     "<title>%d %s</title>\r\n"
593                     "</head><body>\r\n"
594                     "<h1>%s</h1>\r\n"
595                     "<p>%s</p>\r\n"
596                     "<hr />\r\n"
597                     "%s"
598                     "</body></html>\r\n",
599                     status_code,
600                     status_title,
601                     status_title,
602                     text ? text : "",
603                     ast_str_buffer(server_address));
604
605         ast_free(server_address);
606
607         ast_http_send(ser,
608                       AST_HTTP_UNKNOWN,
609                       status_code,
610                       status_title,
611                       http_header_data,
612                       out,
613                       0,
614                       0);
615 }
616
617 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
618         const unsigned long nonce, const unsigned long opaque, int stale,
619         const char *text)
620 {
621         int status_code = 401;
622         char *status_title = "Unauthorized";
623         struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
624
625         if (http_header_data) {
626                 ast_str_set(&http_header_data,
627                             0,
628                             "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
629                             "Content-type: text/html\r\n",
630                             realm ? realm : "Asterisk",
631                             nonce,
632                             opaque,
633                             stale ? ", stale=true" : "");
634         }
635
636         ast_http_create_response(ser,
637                                  status_code,
638                                  status_title,
639                                  http_header_data,
640                                  text);
641 }
642
643 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code,
644         const char *status_title, const char *text)
645 {
646         struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
647
648         if (http_header_data) {
649                 ast_str_set(&http_header_data, 0, "Content-type: text/html\r\n");
650         }
651
652         ast_http_create_response(ser,
653                                  status_code,
654                                  status_title,
655                                  http_header_data,
656                                  text);
657 }
658
659 /*!
660  * \brief Link the new uri into the list.
661  *
662  * They are sorted by length of
663  * the string, not alphabetically. Duplicate entries are not replaced,
664  * but the insertion order (using <= and not just <) makes sure that
665  * more recent insertions hide older ones.
666  * On a lookup, we just scan the list and stop at the first matching entry.
667  */
668 int ast_http_uri_link(struct ast_http_uri *urih)
669 {
670         struct ast_http_uri *uri;
671         int len = strlen(urih->uri);
672
673         AST_RWLIST_WRLOCK(&uris);
674
675         urih->prefix = prefix;
676
677         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
678                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
679                 AST_RWLIST_UNLOCK(&uris);
680                 return 0;
681         }
682
683         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
684                 if (AST_RWLIST_NEXT(uri, entry) &&
685                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
686                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
687                         AST_RWLIST_UNLOCK(&uris);
688
689                         return 0;
690                 }
691         }
692
693         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
694
695         AST_RWLIST_UNLOCK(&uris);
696
697         return 0;
698 }
699
700 void ast_http_uri_unlink(struct ast_http_uri *urih)
701 {
702         AST_RWLIST_WRLOCK(&uris);
703         AST_RWLIST_REMOVE(&uris, urih, entry);
704         AST_RWLIST_UNLOCK(&uris);
705 }
706
707 void ast_http_uri_unlink_all_with_key(const char *key)
708 {
709         struct ast_http_uri *urih;
710         AST_RWLIST_WRLOCK(&uris);
711         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
712                 if (!strcmp(urih->key, key)) {
713                         AST_RWLIST_REMOVE_CURRENT(entry);
714                         if (urih->dmallocd) {
715                                 ast_free(urih->data);
716                         }
717                         if (urih->mallocd) {
718                                 ast_free(urih);
719                         }
720                 }
721         }
722         AST_RWLIST_TRAVERSE_SAFE_END;
723         AST_RWLIST_UNLOCK(&uris);
724 }
725
726 /*!
727  * \brief Retrieves the header with the given field name.
728  *
729  * \param headers Headers to search.
730  * \param field_name Name of the header to find.
731  * \return Associated header value.
732  * \return \c NULL if header is not present.
733  */
734 static const char *get_header(struct ast_variable *headers, const char *field_name)
735 {
736         struct ast_variable *v;
737
738         for (v = headers; v; v = v->next) {
739                 if (!strcasecmp(v->name, field_name)) {
740                         return v->value;
741                 }
742         }
743         return NULL;
744 }
745
746 /*!
747  * \brief Retrieves the content type specified in the "Content-Type" header.
748  *
749  * This function only returns the "type/subtype" and any trailing parameter is
750  * not included.
751  *
752  * \note the return value is an allocated string that needs to be freed.
753  *
754  * \retval the content type/subtype or NULL if the header is not found.
755  */
756 static char *get_content_type(struct ast_variable *headers)
757 {
758         const char *content_type = get_header(headers, "Content-Type");
759         const char *param;
760         size_t size;
761
762         if (!content_type) {
763                 return NULL;
764         }
765
766         param = strchr(content_type, ';');
767         size = param ? param - content_type : strlen(content_type);
768
769         return ast_strndup(content_type, size);
770 }
771
772 /*!
773  * \brief Returns the value of the Content-Length header.
774  *
775  * \param headers HTTP headers.
776  *
777  * \retval length Value of the Content-Length header.
778  * \retval 0 if header is not present.
779  * \retval -1 if header is invalid.
780  */
781 static int get_content_length(struct ast_variable *headers)
782 {
783         const char *content_length = get_header(headers, "Content-Length");
784         int length;
785
786         if (!content_length) {
787                 /* Missing content length; assume zero */
788                 return 0;
789         }
790
791         length = 0;
792         if (sscanf(content_length, "%30d", &length) != 1) {
793                 /* Invalid Content-Length value */
794                 length = -1;
795         }
796         return length;
797 }
798
799 /*!
800  * \brief Returns the value of the Transfer-Encoding header.
801  *
802  * \param headers HTTP headers.
803  * \retval string Value of the Transfer-Encoding header.
804  * \retval NULL if header is not present.
805  */
806 static const char *get_transfer_encoding(struct ast_variable *headers)
807 {
808         return get_header(headers, "Transfer-Encoding");
809 }
810
811 /*!
812  * \internal
813  * \brief Determine if the HTTP peer wants the connection closed.
814  *
815  * \param headers List of HTTP headers
816  *
817  * \retval 0 keep connection open.
818  * \retval -1 close connection.
819  */
820 static int http_check_connection_close(struct ast_variable *headers)
821 {
822         const char *connection = get_header(headers, "Connection");
823         int close_connection = 0;
824
825         if (connection && !strcasecmp(connection, "close")) {
826                 close_connection = -1;
827         }
828         return close_connection;
829 }
830
831 void ast_http_request_close_on_completion(struct ast_tcptls_session_instance *ser)
832 {
833         struct http_worker_private_data *request = ser->private_data;
834
835         ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
836 }
837
838 /*!
839  * \internal
840  * \brief Initialize the request tracking information in case of early failure.
841  * \since 12.4.0
842  *
843  * \param request Request tracking information.
844  *
845  * \return Nothing
846  */
847 static void http_request_tracking_init(struct http_worker_private_data *request)
848 {
849         ast_set_flags_to(&request->flags,
850                 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
851                 /* Assume close in case request fails early */
852                 HTTP_FLAG_CLOSE_ON_COMPLETION);
853 }
854
855 /*!
856  * \internal
857  * \brief Setup the HTTP request tracking information.
858  * \since 12.4.0
859  *
860  * \param ser HTTP TCP/TLS session object.
861  * \param headers List of HTTP headers.
862  *
863  * \retval 0 on success.
864  * \retval -1 on error.
865  */
866 static int http_request_tracking_setup(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
867 {
868         struct http_worker_private_data *request = ser->private_data;
869         const char *transfer_encoding;
870
871         ast_set_flags_to(&request->flags,
872                 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
873                 http_check_connection_close(headers) ? HTTP_FLAG_CLOSE_ON_COMPLETION : 0);
874
875         transfer_encoding = get_transfer_encoding(headers);
876         if (transfer_encoding && !strcasecmp(transfer_encoding, "chunked")) {
877                 request->body_length = -1;
878                 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
879                 return 0;
880         }
881
882         request->body_length = get_content_length(headers);
883         if (0 < request->body_length) {
884                 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
885         } else if (request->body_length < 0) {
886                 /* Invalid Content-Length */
887                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
888                 ast_http_error(ser, 400, "Bad Request", "Invalid Content-Length in request!");
889                 return -1;
890         }
891         return 0;
892 }
893
894 void ast_http_body_read_status(struct ast_tcptls_session_instance *ser, int read_success)
895 {
896         struct http_worker_private_data *request;
897
898         request = ser->private_data;
899         if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
900                 || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
901                 /* No body to read. */
902                 return;
903         }
904         ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
905         if (!read_success) {
906                 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
907         }
908 }
909
910 /*!
911  * \internal
912  * \brief Read the next length bytes from the HTTP body.
913  * \since 12.4.0
914  *
915  * \param ser HTTP TCP/TLS session object.
916  * \param buf Where to put the contents reading.
917  * \param length How much contents to read.
918  * \param what_getting Name of the contents reading.
919  *
920  * \retval 0 on success.
921  * \retval -1 on error.
922  */
923 static int http_body_read_contents(struct ast_tcptls_session_instance *ser, char *buf, int length, const char *what_getting)
924 {
925         int res;
926         int total = 0;
927
928         /* Stream is in exclusive mode so we get it all if possible. */
929         while (total != length) {
930                 res = ast_iostream_read(ser->stream, buf + total, length - total);
931                 if (res <= 0) {
932                         break;
933                 }
934
935                 total += res;
936         }
937
938         if (total != length) {
939                 ast_log(LOG_WARNING, "Wrong HTTP content read. Request %s (Wanted %d, Read %d)\n",
940                         what_getting, length, res);
941                 return -1;
942         }
943
944         return 0;
945 }
946
947 /*!
948  * \internal
949  * \brief Read and discard the next length bytes from the HTTP body.
950  * \since 12.4.0
951  *
952  * \param ser HTTP TCP/TLS session object.
953  * \param length How much contents to discard
954  * \param what_getting Name of the contents discarding.
955  *
956  * \retval 0 on success.
957  * \retval -1 on error.
958  */
959 static int http_body_discard_contents(struct ast_tcptls_session_instance *ser, int length, const char *what_getting)
960 {
961         ssize_t res;
962
963         res = ast_iostream_discard(ser->stream, length);
964         if (res < length) {
965                 ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d but got %zd)\n",
966                         what_getting, length, res);
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 (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
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 = ast_iostream_read(ser->stream, chunk_sync, sizeof(chunk_sync));
1071         if (res < sizeof(chunk_sync)) {
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 (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
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                 ssize_t len;
1761                 char *name;
1762                 char *value;
1763
1764                 len = ast_iostream_gets(ser->stream, header_line, sizeof(header_line));
1765                 if (len <= 0) {
1766                         ast_http_error(ser, 400, "Bad Request", "Timeout");
1767                         return -1;
1768                 }
1769                 if (header_line[len - 1] != '\n') {
1770                         /* We didn't get a full line */
1771                         ast_http_error(ser, 400, "Bad Request",
1772                                 (len == sizeof(header_line) - 1) ? "Header line too long" : "Timeout");
1773                         return -1;
1774                 }
1775
1776                 /* Trim trailing characters */
1777                 ast_trim_blanks(header_line);
1778                 if (ast_strlen_zero(header_line)) {
1779                         /* A blank line ends the request header section. */
1780                         break;
1781                 }
1782
1783                 value = header_line;
1784                 name = strsep(&value, ":");
1785                 if (!value) {
1786                         continue;
1787                 }
1788
1789                 value = ast_skip_blanks(value);
1790                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1791                         continue;
1792                 }
1793
1794                 ast_trim_blanks(name);
1795
1796                 if (!remaining_headers--) {
1797                         /* Too many headers. */
1798                         ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
1799                         return -1;
1800                 }
1801                 if (!*headers) {
1802                         *headers = ast_variable_new(name, value, __FILE__);
1803                         tail = *headers;
1804                 } else {
1805                         tail->next = ast_variable_new(name, value, __FILE__);
1806                         tail = tail->next;
1807                 }
1808                 if (!tail) {
1809                         /*
1810                          * Variable allocation failure.
1811                          * Try to make some room.
1812                          */
1813                         ast_variables_destroy(*headers);
1814                         *headers = NULL;
1815
1816                         ast_http_error(ser, 500, "Server Error", "Out of memory");
1817                         return -1;
1818                 }
1819         }
1820
1821         return 0;
1822 }
1823
1824 /*!
1825  * \internal
1826  * \brief Process a HTTP request.
1827  * \since 12.4.0
1828  *
1829  * \param ser HTTP TCP/TLS session object.
1830  *
1831  * \retval 0 Continue and process the next HTTP request.
1832  * \retval -1 Fatal HTTP connection error.  Force the HTTP connection closed.
1833  */
1834 static int httpd_process_request(struct ast_tcptls_session_instance *ser)
1835 {
1836         RAII_VAR(struct ast_variable *, headers, NULL, ast_variables_destroy);
1837         char *uri;
1838         char *method;
1839         const char *transfer_encoding;
1840         struct http_worker_private_data *request;
1841         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1842         int res;
1843         ssize_t len;
1844         char request_line[MAX_HTTP_LINE_LENGTH];
1845
1846         len = ast_iostream_gets(ser->stream, request_line, sizeof(request_line));
1847         if (len <= 0) {
1848                 return -1;
1849         }
1850
1851         /* Re-initialize the request body tracking data. */
1852         request = ser->private_data;
1853         http_request_tracking_init(request);
1854
1855         if (request_line[len - 1] != '\n') {
1856                 /* We didn't get a full line */
1857                 ast_http_error(ser, 400, "Bad Request",
1858                         (len == sizeof(request_line) - 1) ? "Request line too long" : "Timeout");
1859                 return -1;
1860         }
1861
1862         /* Get method */
1863         method = ast_skip_blanks(request_line);
1864         uri = ast_skip_nonblanks(method);
1865         if (*uri) {
1866                 *uri++ = '\0';
1867         }
1868
1869         if (!strcasecmp(method,"GET")) {
1870                 http_method = AST_HTTP_GET;
1871         } else if (!strcasecmp(method,"POST")) {
1872                 http_method = AST_HTTP_POST;
1873         } else if (!strcasecmp(method,"HEAD")) {
1874                 http_method = AST_HTTP_HEAD;
1875         } else if (!strcasecmp(method,"PUT")) {
1876                 http_method = AST_HTTP_PUT;
1877         } else if (!strcasecmp(method,"DELETE")) {
1878                 http_method = AST_HTTP_DELETE;
1879         } else if (!strcasecmp(method,"OPTIONS")) {
1880                 http_method = AST_HTTP_OPTIONS;
1881         }
1882
1883         uri = ast_skip_blanks(uri);     /* Skip white space */
1884         if (*uri) {                     /* terminate at the first blank */
1885                 char *c = ast_skip_nonblanks(uri);
1886
1887                 if (*c) {
1888                         *c = '\0';
1889                 }
1890         } else {
1891                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1892                 return -1;
1893         }
1894
1895         if (ast_shutdown_final()) {
1896                 ast_http_error(ser, 503, "Service Unavailable", "Shutdown in progress");
1897                 return -1;
1898         }
1899
1900         /* process "Request Headers" lines */
1901         if (http_request_headers_get(ser, &headers)) {
1902                 return -1;
1903         }
1904
1905         transfer_encoding = get_transfer_encoding(headers);
1906         /* Transfer encoding defaults to identity */
1907         if (!transfer_encoding) {
1908                 transfer_encoding = "identity";
1909         }
1910
1911         /*
1912          * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
1913          * codings we don't understand.
1914          */
1915         if (strcasecmp(transfer_encoding, "identity") != 0 &&
1916                 strcasecmp(transfer_encoding, "chunked") != 0) {
1917                 /* Transfer encodings not supported */
1918                 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
1919                 return -1;
1920         }
1921
1922         if (http_request_tracking_setup(ser, headers)
1923                 || handle_uri(ser, uri, http_method, headers)
1924                 || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)) {
1925                 res = -1;
1926         } else {
1927                 res = 0;
1928         }
1929         return res;
1930 }
1931
1932 static void *httpd_helper_thread(void *data)
1933 {
1934         struct ast_tcptls_session_instance *ser = data;
1935         int timeout;
1936         int arg = 1;
1937
1938         if (!ser) {
1939                 ao2_cleanup(ser);
1940                 return NULL;
1941         }
1942
1943         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1944                 ast_log(LOG_WARNING, "HTTP session count exceeded %d sessions.\n",
1945                         session_limit);
1946                 goto done;
1947         }
1948         ast_debug(1, "HTTP opening session.  Top level\n");
1949
1950         /*
1951          * Here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
1952          * This is necessary to prevent delays (caused by buffering) as we
1953          * write to the socket in bits and pieces.
1954          */
1955         if (setsockopt(ast_iostream_get_fd(ser->stream), IPPROTO_TCP, TCP_NODELAY, (char *) &arg, sizeof(arg)) < 0) {
1956                 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
1957         }
1958         ast_iostream_nonblock(ser->stream);
1959
1960         /* Setup HTTP worker private data to keep track of request body reading. */
1961         ao2_cleanup(ser->private_data);
1962         ser->private_data = ao2_alloc_options(sizeof(struct http_worker_private_data), NULL,
1963                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1964         if (!ser->private_data) {
1965                 ast_http_error(ser, 500, "Server Error", "Out of memory");
1966                 goto done;
1967         }
1968         http_request_tracking_init(ser->private_data);
1969
1970         /* Determine initial HTTP request wait timeout. */
1971         timeout = session_keep_alive;
1972         if (timeout <= 0) {
1973                 /* Persistent connections not enabled. */
1974                 timeout = session_inactivity;
1975         }
1976         if (timeout < MIN_INITIAL_REQUEST_TIMEOUT) {
1977                 timeout = MIN_INITIAL_REQUEST_TIMEOUT;
1978         }
1979
1980         /* We can let the stream wait for data to arrive. */
1981         ast_iostream_set_exclusive_input(ser->stream, 1);
1982
1983         for (;;) {
1984                 /* Wait for next potential HTTP request message. */
1985                 ast_iostream_set_timeout_idle_inactivity(ser->stream, timeout, session_inactivity);
1986                 if (httpd_process_request(ser)) {
1987                         /* Break the connection or the connection closed */
1988                         break;
1989                 }
1990                 if (!ser->stream) {
1991                         /* Web-socket or similar that took the connection */
1992                         break;
1993                 }
1994
1995                 timeout = session_keep_alive;
1996                 if (timeout <= 0) {
1997                         /* Persistent connections not enabled. */
1998                         break;
1999                 }
2000         }
2001
2002 done:
2003         ast_atomic_fetchadd_int(&session_count, -1);
2004
2005         ast_debug(1, "HTTP closing session.  Top level\n");
2006         ast_tcptls_close_session_file(ser);
2007
2008         ao2_ref(ser, -1);
2009         return NULL;
2010 }
2011
2012 /*!
2013  * \brief Add a new URI redirect
2014  * The entries in the redirect list are sorted by length, just like the list
2015  * of URI handlers.
2016  */
2017 static void add_redirect(const char *value)
2018 {
2019         char *target, *dest;
2020         struct http_uri_redirect *redirect, *cur;
2021         unsigned int target_len;
2022         unsigned int total_len;
2023
2024         dest = ast_strdupa(value);
2025         dest = ast_skip_blanks(dest);
2026         target = strsep(&dest, " ");
2027         target = ast_skip_blanks(target);
2028         target = strsep(&target, " "); /* trim trailing whitespace */
2029
2030         if (!dest) {
2031                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
2032                 return;
2033         }
2034
2035         target_len = strlen(target) + 1;
2036         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
2037
2038         if (!(redirect = ast_calloc(1, total_len))) {
2039                 return;
2040         }
2041         redirect->dest = redirect->target + target_len;
2042         strcpy(redirect->target, target);
2043         strcpy(redirect->dest, dest);
2044
2045         AST_RWLIST_WRLOCK(&uri_redirects);
2046
2047         target_len--; /* So we can compare directly with strlen() */
2048         if (AST_RWLIST_EMPTY(&uri_redirects)
2049                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
2050                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
2051                 AST_RWLIST_UNLOCK(&uri_redirects);
2052
2053                 return;
2054         }
2055
2056         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
2057                 if (AST_RWLIST_NEXT(cur, entry)
2058                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
2059                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
2060                         AST_RWLIST_UNLOCK(&uri_redirects);
2061                         return;
2062                 }
2063         }
2064
2065         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
2066
2067         AST_RWLIST_UNLOCK(&uri_redirects);
2068 }
2069
2070 static int __ast_http_load(int reload)
2071 {
2072         struct ast_config *cfg;
2073         struct ast_variable *v;
2074         int enabled=0;
2075         int newenablestatic=0;
2076         char newprefix[MAX_PREFIX] = "";
2077         char server_name[MAX_SERVER_NAME_LENGTH];
2078         struct http_uri_redirect *redirect;
2079         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2080         uint32_t bindport = DEFAULT_PORT;
2081         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
2082         int num_addrs = 0;
2083         int http_tls_was_enabled = 0;
2084
2085         cfg = ast_config_load2("http.conf", "http", config_flags);
2086         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
2087                 return 0;
2088         }
2089
2090         /* Even if the http.conf hasn't been updated, the TLS certs/keys may have been */
2091         if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
2092                 if (http_tls_cfg.enabled && ast_ssl_setup(https_desc.tls_cfg)) {
2093                         ast_tcptls_server_start(&https_desc);
2094                 }
2095                 return 0;
2096         }
2097
2098         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
2099
2100         http_tls_cfg.enabled = 0;
2101
2102         ast_free(http_tls_cfg.certfile);
2103         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
2104
2105         ast_free(http_tls_cfg.capath);
2106         http_tls_cfg.capath = ast_strdup("");
2107
2108         ast_free(http_tls_cfg.pvtfile);
2109         http_tls_cfg.pvtfile = ast_strdup("");
2110
2111         /* Apply modern intermediate settings according to the Mozilla OpSec team as of July 30th, 2015 but disable TLSv1 */
2112         ast_set_flag(&http_tls_cfg.flags, AST_SSL_DISABLE_TLSV1 | AST_SSL_SERVER_CIPHER_ORDER);
2113
2114         ast_free(http_tls_cfg.cipher);
2115         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");
2116
2117         AST_RWLIST_WRLOCK(&uri_redirects);
2118         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2119                 ast_free(redirect);
2120         }
2121         AST_RWLIST_UNLOCK(&uri_redirects);
2122
2123         ast_sockaddr_setnull(&https_desc.local_address);
2124
2125         session_limit = DEFAULT_SESSION_LIMIT;
2126         session_inactivity = DEFAULT_SESSION_INACTIVITY;
2127         session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2128
2129         snprintf(server_name, sizeof(server_name), "Asterisk/%s", ast_get_version());
2130
2131         v = ast_variable_browse(cfg, "general");
2132         for (; v; v = v->next) {
2133                 /* read tls config options while preventing unsupported options from being set */
2134                 if (strcasecmp(v->name, "tlscafile")
2135                         && strcasecmp(v->name, "tlscapath")
2136                         && strcasecmp(v->name, "tlscadir")
2137                         && strcasecmp(v->name, "tlsverifyclient")
2138                         && strcasecmp(v->name, "tlsdontverifyserver")
2139                         && strcasecmp(v->name, "tlsclientmethod")
2140                         && strcasecmp(v->name, "sslclientmethod")
2141                         && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
2142                         continue;
2143                 }
2144
2145                 if (!strcasecmp(v->name, "servername")) {
2146                         if (!ast_strlen_zero(v->value)) {
2147                                 ast_copy_string(server_name, v->value, sizeof(server_name));
2148                         } else {
2149                                 server_name[0] = '\0';
2150                         }
2151                 } else if (!strcasecmp(v->name, "enabled")) {
2152                         enabled = ast_true(v->value);
2153                 } else if (!strcasecmp(v->name, "enablestatic")) {
2154                         newenablestatic = ast_true(v->value);
2155                 } else if (!strcasecmp(v->name, "bindport")) {
2156                         if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT,
2157                                 &bindport, DEFAULT_PORT, 0, 65535)) {
2158                                 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %" PRId32 "\n",
2159                                         v->value, DEFAULT_PORT);
2160                         }
2161                 } else if (!strcasecmp(v->name, "bindaddr")) {
2162                         if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
2163                                 ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
2164                         }
2165                 } else if (!strcasecmp(v->name, "prefix")) {
2166                         if (!ast_strlen_zero(v->value)) {
2167                                 newprefix[0] = '/';
2168                                 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
2169                         } else {
2170                                 newprefix[0] = '\0';
2171                         }
2172                 } else if (!strcasecmp(v->name, "redirect")) {
2173                         add_redirect(v->value);
2174                 } else if (!strcasecmp(v->name, "sessionlimit")) {
2175                         if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2176                                 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
2177                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2178                                         v->name, v->value, v->lineno);
2179                         }
2180                 } else if (!strcasecmp(v->name, "session_inactivity")) {
2181                         if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2182                                 &session_inactivity, DEFAULT_SESSION_INACTIVITY, 1, INT_MAX)) {
2183                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2184                                         v->name, v->value, v->lineno);
2185                         }
2186                 } else if (!strcasecmp(v->name, "session_keep_alive")) {
2187                         if (sscanf(v->value, "%30d", &session_keep_alive) != 1
2188                                 || session_keep_alive < 0) {
2189                                 session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2190                                 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2191                                         v->name, v->value, v->lineno);
2192                         }
2193                 } else {
2194                         ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
2195                 }
2196         }
2197
2198         ast_config_destroy(cfg);
2199
2200         if (strcmp(prefix, newprefix)) {
2201                 ast_copy_string(prefix, newprefix, sizeof(prefix));
2202         }
2203
2204         ast_copy_string(http_server_name, server_name, sizeof(http_server_name));
2205         enablestatic = newenablestatic;
2206
2207         if (num_addrs && enabled) {
2208                 int i;
2209                 for (i = 0; i < num_addrs; ++i) {
2210                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
2211                         if (!ast_sockaddr_port(&http_desc.local_address)) {
2212                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
2213                         }
2214                         ast_tcptls_server_start(&http_desc);
2215                         if (http_desc.accept_fd == -1) {
2216                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
2217                                 ast_sockaddr_setnull(&http_desc.local_address);
2218                         } else {
2219                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
2220                                 break;
2221                         }
2222                 }
2223                 /* When no specific TLS bindaddr is specified, we just use
2224                  * the non-TLS bindaddress here.
2225                  */
2226                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
2227                         ast_sockaddr_copy(&https_desc.local_address, &http_desc.local_address);
2228                         /* Of course, we can't use the same port though.
2229                          * Since no bind address was specified, we just use the
2230                          * default TLS port
2231                          */
2232                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2233                 }
2234         }
2235         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
2236                 ast_tcptls_server_stop(&https_desc);
2237         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
2238                 /* We can get here either because a TLS-specific address was specified
2239                  * or because we copied the non-TLS address here. In the case where
2240                  * we read an explicit address from the config, there may have been
2241                  * no port specified, so we'll just use the default TLS port.
2242                  */
2243                 if (!ast_sockaddr_port(&https_desc.local_address)) {
2244                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2245                 }
2246                 if (ast_ssl_setup(https_desc.tls_cfg)) {
2247                         ast_tcptls_server_start(&https_desc);
2248                 }
2249         }
2250
2251         return 0;
2252 }
2253
2254 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2255 {
2256         struct ast_http_uri *urih;
2257         struct http_uri_redirect *redirect;
2258
2259         switch (cmd) {
2260         case CLI_INIT:
2261                 e->command = "http show status";
2262                 e->usage =
2263                         "Usage: http show status\n"
2264                         "       Lists status of internal HTTP engine\n";
2265                 return NULL;
2266         case CLI_GENERATE:
2267                 return NULL;
2268         }
2269
2270         if (a->argc != 3) {
2271                 return CLI_SHOWUSAGE;
2272         }
2273         ast_cli(a->fd, "HTTP Server Status:\n");
2274         ast_cli(a->fd, "Prefix: %s\n", prefix);
2275         ast_cli(a->fd, "Server: %s\n", http_server_name);
2276         if (ast_sockaddr_isnull(&http_desc.old_address)) {
2277                 ast_cli(a->fd, "Server Disabled\n\n");
2278         } else {
2279                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
2280                         ast_sockaddr_stringify(&http_desc.old_address));
2281                 if (http_tls_cfg.enabled) {
2282                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
2283                                 ast_sockaddr_stringify(&https_desc.old_address));
2284                 }
2285         }
2286
2287         ast_cli(a->fd, "Enabled URI's:\n");
2288         AST_RWLIST_RDLOCK(&uris);
2289         if (AST_RWLIST_EMPTY(&uris)) {
2290                 ast_cli(a->fd, "None.\n");
2291         } else {
2292                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
2293                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
2294         }
2295         AST_RWLIST_UNLOCK(&uris);
2296
2297         ast_cli(a->fd, "\nEnabled Redirects:\n");
2298         AST_RWLIST_RDLOCK(&uri_redirects);
2299         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
2300                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
2301         if (AST_RWLIST_EMPTY(&uri_redirects)) {
2302                 ast_cli(a->fd, "  None.\n");
2303         }
2304         AST_RWLIST_UNLOCK(&uri_redirects);
2305
2306         return CLI_SUCCESS;
2307 }
2308
2309 static int reload_module(void)
2310 {
2311         return __ast_http_load(1);
2312 }
2313
2314 static struct ast_cli_entry cli_http[] = {
2315         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
2316 };
2317
2318 static int unload_module(void)
2319 {
2320         struct http_uri_redirect *redirect;
2321         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
2322
2323         ast_tcptls_server_stop(&http_desc);
2324         if (http_tls_cfg.enabled) {
2325                 ast_tcptls_server_stop(&https_desc);
2326         }
2327         ast_free(http_tls_cfg.certfile);
2328         ast_free(http_tls_cfg.capath);
2329         ast_free(http_tls_cfg.pvtfile);
2330         ast_free(http_tls_cfg.cipher);
2331
2332         ast_http_uri_unlink(&statusuri);
2333         ast_http_uri_unlink(&staticuri);
2334
2335         AST_RWLIST_WRLOCK(&uri_redirects);
2336         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2337                 ast_free(redirect);
2338         }
2339         AST_RWLIST_UNLOCK(&uri_redirects);
2340
2341         return 0;
2342 }
2343
2344 static int load_module(void)
2345 {
2346         ast_http_uri_link(&statusuri);
2347         ast_http_uri_link(&staticuri);
2348         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
2349
2350         return __ast_http_load(0) ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_SUCCESS;
2351 }
2352
2353 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Built-in HTTP Server",
2354         .support_level = AST_MODULE_SUPPORT_CORE,
2355         .load = load_module,
2356         .unload = unload_module,
2357         .reload = reload_module,
2358         .load_pri = AST_MODPRI_CORE,
2359         .requires = "extconfig",
2360 );