Debian Codegraph @

main/http.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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 <[email protected]>
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/acl.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/tcptls.h"
57 #include "asterisk/http.h"
58 #include "asterisk/utils.h"
59 #include "asterisk/strings.h"
60 #include "asterisk/config.h"
61 #include "asterisk/stringfields.h"
62 #include "asterisk/ast_version.h"
63 #include "asterisk/manager.h"
64 #include "asterisk/module.h"
65 #include "asterisk/astobj2.h"
66 #include "asterisk/netsock2.h"
67 #include "asterisk/json.h"
68
69 #define MAX_PREFIX 80
70 #define DEFAULT_PORT 8088
71 #define DEFAULT_TLS_PORT 8089
72 #define DEFAULT_SESSION_LIMIT 100
73 /*! (ms) Idle time waiting for data. */
74 #define DEFAULT_SESSION_INACTIVITY 30000
75 /*! (ms) Min timeout for initial HTTP request to start coming in. */
76 #define MIN_INITIAL_REQUEST_TIMEOUT 10000
77 /*! (ms) Idle time between HTTP requests */
78 #define DEFAULT_SESSION_KEEP_ALIVE 15000
79 /*! Max size for the http server name */
80 #define MAX_SERVER_NAME_LENGTH 128
81 /*! Max size for the http response header */
82 #define DEFAULT_RESPONSE_HEADER_LENGTH 512
83
84 /*! Maximum application/json or application/x-www-form-urlencoded body content length. */
85 #if !defined(LOW_MEMORY)
86 #define MAX_CONTENT_LENGTH 40960
87 #else
88 #define MAX_CONTENT_LENGTH 1024
89 #endif /* !defined(LOW_MEMORY) */
90
91 /*! Initial response body length. */
92 #if !defined(LOW_MEMORY)
93 #define INITIAL_RESPONSE_BODY_BUFFER 1024
94 #else
95 #define INITIAL_RESPONSE_BODY_BUFFER 512
96 #endif /* !defined(LOW_MEMORY) */
97
98 /*! Maximum line length for HTTP requests. */
99 #if !defined(LOW_MEMORY)
100 #define MAX_HTTP_LINE_LENGTH 4096
101 #else
102 #define MAX_HTTP_LINE_LENGTH 1024
103 #endif /* !defined(LOW_MEMORY) */
104
105 static char http_server_name[MAX_SERVER_NAME_LENGTH];
106
107 static int session_limit = DEFAULT_SESSION_LIMIT;
108 static int session_inactivity = DEFAULT_SESSION_INACTIVITY;
109 static int session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
110 static int session_count = 0;
111
112 static struct ast_tls_config http_tls_cfg;
113
114 static void *httpd_helper_thread(void *arg);
115
116 /*!
117 * For standard configuration we have up to two accepting threads,
118 * one for http, one for https. If TEST_FRAMEWORK is enabled it's
119 * possible to have more than one running http server.
120 */
121 struct ast_http_server {
122 struct ast_tcptls_session_args args;
123 char *name;
124 char *address;
125 };
126
127 /*!
128 * The default configured HTTP server
129 */
130 struct ast_http_server *global_http_server = NULL;
131
132 static struct ast_tcptls_session_args https_desc = {
133 .accept_fd = -1,
134 .master = AST_PTHREADT_NULL,
135 .tls_cfg = &http_tls_cfg,
136 .poll_timeout = -1,
137 .name = "https server",
138 .accept_fn = ast_tcptls_server_root,
139 .worker_fn = httpd_helper_thread,
140 };
141
142 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri); /*!< list of supported handlers */
143
144 /* all valid URIs must be prepended by the string in prefix. */
145 static char prefix[MAX_PREFIX];
146 static int static_uri_enabled;
147 static int status_uri_enabled;
148
149 /*! \brief Limit the kinds of files we're willing to serve up */
150 static struct {
151 const char *ext;
152 const char *mtype;
153 } mimetypes[] = {
154 { "png", "image/png" },
155 { "xml", "text/xml" },
156 { "jpg", "image/jpeg" },
157 { "js", "application/x-javascript" },
158 { "wav", "audio/x-wav" },
159 { "mp3", "audio/mpeg" },
160 { "svg", "image/svg+xml" },
161 { "svgz", "image/svg+xml" },
162 { "gif", "image/gif" },
163 { "html", "text/html" },
164 { "htm", "text/html" },
165 { "css", "text/css" },
166 { "cnf", "text/plain" },
167 { "cfg", "text/plain" },
168 { "bin", "application/octet-stream" },
169 { "sbn", "application/octet-stream" },
170 { "ld", "application/octet-stream" },
171 };
172
173 struct http_uri_redirect {
174 AST_LIST_ENTRY(http_uri_redirect) entry;
175 char *dest;
176 char target[0];
177 };
178
179 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
180
181 /*! \brief Per-path ACL restriction */
182 struct http_restriction {
183 AST_LIST_ENTRY(http_restriction) entry;
184 struct ast_acl_list *acl;
185 char path[];
186 };
187
188 AST_LIST_HEAD_NOLOCK(http_restriction_list, http_restriction);
189
190 static AST_RWLIST_HEAD_STATIC(restrictions, http_restriction);
191
192 static int check_restriction_acl(struct ast_tcptls_session_instance *ser, const char *uri);
193
194 static const struct ast_cfhttp_methods_text {
195 enum ast_http_method method;
196 const char *text;
197 } ast_http_methods_text[] = {
198 { AST_HTTP_UNKNOWN, "UNKNOWN" },
199 { AST_HTTP_GET, "GET" },
200 { AST_HTTP_POST, "POST" },
201 { AST_HTTP_HEAD, "HEAD" },
202 { AST_HTTP_PUT, "PUT" },
203 { AST_HTTP_DELETE, "DELETE" },
204 { AST_HTTP_OPTIONS, "OPTIONS" },
205 };
206
207 const char *ast_get_http_method(enum ast_http_method method)
208 {
209 int x;
210
211 for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
212 if (ast_http_methods_text[x].method == method) {
213 return ast_http_methods_text[x].text;
214 }
215 }
216
217 return NULL;
218 }
219
220 enum ast_http_method ast_get_http_method_from_string(const char *method)
221 {
222 int x;
223
224 for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
225 if (ast_strings_equal(method, ast_http_methods_text[x].text)) {
226 return ast_http_methods_text[x].method;
227 }
228 }
229
230 return AST_HTTP_UNKNOWN;
231 }
232
233 const char *ast_http_ftype2mtype(const char *ftype)
234 {
235 int x;
236
237 if (ftype) {
238 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
239 if (!strcasecmp(ftype, mimetypes[x].ext)) {
240 return mimetypes[x].mtype;
241 }
242 }
243 }
244 return NULL;
245 }
246
247 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
248 {
249 uint32_t mngid = 0;
250 struct ast_variable *v, *cookies;
251
252 cookies = ast_http_get_cookies(headers);
253 for (v = cookies; v; v = v->next) {
254 if (!strcasecmp(v->name, "mansession_id")) {
255 sscanf(v->value, "%30x", &mngid);
256 break;
257 }
258 }
259 ast_variables_destroy(cookies);
260 return mngid;
261 }
262
263 void ast_http_prefix(char *buf, int len)
264 {
265 if (buf) {
266 ast_copy_string(buf, prefix, len);
267 }
268 }
269
270 static int static_callback(struct ast_tcptls_session_instance *ser,
271 const struct ast_http_uri *urih, const char *uri,
272 enum ast_http_method method, struct ast_variable *get_vars,
273 struct ast_variable *headers)
274 {
275 char *path;
276 const char *ftype;
277 const char *mtype;
278 char wkspace[80];
279 struct stat st;
280 int len;
281 int fd;
282 struct ast_str *http_header;
283 struct timeval tv;
284 struct ast_tm tm;
285 char timebuf[80], etag[23];
286 struct ast_variable *v;
287 int not_modified = 0;
288
289 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
290 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
291 return 0;
292 }
293
294 /* Yuck. I'm not really sold on this, but if you don't deliver static content it
295 * makes your configuration substantially more challenging, but this seems like a
296 * rather irritating feature creep on Asterisk.
297 *
298 * XXX: It is not clear to me what this comment means or if it is any longer
299 * relevant. */
300 if (ast_strlen_zero(uri)) {
301 goto out403;
302 }
303
304 /* Disallow any funny filenames at all (checking first character only??) */
305 if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
306 goto out403;
307 }
308
309 if (strstr(uri, "/..")) {
310 goto out403;
311 }
312
313 if ((ftype = strrchr(uri, '.'))) {
314 ftype++;
315 }
316
317 if (!(mtype = ast_http_ftype2mtype(ftype))) {
318 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
319 mtype = wkspace;
320 }
321
322 /* Cap maximum length */
323 if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
324 goto out403;
325 }
326
327 path = ast_alloca(len);
328 sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
329 if (stat(path, &st)) {
330 goto out404;
331 }
332
333 if (S_ISDIR(st.st_mode)) {
334 goto out404;
335 }
336
337 if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
338 goto out403;
339 }
340
341 fd = open(path, O_RDONLY);
342 if (fd < 0) {
343 goto out403;
344 }
345
346 /* make "Etag:" http header value */
347 snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
348
349 /* make "Last-Modified:" http header value */
350 tv.tv_sec = st.st_mtime;
351 tv.tv_usec = 0;
352 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
353
354 /* check received "If-None-Match" request header and Etag value for file */
355 for (v = headers; v; v = v->next) {
356 if (!strcasecmp(v->name, "If-None-Match")) {
357 if (!strcasecmp(v->value, etag)) {
358 not_modified = 1;
359 }
360 break;
361 }
362 }
363
364 http_header = ast_str_create(255);
365 if (!http_header) {
366 ast_http_request_close_on_completion(ser);
367 ast_http_error(ser, 500, "Server Error", "Out of memory");
368 close(fd);
369 return 0;
370 }
371
372 ast_str_set(&http_header, 0, "Content-type: %s\r\n"
373 "ETag: %s\r\n"
374 "Last-Modified: %s\r\n",
375 mtype,
376 etag,
377 timebuf);
378
379 /* ast_http_send() frees http_header, so we don't need to do it before returning */
380 if (not_modified) {
381 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
382 } else {
383 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
384 }
385 close(fd);
386 return 0;
387
388 out404:
389 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
390 return 0;
391
392 out403:
393 ast_http_request_close_on_completion(ser);
394 ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
395 return 0;
396 }
397
398 static void str_append_escaped(struct ast_str **str, const char *in)
399 {
400 const char *cur = in;
401
402 while(*cur) {
403 switch (*cur) {
404 case '<':
405 ast_str_append(str, 0, "&lt;");
406 break;
407 case '>':
408 ast_str_append(str, 0, "&gt;");
409 break;
410 case '&':
411 ast_str_append(str, 0, "&amp;");
412 break;
413 case '"':
414 ast_str_append(str, 0, "&quot;");
415 break;
416 default:
417 ast_str_append(str, 0, "%c", *cur);
418 break;
419 }
420 cur++;
421 }
422
423 return;
424 }
425
426 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
427 const struct ast_http_uri *urih, const char *uri,
428 enum ast_http_method method, struct ast_variable *get_vars,
429 struct ast_variable *headers)
430 {
431 struct ast_str *out;
432 struct ast_variable *v, *cookies = NULL;
433
434 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
435 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
436 return 0;
437 }
438
439 out = ast_str_create(512);
440 if (!out) {
441 ast_http_request_close_on_completion(ser);
442 ast_http_error(ser, 500, "Server Error", "Out of memory");
443 return 0;
444 }
445
446 ast_str_append(&out, 0,
447 "<html><title>Asterisk HTTP Status</title>\r\n"
448 "<body bgcolor=\"#ffffff\">\r\n"
449 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
450 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
451
452 ast_str_append(&out, 0, "<tr><td><i>Server</i></td><td><b>%s</b></td></tr>\r\n", http_server_name);
453 ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
454 if (global_http_server) {
455 ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
456 ast_sockaddr_stringify(&global_http_server->args.old_address));
457 }
458 if (http_tls_cfg.enabled) {
459 ast_str_append(&out, 0, "<tr><td><i>TLS Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
460 ast_sockaddr_stringify(&https_desc.old_address));
461 }
462 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
463 for (v = get_vars; v; v = v->next) {
464 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '");
465 str_append_escaped(&out, v->name);
466 ast_str_append(&out, 0, "'</i></td><td>");
467 str_append_escaped(&out, v->value);
468 ast_str_append(&out, 0, "</td></tr>\r\n");
469 }
470 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
471
472 cookies = ast_http_get_cookies(headers);
473 for (v = cookies; v; v = v->next) {
474 ast_str_append(&out, 0, "<tr><td><i>Cookie '");
475 str_append_escaped(&out, v->name);
476 ast_str_append(&out, 0, "'</i></td><td>");
477 str_append_escaped(&out, v->value);
478 ast_str_append(&out, 0, "</td></tr>\r\n");
479 }
480 ast_variables_destroy(cookies);
481
482 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");
483 ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
484 return 0;
485 }
486
487 static struct ast_http_uri status_uri = {
488 .callback = httpstatus_callback,
489 .description = "Asterisk HTTP General Status",
490 .uri = "httpstatus",
491 .has_subtree = 0,
492 .data = NULL,
493 .key = __FILE__,
494 };
495
496 static struct ast_http_uri static_uri = {
497 .callback = static_callback,
498 .description = "Asterisk HTTP Static Delivery",
499 .uri = "static",
500 .has_subtree = 1,
501 .data = NULL,
502 .key= __FILE__,
503 };
504
505 enum http_private_flags {
506 /*! TRUE if the HTTP request has a body. */
507 HTTP_FLAG_HAS_BODY = (1 << 0),
508 /*! TRUE if the HTTP request body has been read. */
509 HTTP_FLAG_BODY_READ = (1 << 1),
510 /*! TRUE if the HTTP request must close when completed. */
511 HTTP_FLAG_CLOSE_ON_COMPLETION = (1 << 2),
512 };
513
514 /*! HTTP tcptls worker_fn private data. */
515 struct http_worker_private_data {
516 /*! Body length or -1 if chunked. Valid if HTTP_FLAG_HAS_BODY is TRUE. */
517 int body_length;
518 /*! HTTP body tracking flags */
519 struct ast_flags flags;
520 };
521
522 void ast_http_send(struct ast_tcptls_session_instance *ser,
523 enum ast_http_method method, int status_code, const char *status_title,
524 struct ast_str *http_header, struct ast_str *out, int fd,
525 unsigned int static_content)
526 {
527 struct timeval now = ast_tvnow();
528 struct ast_tm tm;
529 char timebuf[80];
530 char buf[256];
531 int len;
532 int content_length = 0;
533 int close_connection;
534 struct ast_str *server_header_field = ast_str_create(MAX_SERVER_NAME_LENGTH);
535 int send_content;
536
537 if (!ser || !server_header_field) {
538 /* The connection is not open. */
539 ast_free(http_header);
540 ast_free(out);
541 ast_free(server_header_field);
542 return;
543 }
544
545 if(!ast_strlen_zero(http_server_name)) {
546 ast_str_set(&server_header_field,
547 0,
548 "Server: %s\r\n",
549 http_server_name);
550 }
551
552 /*
553 * We shouldn't be sending non-final status codes to this
554 * function because we may close the connection before
555 * returning.
556 */
557 ast_assert(200 <= status_code);
558
559 if (session_keep_alive <= 0) {
560 close_connection = 1;
561 } else {
562 struct http_worker_private_data *request;
563
564 request = ser->private_data;
565 if (!request
566 || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)
567 || ast_http_body_discard(ser)) {
568 close_connection = 1;
569 } else {
570 close_connection = 0;
571 }
572 }
573
574 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
575
576 /* calc content length */
577 if (out) {
578 content_length += ast_str_strlen(out);
579 }
580
581 if (fd) {
582 content_length += lseek(fd, 0, SEEK_END);
583 lseek(fd, 0, SEEK_SET);
584 }
585
586 send_content = method != AST_HTTP_HEAD || status_code >= 400;
587
588 /* send http header */
589 if (ast_iostream_printf(ser->stream,
590 "HTTP/1.1 %d %s\r\n"
591 "%s"
592 "Date: %s\r\n"
593 "%s"
594 "%s"
595 "%s"
596 "Content-Length: %d\r\n"
597 "\r\n"
598 "%s",
599 status_code, status_title ? status_title : "OK",
600 ast_str_buffer(server_header_field),
601 timebuf,
602 close_connection ? "Connection: close\r\n" : "",
603 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
604 http_header ? ast_str_buffer(http_header) : "",
605 content_length,
606 send_content && out && ast_str_strlen(out) ? ast_str_buffer(out) : ""
607 ) <= 0) {
608 ast_debug(1, "ast_iostream_printf() failed: %s\n", strerror(errno));
609 close_connection = 1;
610 } else if (send_content && fd) {
611 /* send file content */
612 while ((len = read(fd, buf, sizeof(buf))) > 0) {
613 if (ast_iostream_write(ser->stream, buf, len) != len) {
614 ast_debug(1, "ast_iostream_write() failed: %s\n", strerror(errno));
615 close_connection = 1;
616 break;
617 }
618 }
619 }
620
621 ast_free(http_header);
622 ast_free(out);
623 ast_free(server_header_field);
624
625 if (close_connection) {
626 ast_debug(1, "HTTP closing session. status_code:%d\n", status_code);
627 ast_tcptls_close_session_file(ser);
628 } else {
629 ast_debug(1, "HTTP keeping session open. status_code:%d\n", status_code);
630 }
631 }
632
633 void ast_http_create_response(struct ast_tcptls_session_instance *ser, int status_code,
634 const char *status_title, struct ast_str *http_header_data, const char *text)
635 {
636 char server_name[MAX_SERVER_NAME_LENGTH];
637 char escaped_text[512];
638 struct ast_str *server_address = ast_str_create(MAX_SERVER_NAME_LENGTH);
639 struct ast_str *out = ast_str_create(INITIAL_RESPONSE_BODY_BUFFER);
640
641 if (!http_header_data || !server_address || !out) {
642 ast_free(http_header_data);
643 ast_free(server_address);
644 ast_free(out);
645 if (ser) {
646 ast_debug(1, "HTTP closing session. OOM.\n");
647 ast_tcptls_close_session_file(ser);
648 }
649 return;
650 }
651
652 if(!ast_strlen_zero(http_server_name)) {
653 ast_xml_escape(http_server_name, server_name, sizeof(server_name));
654 ast_str_set(&server_address,
655 0,
656 "<address>%s</address>\r\n",
657 server_name);
658 }
659
660 /* Escape text to prevent reflected XSS in error pages */
661 if (!ast_strlen_zero(text)) {
662 ast_xml_escape(text, escaped_text, sizeof(escaped_text));
663 } else {
664 escaped_text[0] = '\0';
665 }
666
667 ast_str_set(&out,
668 0,
669 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
670 "<html><head>\r\n"
671 "<title>%d %s</title>\r\n"
672 "</head><body>\r\n"
673 "<h1>%s</h1>\r\n"
674 "<p>%s</p>\r\n"
675 "<hr />\r\n"
676 "%s"
677 "</body></html>\r\n",
678 status_code,
679 status_title,
680 status_title,
681 escaped_text,
682 ast_str_buffer(server_address));
683
684 ast_free(server_address);
685
686 ast_http_send(ser,
687 AST_HTTP_UNKNOWN,
688 status_code,
689 status_title,
690 http_header_data,
691 out,
692 0,
693 0);
694 }
695
696 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
697 const unsigned long nonce, const unsigned long opaque, int stale,
698 const char *text)
699 {
700 int status_code = 401;
701 char *status_title = "Unauthorized";
702 struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
703
704 if (http_header_data) {
705 ast_str_set(&http_header_data,
706 0,
707 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
708 "Content-type: text/html\r\n",
709 realm ? realm : "Asterisk",
710 nonce,
711 opaque,
712 stale ? ", stale=true" : "");
713 }
714
715 ast_http_create_response(ser,
716 status_code,
717 status_title,
718 http_header_data,
719 text);
720 }
721
722 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code,
723 const char *status_title, const char *text)
724 {
725 struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
726
727 if (http_header_data) {
728 ast_str_set(&http_header_data, 0, "Content-type: text/html\r\n");
729 }
730
731 ast_http_create_response(ser,
732 status_code,
733 status_title,
734 http_header_data,
735 text);
736 }
737
738 /*!
739 * \brief Link the new uri into the list.
740 *
741 * They are sorted by length of
742 * the string, not alphabetically. Duplicate entries are not replaced,
743 * but the insertion order (using <= and not just <) makes sure that
744 * more recent insertions hide older ones.
745 * On a lookup, we just scan the list and stop at the first matching entry.
746 */
747 int ast_http_uri_link(struct ast_http_uri *urih)
748 {
749 struct ast_http_uri *uri;
750 int len = strlen(urih->uri);
751
752 AST_RWLIST_WRLOCK(&uris);
753
754 urih->prefix = prefix;
755
756 if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
757 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
758 AST_RWLIST_UNLOCK(&uris);
759 return 0;
760 }
761
762 AST_RWLIST_TRAVERSE(&uris, uri, entry) {
763 if (AST_RWLIST_NEXT(uri, entry) &&
764 strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
765 AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
766 AST_RWLIST_UNLOCK(&uris);
767
768 return 0;
769 }
770 }
771
772 AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
773
774 AST_RWLIST_UNLOCK(&uris);
775
776 return 0;
777 }
778
779 void ast_http_uri_unlink(struct ast_http_uri *urih)
780 {
781 AST_RWLIST_WRLOCK(&uris);
782 AST_RWLIST_REMOVE(&uris, urih, entry);
783 AST_RWLIST_UNLOCK(&uris);
784 }
785
786 void ast_http_uri_unlink_all_with_key(const char *key)
787 {
788 struct ast_http_uri *urih;
789 AST_RWLIST_WRLOCK(&uris);
790 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
791 if (!strcmp(urih->key, key)) {
792 AST_RWLIST_REMOVE_CURRENT(entry);
793 if (urih->dmallocd) {
794 ast_free(urih->data);
795 }
796 if (urih->mallocd) {
797 ast_free(urih);
798 }
799 }
800 }
801 AST_RWLIST_TRAVERSE_SAFE_END;
802 AST_RWLIST_UNLOCK(&uris);
803 }
804
805 /*!
806 * \brief Retrieves the header with the given field name.
807 *
808 * \param headers Headers to search.
809 * \param field_name Name of the header to find.
810 * \return Associated header value.
811 * \retval NULL if header is not present.
812 */
813 static const char *get_header(struct ast_variable *headers, const char *field_name)
814 {
815 struct ast_variable *v;
816
817 for (v = headers; v; v = v->next) {
818 if (!strcasecmp(v->name, field_name)) {
819 return v->value;
820 }
821 }
822 return NULL;
823 }
824
825 /*!
826 * \brief Retrieves the content type specified in the "Content-Type" header.
827 *
828 * This function only returns the "type/subtype" and any trailing parameter is
829 * not included.
830 *
831 * \note the return value is an allocated string that needs to be freed.
832 *
833 * \return the content type/subtype
834 * \retval NULL if the header is not found.
835 */
836 static char *get_content_type(struct ast_variable *headers)
837 {
838 const char *content_type = get_header(headers, "Content-Type");
839 const char *param;
840 size_t size;
841
842 if (!content_type) {
843 return NULL;
844 }
845
846 param = strchr(content_type, ';');
847 size = param ? param - content_type : strlen(content_type);
848
849 return ast_strndup(content_type, size);
850 }
851
852 /*!
853 * \brief Returns the value of the Content-Length header.
854 *
855 * \param headers HTTP headers.
856 *
857 * \return length Value of the Content-Length header.
858 * \retval 0 if header is not present.
859 * \retval -1 if header is invalid.
860 */
861 static int get_content_length(struct ast_variable *headers)
862 {
863 const char *content_length = get_header(headers, "Content-Length");
864 int length;
865
866 if (!content_length) {
867 /* Missing content length; assume zero */
868 return 0;
869 }
870
871 length = 0;
872 if (sscanf(content_length, "%30d", &length) != 1) {
873 /* Invalid Content-Length value */
874 length = -1;
875 }
876 return length;
877 }
878
879 /*!
880 * \brief Returns the value of the Transfer-Encoding header.
881 *
882 * \param headers HTTP headers.
883 * \return string Value of the Transfer-Encoding header.
884 * \retval NULL if header is not present.
885 */
886 static const char *get_transfer_encoding(struct ast_variable *headers)
887 {
888 return get_header(headers, "Transfer-Encoding");
889 }
890
891 /*!
892 * \internal
893 * \brief Determine if the HTTP peer wants the connection closed.
894 *
895 * \param headers List of HTTP headers
896 *
897 * \retval 0 keep connection open.
898 * \retval -1 close connection.
899 */
900 static int http_check_connection_close(struct ast_variable *headers)
901 {
902 const char *connection = get_header(headers, "Connection");
903 int close_connection = 0;
904
905 if (connection && !strcasecmp(connection, "close")) {
906 close_connection = -1;
907 }
908 return close_connection;
909 }
910
911 void ast_http_request_close_on_completion(struct ast_tcptls_session_instance *ser)
912 {
913 struct http_worker_private_data *request = ser->private_data;
914
915 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
916 }
917
918 /*!
919 * \internal
920 * \brief Initialize the request tracking information in case of early failure.
921 * \since 12.4.0
922 *
923 * \param request Request tracking information.
924 */
925 static void http_request_tracking_init(struct http_worker_private_data *request)
926 {
927 ast_set_flags_to(&request->flags,
928 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
929 /* Assume close in case request fails early */
930 HTTP_FLAG_CLOSE_ON_COMPLETION);
931 }
932
933 /*!
934 * \internal
935 * \brief Setup the HTTP request tracking information.
936 * \since 12.4.0
937 *
938 * \param ser HTTP TCP/TLS session object.
939 * \param headers List of HTTP headers.
940 *
941 * \retval 0 on success.
942 * \retval -1 on error.
943 */
944 static int http_request_tracking_setup(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
945 {
946 struct http_worker_private_data *request = ser->private_data;
947 const char *transfer_encoding;
948
949 ast_set_flags_to(&request->flags,
950 HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
951 http_check_connection_close(headers) ? HTTP_FLAG_CLOSE_ON_COMPLETION : 0);
952
953 transfer_encoding = get_transfer_encoding(headers);
954 if (transfer_encoding && !strcasecmp(transfer_encoding, "chunked")) {
955 request->body_length = -1;
956 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
957 return 0;
958 }
959
960 request->body_length = get_content_length(headers);
961 if (0 < request->body_length) {
962 ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
963 } else if (request->body_length < 0) {
964 /* Invalid Content-Length */
965 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
966 ast_http_error(ser, 400, "Bad Request", "Invalid Content-Length in request!");
967 return -1;
968 }
969 return 0;
970 }
971
972 void ast_http_body_read_status(struct ast_tcptls_session_instance *ser, int read_success)
973 {
974 struct http_worker_private_data *request;
975
976 request = ser->private_data;
977 if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
978 || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
979 /* No body to read. */
980 return;
981 }
982 ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
983 if (!read_success) {
984 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
985 }
986 }
987
988 /*!
989 * \internal
990 * \brief Read the next length bytes from the HTTP body.
991 * \since 12.4.0
992 *
993 * \param ser HTTP TCP/TLS session object.
994 * \param buf Where to put the contents reading.
995 * \param length How much contents to read.
996 * \param what_getting Name of the contents reading.
997 *
998 * \retval 0 on success.
999 * \retval -1 on error.
1000 */
1001 static int http_body_read_contents(struct ast_tcptls_session_instance *ser, char *buf, int length, const char *what_getting)
1002 {
1003 int res;
1004 int total = 0;
1005
1006 /* Stream is in exclusive mode so we get it all if possible. */
1007 while (total != length) {
1008 res = ast_iostream_read(ser->stream, buf + total, length - total);
1009 if (res <= 0) {
1010 break;
1011 }
1012
1013 total += res;
1014 }
1015
1016 if (total != length) {
1017 ast_log(LOG_WARNING, "Wrong HTTP content read. Request %s (Wanted %d, Read %d)\n",
1018 what_getting, length, res);
1019 return -1;
1020 }
1021
1022 return 0;
1023 }
1024
1025 /*!
1026 * \internal
1027 * \brief Read and discard the next length bytes from the HTTP body.
1028 * \since 12.4.0
1029 *
1030 * \param ser HTTP TCP/TLS session object.
1031 * \param length How much contents to discard
1032 * \param what_getting Name of the contents discarding.
1033 *
1034 * \retval 0 on success.
1035 * \retval -1 on error.
1036 */
1037 static int http_body_discard_contents(struct ast_tcptls_session_instance *ser, int length, const char *what_getting)
1038 {
1039 ssize_t res;
1040
1041 res = ast_iostream_discard(ser->stream, length);
1042 if (res < length) {
1043 ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d but got %zd)\n",
1044 what_getting, length, res);
1045 return -1;
1046 }
1047 return 0;
1048 }
1049
1050 /*!
1051 * \internal
1052 * \brief decode chunked mode hexadecimal value
1053 *
1054 * \param s string to decode
1055 * \param len length of string
1056 *
1057 * \return length on success.
1058 * \retval -1 on error.
1059 */
1060 static int chunked_atoh(const char *s, int len)
1061 {
1062 int value = 0;
1063 char c;
1064
1065 if (*s < '0') {
1066 /* zero value must be 0\n not just \n */
1067 return -1;
1068 }
1069
1070 while (len--) {
1071 c = *s++;
1072 if (c == '\x0D') {
1073 return value;
1074 }
1075 if (c == ';') {
1076 /* We have a chunk-extension that we don't care about. */
1077 while (len--) {
1078 if (*s++ == '\x0D') {
1079 return value;
1080 }
1081 }
1082 break;
1083 }
1084 value <<= 4;
1085 if (c >= '0' && c <= '9') {
1086 value += c - '0';
1087 continue;
1088 }
1089 if (c >= 'a' && c <= 'f') {
1090 value += 10 + c - 'a';
1091 continue;
1092 }
1093 if (c >= 'A' && c <= 'F') {
1094 value += 10 + c - 'A';
1095 continue;
1096 }
1097 /* invalid character */
1098 return -1;
1099 }
1100 /* end of string */
1101 return -1;
1102 }
1103
1104 /*!
1105 * \internal
1106 * \brief Read and convert the chunked body header length.
1107 * \since 12.4.0
1108 *
1109 * \param ser HTTP TCP/TLS session object.
1110 *
1111 * \return length Size of chunk to expect.
1112 * \retval -1 on error.
1113 */
1114 static int http_body_get_chunk_length(struct ast_tcptls_session_instance *ser)
1115 {
1116 int length;
1117 char header_line[MAX_HTTP_LINE_LENGTH];
1118
1119 /* get the line of hexadecimal giving chunk-size w/ optional chunk-extension */
1120 if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1121 ast_log(LOG_WARNING, "Short HTTP read of chunked header\n");
1122 return -1;
1123 }
1124 length = chunked_atoh(header_line, strlen(header_line));
1125 if (length < 0) {
1126 ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
1127 return -1;
1128 }
1129 return length;
1130 }
1131
1132 /*!
1133 * \internal
1134 * \brief Read and check the chunk contents line termination.
1135 * \since 12.4.0
1136 *
1137 * \param ser HTTP TCP/TLS session object.
1138 *
1139 * \retval 0 on success.
1140 * \retval -1 on error.
1141 */
1142 static int http_body_check_chunk_sync(struct ast_tcptls_session_instance *ser)
1143 {
1144 int res;
1145 char chunk_sync[2];
1146
1147 /* Stay in fread until get the expected CRLF or timeout. */
1148 res = ast_iostream_read(ser->stream, chunk_sync, sizeof(chunk_sync));
1149 if (res < sizeof(chunk_sync)) {
1150 ast_log(LOG_WARNING, "Short HTTP chunk sync read (Wanted %zu)\n",
1151 sizeof(chunk_sync));
1152 return -1;
1153 }
1154 if (chunk_sync[0] != 0x0D || chunk_sync[1] != 0x0A) {
1155 ast_log(LOG_WARNING, "HTTP chunk sync bytes wrong (0x%02hhX, 0x%02hhX)\n",
1156 (unsigned char) chunk_sync[0], (unsigned char) chunk_sync[1]);
1157 return -1;
1158 }
1159
1160 return 0;
1161 }
1162
1163 /*!
1164 * \internal
1165 * \brief Read and discard any chunked trailer entity-header lines.
1166 * \since 12.4.0
1167 *
1168 * \param ser HTTP TCP/TLS session object.
1169 *
1170 * \retval 0 on success.
1171 * \retval -1 on error.
1172 */
1173 static int http_body_discard_chunk_trailer_headers(struct ast_tcptls_session_instance *ser)
1174 {
1175 char header_line[MAX_HTTP_LINE_LENGTH];
1176
1177 for (;;) {
1178 if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
1179 ast_log(LOG_WARNING, "Short HTTP read of chunked trailer header\n");
1180 return -1;
1181 }
1182
1183 /* Trim trailing whitespace */
1184 ast_trim_blanks(header_line);
1185 if (ast_strlen_zero(header_line)) {
1186 /* A blank line ends the chunked-body */
1187 break;
1188 }
1189 }
1190 return 0;
1191 }
1192
1193 int ast_http_body_discard(struct ast_tcptls_session_instance *ser)
1194 {
1195 struct http_worker_private_data *request;
1196
1197 request = ser->private_data;
1198 if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
1199 || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
1200 /* No body to read or it has already been read. */
1201 return 0;
1202 }
1203 ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
1204
1205 ast_debug(1, "HTTP discarding unused request body\n");
1206
1207 ast_assert(request->body_length != 0);
1208 if (0 < request->body_length) {
1209 if (http_body_discard_contents(ser, request->body_length, "body")) {
1210 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1211 return -1;
1212 }
1213 return 0;
1214 }
1215
1216 /* parse chunked-body */
1217 for (;;) {
1218 int length;
1219
1220 length = http_body_get_chunk_length(ser);
1221 if (length < 0) {
1222 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1223 return -1;
1224 }
1225 if (length == 0) {
1226 /* parsed last-chunk */
1227 break;
1228 }
1229
1230 if (http_body_discard_contents(ser, length, "chunk-data")
1231 || http_body_check_chunk_sync(ser)) {
1232 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1233 return -1;
1234 }
1235 }
1236
1237 /* Read and discard any trailer entity-header lines. */
1238 if (http_body_discard_chunk_trailer_headers(ser)) {
1239 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1240 return -1;
1241 }
1242 return 0;
1243 }
1244
1245 /*!
1246 * \brief Returns the contents (body) of the HTTP request
1247 *
1248 * \param return_length ptr to int that returns content length
1249 * \param ser HTTP TCP/TLS session object
1250 * \param headers List of HTTP headers
1251 * \return ptr to content (zero terminated)
1252 * \retval NULL on failure
1253 * \note Since returned ptr is malloc'd, it should be free'd by caller
1254 */
1255 static char *ast_http_get_contents(int *return_length,
1256 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1257 {
1258 struct http_worker_private_data *request;
1259 int content_length;
1260 int bufsize;
1261 char *buf;
1262
1263 request = ser->private_data;
1264 if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)) {
1265 /* no content - not an error */
1266 return NULL;
1267 }
1268 if (ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
1269 /* Already read the body. Cannot read again. Assume no content. */
1270 ast_assert(0);
1271 return NULL;
1272 }
1273 ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
1274
1275 ast_debug(2, "HTTP consuming request body\n");
1276
1277 ast_assert(request->body_length != 0);
1278 if (0 < request->body_length) {
1279 /* handle regular non-chunked content */
1280 content_length = request->body_length;
1281 if (content_length > MAX_CONTENT_LENGTH) {
1282 ast_log(LOG_WARNING, "Excessively long HTTP content. (%d > %d)\n",
1283 content_length, MAX_CONTENT_LENGTH);
1284 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1285 errno = EFBIG;
1286 return NULL;
1287 }
1288 buf = ast_malloc(content_length + 1);
1289 if (!buf) {
1290 /* Malloc sets ENOMEM */
1291 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1292 return NULL;
1293 }
1294
1295 if (http_body_read_contents(ser, buf, content_length, "body")) {
1296 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1297 errno = EIO;
1298 ast_free(buf);
1299 return NULL;
1300 }
1301
1302 buf[content_length] = 0;
1303 *return_length = content_length;
1304 return buf;
1305 }
1306
1307 /* pre-allocate buffer */
1308 bufsize = 250;
1309 buf = ast_malloc(bufsize);
1310 if (!buf) {
1311 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1312 return NULL;
1313 }
1314
1315 /* parse chunked-body */
1316 content_length = 0;
1317 for (;;) {
1318 int chunk_length;
1319
1320 chunk_length = http_body_get_chunk_length(ser);
1321 if (chunk_length < 0) {
1322 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1323 errno = EIO;
1324 ast_free(buf);
1325 return NULL;
1326 }
1327 if (chunk_length == 0) {
1328 /* parsed last-chunk */
1329 break;
1330 }
1331 if (content_length + chunk_length > MAX_CONTENT_LENGTH) {
1332 ast_log(LOG_WARNING,
1333 "Excessively long HTTP accumulated chunked body. (%d + %d > %d)\n",
1334 content_length, chunk_length, MAX_CONTENT_LENGTH);
1335 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1336 errno = EFBIG;
1337 ast_free(buf);
1338 return NULL;
1339 }
1340
1341 /* insure buffer is large enough +1 */
1342 if (content_length + chunk_length >= bufsize) {
1343 char *new_buf;
1344
1345 /* Increase bufsize until it can handle the expected data. */
1346 do {
1347 bufsize *= 2;
1348 } while (content_length + chunk_length >= bufsize);
1349
1350 new_buf = ast_realloc(buf, bufsize);
1351 if (!new_buf) {
1352 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1353 ast_free(buf);
1354 return NULL;
1355 }
1356 buf = new_buf;
1357 }
1358
1359 if (http_body_read_contents(ser, buf + content_length, chunk_length, "chunk-data")
1360 || http_body_check_chunk_sync(ser)) {
1361 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1362 errno = EIO;
1363 ast_free(buf);
1364 return NULL;
1365 }
1366 content_length += chunk_length;
1367 }
1368
1369 /*
1370 * Read and discard any trailer entity-header lines
1371 * which we don't care about.
1372 *
1373 * XXX In the future we may need to add the trailer headers
1374 * to the passed in headers list rather than discarding them.
1375 */
1376 if (http_body_discard_chunk_trailer_headers(ser)) {
1377 ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
1378 errno = EIO;
1379 ast_free(buf);
1380 return NULL;
1381 }
1382
1383 buf[content_length] = 0;
1384 *return_length = content_length;
1385 return buf;
1386 }
1387
1388 struct ast_json *ast_http_get_json(
1389 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1390 {
1391 int content_length = 0;
1392 struct ast_json *body;
1393 RAII_VAR(char *, buf, NULL, ast_free);
1394 RAII_VAR(char *, type, get_content_type(headers), ast_free);
1395
1396 /* Use errno to distinguish errors from no body */
1397 errno = 0;
1398
1399 if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
1400 /* Content type is not JSON. Don't read the body. */
1401 return NULL;
1402 }
1403
1404 buf = ast_http_get_contents(&content_length, ser, headers);
1405 if (!buf || !content_length) {
1406 /*
1407 * errno already set
1408 * or it is not an error to have zero content
1409 */
1410 return NULL;
1411 }
1412
1413 body = ast_json_load_buf(buf, content_length, NULL);
1414 if (!body) {
1415 /* Failed to parse JSON; treat as an I/O error */
1416 errno = EIO;
1417 return NULL;
1418 }
1419
1420 return body;
1421 }
1422
1423 /*
1424 * get post variables from client Request Entity-Body, if content type is
1425 * application/x-www-form-urlencoded
1426 */
1427 struct ast_variable *ast_http_parse_post_form(char *buf, int content_length,
1428 const char *content_type)
1429 {
1430 struct ast_variable *v, *post_vars=NULL, *prev = NULL;
1431 char *var, *val;
1432
1433 /* Use errno to distinguish errors from no params */
1434 errno = 0;
1435
1436 if (ast_strlen_zero(content_type) ||
1437 strcasecmp(content_type, "application/x-www-form-urlencoded") != 0) {
1438 /* Content type is not form data. Don't read the body. */
1439 return NULL;
1440 }
1441
1442 while ((val = strsep(&buf, "&"))) {
1443 var = strsep(&val, "=");
1444 if (val) {
1445 ast_uri_decode(val, ast_uri_http_legacy);
1446 } else {
1447 val = "";
1448 }
1449 ast_uri_decode(var, ast_uri_http_legacy);
1450 if ((v = ast_variable_new(var, val, ""))) {
1451 if (post_vars) {
1452 prev->next = v;
1453 } else {
1454 post_vars = v;
1455 }
1456 prev = v;
1457 }
1458 }
1459
1460 return post_vars;
1461 }
1462
1463 struct ast_variable *ast_http_get_post_vars(
1464 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
1465 {
1466 int content_length = 0;
1467 RAII_VAR(char *, buf, NULL, ast_free);
1468 RAII_VAR(char *, type, get_content_type(headers), ast_free);
1469
1470 /* Use errno to distinguish errors from no params */
1471 errno = 0;
1472
1473 if (ast_strlen_zero(type) ||
1474 strcasecmp(type, "application/x-www-form-urlencoded")) {
1475 /* Content type is not form data. Don't read the body. */
1476 return NULL;
1477 }
1478
1479 buf = ast_http_get_contents(&content_length, ser, headers);
1480 if (!buf || !content_length) {
1481 /*
1482 * errno already set
1483 * or it is not an error to have zero content
1484 */
1485 return NULL;
1486 }
1487
1488 return ast_http_parse_post_form(buf, content_length, type);
1489 }
1490
1491 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
1492 enum ast_http_method method, struct ast_variable *headers)
1493 {
1494 char *c;
1495 int res = 0;
1496 char *params = uri;
1497 struct ast_http_uri *urih = NULL;
1498 int l;
1499 struct ast_variable *get_vars = NULL, *v, *prev = NULL;
1500 struct http_uri_redirect *redirect;
1501
1502 ast_debug(2, "HTTP Request URI is %s \n", uri);
1503
1504 strsep(&params, "?");
1505 /* Extract arguments from the request and store them in variables. */
1506 if (params) {
1507 char *var, *val;
1508
1509 while ((val = strsep(&params, "&"))) {
1510 var = strsep(&val, "=");
1511 if (val) {
1512 ast_uri_decode(val, ast_uri_http_legacy);
1513 } else {
1514 val = "";
1515 }
1516 ast_uri_decode(var, ast_uri_http_legacy);
1517 if ((v = ast_variable_new(var, val, ""))) {
1518 if (get_vars) {
1519 prev->next = v;
1520 } else {
1521 get_vars = v;
1522 }
1523 prev = v;
1524 }
1525 }
1526 }
1527
1528 /* Check path-based ACL restrictions */
1529 if (check_restriction_acl(ser, uri) != 0) {
1530 ast_http_request_close_on_completion(ser);
1531 ast_http_error(ser, 403, "Forbidden", "Access denied by ACL");
1532 goto cleanup;
1533 }
1534
1535 AST_RWLIST_RDLOCK(&uri_redirects);
1536 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
1537 if (!strcasecmp(uri, redirect->target)) {
1538 struct ast_str *http_header = ast_str_create(128);
1539
1540 if (!http_header) {
1541 ast_http_request_close_on_completion(ser);
1542 ast_http_error(ser, 500, "Server Error", "Out of memory");
1543 break;
1544 }
1545 ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
1546 ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
1547 break;
1548 }
1549 }
1550 AST_RWLIST_UNLOCK(&uri_redirects);
1551 if (redirect) {
1552 goto cleanup;
1553 }
1554
1555 /* We want requests to start with the (optional) prefix and '/' */
1556 l = strlen(prefix);
1557 if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
1558 uri += l + 1;
1559 /* scan registered uris to see if we match one. */
1560 AST_RWLIST_RDLOCK(&uris);
1561 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
1562 l = strlen(urih->uri);
1563 c = uri + l; /* candidate */
1564 ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
1565 if (strncasecmp(urih->uri, uri, l) /* no match */
1566 || (*c && *c != '/')) { /* substring */
1567 continue;
1568 }
1569 if (*c == '/') {
1570 c++;
1571 }
1572 if (!*c || urih->has_subtree) {
1573 uri = c;
1574 break;
1575 }
1576 }
1577 AST_RWLIST_UNLOCK(&uris);
1578 }
1579 if (urih) {
1580 ast_debug(1, "Match made with [%s]\n", urih->uri);
1581 if (!urih->no_decode_uri) {
1582 ast_uri_decode(uri, ast_uri_http_legacy);
1583 }
1584 res = urih->callback(ser, urih, uri, method, get_vars, headers);
1585 } else {
1586 ast_debug(1, "Request from %s for URI [%s] has no registered handler\n",
1587 ast_sockaddr_stringify_addr(&ser->remote_address), uri);
1588 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
1589 }
1590
1591 cleanup:
1592 ast_variables_destroy(get_vars);
1593 return res;
1594 }
1595
1596 static struct ast_variable *parse_cookies(const char *cookies)
1597 {
1598 char *parse = ast_strdupa(cookies);
1599 char *cur;
1600 struct ast_variable *vars = NULL, *var;
1601
1602 while ((cur = strsep(&parse, ";"))) {
1603 char *name, *val;
1604
1605 name = val = cur;
1606 strsep(&val, "=");
1607
1608 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1609 continue;
1610 }
1611
1612 name = ast_strip(name);
1613 val = ast_strip_quoted(val, "\"", "\"");
1614
1615 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1616 continue;
1617 }
1618
1619 ast_debug(1, "HTTP Cookie, Name: '%s' Value: '%s'\n", name, val);
1620
1621 var = ast_variable_new(name, val, __FILE__);
1622 var->next = vars;
1623 vars = var;
1624 }
1625
1626 return vars;
1627 }
1628
1629 /* get cookie from Request headers */
1630 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
1631 {
1632 struct ast_variable *v, *cookies = NULL;
1633
1634 for (v = headers; v; v = v->next) {
1635 if (!strcasecmp(v->name, "Cookie")) {
1636 ast_variables_destroy(cookies);
1637 cookies = parse_cookies(v->value);
1638 }
1639 }
1640 return cookies;
1641 }
1642
1643 static struct ast_http_auth *auth_create(const char *userid, const char *password)
1644 {
1645 struct ast_http_auth *auth;
1646 size_t userid_len;
1647 size_t password_len;
1648
1649 if (!userid || !password) {
1650 ast_log(LOG_ERROR, "Invalid userid/password\n");
1651 return NULL;
1652 }
1653
1654 userid_len = strlen(userid) + 1;
1655 password_len = strlen(password) + 1;
1656
1657 /* Allocate enough room to store everything in one memory block */
1658 auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
1659 if (!auth) {
1660 return NULL;
1661 }
1662
1663 /* Put the userid right after the struct */
1664 auth->userid = (char *)(auth + 1);
1665 strcpy(auth->userid, userid);
1666
1667 /* Put the password right after the userid */
1668 auth->password = auth->userid + userid_len;
1669 strcpy(auth->password, password);
1670
1671 return auth;
1672 }
1673
1674 #define BASIC_PREFIX "Basic "
1675 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
1676
1677 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
1678 {
1679 struct ast_variable *v;
1680
1681 for (v = headers; v; v = v->next) {
1682 const char *base64;
1683 char decoded[256] = {};
1684 char *username;
1685 char *password;
1686 #ifdef AST_DEVMODE
1687 int cnt;
1688 #endif /* AST_DEVMODE */
1689
1690 if (strcasecmp("Authorization", v->name) != 0) {
1691 continue;
1692 }
1693
1694 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1695 ast_log(LOG_DEBUG,
1696 "Unsupported Authorization scheme\n");
1697 continue;
1698 }
1699
1700 /* Basic auth header parsing. RFC 2617, section 2.
1701 * credentials = "Basic" basic-credentials
1702 * basic-credentials = base64-user-pass
1703 * base64-user-pass = <base64 encoding of user-pass,
1704 * except not limited to 76 char/line>
1705 * user-pass = userid ":" password
1706 */
1707
1708 base64 = v->value + BASIC_LEN;
1709
1710 /* This will truncate "userid:password" lines to
1711 * sizeof(decoded). The array is long enough that this shouldn't
1712 * be a problem */
1713 #ifdef AST_DEVMODE
1714 cnt =
1715 #endif /* AST_DEVMODE */
1716 ast_base64decode((unsigned char*)decoded, base64,
1717 sizeof(decoded) - 1);
1718 ast_assert(cnt < sizeof(decoded));
1719
1720 /* Split the string at the colon */
1721 password = decoded;
1722 username = strsep(&password, ":");
1723 if (!password) {
1724 ast_log(LOG_WARNING, "Invalid Authorization header\n");
1725 return NULL;
1726 }
1727
1728 return auth_create(username, password);
1729 }
1730
1731 return NULL;
1732 }
1733
1734 struct ast_variable *ast_http_create_basic_auth_header(const char *userid,
1735 const char *password)
1736 {
1737 int encoded_size = 0;
1738 int userinfo_len = 0;
1739 RAII_VAR(char *, userinfo, NULL, ast_free);
1740 char *encoded_userinfo = NULL;
1741 struct ast_variable *auth_header = NULL;
1742
1743 if (ast_strlen_zero(userid)) {
1744 return NULL;
1745 }
1746
1747 if (strchr(userid, ':')) {
1748 userinfo = ast_strdup(userid);
1749 userinfo_len = strlen(userinfo);
1750 } else {
1751 if (ast_strlen_zero(password)) {
1752 return NULL;
1753 }
1754 userinfo_len = ast_asprintf(&userinfo, "%s:%s", userid, password);
1755 }
1756 if (!userinfo) {
1757 return NULL;
1758 }
1759
1760 /*
1761 * The header value is "Basic " + base64(userinfo).
1762 * Doubling the userinfo length then adding the length
1763 * of the "Basic " prefix is a conservative estimate of the
1764 * final encoded size.
1765 */
1766 encoded_size = userinfo_len * 2 * sizeof(char) + 1 + BASIC_LEN;
1767 encoded_userinfo = ast_alloca(encoded_size);
1768 strcpy(encoded_userinfo, BASIC_PREFIX); /* Safe */
1769 ast_base64encode(encoded_userinfo + BASIC_LEN, (unsigned char *)userinfo,
1770 userinfo_len, encoded_size - BASIC_LEN);
1771
1772 auth_header = ast_variable_new("Authorization",
1773 encoded_userinfo, "");
1774
1775 return auth_header;
1776 }
1777
1778 int ast_http_response_status_line(const char *buf, const char *version, int code)
1779 {
1780 int status_code;
1781 size_t size = strlen(version);
1782
1783 if (strncmp(buf, version, size) || buf[size] != ' ') {
1784 ast_log(LOG_ERROR, "HTTP version not supported - "
1785 "expected %s\n", version);
1786 return -1;
1787 }
1788
1789 /* skip to status code (version + space) */
1790 buf += size + 1;
1791
1792 if (sscanf(buf, "%d", &status_code) != 1) {
1793 ast_log(LOG_ERROR, "Could not read HTTP status code - "
1794 "%s\n", buf);
1795 return -1;
1796 }
1797
1798 return status_code;
1799 }
1800
1801 static void remove_excess_lws(char *s)
1802 {
1803 char *p, *res = s;
1804 char *buf = ast_malloc(strlen(s) + 1);
1805 char *buf_end;
1806
1807 if (!buf) {
1808 return;
1809 }
1810
1811 buf_end = buf;
1812
1813 while (*s && *(s = ast_skip_blanks(s))) {
1814 p = s;
1815 s = ast_skip_nonblanks(s);
1816
1817 if (buf_end != buf) {
1818 *buf_end++ = ' ';
1819 }
1820
1821 memcpy(buf_end, p, s - p);
1822 buf_end += s - p;
1823 }
1824 *buf_end = '\0';
1825 /* safe since buf will always be less than or equal to res */
1826 strcpy(res, buf);
1827 ast_free(buf);
1828 }
1829
1830 int ast_http_header_parse(char *buf, char **name, char **value)
1831 {
1832 ast_trim_blanks(buf);
1833 if (ast_strlen_zero(buf)) {
1834 return -1;
1835 }
1836
1837 *value = buf;
1838 *name = strsep(value, ":");
1839 if (!*value) {
1840 return 1;
1841 }
1842
1843 *value = ast_skip_blanks(*value);
1844 if (ast_strlen_zero(*value) || ast_strlen_zero(*name)) {
1845 return 1;
1846 }
1847
1848 remove_excess_lws(*value);
1849 return 0;
1850 }
1851
1852 int ast_http_header_match(const char *name, const char *expected_name,
1853 const char *value, const char *expected_value)
1854 {
1855 if (strcasecmp(name, expected_name)) {
1856 /* no value to validate if names don't match */
1857 return 0;
1858 }
1859
1860 if (strcasecmp(value, expected_value)) {
1861 ast_log(LOG_ERROR, "Invalid header value - expected %s "
1862 "received %s", value, expected_value);
1863 return -1;
1864 }
1865 return 1;
1866 }
1867
1868 int ast_http_header_match_in(const char *name, const char *expected_name,
1869 const char *value, const char *expected_value)
1870 {
1871 if (strcasecmp(name, expected_name)) {
1872 /* no value to validate if names don't match */
1873 return 0;
1874 }
1875
1876 if (!strcasestr(expected_value, value)) {
1877 ast_log(LOG_ERROR, "Header '%s' - could not locate '%s' "
1878 "in '%s'\n", name, value, expected_value);
1879 return -1;
1880
1881 }
1882 return 1;
1883 }
1884
1885 /*! Limit the number of request headers in case the sender is being ridiculous. */
1886 #define MAX_HTTP_REQUEST_HEADERS 100
1887
1888 /*!
1889 * \internal
1890 * \brief Read the request headers.
1891 * \since 12.4.0
1892 *
1893 * \param ser HTTP TCP/TLS session object.
1894 * \param headers Where to put the request headers list pointer.
1895 *
1896 * \retval 0 on success.
1897 * \retval -1 on error.
1898 */
1899 static int http_request_headers_get(struct ast_tcptls_session_instance *ser, struct ast_variable **headers)
1900 {
1901 struct ast_variable *tail = *headers;
1902 int remaining_headers;
1903 char header_line[MAX_HTTP_LINE_LENGTH];
1904
1905 remaining_headers = MAX_HTTP_REQUEST_HEADERS;
1906 for (;;) {
1907 ssize_t len;
1908 char *name;
1909 char *value;
1910
1911 len = ast_iostream_gets(ser->stream, header_line, sizeof(header_line));
1912 if (len <= 0) {
1913 ast_http_error(ser, 400, "Bad Request", "Timeout");
1914 return -1;
1915 }
1916 if (header_line[len - 1] != '\n') {
1917 /* We didn't get a full line */
1918 ast_http_error(ser, 400, "Bad Request",
1919 (len == sizeof(header_line) - 1) ? "Header line too long" : "Timeout");
1920 return -1;
1921 }
1922
1923 /* Trim trailing characters */
1924 ast_trim_blanks(header_line);
1925 if (ast_strlen_zero(header_line)) {
1926 /* A blank line ends the request header section. */
1927 break;
1928 }
1929
1930 value = header_line;
1931 name = strsep(&value, ":");
1932 if (!value) {
1933 continue;
1934 }
1935
1936 value = ast_skip_blanks(value);
1937 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1938 continue;
1939 }
1940
1941 ast_trim_blanks(name);
1942
1943 if (!remaining_headers--) {
1944 /* Too many headers. */
1945 ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
1946 return -1;
1947 }
1948 if (!*headers) {
1949 *headers = ast_variable_new(name, value, __FILE__);
1950 tail = *headers;
1951 } else {
1952 tail->next = ast_variable_new(name, value, __FILE__);
1953 tail = tail->next;
1954 }
1955 if (!tail) {
1956 /*
1957 * Variable allocation failure.
1958 * Try to make some room.
1959 */
1960 ast_variables_destroy(*headers);
1961 *headers = NULL;
1962
1963 ast_http_error(ser, 500, "Server Error", "Out of memory");
1964 return -1;
1965 }
1966 }
1967
1968 return 0;
1969 }
1970
1971 /*!
1972 * \internal
1973 * \brief Process a HTTP request.
1974 * \since 12.4.0
1975 *
1976 * \param ser HTTP TCP/TLS session object.
1977 *
1978 * \retval 0 Continue and process the next HTTP request.
1979 * \retval -1 Fatal HTTP connection error. Force the HTTP connection closed.
1980 */
1981 static int httpd_process_request(struct ast_tcptls_session_instance *ser)
1982 {
1983 RAII_VAR(struct ast_variable *, headers, NULL, ast_variables_destroy);
1984 char *uri;
1985 char *method;
1986 const char *transfer_encoding;
1987 struct http_worker_private_data *request;
1988 enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1989 int res;
1990 ssize_t len;
1991 char request_line[MAX_HTTP_LINE_LENGTH];
1992
1993 len = ast_iostream_gets(ser->stream, request_line, sizeof(request_line));
1994 if (len <= 0) {
1995 return -1;
1996 }
1997
1998 /* Re-initialize the request body tracking data. */
1999 request = ser->private_data;
2000 http_request_tracking_init(request);
2001
2002 if (request_line[len - 1] != '\n') {
2003 /* We didn't get a full line */
2004 ast_http_error(ser, 400, "Bad Request",
2005 (len == sizeof(request_line) - 1) ? "Request line too long" : "Timeout");
2006 return -1;
2007 }
2008
2009 /* Get method */
2010 method = ast_skip_blanks(request_line);
2011 uri = ast_skip_nonblanks(method);
2012 if (*uri) {
2013 *uri++ = '\0';
2014 }
2015
2016 if (!strcasecmp(method,"GET")) {
2017 http_method = AST_HTTP_GET;
2018 } else if (!strcasecmp(method,"POST")) {
2019 http_method = AST_HTTP_POST;
2020 } else if (!strcasecmp(method,"HEAD")) {
2021 http_method = AST_HTTP_HEAD;
2022 } else if (!strcasecmp(method,"PUT")) {
2023 http_method = AST_HTTP_PUT;
2024 } else if (!strcasecmp(method,"DELETE")) {
2025 http_method = AST_HTTP_DELETE;
2026 } else if (!strcasecmp(method,"OPTIONS")) {
2027 http_method = AST_HTTP_OPTIONS;
2028 }
2029
2030 uri = ast_skip_blanks(uri); /* Skip white space */
2031 if (*uri) { /* terminate at the first blank */
2032 char *c = ast_skip_nonblanks(uri);
2033
2034 if (*c) {
2035 *c = '\0';
2036 }
2037 } else {
2038 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
2039 return -1;
2040 }
2041
2042 if (ast_shutdown_final()) {
2043 ast_http_error(ser, 503, "Service Unavailable", "Shutdown in progress");
2044 return -1;
2045 }
2046
2047 /* process "Request Headers" lines */
2048 if (http_request_headers_get(ser, &headers)) {
2049 return -1;
2050 }
2051
2052 transfer_encoding = get_transfer_encoding(headers);
2053 /* Transfer encoding defaults to identity */
2054 if (!transfer_encoding) {
2055 transfer_encoding = "identity";
2056 }
2057
2058 /*
2059 * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
2060 * codings we don't understand.
2061 */
2062 if (strcasecmp(transfer_encoding, "identity") != 0 &&
2063 strcasecmp(transfer_encoding, "chunked") != 0) {
2064 /* Transfer encodings not supported */
2065 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
2066 return -1;
2067 }
2068
2069 if (http_request_tracking_setup(ser, headers)
2070 || handle_uri(ser, uri, http_method, headers)
2071 || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)) {
2072 res = -1;
2073 } else {
2074 res = 0;
2075 }
2076 return res;
2077 }
2078
2079 static void *httpd_helper_thread(void *data)
2080 {
2081 struct ast_tcptls_session_instance *ser = data;
2082 int timeout;
2083 int arg = 1;
2084
2085 if (!ser) {
2086 ao2_cleanup(ser);
2087 return NULL;
2088 }
2089
2090 if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
2091 ast_log(LOG_WARNING, "HTTP session count exceeded %d sessions.\n",
2092 session_limit);
2093 goto done;
2094 }
2095 ast_debug(1, "HTTP opening session. Top level\n");
2096
2097 /*
2098 * Here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
2099 * This is necessary to prevent delays (caused by buffering) as we
2100 * write to the socket in bits and pieces.
2101 */
2102 if (setsockopt(ast_iostream_get_fd(ser->stream), IPPROTO_TCP, TCP_NODELAY, (char *) &arg, sizeof(arg)) < 0) {
2103 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
2104 }
2105 ast_iostream_nonblock(ser->stream);
2106
2107 /* Setup HTTP worker private data to keep track of request body reading. */
2108 ao2_cleanup(ser->private_data);
2109 ser->private_data = ao2_alloc_options(sizeof(struct http_worker_private_data), NULL,
2110 AO2_ALLOC_OPT_LOCK_NOLOCK);
2111 if (!ser->private_data) {
2112 ast_http_error(ser, 500, "Server Error", "Out of memory");
2113 goto done;
2114 }
2115 http_request_tracking_init(ser->private_data);
2116
2117 /* Determine initial HTTP request wait timeout. */
2118 timeout = session_keep_alive;
2119 if (timeout <= 0) {
2120 /* Persistent connections not enabled. */
2121 timeout = session_inactivity;
2122 }
2123 if (timeout < MIN_INITIAL_REQUEST_TIMEOUT) {
2124 timeout = MIN_INITIAL_REQUEST_TIMEOUT;
2125 }
2126
2127 /* We can let the stream wait for data to arrive. */
2128 ast_iostream_set_exclusive_input(ser->stream, 1);
2129
2130 for (;;) {
2131 /* Wait for next potential HTTP request message. */
2132 ast_iostream_set_timeout_idle_inactivity(ser->stream, timeout, session_inactivity);
2133 if (httpd_process_request(ser)) {
2134 /* Break the connection or the connection closed */
2135 break;
2136 }
2137 if (!ser->stream) {
2138 /* Web-socket or similar that took the connection */
2139 break;
2140 }
2141
2142 timeout = session_keep_alive;
2143 if (timeout <= 0) {
2144 /* Persistent connections not enabled. */
2145 break;
2146 }
2147 }
2148
2149 done:
2150 ast_atomic_fetchadd_int(&session_count, -1);
2151
2152 ast_debug(1, "HTTP closing session. Top level\n");
2153 ast_tcptls_close_session_file(ser);
2154
2155 ao2_ref(ser, -1);
2156 return NULL;
2157 }
2158
2159 /*!
2160 * \brief Check if a URI path is allowed or denied by acl
2161 * \param ser TCP/TLS session instance
2162 * \param uri The URI path to check
2163 * \return 0 if allowed, -1 if denied
2164 */
2165 static int check_restriction_acl(struct ast_tcptls_session_instance *ser, const char *uri)
2166 {
2167 struct http_restriction *restriction;
2168 int denied = 0;
2169
2170 AST_RWLIST_RDLOCK(&restrictions);
2171 AST_RWLIST_TRAVERSE(&restrictions, restriction, entry) {
2172 if (ast_begins_with(uri, restriction->path)) {
2173 if (restriction->acl && !ast_acl_list_is_empty(restriction->acl)) {
2174 if (ast_apply_acl(restriction->acl, &ser->remote_address,
2175 "HTTP Path ACL") == AST_SENSE_DENY) {
2176 ast_debug(2, "HTTP request for uri '%s' from %s denied by acl by restriction on '%s'\n",
2177 uri, ast_sockaddr_stringify(&ser->remote_address), restriction->path);
2178 denied = -1;
2179 break;
2180 }
2181 }
2182 }
2183 }
2184 AST_RWLIST_UNLOCK(&restrictions);
2185
2186 return denied;
2187 }
2188
2189 /*!
2190 * \brief Add a new URI redirect
2191 * The entries in the redirect list are sorted by length, just like the list
2192 * of URI handlers.
2193 */
2194 static void add_redirect(const char *value)
2195 {
2196 char *target, *dest;
2197 struct http_uri_redirect *redirect, *cur;
2198 unsigned int target_len;
2199 unsigned int total_len;
2200 size_t dest_len;
2201
2202 dest = ast_strdupa(value);
2203 dest = ast_skip_blanks(dest);
2204 target = strsep(&dest, " ");
2205 target = ast_skip_blanks(target);
2206 target = strsep(&target, " "); /* trim trailing whitespace */
2207
2208 if (!dest) {
2209 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
2210 return;
2211 }
2212
2213 target_len = strlen(target) + 1;
2214 dest_len = strlen(dest) + 1;
2215 total_len = sizeof(*redirect) + target_len + dest_len;
2216
2217 if (!(redirect = ast_calloc(1, total_len))) {
2218 return;
2219 }
2220 redirect->dest = redirect->target + target_len;
2221 strcpy(redirect->target, target);
2222 ast_copy_string(redirect->dest, dest, dest_len);
2223
2224 AST_RWLIST_WRLOCK(&uri_redirects);
2225
2226 target_len--; /* So we can compare directly with strlen() */
2227 if (AST_RWLIST_EMPTY(&uri_redirects)
2228 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
2229 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
2230 AST_RWLIST_UNLOCK(&uri_redirects);
2231
2232 return;
2233 }
2234
2235 AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
2236 if (AST_RWLIST_NEXT(cur, entry)
2237 && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
2238 AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
2239 AST_RWLIST_UNLOCK(&uri_redirects);
2240 return;
2241 }
2242 }
2243
2244 AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
2245
2246 AST_RWLIST_UNLOCK(&uri_redirects);
2247 }
2248
2249 /*! \brief Number of HTTP server buckets */
2250 #define HTTP_SERVER_BUCKETS 5
2251
2252 struct ao2_container *http_servers = NULL;
2253
2254 AO2_STRING_FIELD_HASH_FN(ast_http_server, address);
2255 AO2_STRING_FIELD_CMP_FN(ast_http_server, address);
2256
2257 static void http_server_destroy(void *obj)
2258 {
2259 struct ast_http_server *server = obj;
2260
2261 ast_tcptls_server_stop(&server->args);
2262
2263 ast_verb(1, "Stopped http server '%s' listening at '%s'\n", server->name, server->address);
2264
2265 ast_free(server->name);
2266 ast_free(server->address);
2267 }
2268
2269 static struct ast_http_server *http_server_create(const char *name, const char *address,
2270 const struct ast_sockaddr *addr)
2271 {
2272 struct ast_http_server *server;
2273
2274 server = ao2_alloc(sizeof(*server), http_server_destroy);
2275 if (!server) {
2276 ast_log(LOG_ERROR, "Unable to allocate HTTP server '%s' at address '%s'\n",
2277 name, address);
2278 return NULL;
2279 }
2280
2281 if (!(server->address = ast_strdup(address)) || !(server->name = ast_strdup(name))) {
2282 ast_log(LOG_ERROR, "Unable to complete setup for HTTP server '%s' at address '%s'\n",
2283 name, address);
2284 ao2_ref(server, -1);
2285 return NULL;
2286 }
2287
2288 server->args.accept_fd = -1;
2289 server->args.master = AST_PTHREADT_NULL;
2290 server->args.tls_cfg = NULL;
2291 server->args.poll_timeout = -1;
2292 server->args.name = server->name;
2293 server->args.accept_fn = ast_tcptls_server_root;
2294 server->args.worker_fn = httpd_helper_thread;
2295
2296 ast_sockaddr_copy(&server->args.local_address, addr);
2297
2298 return server;
2299 }
2300
2301 static int http_server_start(struct ast_http_server *server)
2302 {
2303 if (server->args.accept_fd != -1) {
2304 /* Already running */
2305 return 0;
2306 }
2307
2308 ast_tcptls_server_start(&server->args);
2309 if (server->args.accept_fd == -1) {
2310 ast_log(LOG_WARNING, "Failed to start HTTP server '%s' at address '%s'\n",
2311 server->name, server->address);
2312 return -1;
2313 }
2314
2315 if (!ao2_link_flags(http_servers, server, OBJ_NOLOCK)) {
2316 ast_log(LOG_WARNING, "Failed to link HTTP server '%s' at address '%s'\n",
2317 server->name, server->address);
2318 return -1;
2319 }
2320
2321 ast_verb(1, "Bound HTTP server '%s' to address %s\n", server->name, server->address);
2322
2323 return 0;
2324 }
2325
2326 /*!
2327 * \brief Discard/Drop a HTTP server
2328 *
2329 * Decrements the reference to the given object, and unlinks it from the servers
2330 * container if it's the last reference.
2331 *
2332 * After a server object has been added to the container this method should always
2333 * be called to decrement the object's reference instead of the regular ao2 methods.
2334 *
2335 * \note NULL tolerant
2336 *
2337 * \param server The server object
2338 */
2339 static void http_server_discard(struct ast_http_server *server)
2340 {
2341 if (!server) {
2342 return;
2343 }
2344
2345 /*
2346 * If only two references were on the object then the last one is from
2347 * the servers container, so remove from container now.
2348 */
2349 if (ao2_ref(server, -1) == 2) {
2350 ao2_unlink(http_servers, server);
2351 }
2352 }
2353
2354 /*!
2355 * \brief Retrieve, or create a HTTP server object by sock address
2356 *
2357 * Look for, and return a matching server object by addr. If an object is not found
2358 * then create a new one.
2359 *
2360 * \note This method should be called with the http_servers container already locked.
2361 *
2362 * \param name The name of the server
2363 * \param addr The address to match on, or create a new object with
2364 *
2365 * \return a HTTP server object, or NULL on error
2366 */
2367 static struct ast_http_server *http_server_get_by_addr(
2368 const char *name, const struct ast_sockaddr *addr)
2369 {
2370 struct ast_http_server *server;
2371 const char *address;
2372
2373 address = ast_sockaddr_stringify(addr);
2374 if (ast_strlen_zero(address)) {
2375 return NULL;
2376 }
2377
2378 server = ao2_find(http_servers, address, OBJ_KEY | OBJ_NOLOCK);
2379
2380 return server ?: http_server_create(name, address, addr);
2381 }
2382
2383 /*!
2384 * \brief Retrieve, or create a HTTP server object by host
2385 *
2386 * Resolve the given host, and then look for, and return a matching server object.
2387 * If an object is not found then create a new one.
2388 *
2389 * \note This method should be called with the http_servers container already locked.
2390 *
2391 * \param name The name of the server
2392 * \param host The host to resolve, and match on or create a new object with
2393 * \param port Optional port used if one is not specified with the host (default 8088)
2394 *
2395 * \return a HTTP server object, or NULL on error
2396 */
2397 static struct ast_http_server *http_server_get_by_host(const char *name, const char *host,
2398 uint32_t port)
2399 {
2400 struct ast_sockaddr *addrs = NULL;
2401 int num_addrs;
2402 int i;
2403
2404 if (!(num_addrs = ast_sockaddr_resolve(&addrs, host, 0, AST_AF_UNSPEC))) {
2405 ast_log(LOG_WARNING, "Unable to resolve host '%s'\n", host);
2406 return NULL;
2407 }
2408
2409 if (port == 0) {
2410 port = DEFAULT_PORT;
2411 }
2412
2413 for (i = 0; i < num_addrs; ++i) {
2414 struct ast_http_server *server;
2415
2416 /* Use the given port if one was not specified already */
2417 if (!ast_sockaddr_port(&addrs[i])) {
2418 ast_sockaddr_set_port(&addrs[i], port);
2419 }
2420
2421 server = http_server_get_by_addr(name, &addrs[i]);
2422 if (server) {
2423 ast_free(addrs);
2424 return server;
2425 }
2426 }
2427
2428 ast_free(addrs);
2429 return NULL;
2430 }
2431
2432 /*!
2433 * \brief Retrieve, or create and start a HTTP server
2434 *
2435 * Resolve the given host, and retrieve a listening server object. If the server is
2436 * not already listening then start it. If a replace_me parameter is given, and it
2437 * points to a non-NULL value then that server is discarded and replaced.
2438 *
2439 * \param name The name of the server
2440 * \param host The host to resolve, and match on or create a new object with
2441 * \param port Optional port used if one is not specified with the host (default 8088)
2442 * \param[out] replace_me Optional server to be replaced
2443 *
2444 * \note If replace_me is specified the returned value is always the same as what's
2445 * passed back out in the variable.
2446 *
2447 * \return a HTTP server object, or NULL on error
2448 */
2449 static struct ast_http_server *http_server_get(const char *name, const char *host,
2450 uint32_t port, struct ast_http_server **replace_me)
2451 {
2452 struct ast_http_server *server;
2453
2454 ao2_lock(http_servers);
2455
2456 server = http_server_get_by_host(name, host, port);
2457
2458 if (replace_me) {
2459 /* Only replace if different */
2460 if (*replace_me == server) {
2461 ao2_cleanup(server);
2462 ao2_unlock(http_servers);
2463 return *replace_me;
2464 }
2465
2466 if (*replace_me) {
2467 http_server_discard(*replace_me);
2468 }
2469
2470 *replace_me = server;
2471 }
2472
2473 if (server && http_server_start(server)) {
2474 if (replace_me) {
2475 *replace_me = NULL;
2476 }
2477
2478 ao2_ref(server, -1);
2479 server = NULL;
2480 }
2481
2482 ao2_unlock(http_servers);
2483 return server;
2484 }
2485
2486 #ifdef TEST_FRAMEWORK
2487
2488 struct ast_http_server *ast_http_test_server_get(const char *name, const char *host)
2489 {
2490 struct ast_http_server *server;
2491
2492 /*
2493 * Currently multiple HTTP servers are only allowed when the TEST_FRAMEWORK
2494 * is enabled, leaving the follow 'todos' if they become a problem or if this
2495 * ability moves outside the TEST_FRAMEWORK.
2496 *
2497 * TODO: Add locking around global_http_server use. If this module is reloading
2498 * it's possible for the global_http_server to exist here, and then become
2499 * NULL between the check and return.
2500 *
2501 * TODO: Make it so 'localhost' and 'any' addresses equate.
2502 */
2503
2504 if (ast_strlen_zero(host)) {
2505 /* Use configured server if one available */
2506 if (global_http_server) {
2507 ast_module_ref(ast_module_info->self);
2508 return ao2_bump(global_http_server);
2509 }
2510
2511 host = "localhost:8088";
2512 }
2513
2514 if (!name) {
2515 name = "http test server";
2516 }
2517
2518 server = http_server_get(name, host, 0, NULL);
2519 if (server) {
2520 ast_module_ref(ast_module_info->self);
2521 }
2522
2523 return server;
2524 }
2525
2526 void ast_http_test_server_discard(struct ast_http_server *server)
2527 {
2528 if (server) {
2529 http_server_discard(server);
2530 ast_module_unref(ast_module_info->self);
2531 }
2532 }
2533
2534 #endif
2535
2536 static int __ast_http_load(int reload)
2537 {
2538 struct ast_config *cfg;
2539 struct ast_variable *v;
2540 int enabled = 0;
2541 int new_static_uri_enabled = 0;
2542 int new_status_uri_enabled = 0;
2543 char newprefix[MAX_PREFIX] = "";
2544 char server_name[MAX_SERVER_NAME_LENGTH];
2545 struct http_uri_redirect *redirect;
2546 struct http_restriction *restriction;
2547 struct http_restriction_list new_restrictions = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
2548 struct http_restriction_list old_restrictions = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
2549 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2550 uint32_t bindport = DEFAULT_PORT;
2551 int http_tls_was_enabled = 0;
2552 const char *bindaddr = NULL;
2553 const char *cat = NULL;
2554
2555 cfg = ast_config_load2("http.conf", "http", config_flags);
2556 if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
2557 return 0;
2558 }
2559
2560 /* Even if the http.conf hasn't been updated, the TLS certs/keys may have been */
2561 if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
2562 if (http_tls_cfg.enabled && ast_ssl_setup(https_desc.tls_cfg)) {
2563 ast_tcptls_server_start(&https_desc);
2564 }
2565 return 0;
2566 }
2567
2568 http_tls_was_enabled = (reload && http_tls_cfg.enabled);
2569
2570 http_tls_cfg.enabled = 0;
2571
2572 ast_free(http_tls_cfg.certfile);
2573 http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
2574
2575 ast_free(http_tls_cfg.capath);
2576 http_tls_cfg.capath = ast_strdup("");
2577
2578 ast_free(http_tls_cfg.pvtfile);
2579 http_tls_cfg.pvtfile = ast_strdup("");
2580
2581 /* Apply modern intermediate settings according to the Mozilla OpSec team as of July 30th, 2015 but disable TLSv1 */
2582 ast_set_flag(&http_tls_cfg.flags, AST_SSL_DISABLE_TLSV1 | AST_SSL_SERVER_CIPHER_ORDER);
2583
2584 ast_free(http_tls_cfg.cipher);
2585 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");
2586
2587 AST_RWLIST_WRLOCK(&uri_redirects);
2588 while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2589 ast_free(redirect);
2590 }
2591 AST_RWLIST_UNLOCK(&uri_redirects);
2592
2593 ast_sockaddr_setnull(&https_desc.local_address);
2594
2595 session_limit = DEFAULT_SESSION_LIMIT;
2596 session_inactivity = DEFAULT_SESSION_INACTIVITY;
2597 session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2598
2599 snprintf(server_name, sizeof(server_name), "Asterisk/%s", ast_get_version());
2600
2601 v = ast_variable_browse(cfg, "general");
2602 for (; v; v = v->next) {
2603 /* read tls config options while preventing unsupported options from being set */
2604 if (strcasecmp(v->name, "tlscafile")
2605 && strcasecmp(v->name, "tlscapath")
2606 && strcasecmp(v->name, "tlscadir")
2607 && strcasecmp(v->name, "tlsverifyclient")
2608 && strcasecmp(v->name, "tlsdontverifyserver")
2609 && strcasecmp(v->name, "tlsclientmethod")
2610 && strcasecmp(v->name, "sslclientmethod")
2611 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
2612 continue;
2613 }
2614
2615 if (!strcasecmp(v->name, "servername")) {
2616 if (!ast_strlen_zero(v->value)) {
2617 ast_copy_string(server_name, v->value, sizeof(server_name));
2618 } else {
2619 server_name[0] = '\0';
2620 }
2621 } else if (!strcasecmp(v->name, "enabled")) {
2622 enabled = ast_true(v->value);
2623 } else if (!strcasecmp(v->name, "enablestatic") || !strcasecmp(v->name, "enable_static")) {
2624 new_static_uri_enabled = ast_true(v->value);
2625 } else if (!strcasecmp(v->name, "enable_status")) {
2626 new_status_uri_enabled = ast_true(v->value);
2627 } else if (!strcasecmp(v->name, "bindport")) {
2628 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT,
2629 &bindport, DEFAULT_PORT, 0, 65535)) {
2630 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %" PRId32 "\n",
2631 v->value, DEFAULT_PORT);
2632 }
2633 } else if (!strcasecmp(v->name, "bindaddr")) {
2634 bindaddr = ast_strdupa(v->value);
2635 } else if (!strcasecmp(v->name, "prefix")) {
2636 if (!ast_strlen_zero(v->value)) {
2637 newprefix[0] = '/';
2638 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
2639 } else {
2640 newprefix[0] = '\0';
2641 }
2642 } else if (!strcasecmp(v->name, "redirect")) {
2643 add_redirect(v->value);
2644 } else if (!strcasecmp(v->name, "sessionlimit")) {
2645 if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2646 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
2647 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2648 v->name, v->value, v->lineno);
2649 }
2650 } else if (!strcasecmp(v->name, "session_inactivity")) {
2651 if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
2652 &session_inactivity, DEFAULT_SESSION_INACTIVITY, 1, INT_MAX)) {
2653 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2654 v->name, v->value, v->lineno);
2655 }
2656 } else if (!strcasecmp(v->name, "session_keep_alive")) {
2657 if (sscanf(v->value, "%30d", &session_keep_alive) != 1
2658 || session_keep_alive < 0) {
2659 session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
2660 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
2661 v->name, v->value, v->lineno);
2662 }
2663 } else {
2664 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
2665 }
2666 }
2667
2668 while ((cat = ast_category_browse(cfg, cat))) {
2669 const char *type;
2670 struct http_restriction *new_restriction;
2671 struct ast_acl_list *acl = NULL;
2672 int acl_error = 0;
2673 int acl_subscription_flag = 0;
2674
2675 if (strcasecmp(cat, "general") == 0) {
2676 continue;
2677 }
2678
2679 type = ast_variable_retrieve(cfg, cat, "type");
2680 if (!type || strcasecmp(type, "restriction") != 0) {
2681 continue;
2682 }
2683
2684 new_restriction = ast_calloc(1, sizeof(*new_restriction) + strlen(cat) + 1);
2685 if (!new_restriction) {
2686 continue;
2687 }
2688
2689 /* Safe */
2690 strcpy(new_restriction->path, cat);
2691
2692 /* Parse ACL options for this restriction */
2693 for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
2694 if (!strcasecmp(v->name, "permit") ||
2695 !strcasecmp(v->name, "deny") ||
2696 !strcasecmp(v->name, "acl")) {
2697 ast_append_acl(v->name, v->value, &acl, &acl_error, &acl_subscription_flag);
2698 if (acl_error) {
2699 ast_log(LOG_ERROR, "Bad ACL '%s' at line '%d' of http.conf for restriction '%s'\n",
2700 v->value, v->lineno, cat);
2701 }
2702 }
2703 }
2704
2705 new_restriction->acl = acl;
2706
2707 AST_LIST_INSERT_TAIL(&new_restrictions, new_restriction, entry);
2708 ast_debug(2, "HTTP: Added restriction for path '%s'\n", cat);
2709 }
2710
2711 AST_RWLIST_WRLOCK(&restrictions);
2712 AST_RWLIST_APPEND_LIST(&old_restrictions, &restrictions, entry);
2713 AST_RWLIST_APPEND_LIST(&restrictions, &new_restrictions, entry);
2714 AST_RWLIST_UNLOCK(&restrictions);
2715
2716 while ((restriction = AST_LIST_REMOVE_HEAD(&old_restrictions, entry))) {
2717 if (restriction->acl) {
2718 ast_free_acl_list(restriction->acl);
2719 }
2720 ast_free(restriction);
2721 }
2722
2723 ast_config_destroy(cfg);
2724
2725 if (strcmp(prefix, newprefix)) {
2726 ast_copy_string(prefix, newprefix, sizeof(prefix));
2727 }
2728
2729 ast_copy_string(http_server_name, server_name, sizeof(http_server_name));
2730
2731 if (enabled) {
2732 http_server_get("http server", bindaddr, bindport, &global_http_server);
2733 } else if (global_http_server) {
2734 http_server_discard(global_http_server);
2735 global_http_server = NULL;
2736 }
2737
2738 /* When no specific TLS bindaddr is specified, we just use
2739 * the non-TLS bindaddress here.
2740 */
2741 if (global_http_server && ast_sockaddr_isnull(&https_desc.local_address) &&
2742 global_http_server->args.accept_fd != -1) {
2743
2744 ast_sockaddr_copy(&https_desc.local_address, &global_http_server->args.local_address);
2745 /* Of course, we can't use the same port though.
2746 * Since no bind address was specified, we just use the
2747 * default TLS port
2748 */
2749 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2750 }
2751
2752 if (http_tls_was_enabled && !http_tls_cfg.enabled) {
2753 ast_tcptls_server_stop(&https_desc);
2754 } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
2755 /* We can get here either because a TLS-specific address was specified
2756 * or because we copied the non-TLS address here. In the case where
2757 * we read an explicit address from the config, there may have been
2758 * no port specified, so we'll just use the default TLS port.
2759 */
2760 if (!ast_sockaddr_port(&https_desc.local_address)) {
2761 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
2762 }
2763 if (ast_ssl_setup(https_desc.tls_cfg)) {
2764 ast_tcptls_server_start(&https_desc);
2765 }
2766 }
2767
2768 if (static_uri_enabled && !new_static_uri_enabled) {
2769 ast_http_uri_unlink(&static_uri);
2770 } else if (!static_uri_enabled && new_static_uri_enabled) {
2771 ast_http_uri_link(&static_uri);
2772 }
2773
2774 static_uri_enabled = new_static_uri_enabled;
2775
2776 if (status_uri_enabled && !new_status_uri_enabled) {
2777 ast_http_uri_unlink(&status_uri);
2778 } else if (!status_uri_enabled && new_status_uri_enabled) {
2779 ast_http_uri_link(&status_uri);
2780 }
2781
2782 status_uri_enabled = new_status_uri_enabled;
2783
2784 return 0;
2785 }
2786
2787 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2788 {
2789 struct ast_http_uri *urih;
2790 struct http_uri_redirect *redirect;
2791
2792 switch (cmd) {
2793 case CLI_INIT:
2794 e->command = "http show status";
2795 e->usage =
2796 "Usage: http show status\n"
2797 " Lists status of internal HTTP engine\n";
2798 return NULL;
2799 case CLI_GENERATE:
2800 return NULL;
2801 }
2802
2803 if (a->argc != 3) {
2804 return CLI_SHOWUSAGE;
2805 }
2806 ast_cli(a->fd, "HTTP Server Status:\n");
2807 ast_cli(a->fd, "Prefix: %s\n", prefix);
2808 ast_cli(a->fd, "Server: %s\n", http_server_name);
2809 if (!global_http_server) {
2810 ast_cli(a->fd, "Server Disabled\n\n");
2811 } else {
2812 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
2813 ast_sockaddr_stringify(&global_http_server->args.old_address));
2814 if (http_tls_cfg.enabled) {
2815 ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
2816 ast_sockaddr_stringify(&https_desc.old_address));
2817 }
2818 }
2819
2820 ast_cli(a->fd, "Enabled URI's:\n");
2821 AST_RWLIST_RDLOCK(&uris);
2822 if (AST_RWLIST_EMPTY(&uris)) {
2823 ast_cli(a->fd, "None.\n");
2824 } else {
2825 AST_RWLIST_TRAVERSE(&uris, urih, entry)
2826 ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
2827 }
2828 AST_RWLIST_UNLOCK(&uris);
2829
2830 ast_cli(a->fd, "\nEnabled Redirects:\n");
2831 AST_RWLIST_RDLOCK(&uri_redirects);
2832 if (AST_RWLIST_EMPTY(&uri_redirects)) {
2833 ast_cli(a->fd, " None.\n");
2834 } else {
2835 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
2836 ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
2837 }
2838 AST_RWLIST_UNLOCK(&uri_redirects);
2839
2840 ast_cli(a->fd, "\nPath Restrictions:\n");
2841 AST_RWLIST_RDLOCK(&restrictions);
2842 if (AST_RWLIST_EMPTY(&restrictions)) {
2843 ast_cli(a->fd, " None.\n");
2844 } else {
2845 struct http_restriction *restriction;
2846 AST_RWLIST_TRAVERSE(&restrictions, restriction, entry) {
2847 ast_cli(a->fd, " Path: %s\n", restriction->path);
2848 if (restriction->acl && !ast_acl_list_is_empty(restriction->acl)) {
2849 ast_acl_output(a->fd, restriction->acl, " ");
2850 } else {
2851 ast_cli(a->fd, " No ACL configured\n");
2852 }
2853 }
2854 }
2855 AST_RWLIST_UNLOCK(&restrictions);
2856
2857 return CLI_SUCCESS;
2858 }
2859
2860 static int reload_module(void)
2861 {
2862 return __ast_http_load(1);
2863 }
2864
2865 static struct ast_cli_entry cli_http[] = {
2866 AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
2867 };
2868
2869 static int unload_module(void)
2870 {
2871 struct http_uri_redirect *redirect;
2872 struct http_restriction *restriction;
2873 ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
2874
2875 ao2_cleanup(global_http_server);
2876 ao2_cleanup(http_servers);
2877
2878 if (http_tls_cfg.enabled) {
2879 ast_tcptls_server_stop(&https_desc);
2880 }
2881 ast_free(http_tls_cfg.certfile);
2882 ast_free(http_tls_cfg.capath);
2883 ast_free(http_tls_cfg.pvtfile);
2884 ast_free(http_tls_cfg.cipher);
2885
2886 if (status_uri_enabled) {
2887 ast_http_uri_unlink(&status_uri);
2888 }
2889
2890 if (static_uri_enabled) {
2891 ast_http_uri_unlink(&static_uri);
2892 }
2893
2894 AST_RWLIST_WRLOCK(&uri_redirects);
2895 while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
2896 ast_free(redirect);
2897 }
2898 AST_RWLIST_UNLOCK(&uri_redirects);
2899
2900 AST_RWLIST_WRLOCK(&restrictions);
2901 while ((restriction = AST_RWLIST_REMOVE_HEAD(&restrictions, entry))) {
2902 if (restriction->acl) {
2903 ast_free_acl_list(restriction->acl);
2904 }
2905 ast_free(restriction);
2906 }
2907 AST_RWLIST_UNLOCK(&restrictions);
2908
2909 return 0;
2910 }
2911
2912 static int load_module(void)
2913 {
2914 ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
2915
2916 http_servers = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
2917 HTTP_SERVER_BUCKETS, ast_http_server_hash_fn, NULL, ast_http_server_cmp_fn);
2918 if (!http_servers) {
2919 return AST_MODULE_LOAD_FAILURE;
2920 }
2921
2922 if (__ast_http_load(0)) {
2923 ao2_cleanup(http_servers);
2924 http_servers = NULL;
2925 return AST_MODULE_LOAD_FAILURE;
2926 }
2927
2928 return AST_MODULE_LOAD_SUCCESS;
2929 }
2930
2931 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Built-in HTTP Server",
2932 .support_level = AST_MODULE_SUPPORT_CORE,
2933 .load = load_module,
2934 .unload = unload_module,
2935 .reload = reload_module,
2936 .load_pri = AST_MODPRI_CORE,
2937 .requires = "extconfig",
2938 );