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 * \extref GMime http://spruce.sourceforge.net/gmime/
30 * \ref AstHTTP - AMI over the http protocol
34 <support_level>core</support_level>
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44 #include <sys/signal.h>
47 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
48 #include "asterisk/cli.h"
49 #include "asterisk/tcptls.h"
50 #include "asterisk/http.h"
51 #include "asterisk/utils.h"
52 #include "asterisk/strings.h"
53 #include "asterisk/config.h"
54 #include "asterisk/stringfields.h"
55 #include "asterisk/ast_version.h"
56 #include "asterisk/manager.h"
57 #include "asterisk/_private.h"
58 #include "asterisk/astobj2.h"
59 #include "asterisk/netsock2.h"
62 #define DEFAULT_PORT 8088
63 #define DEFAULT_TLS_PORT 8089
64 #define DEFAULT_SESSION_LIMIT 100
66 /* See http.h for more information about the SSL implementation */
67 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
68 #define DO_SSL /* comment in/out if you want to support ssl */
71 static int session_limit = DEFAULT_SESSION_LIMIT;
72 static int session_count = 0;
74 static struct ast_tls_config http_tls_cfg;
76 static void *httpd_helper_thread(void *arg);
79 * we have up to two accepting threads, one for http, one for https
81 static struct ast_tcptls_session_args http_desc = {
83 .master = AST_PTHREADT_NULL,
86 .name = "http server",
87 .accept_fn = ast_tcptls_server_root,
88 .worker_fn = httpd_helper_thread,
91 static struct ast_tcptls_session_args https_desc = {
93 .master = AST_PTHREADT_NULL,
94 .tls_cfg = &http_tls_cfg,
96 .name = "https server",
97 .accept_fn = ast_tcptls_server_root,
98 .worker_fn = httpd_helper_thread,
101 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri); /*!< list of supported handlers */
103 /* all valid URIs must be prepended by the string in prefix. */
104 static char prefix[MAX_PREFIX];
105 static int enablestatic;
107 /*! \brief Limit the kinds of files we're willing to serve up */
112 { "png", "image/png" },
113 { "xml", "text/xml" },
114 { "jpg", "image/jpeg" },
115 { "js", "application/x-javascript" },
116 { "wav", "audio/x-wav" },
117 { "mp3", "audio/mpeg" },
118 { "svg", "image/svg+xml" },
119 { "svgz", "image/svg+xml" },
120 { "gif", "image/gif" },
121 { "html", "text/html" },
122 { "htm", "text/html" },
123 { "css", "text/css" },
124 { "cnf", "text/plain" },
125 { "cfg", "text/plain" },
126 { "bin", "application/octet-stream" },
127 { "sbn", "application/octet-stream" },
128 { "ld", "application/octet-stream" },
131 struct http_uri_redirect {
132 AST_LIST_ENTRY(http_uri_redirect) entry;
137 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
139 static const struct ast_cfhttp_methods_text {
140 enum ast_http_method method;
142 } ast_http_methods_text[] = {
143 { AST_HTTP_UNKNOWN, "UNKNOWN" },
144 { AST_HTTP_GET, "GET" },
145 { AST_HTTP_POST, "POST" },
146 { AST_HTTP_HEAD, "HEAD" },
147 { AST_HTTP_PUT, "PUT" },
150 const char *ast_get_http_method(enum ast_http_method method)
154 for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
155 if (ast_http_methods_text[x].method == method) {
156 return ast_http_methods_text[x].text;
163 const char *ast_http_ftype2mtype(const char *ftype)
168 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
169 if (!strcasecmp(ftype, mimetypes[x].ext)) {
170 return mimetypes[x].mtype;
177 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
180 struct ast_variable *v, *cookies;
182 cookies = ast_http_get_cookies(headers);
183 for (v = cookies; v; v = v->next) {
184 if (!strcasecmp(v->name, "mansession_id")) {
185 sscanf(v->value, "%30x", &mngid);
190 ast_variables_destroy(cookies);
195 void ast_http_prefix(char *buf, int len)
198 ast_copy_string(buf, prefix, len);
202 static int static_callback(struct ast_tcptls_session_instance *ser,
203 const struct ast_http_uri *urih, const char *uri,
204 enum ast_http_method method, struct ast_variable *get_vars,
205 struct ast_variable *headers)
214 struct ast_str *http_header;
217 char timebuf[80], etag[23];
218 struct ast_variable *v;
219 int not_modified = 0;
221 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
222 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
226 /* Yuck. I'm not really sold on this, but if you don't deliver static content it makes your configuration
227 substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
228 if (!enablestatic || ast_strlen_zero(uri)) {
232 /* Disallow any funny filenames at all */
233 if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
237 if (strstr(uri, "/..")) {
241 if ((ftype = strrchr(uri, '.'))) {
245 if (!(mtype = ast_http_ftype2mtype(ftype))) {
246 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
249 /* Cap maximum length */
250 if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
255 sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
256 if (stat(path, &st)) {
260 if (S_ISDIR(st.st_mode)) {
264 fd = open(path, O_RDONLY);
269 if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
273 /* make "Etag:" http header value */
274 snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
276 /* make "Last-Modified:" http header value */
277 tv.tv_sec = st.st_mtime;
279 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
281 /* check received "If-None-Match" request header and Etag value for file */
282 for (v = headers; v; v = v->next) {
283 if (!strcasecmp(v->name, "If-None-Match")) {
284 if (!strcasecmp(v->value, etag)) {
291 if ( (http_header = ast_str_create(255)) == NULL) {
295 ast_str_set(&http_header, 0, "Content-type: %s\r\n"
297 "Last-Modified: %s\r\n",
302 /* ast_http_send() frees http_header, so we don't need to do it before returning */
304 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
306 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
312 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
316 ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
320 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
321 const struct ast_http_uri *urih, const char *uri,
322 enum ast_http_method method, struct ast_variable *get_vars,
323 struct ast_variable *headers)
326 struct ast_variable *v, *cookies = NULL;
328 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
329 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
333 if ( (out = ast_str_create(512)) == NULL) {
337 ast_str_append(&out, 0,
338 "<title>Asterisk HTTP Status</title>\r\n"
339 "<body bgcolor=\"#ffffff\">\r\n"
340 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
341 "<h2> Asterisk™ HTTP Status</h2></td></tr>\r\n");
343 ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
344 ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
345 ast_sockaddr_stringify_addr(&http_desc.old_address));
346 ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
347 ast_sockaddr_stringify_port(&http_desc.old_address));
348 if (http_tls_cfg.enabled) {
349 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
350 ast_sockaddr_stringify_port(&https_desc.old_address));
352 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
353 for (v = get_vars; v; v = v->next) {
354 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
356 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
358 cookies = ast_http_get_cookies(headers);
359 for (v = cookies; v; v = v->next) {
360 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
362 ast_variables_destroy(cookies);
364 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");
365 ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
369 static struct ast_http_uri statusuri = {
370 .callback = httpstatus_callback,
371 .description = "Asterisk HTTP General Status",
378 static struct ast_http_uri staticuri = {
379 .callback = static_callback,
380 .description = "Asterisk HTTP Static Delivery",
388 /* send http/1.1 response */
389 /* free content variable and close socket*/
390 void ast_http_send(struct ast_tcptls_session_instance *ser,
391 enum ast_http_method method, int status_code, const char *status_title,
392 struct ast_str *http_header, struct ast_str *out, const int fd,
393 unsigned int static_content)
395 struct timeval now = ast_tvnow();
398 int content_length = 0;
400 if (!ser || 0 == ser->f) {
404 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
406 /* calc content length */
408 content_length += strlen(ast_str_buffer(out));
412 content_length += lseek(fd, 0, SEEK_END);
413 lseek(fd, 0, SEEK_SET);
416 /* send http header */
417 fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
418 "Server: Asterisk/%s\r\n"
420 "Connection: close\r\n"
422 "Content-Length: %d\r\n"
425 status_code, status_title ? status_title : "OK",
428 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
430 http_header ? ast_str_buffer(http_header) : ""
434 if (method != AST_HTTP_HEAD || status_code >= 400) {
436 fprintf(ser->f, "%s", ast_str_buffer(out));
442 while ((len = read(fd, buf, sizeof(buf))) > 0) {
443 if (fwrite(buf, len, 1, ser->f) != 1) {
444 ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
452 ast_free(http_header);
463 /* Send http "401 Unauthorized" responce and close socket*/
464 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
465 const unsigned long nonce, const unsigned long opaque, int stale,
468 struct ast_str *http_headers = ast_str_create(128);
469 struct ast_str *out = ast_str_create(512);
471 if (!http_headers || !out) {
472 ast_free(http_headers);
477 ast_str_set(&http_headers, 0,
478 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
479 "Content-type: text/html\r\n",
480 realm ? realm : "Asterisk",
483 stale ? ", stale=true" : "");
486 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
488 "<title>401 Unauthorized</title>\r\n"
490 "<h1>401 Unauthorized</h1>\r\n"
493 "<address>Asterisk Server</address>\r\n"
494 "</body></html>\r\n",
497 ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
501 /* send http error response and close socket*/
502 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
504 struct ast_str *http_headers = ast_str_create(40);
505 struct ast_str *out = ast_str_create(256);
507 if (!http_headers || !out) {
508 ast_free(http_headers);
513 ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
516 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
518 "<title>%d %s</title>\r\n"
523 "<address>Asterisk Server</address>\r\n"
524 "</body></html>\r\n",
525 status_code, status_title, status_title, text);
527 ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
532 * Link the new uri into the list.
534 * They are sorted by length of
535 * the string, not alphabetically. Duplicate entries are not replaced,
536 * but the insertion order (using <= and not just <) makes sure that
537 * more recent insertions hide older ones.
538 * On a lookup, we just scan the list and stop at the first matching entry.
540 int ast_http_uri_link(struct ast_http_uri *urih)
542 struct ast_http_uri *uri;
543 int len = strlen(urih->uri);
545 AST_RWLIST_WRLOCK(&uris);
547 if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
548 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
549 AST_RWLIST_UNLOCK(&uris);
553 AST_RWLIST_TRAVERSE(&uris, uri, entry) {
554 if (AST_RWLIST_NEXT(uri, entry) &&
555 strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
556 AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
557 AST_RWLIST_UNLOCK(&uris);
563 AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
565 AST_RWLIST_UNLOCK(&uris);
570 void ast_http_uri_unlink(struct ast_http_uri *urih)
572 AST_RWLIST_WRLOCK(&uris);
573 AST_RWLIST_REMOVE(&uris, urih, entry);
574 AST_RWLIST_UNLOCK(&uris);
577 void ast_http_uri_unlink_all_with_key(const char *key)
579 struct ast_http_uri *urih;
580 AST_RWLIST_WRLOCK(&uris);
581 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
582 if (!strcmp(urih->key, key)) {
583 AST_RWLIST_REMOVE_CURRENT(entry);
585 if (urih->dmallocd) {
586 ast_free(urih->data);
592 AST_RWLIST_TRAVERSE_SAFE_END;
593 AST_RWLIST_UNLOCK(&uris);
597 * get post variables from client Request Entity-Body, if content type is
598 * application/x-www-form-urlencoded
600 struct ast_variable *ast_http_get_post_vars(
601 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
603 int content_length = 0;
604 struct ast_variable *v, *post_vars=NULL, *prev = NULL;
605 char *buf, *var, *val;
607 for (v = headers; v; v = v->next) {
608 if (!strcasecmp(v->name, "Content-Type")) {
609 if (strcasecmp(v->value, "application/x-www-form-urlencoded")) {
616 for (v = headers; v; v = v->next) {
617 if (!strcasecmp(v->name, "Content-Length")) {
618 content_length = atoi(v->value) + 1;
623 if (!content_length) {
627 if (!(buf = alloca(content_length))) {
630 if (!fgets(buf, content_length, ser->f)) {
634 while ((val = strsep(&buf, "&"))) {
635 var = strsep(&val, "=");
637 ast_uri_decode(val, ast_uri_http_legacy);
641 ast_uri_decode(var, ast_uri_http_legacy);
642 if ((v = ast_variable_new(var, val, ""))) {
654 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
655 enum ast_http_method method, struct ast_variable *headers)
660 struct ast_http_uri *urih = NULL;
662 struct ast_variable *get_vars = NULL, *v, *prev = NULL;
663 struct http_uri_redirect *redirect;
665 ast_debug(2, "HTTP Request URI is %s \n", uri);
667 strsep(¶ms, "?");
668 /* Extract arguments from the request and store them in variables. */
672 while ((val = strsep(¶ms, "&"))) {
673 var = strsep(&val, "=");
675 ast_uri_decode(val, ast_uri_http_legacy);
679 ast_uri_decode(var, ast_uri_http_legacy);
680 if ((v = ast_variable_new(var, val, ""))) {
690 ast_uri_decode(uri, ast_uri_http_legacy);
692 AST_RWLIST_RDLOCK(&uri_redirects);
693 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
694 if (!strcasecmp(uri, redirect->target)) {
695 struct ast_str *http_header = ast_str_create(128);
696 ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
697 ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
702 AST_RWLIST_UNLOCK(&uri_redirects);
707 /* We want requests to start with the (optional) prefix and '/' */
709 if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
711 /* scan registered uris to see if we match one. */
712 AST_RWLIST_RDLOCK(&uris);
713 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
714 ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
715 l = strlen(urih->uri);
716 c = uri + l; /* candidate */
717 if (strncasecmp(urih->uri, uri, l) /* no match */
718 || (*c && *c != '/')) { /* substring */
724 if (!*c || urih->has_subtree) {
729 AST_RWLIST_UNLOCK(&uris);
732 res = urih->callback(ser, urih, uri, method, get_vars, headers);
734 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
738 ast_variables_destroy(get_vars);
743 #if defined(HAVE_FUNOPEN)
747 #define HOOK_T ssize_t
752 * replacement read/write functions for SSL support.
753 * We use wrappers rather than SSL_read/SSL_write directly so
754 * we can put in some debugging.
756 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
758 int i = SSL_read(cookie, buf, len-1);
762 ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
767 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
770 char *s = alloca(len+1);
771 strncpy(s, buf, len);
773 ast_verbose("ssl write size %d <%s>\n", (int)len, s);
775 return SSL_write(cookie, buf, len);
778 static int ssl_close(void *cookie)
780 close(SSL_get_fd(cookie));
781 SSL_shutdown(cookie);
787 static struct ast_variable *parse_cookies(char *cookies)
790 struct ast_variable *vars = NULL, *var;
792 while ((cur = strsep(&cookies, ";"))) {
798 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
802 name = ast_strip(name);
803 val = ast_strip_quoted(val, "\"", "\"");
805 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
809 ast_debug(1, "HTTP Cookie, Name: '%s' Value: '%s'\n", name, val);
811 var = ast_variable_new(name, val, __FILE__);
819 /* get cookie from Request headers */
820 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
822 struct ast_variable *v, *cookies=NULL;
824 for (v = headers; v; v = v->next) {
825 if (!strncasecmp(v->name, "Cookie", 6)) {
826 char *tmp = ast_strdupa(v->value);
828 ast_variables_destroy(cookies);
831 cookies = parse_cookies(tmp);
838 static void *httpd_helper_thread(void *data)
841 char header_line[4096];
842 struct ast_tcptls_session_instance *ser = data;
843 struct ast_variable *headers = NULL;
844 struct ast_variable *tail = headers;
846 enum ast_http_method http_method = AST_HTTP_UNKNOWN;
848 if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
852 if (!fgets(buf, sizeof(buf), ser->f)) {
857 method = ast_skip_blanks(buf);
858 uri = ast_skip_nonblanks(method);
863 if (!strcasecmp(method,"GET")) {
864 http_method = AST_HTTP_GET;
865 } else if (!strcasecmp(method,"POST")) {
866 http_method = AST_HTTP_POST;
867 } else if (!strcasecmp(method,"HEAD")) {
868 http_method = AST_HTTP_HEAD;
869 } else if (!strcasecmp(method,"PUT")) {
870 http_method = AST_HTTP_PUT;
873 uri = ast_skip_blanks(uri); /* Skip white space */
875 if (*uri) { /* terminate at the first blank */
876 char *c = ast_skip_nonblanks(uri);
883 /* process "Request Headers" lines */
884 while (fgets(header_line, sizeof(header_line), ser->f)) {
887 /* Trim trailing characters */
888 ast_trim_blanks(header_line);
889 if (ast_strlen_zero(header_line)) {
894 name = strsep(&value, ":");
899 value = ast_skip_blanks(value);
900 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
904 ast_trim_blanks(name);
907 headers = ast_variable_new(name, value, __FILE__);
910 tail->next = ast_variable_new(name, value, __FILE__);
916 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
920 handle_uri(ser, uri, http_method, headers);
923 ast_atomic_fetchadd_int(&session_count, -1);
925 /* clean up all the header information */
927 ast_variables_destroy(headers);
939 * \brief Add a new URI redirect
940 * The entries in the redirect list are sorted by length, just like the list
943 static void add_redirect(const char *value)
946 struct http_uri_redirect *redirect, *cur;
947 unsigned int target_len;
948 unsigned int total_len;
950 dest = ast_strdupa(value);
951 dest = ast_skip_blanks(dest);
952 target = strsep(&dest, " ");
953 target = ast_skip_blanks(target);
954 target = strsep(&target, " "); /* trim trailing whitespace */
957 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
961 target_len = strlen(target) + 1;
962 total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
964 if (!(redirect = ast_calloc(1, total_len))) {
967 redirect->dest = redirect->target + target_len;
968 strcpy(redirect->target, target);
969 strcpy(redirect->dest, dest);
971 AST_RWLIST_WRLOCK(&uri_redirects);
973 target_len--; /* So we can compare directly with strlen() */
974 if (AST_RWLIST_EMPTY(&uri_redirects)
975 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
976 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
977 AST_RWLIST_UNLOCK(&uri_redirects);
982 AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
983 if (AST_RWLIST_NEXT(cur, entry)
984 && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
985 AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
986 AST_RWLIST_UNLOCK(&uri_redirects);
991 AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
993 AST_RWLIST_UNLOCK(&uri_redirects);
996 static int __ast_http_load(int reload)
998 struct ast_config *cfg;
999 struct ast_variable *v;
1001 int newenablestatic=0;
1002 char newprefix[MAX_PREFIX] = "";
1003 struct http_uri_redirect *redirect;
1004 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1005 uint32_t bindport = DEFAULT_PORT;
1006 struct ast_sockaddr *addrs = NULL;
1008 int http_tls_was_enabled = 0;
1010 cfg = ast_config_load2("http.conf", "http", config_flags);
1011 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1015 http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1017 http_tls_cfg.enabled = 0;
1018 if (http_tls_cfg.certfile) {
1019 ast_free(http_tls_cfg.certfile);
1021 http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1023 if (http_tls_cfg.pvtfile) {
1024 ast_free(http_tls_cfg.pvtfile);
1026 http_tls_cfg.pvtfile = ast_strdup("");
1028 if (http_tls_cfg.cipher) {
1029 ast_free(http_tls_cfg.cipher);
1031 http_tls_cfg.cipher = ast_strdup("");
1033 AST_RWLIST_WRLOCK(&uri_redirects);
1034 while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1037 AST_RWLIST_UNLOCK(&uri_redirects);
1039 ast_sockaddr_setnull(&https_desc.local_address);
1042 v = ast_variable_browse(cfg, "general");
1043 for (; v; v = v->next) {
1045 /* handle tls conf */
1046 if (!ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1050 if (!strcasecmp(v->name, "enabled")) {
1051 enabled = ast_true(v->value);
1052 } else if (!strcasecmp(v->name, "enablestatic")) {
1053 newenablestatic = ast_true(v->value);
1054 } else if (!strcasecmp(v->name, "bindport")) {
1055 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1056 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1058 } else if (!strcasecmp(v->name, "bindaddr")) {
1059 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1060 ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1062 ast_log(LOG_WARNING, "Got %d addresses\n", num_addrs);
1064 } else if (!strcasecmp(v->name, "prefix")) {
1065 if (!ast_strlen_zero(v->value)) {
1067 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1069 newprefix[0] = '\0';
1071 } else if (!strcasecmp(v->name, "redirect")) {
1072 add_redirect(v->value);
1073 } else if (!strcasecmp(v->name, "sessionlimit")) {
1074 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1075 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1076 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1077 v->name, v->value, v->lineno);
1080 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1084 ast_config_destroy(cfg);
1087 if (strcmp(prefix, newprefix)) {
1088 ast_copy_string(prefix, newprefix, sizeof(prefix));
1090 enablestatic = newenablestatic;
1092 if (num_addrs && enabled) {
1094 for (i = 0; i < num_addrs; ++i) {
1095 ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1096 if (!ast_sockaddr_port(&http_desc.local_address)) {
1097 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1099 ast_tcptls_server_start(&http_desc);
1100 if (http_desc.accept_fd == -1) {
1101 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1102 ast_sockaddr_setnull(&http_desc.local_address);
1104 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1108 /* When no specific TLS bindaddr is specified, we just use
1109 * the non-TLS bindaddress here.
1111 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1112 ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1113 /* Of course, we can't use the same port though.
1114 * Since no bind address was specified, we just use the
1117 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1120 if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1121 ast_tcptls_server_stop(&https_desc);
1122 } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1123 /* We can get here either because a TLS-specific address was specified
1124 * or because we copied the non-TLS address here. In the case where
1125 * we read an explicit address from the config, there may have been
1126 * no port specified, so we'll just use the default TLS port.
1128 if (!ast_sockaddr_port(&https_desc.local_address)) {
1129 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1131 if (ast_ssl_setup(https_desc.tls_cfg)) {
1132 ast_tcptls_server_start(&https_desc);
1139 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1141 struct ast_http_uri *urih;
1142 struct http_uri_redirect *redirect;
1146 e->command = "http show status";
1148 "Usage: http show status\n"
1149 " Lists status of internal HTTP engine\n";
1156 return CLI_SHOWUSAGE;
1158 ast_cli(a->fd, "HTTP Server Status:\n");
1159 ast_cli(a->fd, "Prefix: %s\n", prefix);
1160 if (ast_sockaddr_isnull(&http_desc.old_address)) {
1161 ast_cli(a->fd, "Server Disabled\n\n");
1163 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1164 ast_sockaddr_stringify(&http_desc.old_address));
1165 if (http_tls_cfg.enabled) {
1166 ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1167 ast_sockaddr_stringify(&https_desc.old_address));
1171 ast_cli(a->fd, "Enabled URI's:\n");
1172 AST_RWLIST_RDLOCK(&uris);
1173 if (AST_RWLIST_EMPTY(&uris)) {
1174 ast_cli(a->fd, "None.\n");
1176 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1177 ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1179 AST_RWLIST_UNLOCK(&uris);
1181 ast_cli(a->fd, "\nEnabled Redirects:\n");
1182 AST_RWLIST_RDLOCK(&uri_redirects);
1183 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1184 ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
1185 if (AST_RWLIST_EMPTY(&uri_redirects)) {
1186 ast_cli(a->fd, " None.\n");
1188 AST_RWLIST_UNLOCK(&uri_redirects);
1193 int ast_http_reload(void)
1195 return __ast_http_load(1);
1198 static struct ast_cli_entry cli_http[] = {
1199 AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1202 int ast_http_init(void)
1204 ast_http_uri_link(&statusuri);
1205 ast_http_uri_link(&staticuri);
1206 ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1208 return __ast_http_load(0);