2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief http server for AMI access
23 * \author Mark Spencer <markster@digium.com>
25 * This program implements a tiny http server
26 * and was inspired by micro-httpd by Jef Poskanzer
28 * GMime http://spruce.sourceforge.net/gmime/
30 * \ref AstHTTP - AMI over the http protocol
33 /*! \li \ref http.c uses the configuration file \ref http.conf
34 * \addtogroup configuration_file
37 /*! \page http.conf http.conf
38 * \verbinclude http.conf.sample
42 <support_level>core</support_level>
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
52 #include <sys/signal.h>
55 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
56 #include "asterisk/cli.h"
57 #include "asterisk/tcptls.h"
58 #include "asterisk/http.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/strings.h"
61 #include "asterisk/config.h"
62 #include "asterisk/stringfields.h"
63 #include "asterisk/ast_version.h"
64 #include "asterisk/manager.h"
65 #include "asterisk/_private.h"
66 #include "asterisk/astobj2.h"
67 #include "asterisk/netsock2.h"
70 #define DEFAULT_PORT 8088
71 #define DEFAULT_TLS_PORT 8089
72 #define DEFAULT_SESSION_LIMIT 100
74 /* See http.h for more information about the SSL implementation */
75 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
76 #define DO_SSL /* comment in/out if you want to support ssl */
79 static int session_limit = DEFAULT_SESSION_LIMIT;
80 static int session_count = 0;
82 static struct ast_tls_config http_tls_cfg;
84 static void *httpd_helper_thread(void *arg);
87 * we have up to two accepting threads, one for http, one for https
89 static struct ast_tcptls_session_args http_desc = {
91 .master = AST_PTHREADT_NULL,
94 .name = "http server",
95 .accept_fn = ast_tcptls_server_root,
96 .worker_fn = httpd_helper_thread,
99 static struct ast_tcptls_session_args https_desc = {
101 .master = AST_PTHREADT_NULL,
102 .tls_cfg = &http_tls_cfg,
104 .name = "https server",
105 .accept_fn = ast_tcptls_server_root,
106 .worker_fn = httpd_helper_thread,
109 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri); /*!< list of supported handlers */
111 /* all valid URIs must be prepended by the string in prefix. */
112 static char prefix[MAX_PREFIX];
113 static int enablestatic;
115 /*! \brief Limit the kinds of files we're willing to serve up */
120 { "png", "image/png" },
121 { "xml", "text/xml" },
122 { "jpg", "image/jpeg" },
123 { "js", "application/x-javascript" },
124 { "wav", "audio/x-wav" },
125 { "mp3", "audio/mpeg" },
126 { "svg", "image/svg+xml" },
127 { "svgz", "image/svg+xml" },
128 { "gif", "image/gif" },
129 { "html", "text/html" },
130 { "htm", "text/html" },
131 { "css", "text/css" },
132 { "cnf", "text/plain" },
133 { "cfg", "text/plain" },
134 { "bin", "application/octet-stream" },
135 { "sbn", "application/octet-stream" },
136 { "ld", "application/octet-stream" },
139 struct http_uri_redirect {
140 AST_LIST_ENTRY(http_uri_redirect) entry;
145 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
147 static const struct ast_cfhttp_methods_text {
148 enum ast_http_method method;
150 } ast_http_methods_text[] = {
151 { AST_HTTP_UNKNOWN, "UNKNOWN" },
152 { AST_HTTP_GET, "GET" },
153 { AST_HTTP_POST, "POST" },
154 { AST_HTTP_HEAD, "HEAD" },
155 { AST_HTTP_PUT, "PUT" },
158 const char *ast_get_http_method(enum ast_http_method method)
162 for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
163 if (ast_http_methods_text[x].method == method) {
164 return ast_http_methods_text[x].text;
171 const char *ast_http_ftype2mtype(const char *ftype)
176 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
177 if (!strcasecmp(ftype, mimetypes[x].ext)) {
178 return mimetypes[x].mtype;
185 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
188 struct ast_variable *v, *cookies;
190 cookies = ast_http_get_cookies(headers);
191 for (v = cookies; v; v = v->next) {
192 if (!strcasecmp(v->name, "mansession_id")) {
193 sscanf(v->value, "%30x", &mngid);
198 ast_variables_destroy(cookies);
203 void ast_http_prefix(char *buf, int len)
206 ast_copy_string(buf, prefix, len);
210 static int static_callback(struct ast_tcptls_session_instance *ser,
211 const struct ast_http_uri *urih, const char *uri,
212 enum ast_http_method method, struct ast_variable *get_vars,
213 struct ast_variable *headers)
222 struct ast_str *http_header;
225 char timebuf[80], etag[23];
226 struct ast_variable *v;
227 int not_modified = 0;
229 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
230 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
234 /* Yuck. I'm not really sold on this, but if you don't deliver static content it makes your configuration
235 substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
236 if (!enablestatic || ast_strlen_zero(uri)) {
240 /* Disallow any funny filenames at all */
241 if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
245 if (strstr(uri, "/..")) {
249 if ((ftype = strrchr(uri, '.'))) {
253 if (!(mtype = ast_http_ftype2mtype(ftype))) {
254 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
257 /* Cap maximum length */
258 if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
262 path = ast_alloca(len);
263 sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
264 if (stat(path, &st)) {
268 if (S_ISDIR(st.st_mode)) {
272 fd = open(path, O_RDONLY);
277 if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
281 /* make "Etag:" http header value */
282 snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
284 /* make "Last-Modified:" http header value */
285 tv.tv_sec = st.st_mtime;
287 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
289 /* check received "If-None-Match" request header and Etag value for file */
290 for (v = headers; v; v = v->next) {
291 if (!strcasecmp(v->name, "If-None-Match")) {
292 if (!strcasecmp(v->value, etag)) {
299 if ( (http_header = ast_str_create(255)) == NULL) {
303 ast_str_set(&http_header, 0, "Content-type: %s\r\n"
305 "Last-Modified: %s\r\n",
310 /* ast_http_send() frees http_header, so we don't need to do it before returning */
312 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
314 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
320 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
324 ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
328 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
329 const struct ast_http_uri *urih, const char *uri,
330 enum ast_http_method method, struct ast_variable *get_vars,
331 struct ast_variable *headers)
334 struct ast_variable *v, *cookies = NULL;
336 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
337 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
341 if ( (out = ast_str_create(512)) == NULL) {
345 ast_str_append(&out, 0,
346 "<title>Asterisk HTTP Status</title>\r\n"
347 "<body bgcolor=\"#ffffff\">\r\n"
348 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
349 "<h2> Asterisk™ HTTP Status</h2></td></tr>\r\n");
351 ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
352 ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
353 ast_sockaddr_stringify_addr(&http_desc.old_address));
354 ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
355 ast_sockaddr_stringify_port(&http_desc.old_address));
356 if (http_tls_cfg.enabled) {
357 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
358 ast_sockaddr_stringify_port(&https_desc.old_address));
360 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
361 for (v = get_vars; v; v = v->next) {
362 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
364 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
366 cookies = ast_http_get_cookies(headers);
367 for (v = cookies; v; v = v->next) {
368 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
370 ast_variables_destroy(cookies);
372 ast_str_append(&out, 0, "</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body>\r\n");
373 ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
377 static struct ast_http_uri statusuri = {
378 .callback = httpstatus_callback,
379 .description = "Asterisk HTTP General Status",
386 static struct ast_http_uri staticuri = {
387 .callback = static_callback,
388 .description = "Asterisk HTTP Static Delivery",
396 /* send http/1.1 response */
397 /* free content variable and close socket*/
398 void ast_http_send(struct ast_tcptls_session_instance *ser,
399 enum ast_http_method method, int status_code, const char *status_title,
400 struct ast_str *http_header, struct ast_str *out, const int fd,
401 unsigned int static_content)
403 struct timeval now = ast_tvnow();
406 int content_length = 0;
408 if (!ser || 0 == ser->f) {
412 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
414 /* calc content length */
416 content_length += strlen(ast_str_buffer(out));
420 content_length += lseek(fd, 0, SEEK_END);
421 lseek(fd, 0, SEEK_SET);
424 /* send http header */
425 fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
426 "Server: Asterisk/%s\r\n"
428 "Connection: close\r\n"
430 "Content-Length: %d\r\n"
433 status_code, status_title ? status_title : "OK",
436 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
438 http_header ? ast_str_buffer(http_header) : ""
442 if (method != AST_HTTP_HEAD || status_code >= 400) {
444 fprintf(ser->f, "%s", ast_str_buffer(out));
450 while ((len = read(fd, buf, sizeof(buf))) > 0) {
451 if (fwrite(buf, len, 1, ser->f) != 1) {
452 ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
460 ast_free(http_header);
471 /* Send http "401 Unauthorized" responce and close socket*/
472 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
473 const unsigned long nonce, const unsigned long opaque, int stale,
476 struct ast_str *http_headers = ast_str_create(128);
477 struct ast_str *out = ast_str_create(512);
479 if (!http_headers || !out) {
480 ast_free(http_headers);
485 ast_str_set(&http_headers, 0,
486 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
487 "Content-type: text/html\r\n",
488 realm ? realm : "Asterisk",
491 stale ? ", stale=true" : "");
494 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
496 "<title>401 Unauthorized</title>\r\n"
498 "<h1>401 Unauthorized</h1>\r\n"
501 "<address>Asterisk Server</address>\r\n"
502 "</body></html>\r\n",
505 ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
509 /* send http error response and close socket*/
510 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
512 struct ast_str *http_headers = ast_str_create(40);
513 struct ast_str *out = ast_str_create(256);
515 if (!http_headers || !out) {
516 ast_free(http_headers);
521 ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
524 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
526 "<title>%d %s</title>\r\n"
531 "<address>Asterisk Server</address>\r\n"
532 "</body></html>\r\n",
533 status_code, status_title, status_title, text);
535 ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
540 * Link the new uri into the list.
542 * They are sorted by length of
543 * the string, not alphabetically. Duplicate entries are not replaced,
544 * but the insertion order (using <= and not just <) makes sure that
545 * more recent insertions hide older ones.
546 * On a lookup, we just scan the list and stop at the first matching entry.
548 int ast_http_uri_link(struct ast_http_uri *urih)
550 struct ast_http_uri *uri;
551 int len = strlen(urih->uri);
553 AST_RWLIST_WRLOCK(&uris);
555 if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
556 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
557 AST_RWLIST_UNLOCK(&uris);
561 AST_RWLIST_TRAVERSE(&uris, uri, entry) {
562 if (AST_RWLIST_NEXT(uri, entry) &&
563 strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
564 AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
565 AST_RWLIST_UNLOCK(&uris);
571 AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
573 AST_RWLIST_UNLOCK(&uris);
578 void ast_http_uri_unlink(struct ast_http_uri *urih)
580 AST_RWLIST_WRLOCK(&uris);
581 AST_RWLIST_REMOVE(&uris, urih, entry);
582 AST_RWLIST_UNLOCK(&uris);
585 void ast_http_uri_unlink_all_with_key(const char *key)
587 struct ast_http_uri *urih;
588 AST_RWLIST_WRLOCK(&uris);
589 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
590 if (!strcmp(urih->key, key)) {
591 AST_RWLIST_REMOVE_CURRENT(entry);
592 if (urih->dmallocd) {
593 ast_free(urih->data);
600 AST_RWLIST_TRAVERSE_SAFE_END;
601 AST_RWLIST_UNLOCK(&uris);
604 #define MAX_POST_CONTENT 1025
607 * get post variables from client Request Entity-Body, if content type is
608 * application/x-www-form-urlencoded
610 struct ast_variable *ast_http_get_post_vars(
611 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
613 int content_length = 0;
614 struct ast_variable *v, *post_vars=NULL, *prev = NULL;
615 char *buf, *var, *val;
618 for (v = headers; v; v = v->next) {
619 if (!strcasecmp(v->name, "Content-Type")) {
620 if (strcasecmp(v->value, "application/x-www-form-urlencoded")) {
627 for (v = headers; v; v = v->next) {
628 if (!strcasecmp(v->name, "Content-Length")) {
629 content_length = atoi(v->value);
634 if (content_length <= 0) {
638 if (content_length > MAX_POST_CONTENT - 1) {
639 ast_log(LOG_WARNING, "Excessively long HTTP content. %d is greater than our max of %d\n",
640 content_length, MAX_POST_CONTENT);
641 ast_http_send(ser, AST_HTTP_POST, 413, "Request Entity Too Large", NULL, NULL, 0, 0);
645 buf = ast_malloc(content_length + 1);
650 res = fread(buf, 1, content_length, ser->f);
651 if (res < content_length) {
652 /* Error, distinguishable by ferror() or feof(), but neither
656 buf[content_length] = '\0';
658 while ((val = strsep(&buf, "&"))) {
659 var = strsep(&val, "=");
661 ast_uri_decode(val, ast_uri_http_legacy);
665 ast_uri_decode(var, ast_uri_http_legacy);
666 if ((v = ast_variable_new(var, val, ""))) {
681 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
682 enum ast_http_method method, struct ast_variable *headers)
687 struct ast_http_uri *urih = NULL;
689 struct ast_variable *get_vars = NULL, *v, *prev = NULL;
690 struct http_uri_redirect *redirect;
692 ast_debug(2, "HTTP Request URI is %s \n", uri);
694 strsep(¶ms, "?");
695 /* Extract arguments from the request and store them in variables. */
699 while ((val = strsep(¶ms, "&"))) {
700 var = strsep(&val, "=");
702 ast_uri_decode(val, ast_uri_http_legacy);
706 ast_uri_decode(var, ast_uri_http_legacy);
707 if ((v = ast_variable_new(var, val, ""))) {
717 ast_uri_decode(uri, ast_uri_http_legacy);
719 AST_RWLIST_RDLOCK(&uri_redirects);
720 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
721 if (!strcasecmp(uri, redirect->target)) {
722 struct ast_str *http_header = ast_str_create(128);
723 ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
724 ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
729 AST_RWLIST_UNLOCK(&uri_redirects);
734 /* We want requests to start with the (optional) prefix and '/' */
736 if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
738 /* scan registered uris to see if we match one. */
739 AST_RWLIST_RDLOCK(&uris);
740 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
741 ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
742 l = strlen(urih->uri);
743 c = uri + l; /* candidate */
744 if (strncasecmp(urih->uri, uri, l) /* no match */
745 || (*c && *c != '/')) { /* substring */
751 if (!*c || urih->has_subtree) {
756 AST_RWLIST_UNLOCK(&uris);
759 res = urih->callback(ser, urih, uri, method, get_vars, headers);
761 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
765 ast_variables_destroy(get_vars);
770 #if defined(HAVE_FUNOPEN)
774 #define HOOK_T ssize_t
779 * replacement read/write functions for SSL support.
780 * We use wrappers rather than SSL_read/SSL_write directly so
781 * we can put in some debugging.
783 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
785 int i = SSL_read(cookie, buf, len-1);
789 ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
794 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
797 char *s = ast_alloca(len+1);
798 strncpy(s, buf, len);
800 ast_verbose("ssl write size %d <%s>\n", (int)len, s);
802 return SSL_write(cookie, buf, len);
805 static int ssl_close(void *cookie)
807 close(SSL_get_fd(cookie));
808 SSL_shutdown(cookie);
814 static struct ast_variable *parse_cookies(char *cookies)
817 struct ast_variable *vars = NULL, *var;
819 while ((cur = strsep(&cookies, ";"))) {
825 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
829 name = ast_strip(name);
830 val = ast_strip_quoted(val, "\"", "\"");
832 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
836 ast_debug(1, "HTTP Cookie, Name: '%s' Value: '%s'\n", name, val);
838 var = ast_variable_new(name, val, __FILE__);
846 /* get cookie from Request headers */
847 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
849 struct ast_variable *v, *cookies=NULL;
851 for (v = headers; v; v = v->next) {
852 if (!strncasecmp(v->name, "Cookie", 6)) {
853 char *tmp = ast_strdupa(v->value);
855 ast_variables_destroy(cookies);
858 cookies = parse_cookies(tmp);
865 static void *httpd_helper_thread(void *data)
868 char header_line[4096];
869 struct ast_tcptls_session_instance *ser = data;
870 struct ast_variable *headers = NULL;
871 struct ast_variable *tail = headers;
873 enum ast_http_method http_method = AST_HTTP_UNKNOWN;
875 if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
879 if (!fgets(buf, sizeof(buf), ser->f)) {
884 method = ast_skip_blanks(buf);
885 uri = ast_skip_nonblanks(method);
890 if (!strcasecmp(method,"GET")) {
891 http_method = AST_HTTP_GET;
892 } else if (!strcasecmp(method,"POST")) {
893 http_method = AST_HTTP_POST;
894 } else if (!strcasecmp(method,"HEAD")) {
895 http_method = AST_HTTP_HEAD;
896 } else if (!strcasecmp(method,"PUT")) {
897 http_method = AST_HTTP_PUT;
900 uri = ast_skip_blanks(uri); /* Skip white space */
902 if (*uri) { /* terminate at the first blank */
903 char *c = ast_skip_nonblanks(uri);
910 /* process "Request Headers" lines */
911 while (fgets(header_line, sizeof(header_line), ser->f)) {
914 /* Trim trailing characters */
915 ast_trim_blanks(header_line);
916 if (ast_strlen_zero(header_line)) {
921 name = strsep(&value, ":");
926 value = ast_skip_blanks(value);
927 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
931 ast_trim_blanks(name);
934 headers = ast_variable_new(name, value, __FILE__);
937 tail->next = ast_variable_new(name, value, __FILE__);
943 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
947 handle_uri(ser, uri, http_method, headers);
950 ast_atomic_fetchadd_int(&session_count, -1);
952 /* clean up all the header information */
954 ast_variables_destroy(headers);
966 * \brief Add a new URI redirect
967 * The entries in the redirect list are sorted by length, just like the list
970 static void add_redirect(const char *value)
973 struct http_uri_redirect *redirect, *cur;
974 unsigned int target_len;
975 unsigned int total_len;
977 dest = ast_strdupa(value);
978 dest = ast_skip_blanks(dest);
979 target = strsep(&dest, " ");
980 target = ast_skip_blanks(target);
981 target = strsep(&target, " "); /* trim trailing whitespace */
984 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
988 target_len = strlen(target) + 1;
989 total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
991 if (!(redirect = ast_calloc(1, total_len))) {
994 redirect->dest = redirect->target + target_len;
995 strcpy(redirect->target, target);
996 strcpy(redirect->dest, dest);
998 AST_RWLIST_WRLOCK(&uri_redirects);
1000 target_len--; /* So we can compare directly with strlen() */
1001 if (AST_RWLIST_EMPTY(&uri_redirects)
1002 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1003 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1004 AST_RWLIST_UNLOCK(&uri_redirects);
1009 AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1010 if (AST_RWLIST_NEXT(cur, entry)
1011 && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1012 AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1013 AST_RWLIST_UNLOCK(&uri_redirects);
1018 AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1020 AST_RWLIST_UNLOCK(&uri_redirects);
1023 static int __ast_http_load(int reload)
1025 struct ast_config *cfg;
1026 struct ast_variable *v;
1028 int newenablestatic=0;
1029 char newprefix[MAX_PREFIX] = "";
1030 struct http_uri_redirect *redirect;
1031 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1032 uint32_t bindport = DEFAULT_PORT;
1033 struct ast_sockaddr *addrs = NULL;
1035 int http_tls_was_enabled = 0;
1037 cfg = ast_config_load2("http.conf", "http", config_flags);
1038 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1042 http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1044 http_tls_cfg.enabled = 0;
1045 if (http_tls_cfg.certfile) {
1046 ast_free(http_tls_cfg.certfile);
1048 http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1050 if (http_tls_cfg.pvtfile) {
1051 ast_free(http_tls_cfg.pvtfile);
1053 http_tls_cfg.pvtfile = ast_strdup("");
1055 if (http_tls_cfg.cipher) {
1056 ast_free(http_tls_cfg.cipher);
1058 http_tls_cfg.cipher = ast_strdup("");
1060 AST_RWLIST_WRLOCK(&uri_redirects);
1061 while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1064 AST_RWLIST_UNLOCK(&uri_redirects);
1066 ast_sockaddr_setnull(&https_desc.local_address);
1069 v = ast_variable_browse(cfg, "general");
1070 for (; v; v = v->next) {
1072 /* read tls config options while preventing unsupported options from being set */
1073 if (strcasecmp(v->name, "tlscafile")
1074 && strcasecmp(v->name, "tlscapath")
1075 && strcasecmp(v->name, "tlscadir")
1076 && strcasecmp(v->name, "tlsverifyclient")
1077 && strcasecmp(v->name, "tlsdontverifyserver")
1078 && strcasecmp(v->name, "tlsclientmethod")
1079 && strcasecmp(v->name, "sslclientmethod")
1080 && strcasecmp(v->name, "tlscipher")
1081 && strcasecmp(v->name, "sslcipher")
1082 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1086 if (!strcasecmp(v->name, "enabled")) {
1087 enabled = ast_true(v->value);
1088 } else if (!strcasecmp(v->name, "enablestatic")) {
1089 newenablestatic = ast_true(v->value);
1090 } else if (!strcasecmp(v->name, "bindport")) {
1091 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1092 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1094 } else if (!strcasecmp(v->name, "bindaddr")) {
1095 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1096 ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1098 } else if (!strcasecmp(v->name, "prefix")) {
1099 if (!ast_strlen_zero(v->value)) {
1101 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1103 newprefix[0] = '\0';
1105 } else if (!strcasecmp(v->name, "redirect")) {
1106 add_redirect(v->value);
1107 } else if (!strcasecmp(v->name, "sessionlimit")) {
1108 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1109 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1110 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1111 v->name, v->value, v->lineno);
1114 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1118 ast_config_destroy(cfg);
1121 if (strcmp(prefix, newprefix)) {
1122 ast_copy_string(prefix, newprefix, sizeof(prefix));
1124 enablestatic = newenablestatic;
1126 if (num_addrs && enabled) {
1128 for (i = 0; i < num_addrs; ++i) {
1129 ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1130 if (!ast_sockaddr_port(&http_desc.local_address)) {
1131 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1133 ast_tcptls_server_start(&http_desc);
1134 if (http_desc.accept_fd == -1) {
1135 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1136 ast_sockaddr_setnull(&http_desc.local_address);
1138 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1142 /* When no specific TLS bindaddr is specified, we just use
1143 * the non-TLS bindaddress here.
1145 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1146 ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1147 /* Of course, we can't use the same port though.
1148 * Since no bind address was specified, we just use the
1151 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1154 if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1155 ast_tcptls_server_stop(&https_desc);
1156 } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1157 /* We can get here either because a TLS-specific address was specified
1158 * or because we copied the non-TLS address here. In the case where
1159 * we read an explicit address from the config, there may have been
1160 * no port specified, so we'll just use the default TLS port.
1162 if (!ast_sockaddr_port(&https_desc.local_address)) {
1163 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1165 if (ast_ssl_setup(https_desc.tls_cfg)) {
1166 ast_tcptls_server_start(&https_desc);
1173 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1175 struct ast_http_uri *urih;
1176 struct http_uri_redirect *redirect;
1180 e->command = "http show status";
1182 "Usage: http show status\n"
1183 " Lists status of internal HTTP engine\n";
1190 return CLI_SHOWUSAGE;
1192 ast_cli(a->fd, "HTTP Server Status:\n");
1193 ast_cli(a->fd, "Prefix: %s\n", prefix);
1194 if (ast_sockaddr_isnull(&http_desc.old_address)) {
1195 ast_cli(a->fd, "Server Disabled\n\n");
1197 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1198 ast_sockaddr_stringify(&http_desc.old_address));
1199 if (http_tls_cfg.enabled) {
1200 ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1201 ast_sockaddr_stringify(&https_desc.old_address));
1205 ast_cli(a->fd, "Enabled URI's:\n");
1206 AST_RWLIST_RDLOCK(&uris);
1207 if (AST_RWLIST_EMPTY(&uris)) {
1208 ast_cli(a->fd, "None.\n");
1210 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1211 ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1213 AST_RWLIST_UNLOCK(&uris);
1215 ast_cli(a->fd, "\nEnabled Redirects:\n");
1216 AST_RWLIST_RDLOCK(&uri_redirects);
1217 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1218 ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
1219 if (AST_RWLIST_EMPTY(&uri_redirects)) {
1220 ast_cli(a->fd, " None.\n");
1222 AST_RWLIST_UNLOCK(&uri_redirects);
1227 int ast_http_reload(void)
1229 return __ast_http_load(1);
1232 static struct ast_cli_entry cli_http[] = {
1233 AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1236 static void http_shutdown(void)
1238 ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1241 int ast_http_init(void)
1243 ast_http_uri_link(&statusuri);
1244 ast_http_uri_link(&staticuri);
1245 ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1246 ast_register_atexit(http_shutdown);
1248 return __ast_http_load(0);