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"
68 #include "asterisk/json.h"
71 #define DEFAULT_PORT 8088
72 #define DEFAULT_TLS_PORT 8089
73 #define DEFAULT_SESSION_LIMIT 100
75 /* See http.h for more information about the SSL implementation */
76 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
77 #define DO_SSL /* comment in/out if you want to support ssl */
80 static int session_limit = DEFAULT_SESSION_LIMIT;
81 static int session_count = 0;
83 static struct ast_tls_config http_tls_cfg;
85 static void *httpd_helper_thread(void *arg);
88 * we have up to two accepting threads, one for http, one for https
90 static struct ast_tcptls_session_args http_desc = {
92 .master = AST_PTHREADT_NULL,
95 .name = "http server",
96 .accept_fn = ast_tcptls_server_root,
97 .worker_fn = httpd_helper_thread,
100 static struct ast_tcptls_session_args https_desc = {
102 .master = AST_PTHREADT_NULL,
103 .tls_cfg = &http_tls_cfg,
105 .name = "https server",
106 .accept_fn = ast_tcptls_server_root,
107 .worker_fn = httpd_helper_thread,
110 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri); /*!< list of supported handlers */
112 /* all valid URIs must be prepended by the string in prefix. */
113 static char prefix[MAX_PREFIX];
114 static int enablestatic;
116 /*! \brief Limit the kinds of files we're willing to serve up */
121 { "png", "image/png" },
122 { "xml", "text/xml" },
123 { "jpg", "image/jpeg" },
124 { "js", "application/x-javascript" },
125 { "wav", "audio/x-wav" },
126 { "mp3", "audio/mpeg" },
127 { "svg", "image/svg+xml" },
128 { "svgz", "image/svg+xml" },
129 { "gif", "image/gif" },
130 { "html", "text/html" },
131 { "htm", "text/html" },
132 { "css", "text/css" },
133 { "cnf", "text/plain" },
134 { "cfg", "text/plain" },
135 { "bin", "application/octet-stream" },
136 { "sbn", "application/octet-stream" },
137 { "ld", "application/octet-stream" },
140 struct http_uri_redirect {
141 AST_LIST_ENTRY(http_uri_redirect) entry;
146 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
148 static const struct ast_cfhttp_methods_text {
149 enum ast_http_method method;
151 } ast_http_methods_text[] = {
152 { AST_HTTP_UNKNOWN, "UNKNOWN" },
153 { AST_HTTP_GET, "GET" },
154 { AST_HTTP_POST, "POST" },
155 { AST_HTTP_HEAD, "HEAD" },
156 { AST_HTTP_PUT, "PUT" },
157 { AST_HTTP_DELETE, "DELETE" },
158 { AST_HTTP_OPTIONS, "OPTIONS" },
161 const char *ast_get_http_method(enum ast_http_method method)
165 for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
166 if (ast_http_methods_text[x].method == method) {
167 return ast_http_methods_text[x].text;
174 const char *ast_http_ftype2mtype(const char *ftype)
179 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
180 if (!strcasecmp(ftype, mimetypes[x].ext)) {
181 return mimetypes[x].mtype;
188 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
191 struct ast_variable *v, *cookies;
193 cookies = ast_http_get_cookies(headers);
194 for (v = cookies; v; v = v->next) {
195 if (!strcasecmp(v->name, "mansession_id")) {
196 sscanf(v->value, "%30x", &mngid);
201 ast_variables_destroy(cookies);
206 void ast_http_prefix(char *buf, int len)
209 ast_copy_string(buf, prefix, len);
213 static int static_callback(struct ast_tcptls_session_instance *ser,
214 const struct ast_http_uri *urih, const char *uri,
215 enum ast_http_method method, struct ast_variable *get_vars,
216 struct ast_variable *headers)
225 struct ast_str *http_header;
228 char timebuf[80], etag[23];
229 struct ast_variable *v;
230 int not_modified = 0;
232 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
233 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
237 /* Yuck. I'm not really sold on this, but if you don't deliver static content it makes your configuration
238 substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
239 if (!enablestatic || ast_strlen_zero(uri)) {
243 /* Disallow any funny filenames at all (checking first character only??) */
244 if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
248 if (strstr(uri, "/..")) {
252 if ((ftype = strrchr(uri, '.'))) {
256 if (!(mtype = ast_http_ftype2mtype(ftype))) {
257 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
261 /* Cap maximum length */
262 if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
266 path = ast_alloca(len);
267 sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
268 if (stat(path, &st)) {
272 if (S_ISDIR(st.st_mode)) {
276 if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
280 fd = open(path, O_RDONLY);
285 /* make "Etag:" http header value */
286 snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
288 /* make "Last-Modified:" http header value */
289 tv.tv_sec = st.st_mtime;
291 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
293 /* check received "If-None-Match" request header and Etag value for file */
294 for (v = headers; v; v = v->next) {
295 if (!strcasecmp(v->name, "If-None-Match")) {
296 if (!strcasecmp(v->value, etag)) {
303 if ( (http_header = ast_str_create(255)) == NULL) {
308 ast_str_set(&http_header, 0, "Content-type: %s\r\n"
310 "Last-Modified: %s\r\n",
315 /* ast_http_send() frees http_header, so we don't need to do it before returning */
317 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
319 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
325 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
329 ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
333 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
334 const struct ast_http_uri *urih, const char *uri,
335 enum ast_http_method method, struct ast_variable *get_vars,
336 struct ast_variable *headers)
339 struct ast_variable *v, *cookies = NULL;
341 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
342 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
346 if ( (out = ast_str_create(512)) == NULL) {
350 ast_str_append(&out, 0,
351 "<title>Asterisk HTTP Status</title>\r\n"
352 "<body bgcolor=\"#ffffff\">\r\n"
353 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
354 "<h2> Asterisk™ HTTP Status</h2></td></tr>\r\n");
356 ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
357 ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
358 ast_sockaddr_stringify_addr(&http_desc.old_address));
359 ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
360 ast_sockaddr_stringify_port(&http_desc.old_address));
361 if (http_tls_cfg.enabled) {
362 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
363 ast_sockaddr_stringify_port(&https_desc.old_address));
365 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
366 for (v = get_vars; v; v = v->next) {
367 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
369 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
371 cookies = ast_http_get_cookies(headers);
372 for (v = cookies; v; v = v->next) {
373 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
375 ast_variables_destroy(cookies);
377 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");
378 ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
382 static struct ast_http_uri statusuri = {
383 .callback = httpstatus_callback,
384 .description = "Asterisk HTTP General Status",
391 static struct ast_http_uri staticuri = {
392 .callback = static_callback,
393 .description = "Asterisk HTTP Static Delivery",
401 /* send http/1.1 response */
402 /* free content variable and close socket*/
403 void ast_http_send(struct ast_tcptls_session_instance *ser,
404 enum ast_http_method method, int status_code, const char *status_title,
405 struct ast_str *http_header, struct ast_str *out, const int fd,
406 unsigned int static_content)
408 struct timeval now = ast_tvnow();
411 int content_length = 0;
413 if (!ser || 0 == ser->f) {
417 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
419 /* calc content length */
421 content_length += strlen(ast_str_buffer(out));
425 content_length += lseek(fd, 0, SEEK_END);
426 lseek(fd, 0, SEEK_SET);
429 /* send http header */
430 fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
431 "Server: Asterisk/%s\r\n"
433 "Connection: close\r\n"
435 "Content-Length: %d\r\n"
438 status_code, status_title ? status_title : "OK",
441 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
443 http_header ? ast_str_buffer(http_header) : ""
447 if (method != AST_HTTP_HEAD || status_code >= 400) {
449 fprintf(ser->f, "%s", ast_str_buffer(out));
455 while ((len = read(fd, buf, sizeof(buf))) > 0) {
456 if (fwrite(buf, len, 1, ser->f) != 1) {
457 ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
465 ast_free(http_header);
476 /* Send http "401 Unauthorized" responce and close socket*/
477 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
478 const unsigned long nonce, const unsigned long opaque, int stale,
481 struct ast_str *http_headers = ast_str_create(128);
482 struct ast_str *out = ast_str_create(512);
484 if (!http_headers || !out) {
485 ast_free(http_headers);
490 ast_str_set(&http_headers, 0,
491 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
492 "Content-type: text/html\r\n",
493 realm ? realm : "Asterisk",
496 stale ? ", stale=true" : "");
499 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
501 "<title>401 Unauthorized</title>\r\n"
503 "<h1>401 Unauthorized</h1>\r\n"
506 "<address>Asterisk Server</address>\r\n"
507 "</body></html>\r\n",
510 ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
514 /* send http error response and close socket*/
515 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
517 struct ast_str *http_headers = ast_str_create(40);
518 struct ast_str *out = ast_str_create(256);
520 if (!http_headers || !out) {
521 ast_free(http_headers);
526 ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
529 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
531 "<title>%d %s</title>\r\n"
536 "<address>Asterisk Server</address>\r\n"
537 "</body></html>\r\n",
538 status_code, status_title, status_title, text);
540 ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
545 * Link the new uri into the list.
547 * They are sorted by length of
548 * the string, not alphabetically. Duplicate entries are not replaced,
549 * but the insertion order (using <= and not just <) makes sure that
550 * more recent insertions hide older ones.
551 * On a lookup, we just scan the list and stop at the first matching entry.
553 int ast_http_uri_link(struct ast_http_uri *urih)
555 struct ast_http_uri *uri;
556 int len = strlen(urih->uri);
558 AST_RWLIST_WRLOCK(&uris);
560 if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
561 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
562 AST_RWLIST_UNLOCK(&uris);
566 AST_RWLIST_TRAVERSE(&uris, uri, entry) {
567 if (AST_RWLIST_NEXT(uri, entry) &&
568 strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
569 AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
570 AST_RWLIST_UNLOCK(&uris);
576 AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
578 AST_RWLIST_UNLOCK(&uris);
583 void ast_http_uri_unlink(struct ast_http_uri *urih)
585 AST_RWLIST_WRLOCK(&uris);
586 AST_RWLIST_REMOVE(&uris, urih, entry);
587 AST_RWLIST_UNLOCK(&uris);
590 void ast_http_uri_unlink_all_with_key(const char *key)
592 struct ast_http_uri *urih;
593 AST_RWLIST_WRLOCK(&uris);
594 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
595 if (!strcmp(urih->key, key)) {
596 AST_RWLIST_REMOVE_CURRENT(entry);
597 if (urih->dmallocd) {
598 ast_free(urih->data);
605 AST_RWLIST_TRAVERSE_SAFE_END;
606 AST_RWLIST_UNLOCK(&uris);
609 #define MAX_POST_CONTENT 1025
612 * \brief Retrieves the header with the given field name.
614 * \param headers Headers to search.
615 * \param field_name Name of the header to find.
616 * \return Associated header value.
617 * \return \c NULL if header is not present.
619 static const char *get_header(struct ast_variable *headers,
620 const char *field_name)
622 struct ast_variable *v;
624 for (v = headers; v; v = v->next) {
625 if (!strcasecmp(v->name, field_name)) {
633 * \brief Retrieves the content type specified in the "Content-Type" header.
635 * This function only returns the "type/subtype" and any trailing parameter is
638 * \note the return value is an allocated string that needs to be freed.
640 * \retval the content type/subtype or NULL if the header is not found.
642 static char *get_content_type(struct ast_variable *headers)
644 const char *content_type = get_header(headers, "Content-Type");
652 param = strchr(content_type, ';');
653 size = param ? param - content_type : strlen(content_type);
655 return ast_strndup(content_type, size);
659 * \brief Returns the value of the Content-Length header.
661 * \param headers HTTP headers.
662 * \return Value of the Content-Length header.
663 * \return 0 if header is not present, or is invalid.
665 static int get_content_length(struct ast_variable *headers)
667 const char *content_length = get_header(headers, "Content-Length");
669 if (!content_length) {
670 /* Missing content length; assume zero */
674 /* atoi() will return 0 for invalid inputs, which is good enough for
675 * the HTTP parsing. */
676 return atoi(content_length);
680 * \brief Returns the value of the Transfer-Encoding header.
682 * \param headers HTTP headers.
683 * \return Value of the Transfer-Encoding header.
684 * \return 0 if header is not present, or is invalid.
686 static const char *get_transfer_encoding(struct ast_variable *headers)
688 return get_header(headers, "Transfer-Encoding");
691 struct ast_json *ast_http_get_json(
692 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
694 int content_length = 0;
696 struct ast_json *body;
697 RAII_VAR(char *, buf, NULL, ast_free);
698 RAII_VAR(char *, type, get_content_type(headers), ast_free);
700 /* Use errno to distinguish errors from no body */
703 if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
704 /* Content type is not JSON */
708 content_length = get_content_length(headers);
710 if (content_length <= 0) {
711 /* No content (or streaming content). */
715 if (content_length > MAX_POST_CONTENT - 1) {
717 "Excessively long HTTP content. (%d > %d)\n",
718 content_length, MAX_POST_CONTENT);
723 buf = ast_malloc(content_length);
725 /* Malloc sets ENOMEM */
729 res = fread(buf, 1, content_length, ser->f);
730 if (res < content_length) {
731 /* Error, distinguishable by ferror() or feof(), but neither
732 * is good. Treat either one as I/O error */
733 ast_log(LOG_WARNING, "Short HTTP request body (%d < %d)\n",
734 res, content_length);
739 body = ast_json_load_buf(buf, content_length, NULL);
741 /* Failed to parse JSON; treat as an I/O error */
750 * get post variables from client Request Entity-Body, if content type is
751 * application/x-www-form-urlencoded
753 struct ast_variable *ast_http_get_post_vars(
754 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
756 int content_length = 0;
757 struct ast_variable *v, *post_vars=NULL, *prev = NULL;
759 RAII_VAR(char *, buf, NULL, ast_free_ptr);
760 RAII_VAR(char *, type, get_content_type(headers), ast_free);
763 /* Use errno to distinguish errors from no params */
766 if (ast_strlen_zero(type) ||
767 strcasecmp(type, "application/x-www-form-urlencoded")) {
768 /* Content type is not form data */
772 content_length = get_content_length(headers);
774 if (content_length <= 0) {
778 if (content_length > MAX_POST_CONTENT - 1) {
780 "Excessively long HTTP content. (%d > %d)\n",
781 content_length, MAX_POST_CONTENT);
786 buf = ast_malloc(content_length + 1);
788 /* malloc sets errno to ENOMEM */
792 res = fread(buf, 1, content_length, ser->f);
793 if (res < content_length) {
794 /* Error, distinguishable by ferror() or feof(), but neither
795 * is good. Treat either one as I/O error */
799 buf[content_length] = '\0';
801 while ((val = strsep(&buf, "&"))) {
802 var = strsep(&val, "=");
804 ast_uri_decode(val, ast_uri_http_legacy);
808 ast_uri_decode(var, ast_uri_http_legacy);
809 if ((v = ast_variable_new(var, val, ""))) {
822 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
823 enum ast_http_method method, struct ast_variable *headers)
828 struct ast_http_uri *urih = NULL;
830 struct ast_variable *get_vars = NULL, *v, *prev = NULL;
831 struct http_uri_redirect *redirect;
833 ast_debug(2, "HTTP Request URI is %s \n", uri);
835 strsep(¶ms, "?");
836 /* Extract arguments from the request and store them in variables. */
840 while ((val = strsep(¶ms, "&"))) {
841 var = strsep(&val, "=");
843 ast_uri_decode(val, ast_uri_http_legacy);
847 ast_uri_decode(var, ast_uri_http_legacy);
848 if ((v = ast_variable_new(var, val, ""))) {
859 AST_RWLIST_RDLOCK(&uri_redirects);
860 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
861 if (!strcasecmp(uri, redirect->target)) {
862 struct ast_str *http_header = ast_str_create(128);
863 ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
864 ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
869 AST_RWLIST_UNLOCK(&uri_redirects);
874 /* We want requests to start with the (optional) prefix and '/' */
876 if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
878 /* scan registered uris to see if we match one. */
879 AST_RWLIST_RDLOCK(&uris);
880 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
881 l = strlen(urih->uri);
882 c = uri + l; /* candidate */
883 ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
884 if (strncasecmp(urih->uri, uri, l) /* no match */
885 || (*c && *c != '/')) { /* substring */
891 if (!*c || urih->has_subtree) {
896 AST_RWLIST_UNLOCK(&uris);
899 ast_debug(1, "Match made with [%s]\n", urih->uri);
900 if (!urih->no_decode_uri) {
901 ast_uri_decode(uri, ast_uri_http_legacy);
903 res = urih->callback(ser, urih, uri, method, get_vars, headers);
905 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
906 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
910 ast_variables_destroy(get_vars);
915 #if defined(HAVE_FUNOPEN)
919 #define HOOK_T ssize_t
924 * replacement read/write functions for SSL support.
925 * We use wrappers rather than SSL_read/SSL_write directly so
926 * we can put in some debugging.
928 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
930 int i = SSL_read(cookie, buf, len-1);
934 ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
939 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
942 char *s = ast_alloca(len+1);
943 strncpy(s, buf, len);
945 ast_verbose("ssl write size %d <%s>\n", (int)len, s);
947 return SSL_write(cookie, buf, len);
950 static int ssl_close(void *cookie)
952 close(SSL_get_fd(cookie));
953 SSL_shutdown(cookie);
959 static struct ast_variable *parse_cookies(char *cookies)
962 struct ast_variable *vars = NULL, *var;
964 while ((cur = strsep(&cookies, ";"))) {
970 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
974 name = ast_strip(name);
975 val = ast_strip_quoted(val, "\"", "\"");
977 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
981 ast_debug(1, "HTTP Cookie, Name: '%s' Value: '%s'\n", name, val);
983 var = ast_variable_new(name, val, __FILE__);
991 /* get cookie from Request headers */
992 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
994 struct ast_variable *v, *cookies=NULL;
996 for (v = headers; v; v = v->next) {
997 if (!strcasecmp(v->name, "Cookie")) {
998 char *tmp = ast_strdupa(v->value);
1000 ast_variables_destroy(cookies);
1003 cookies = parse_cookies(tmp);
1009 static struct ast_http_auth *auth_create(const char *userid,
1010 const char *password)
1012 RAII_VAR(struct ast_http_auth *, auth, NULL, ao2_cleanup);
1014 size_t password_len;
1016 if (!userid || !password) {
1017 ast_log(LOG_ERROR, "Invalid userid/password\n");
1021 userid_len = strlen(userid) + 1;
1022 password_len = strlen(password) + 1;
1024 /* Allocate enough room to store everything in one memory block */
1025 auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
1030 /* Put the userid right after the struct */
1031 auth->userid = (char *)(auth + 1);
1032 strcpy(auth->userid, userid);
1034 /* Put the password right after the userid */
1035 auth->password = auth->userid + userid_len;
1036 strcpy(auth->password, password);
1042 #define BASIC_PREFIX "Basic "
1043 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
1045 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
1047 struct ast_variable *v;
1049 for (v = headers; v; v = v->next) {
1051 char decoded[256] = {};
1056 #endif /* AST_DEVMODE */
1058 if (strcasecmp("Authorization", v->name) != 0) {
1062 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1064 "Unsupported Authorization scheme\n");
1068 /* Basic auth header parsing. RFC 2617, section 2.
1069 * credentials = "Basic" basic-credentials
1070 * basic-credentials = base64-user-pass
1071 * base64-user-pass = <base64 encoding of user-pass,
1072 * except not limited to 76 char/line>
1073 * user-pass = userid ":" password
1076 base64 = v->value + BASIC_LEN;
1078 /* This will truncate "userid:password" lines to
1079 * sizeof(decoded). The array is long enough that this shouldn't
1083 #endif /* AST_DEVMODE */
1084 ast_base64decode((unsigned char*)decoded, base64,
1085 sizeof(decoded) - 1);
1086 ast_assert(cnt < sizeof(decoded));
1088 /* Split the string at the colon */
1090 username = strsep(&password, ":");
1092 ast_log(LOG_WARNING, "Invalid Authorization header\n");
1096 return auth_create(username, password);
1102 static void *httpd_helper_thread(void *data)
1105 char header_line[4096];
1106 struct ast_tcptls_session_instance *ser = data;
1107 struct ast_variable *headers = NULL;
1108 struct ast_variable *tail = headers;
1110 enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1111 const char *transfer_encoding;
1113 if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1117 if (!fgets(buf, sizeof(buf), ser->f)) {
1122 method = ast_skip_blanks(buf);
1123 uri = ast_skip_nonblanks(method);
1128 if (!strcasecmp(method,"GET")) {
1129 http_method = AST_HTTP_GET;
1130 } else if (!strcasecmp(method,"POST")) {
1131 http_method = AST_HTTP_POST;
1132 } else if (!strcasecmp(method,"HEAD")) {
1133 http_method = AST_HTTP_HEAD;
1134 } else if (!strcasecmp(method,"PUT")) {
1135 http_method = AST_HTTP_PUT;
1136 } else if (!strcasecmp(method,"DELETE")) {
1137 http_method = AST_HTTP_DELETE;
1138 } else if (!strcasecmp(method,"OPTIONS")) {
1139 http_method = AST_HTTP_OPTIONS;
1142 uri = ast_skip_blanks(uri); /* Skip white space */
1144 if (*uri) { /* terminate at the first blank */
1145 char *c = ast_skip_nonblanks(uri);
1152 /* process "Request Headers" lines */
1153 while (fgets(header_line, sizeof(header_line), ser->f)) {
1156 /* Trim trailing characters */
1157 ast_trim_blanks(header_line);
1158 if (ast_strlen_zero(header_line)) {
1162 value = header_line;
1163 name = strsep(&value, ":");
1168 value = ast_skip_blanks(value);
1169 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1173 ast_trim_blanks(name);
1176 headers = ast_variable_new(name, value, __FILE__);
1179 tail->next = ast_variable_new(name, value, __FILE__);
1184 transfer_encoding = get_transfer_encoding(headers);
1185 /* Transfer encoding defaults to identity */
1186 if (!transfer_encoding) {
1187 transfer_encoding = "identity";
1191 * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
1192 * codings we don't understand.
1194 if (strcasecmp(transfer_encoding, "identity") != 0) {
1195 /* Transfer encodings not supported */
1196 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
1201 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1205 handle_uri(ser, uri, http_method, headers);
1208 ast_atomic_fetchadd_int(&session_count, -1);
1210 /* clean up all the header information */
1212 ast_variables_destroy(headers);
1224 * \brief Add a new URI redirect
1225 * The entries in the redirect list are sorted by length, just like the list
1228 static void add_redirect(const char *value)
1230 char *target, *dest;
1231 struct http_uri_redirect *redirect, *cur;
1232 unsigned int target_len;
1233 unsigned int total_len;
1235 dest = ast_strdupa(value);
1236 dest = ast_skip_blanks(dest);
1237 target = strsep(&dest, " ");
1238 target = ast_skip_blanks(target);
1239 target = strsep(&target, " "); /* trim trailing whitespace */
1242 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
1246 target_len = strlen(target) + 1;
1247 total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
1249 if (!(redirect = ast_calloc(1, total_len))) {
1252 redirect->dest = redirect->target + target_len;
1253 strcpy(redirect->target, target);
1254 strcpy(redirect->dest, dest);
1256 AST_RWLIST_WRLOCK(&uri_redirects);
1258 target_len--; /* So we can compare directly with strlen() */
1259 if (AST_RWLIST_EMPTY(&uri_redirects)
1260 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1261 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1262 AST_RWLIST_UNLOCK(&uri_redirects);
1267 AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1268 if (AST_RWLIST_NEXT(cur, entry)
1269 && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1270 AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1271 AST_RWLIST_UNLOCK(&uri_redirects);
1276 AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1278 AST_RWLIST_UNLOCK(&uri_redirects);
1281 static int __ast_http_load(int reload)
1283 struct ast_config *cfg;
1284 struct ast_variable *v;
1286 int newenablestatic=0;
1287 char newprefix[MAX_PREFIX] = "";
1288 struct http_uri_redirect *redirect;
1289 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1290 uint32_t bindport = DEFAULT_PORT;
1291 RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1293 int http_tls_was_enabled = 0;
1295 cfg = ast_config_load2("http.conf", "http", config_flags);
1296 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1300 http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1302 http_tls_cfg.enabled = 0;
1303 if (http_tls_cfg.certfile) {
1304 ast_free(http_tls_cfg.certfile);
1306 http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1308 if (http_tls_cfg.pvtfile) {
1309 ast_free(http_tls_cfg.pvtfile);
1311 http_tls_cfg.pvtfile = ast_strdup("");
1313 if (http_tls_cfg.cipher) {
1314 ast_free(http_tls_cfg.cipher);
1316 http_tls_cfg.cipher = ast_strdup("");
1318 AST_RWLIST_WRLOCK(&uri_redirects);
1319 while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1322 AST_RWLIST_UNLOCK(&uri_redirects);
1324 ast_sockaddr_setnull(&https_desc.local_address);
1327 v = ast_variable_browse(cfg, "general");
1328 for (; v; v = v->next) {
1330 /* read tls config options while preventing unsupported options from being set */
1331 if (strcasecmp(v->name, "tlscafile")
1332 && strcasecmp(v->name, "tlscapath")
1333 && strcasecmp(v->name, "tlscadir")
1334 && strcasecmp(v->name, "tlsverifyclient")
1335 && strcasecmp(v->name, "tlsdontverifyserver")
1336 && strcasecmp(v->name, "tlsclientmethod")
1337 && strcasecmp(v->name, "sslclientmethod")
1338 && strcasecmp(v->name, "tlscipher")
1339 && strcasecmp(v->name, "sslcipher")
1340 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1344 if (!strcasecmp(v->name, "enabled")) {
1345 enabled = ast_true(v->value);
1346 } else if (!strcasecmp(v->name, "enablestatic")) {
1347 newenablestatic = ast_true(v->value);
1348 } else if (!strcasecmp(v->name, "bindport")) {
1349 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1350 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1352 } else if (!strcasecmp(v->name, "bindaddr")) {
1353 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1354 ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1356 } else if (!strcasecmp(v->name, "prefix")) {
1357 if (!ast_strlen_zero(v->value)) {
1359 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1361 newprefix[0] = '\0';
1363 } else if (!strcasecmp(v->name, "redirect")) {
1364 add_redirect(v->value);
1365 } else if (!strcasecmp(v->name, "sessionlimit")) {
1366 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1367 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1368 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1369 v->name, v->value, v->lineno);
1372 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1376 ast_config_destroy(cfg);
1379 if (strcmp(prefix, newprefix)) {
1380 ast_copy_string(prefix, newprefix, sizeof(prefix));
1382 enablestatic = newenablestatic;
1384 if (num_addrs && enabled) {
1386 for (i = 0; i < num_addrs; ++i) {
1387 ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1388 if (!ast_sockaddr_port(&http_desc.local_address)) {
1389 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1391 ast_tcptls_server_start(&http_desc);
1392 if (http_desc.accept_fd == -1) {
1393 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1394 ast_sockaddr_setnull(&http_desc.local_address);
1396 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1400 /* When no specific TLS bindaddr is specified, we just use
1401 * the non-TLS bindaddress here.
1403 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1404 ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1405 /* Of course, we can't use the same port though.
1406 * Since no bind address was specified, we just use the
1409 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1412 if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1413 ast_tcptls_server_stop(&https_desc);
1414 } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1415 /* We can get here either because a TLS-specific address was specified
1416 * or because we copied the non-TLS address here. In the case where
1417 * we read an explicit address from the config, there may have been
1418 * no port specified, so we'll just use the default TLS port.
1420 if (!ast_sockaddr_port(&https_desc.local_address)) {
1421 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1423 if (ast_ssl_setup(https_desc.tls_cfg)) {
1424 ast_tcptls_server_start(&https_desc);
1431 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1433 struct ast_http_uri *urih;
1434 struct http_uri_redirect *redirect;
1438 e->command = "http show status";
1440 "Usage: http show status\n"
1441 " Lists status of internal HTTP engine\n";
1448 return CLI_SHOWUSAGE;
1450 ast_cli(a->fd, "HTTP Server Status:\n");
1451 ast_cli(a->fd, "Prefix: %s\n", prefix);
1452 if (ast_sockaddr_isnull(&http_desc.old_address)) {
1453 ast_cli(a->fd, "Server Disabled\n\n");
1455 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1456 ast_sockaddr_stringify(&http_desc.old_address));
1457 if (http_tls_cfg.enabled) {
1458 ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1459 ast_sockaddr_stringify(&https_desc.old_address));
1463 ast_cli(a->fd, "Enabled URI's:\n");
1464 AST_RWLIST_RDLOCK(&uris);
1465 if (AST_RWLIST_EMPTY(&uris)) {
1466 ast_cli(a->fd, "None.\n");
1468 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1469 ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1471 AST_RWLIST_UNLOCK(&uris);
1473 ast_cli(a->fd, "\nEnabled Redirects:\n");
1474 AST_RWLIST_RDLOCK(&uri_redirects);
1475 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1476 ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
1477 if (AST_RWLIST_EMPTY(&uri_redirects)) {
1478 ast_cli(a->fd, " None.\n");
1480 AST_RWLIST_UNLOCK(&uri_redirects);
1485 int ast_http_reload(void)
1487 return __ast_http_load(1);
1490 static struct ast_cli_entry cli_http[] = {
1491 AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1494 static void http_shutdown(void)
1496 struct http_uri_redirect *redirect;
1497 ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1499 ast_tcptls_server_stop(&http_desc);
1500 if (http_tls_cfg.enabled) {
1501 ast_tcptls_server_stop(&https_desc);
1503 ast_free(http_tls_cfg.certfile);
1504 ast_free(http_tls_cfg.pvtfile);
1505 ast_free(http_tls_cfg.cipher);
1507 ast_http_uri_unlink(&statusuri);
1508 ast_http_uri_unlink(&staticuri);
1510 AST_RWLIST_WRLOCK(&uri_redirects);
1511 while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1514 AST_RWLIST_UNLOCK(&uri_redirects);
1517 int ast_http_init(void)
1519 ast_http_uri_link(&statusuri);
1520 ast_http_uri_link(&staticuri);
1521 ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1522 ast_register_atexit(http_shutdown);
1524 return __ast_http_load(0);