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" },
156 { AST_HTTP_DELETE, "DELETE" },
157 { AST_HTTP_OPTIONS, "OPTIONS" },
160 const char *ast_get_http_method(enum ast_http_method method)
164 for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
165 if (ast_http_methods_text[x].method == method) {
166 return ast_http_methods_text[x].text;
173 const char *ast_http_ftype2mtype(const char *ftype)
178 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
179 if (!strcasecmp(ftype, mimetypes[x].ext)) {
180 return mimetypes[x].mtype;
187 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
190 struct ast_variable *v, *cookies;
192 cookies = ast_http_get_cookies(headers);
193 for (v = cookies; v; v = v->next) {
194 if (!strcasecmp(v->name, "mansession_id")) {
195 sscanf(v->value, "%30x", &mngid);
200 ast_variables_destroy(cookies);
205 void ast_http_prefix(char *buf, int len)
208 ast_copy_string(buf, prefix, len);
212 static int static_callback(struct ast_tcptls_session_instance *ser,
213 const struct ast_http_uri *urih, const char *uri,
214 enum ast_http_method method, struct ast_variable *get_vars,
215 struct ast_variable *headers)
224 struct ast_str *http_header;
227 char timebuf[80], etag[23];
228 struct ast_variable *v;
229 int not_modified = 0;
231 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
232 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
236 /* Yuck. I'm not really sold on this, but if you don't deliver static content it makes your configuration
237 substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
238 if (!enablestatic || ast_strlen_zero(uri)) {
242 /* Disallow any funny filenames at all (checking first character only??) */
243 if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
247 if (strstr(uri, "/..")) {
251 if ((ftype = strrchr(uri, '.'))) {
255 if (!(mtype = ast_http_ftype2mtype(ftype))) {
256 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
260 /* Cap maximum length */
261 if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
265 path = ast_alloca(len);
266 sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
267 if (stat(path, &st)) {
271 if (S_ISDIR(st.st_mode)) {
275 if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
279 fd = open(path, O_RDONLY);
284 /* make "Etag:" http header value */
285 snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
287 /* make "Last-Modified:" http header value */
288 tv.tv_sec = st.st_mtime;
290 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
292 /* check received "If-None-Match" request header and Etag value for file */
293 for (v = headers; v; v = v->next) {
294 if (!strcasecmp(v->name, "If-None-Match")) {
295 if (!strcasecmp(v->value, etag)) {
302 if ( (http_header = ast_str_create(255)) == NULL) {
307 ast_str_set(&http_header, 0, "Content-type: %s\r\n"
309 "Last-Modified: %s\r\n",
314 /* ast_http_send() frees http_header, so we don't need to do it before returning */
316 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
318 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
324 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
328 ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
332 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
333 const struct ast_http_uri *urih, const char *uri,
334 enum ast_http_method method, struct ast_variable *get_vars,
335 struct ast_variable *headers)
338 struct ast_variable *v, *cookies = NULL;
340 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
341 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
345 if ( (out = ast_str_create(512)) == NULL) {
349 ast_str_append(&out, 0,
350 "<title>Asterisk HTTP Status</title>\r\n"
351 "<body bgcolor=\"#ffffff\">\r\n"
352 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
353 "<h2> Asterisk™ HTTP Status</h2></td></tr>\r\n");
355 ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
356 ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
357 ast_sockaddr_stringify_addr(&http_desc.old_address));
358 ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
359 ast_sockaddr_stringify_port(&http_desc.old_address));
360 if (http_tls_cfg.enabled) {
361 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
362 ast_sockaddr_stringify_port(&https_desc.old_address));
364 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
365 for (v = get_vars; v; v = v->next) {
366 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
368 ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
370 cookies = ast_http_get_cookies(headers);
371 for (v = cookies; v; v = v->next) {
372 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
374 ast_variables_destroy(cookies);
376 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");
377 ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
381 static struct ast_http_uri statusuri = {
382 .callback = httpstatus_callback,
383 .description = "Asterisk HTTP General Status",
390 static struct ast_http_uri staticuri = {
391 .callback = static_callback,
392 .description = "Asterisk HTTP Static Delivery",
400 /* send http/1.1 response */
401 /* free content variable and close socket*/
402 void ast_http_send(struct ast_tcptls_session_instance *ser,
403 enum ast_http_method method, int status_code, const char *status_title,
404 struct ast_str *http_header, struct ast_str *out, const int fd,
405 unsigned int static_content)
407 struct timeval now = ast_tvnow();
410 int content_length = 0;
412 if (!ser || 0 == ser->f) {
416 ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
418 /* calc content length */
420 content_length += strlen(ast_str_buffer(out));
424 content_length += lseek(fd, 0, SEEK_END);
425 lseek(fd, 0, SEEK_SET);
428 /* send http header */
429 fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
430 "Server: Asterisk/%s\r\n"
432 "Connection: close\r\n"
434 "Content-Length: %d\r\n"
437 status_code, status_title ? status_title : "OK",
440 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
442 http_header ? ast_str_buffer(http_header) : ""
446 if (method != AST_HTTP_HEAD || status_code >= 400) {
448 fprintf(ser->f, "%s", ast_str_buffer(out));
454 while ((len = read(fd, buf, sizeof(buf))) > 0) {
455 if (fwrite(buf, len, 1, ser->f) != 1) {
456 ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
464 ast_free(http_header);
475 /* Send http "401 Unauthorized" responce and close socket*/
476 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
477 const unsigned long nonce, const unsigned long opaque, int stale,
480 struct ast_str *http_headers = ast_str_create(128);
481 struct ast_str *out = ast_str_create(512);
483 if (!http_headers || !out) {
484 ast_free(http_headers);
489 ast_str_set(&http_headers, 0,
490 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
491 "Content-type: text/html\r\n",
492 realm ? realm : "Asterisk",
495 stale ? ", stale=true" : "");
498 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
500 "<title>401 Unauthorized</title>\r\n"
502 "<h1>401 Unauthorized</h1>\r\n"
505 "<address>Asterisk Server</address>\r\n"
506 "</body></html>\r\n",
509 ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
513 /* send http error response and close socket*/
514 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
516 struct ast_str *http_headers = ast_str_create(40);
517 struct ast_str *out = ast_str_create(256);
519 if (!http_headers || !out) {
520 ast_free(http_headers);
525 ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
528 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
530 "<title>%d %s</title>\r\n"
535 "<address>Asterisk Server</address>\r\n"
536 "</body></html>\r\n",
537 status_code, status_title, status_title, text);
539 ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
544 * Link the new uri into the list.
546 * They are sorted by length of
547 * the string, not alphabetically. Duplicate entries are not replaced,
548 * but the insertion order (using <= and not just <) makes sure that
549 * more recent insertions hide older ones.
550 * On a lookup, we just scan the list and stop at the first matching entry.
552 int ast_http_uri_link(struct ast_http_uri *urih)
554 struct ast_http_uri *uri;
555 int len = strlen(urih->uri);
557 AST_RWLIST_WRLOCK(&uris);
559 if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
560 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
561 AST_RWLIST_UNLOCK(&uris);
565 AST_RWLIST_TRAVERSE(&uris, uri, entry) {
566 if (AST_RWLIST_NEXT(uri, entry) &&
567 strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
568 AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
569 AST_RWLIST_UNLOCK(&uris);
575 AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
577 AST_RWLIST_UNLOCK(&uris);
582 void ast_http_uri_unlink(struct ast_http_uri *urih)
584 AST_RWLIST_WRLOCK(&uris);
585 AST_RWLIST_REMOVE(&uris, urih, entry);
586 AST_RWLIST_UNLOCK(&uris);
589 void ast_http_uri_unlink_all_with_key(const char *key)
591 struct ast_http_uri *urih;
592 AST_RWLIST_WRLOCK(&uris);
593 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
594 if (!strcmp(urih->key, key)) {
595 AST_RWLIST_REMOVE_CURRENT(entry);
596 if (urih->dmallocd) {
597 ast_free(urih->data);
604 AST_RWLIST_TRAVERSE_SAFE_END;
605 AST_RWLIST_UNLOCK(&uris);
608 #define MAX_POST_CONTENT 1025
611 * get post variables from client Request Entity-Body, if content type is
612 * application/x-www-form-urlencoded
614 struct ast_variable *ast_http_get_post_vars(
615 struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
617 int content_length = 0;
618 struct ast_variable *v, *post_vars=NULL, *prev = NULL;
619 char *buf, *var, *val;
622 for (v = headers; v; v = v->next) {
623 if (!strcasecmp(v->name, "Content-Type")) {
624 if (strcasecmp(v->value, "application/x-www-form-urlencoded")) {
631 for (v = headers; v; v = v->next) {
632 if (!strcasecmp(v->name, "Content-Length")) {
633 content_length = atoi(v->value);
638 if (content_length <= 0) {
642 if (content_length > MAX_POST_CONTENT - 1) {
643 ast_log(LOG_WARNING, "Excessively long HTTP content. %d is greater than our max of %d\n",
644 content_length, MAX_POST_CONTENT);
645 ast_http_send(ser, AST_HTTP_POST, 413, "Request Entity Too Large", NULL, NULL, 0, 0);
649 buf = ast_malloc(content_length + 1);
654 res = fread(buf, 1, content_length, ser->f);
655 if (res < content_length) {
656 /* Error, distinguishable by ferror() or feof(), but neither
660 buf[content_length] = '\0';
662 while ((val = strsep(&buf, "&"))) {
663 var = strsep(&val, "=");
665 ast_uri_decode(val, ast_uri_http_legacy);
669 ast_uri_decode(var, ast_uri_http_legacy);
670 if ((v = ast_variable_new(var, val, ""))) {
685 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
686 enum ast_http_method method, struct ast_variable *headers)
691 struct ast_http_uri *urih = NULL;
693 struct ast_variable *get_vars = NULL, *v, *prev = NULL;
694 struct http_uri_redirect *redirect;
696 ast_debug(2, "HTTP Request URI is %s \n", uri);
698 strsep(¶ms, "?");
699 /* Extract arguments from the request and store them in variables. */
703 while ((val = strsep(¶ms, "&"))) {
704 var = strsep(&val, "=");
706 ast_uri_decode(val, ast_uri_http_legacy);
710 ast_uri_decode(var, ast_uri_http_legacy);
711 if ((v = ast_variable_new(var, val, ""))) {
722 AST_RWLIST_RDLOCK(&uri_redirects);
723 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
724 if (!strcasecmp(uri, redirect->target)) {
725 struct ast_str *http_header = ast_str_create(128);
726 ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
727 ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
732 AST_RWLIST_UNLOCK(&uri_redirects);
737 /* We want requests to start with the (optional) prefix and '/' */
739 if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
741 /* scan registered uris to see if we match one. */
742 AST_RWLIST_RDLOCK(&uris);
743 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
744 l = strlen(urih->uri);
745 c = uri + l; /* candidate */
746 ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
747 if (strncasecmp(urih->uri, uri, l) /* no match */
748 || (*c && *c != '/')) { /* substring */
754 if (!*c || urih->has_subtree) {
759 AST_RWLIST_UNLOCK(&uris);
762 ast_debug(1, "Match made with [%s]\n", urih->uri);
763 if (!urih->no_decode_uri) {
764 ast_uri_decode(uri, ast_uri_http_legacy);
766 res = urih->callback(ser, urih, uri, method, get_vars, headers);
768 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
769 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
773 ast_variables_destroy(get_vars);
778 #if defined(HAVE_FUNOPEN)
782 #define HOOK_T ssize_t
787 * replacement read/write functions for SSL support.
788 * We use wrappers rather than SSL_read/SSL_write directly so
789 * we can put in some debugging.
791 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
793 int i = SSL_read(cookie, buf, len-1);
797 ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
802 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
805 char *s = ast_alloca(len+1);
806 strncpy(s, buf, len);
808 ast_verbose("ssl write size %d <%s>\n", (int)len, s);
810 return SSL_write(cookie, buf, len);
813 static int ssl_close(void *cookie)
815 close(SSL_get_fd(cookie));
816 SSL_shutdown(cookie);
822 static struct ast_variable *parse_cookies(char *cookies)
825 struct ast_variable *vars = NULL, *var;
827 while ((cur = strsep(&cookies, ";"))) {
833 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
837 name = ast_strip(name);
838 val = ast_strip_quoted(val, "\"", "\"");
840 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
844 ast_debug(1, "HTTP Cookie, Name: '%s' Value: '%s'\n", name, val);
846 var = ast_variable_new(name, val, __FILE__);
854 /* get cookie from Request headers */
855 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
857 struct ast_variable *v, *cookies=NULL;
859 for (v = headers; v; v = v->next) {
860 if (!strcasecmp(v->name, "Cookie")) {
861 char *tmp = ast_strdupa(v->value);
863 ast_variables_destroy(cookies);
866 cookies = parse_cookies(tmp);
872 static struct ast_http_auth *auth_create(const char *userid,
873 const char *password)
875 RAII_VAR(struct ast_http_auth *, auth, NULL, ao2_cleanup);
879 if (!userid || !password) {
880 ast_log(LOG_ERROR, "Invalid userid/password\n");
884 userid_len = strlen(userid) + 1;
885 password_len = strlen(password) + 1;
887 /* Allocate enough room to store everything in one memory block */
888 auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
893 /* Put the userid right after the struct */
894 auth->userid = (char *)(auth + 1);
895 strcpy(auth->userid, userid);
897 /* Put the password right after the userid */
898 auth->password = auth->userid + userid_len;
899 strcpy(auth->password, password);
905 #define BASIC_PREFIX "Basic "
906 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
908 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
910 struct ast_variable *v;
912 for (v = headers; v; v = v->next) {
914 char decoded[256] = {};
919 if (strcasecmp("Authorization", v->name) != 0) {
923 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
925 "Unsupported Authorization scheme\n");
929 /* Basic auth header parsing. RFC 2617, section 2.
930 * credentials = "Basic" basic-credentials
931 * basic-credentials = base64-user-pass
932 * base64-user-pass = <base64 encoding of user-pass,
933 * except not limited to 76 char/line>
934 * user-pass = userid ":" password
937 base64 = v->value + BASIC_LEN;
939 /* This will truncate "userid:password" lines to
940 * sizeof(decoded). The array is long enough that this shouldn't
942 cnt = ast_base64decode((unsigned char*)decoded, base64,
943 sizeof(decoded) - 1);
944 ast_assert(cnt < sizeof(decoded));
946 /* Split the string at the colon */
948 username = strsep(&password, ":");
950 ast_log(LOG_WARNING, "Invalid Authorization header\n");
954 return auth_create(username, password);
960 static void *httpd_helper_thread(void *data)
963 char header_line[4096];
964 struct ast_tcptls_session_instance *ser = data;
965 struct ast_variable *headers = NULL;
966 struct ast_variable *tail = headers;
968 enum ast_http_method http_method = AST_HTTP_UNKNOWN;
970 if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
974 if (!fgets(buf, sizeof(buf), ser->f)) {
979 method = ast_skip_blanks(buf);
980 uri = ast_skip_nonblanks(method);
985 if (!strcasecmp(method,"GET")) {
986 http_method = AST_HTTP_GET;
987 } else if (!strcasecmp(method,"POST")) {
988 http_method = AST_HTTP_POST;
989 } else if (!strcasecmp(method,"HEAD")) {
990 http_method = AST_HTTP_HEAD;
991 } else if (!strcasecmp(method,"PUT")) {
992 http_method = AST_HTTP_PUT;
993 } else if (!strcasecmp(method,"DELETE")) {
994 http_method = AST_HTTP_DELETE;
995 } else if (!strcasecmp(method,"OPTIONS")) {
996 http_method = AST_HTTP_OPTIONS;
999 uri = ast_skip_blanks(uri); /* Skip white space */
1001 if (*uri) { /* terminate at the first blank */
1002 char *c = ast_skip_nonblanks(uri);
1009 /* process "Request Headers" lines */
1010 while (fgets(header_line, sizeof(header_line), ser->f)) {
1013 /* Trim trailing characters */
1014 ast_trim_blanks(header_line);
1015 if (ast_strlen_zero(header_line)) {
1019 value = header_line;
1020 name = strsep(&value, ":");
1025 value = ast_skip_blanks(value);
1026 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1030 ast_trim_blanks(name);
1033 headers = ast_variable_new(name, value, __FILE__);
1036 tail->next = ast_variable_new(name, value, __FILE__);
1042 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1046 handle_uri(ser, uri, http_method, headers);
1049 ast_atomic_fetchadd_int(&session_count, -1);
1051 /* clean up all the header information */
1053 ast_variables_destroy(headers);
1065 * \brief Add a new URI redirect
1066 * The entries in the redirect list are sorted by length, just like the list
1069 static void add_redirect(const char *value)
1071 char *target, *dest;
1072 struct http_uri_redirect *redirect, *cur;
1073 unsigned int target_len;
1074 unsigned int total_len;
1076 dest = ast_strdupa(value);
1077 dest = ast_skip_blanks(dest);
1078 target = strsep(&dest, " ");
1079 target = ast_skip_blanks(target);
1080 target = strsep(&target, " "); /* trim trailing whitespace */
1083 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
1087 target_len = strlen(target) + 1;
1088 total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
1090 if (!(redirect = ast_calloc(1, total_len))) {
1093 redirect->dest = redirect->target + target_len;
1094 strcpy(redirect->target, target);
1095 strcpy(redirect->dest, dest);
1097 AST_RWLIST_WRLOCK(&uri_redirects);
1099 target_len--; /* So we can compare directly with strlen() */
1100 if (AST_RWLIST_EMPTY(&uri_redirects)
1101 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1102 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1103 AST_RWLIST_UNLOCK(&uri_redirects);
1108 AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1109 if (AST_RWLIST_NEXT(cur, entry)
1110 && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1111 AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1112 AST_RWLIST_UNLOCK(&uri_redirects);
1117 AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1119 AST_RWLIST_UNLOCK(&uri_redirects);
1122 static int __ast_http_load(int reload)
1124 struct ast_config *cfg;
1125 struct ast_variable *v;
1127 int newenablestatic=0;
1128 char newprefix[MAX_PREFIX] = "";
1129 struct http_uri_redirect *redirect;
1130 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1131 uint32_t bindport = DEFAULT_PORT;
1132 RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1134 int http_tls_was_enabled = 0;
1136 cfg = ast_config_load2("http.conf", "http", config_flags);
1137 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1141 http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1143 http_tls_cfg.enabled = 0;
1144 if (http_tls_cfg.certfile) {
1145 ast_free(http_tls_cfg.certfile);
1147 http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1149 if (http_tls_cfg.pvtfile) {
1150 ast_free(http_tls_cfg.pvtfile);
1152 http_tls_cfg.pvtfile = ast_strdup("");
1154 if (http_tls_cfg.cipher) {
1155 ast_free(http_tls_cfg.cipher);
1157 http_tls_cfg.cipher = ast_strdup("");
1159 AST_RWLIST_WRLOCK(&uri_redirects);
1160 while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1163 AST_RWLIST_UNLOCK(&uri_redirects);
1165 ast_sockaddr_setnull(&https_desc.local_address);
1168 v = ast_variable_browse(cfg, "general");
1169 for (; v; v = v->next) {
1171 /* read tls config options while preventing unsupported options from being set */
1172 if (strcasecmp(v->name, "tlscafile")
1173 && strcasecmp(v->name, "tlscapath")
1174 && strcasecmp(v->name, "tlscadir")
1175 && strcasecmp(v->name, "tlsverifyclient")
1176 && strcasecmp(v->name, "tlsdontverifyserver")
1177 && strcasecmp(v->name, "tlsclientmethod")
1178 && strcasecmp(v->name, "sslclientmethod")
1179 && strcasecmp(v->name, "tlscipher")
1180 && strcasecmp(v->name, "sslcipher")
1181 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1185 if (!strcasecmp(v->name, "enabled")) {
1186 enabled = ast_true(v->value);
1187 } else if (!strcasecmp(v->name, "enablestatic")) {
1188 newenablestatic = ast_true(v->value);
1189 } else if (!strcasecmp(v->name, "bindport")) {
1190 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1191 ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1193 } else if (!strcasecmp(v->name, "bindaddr")) {
1194 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1195 ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1197 } else if (!strcasecmp(v->name, "prefix")) {
1198 if (!ast_strlen_zero(v->value)) {
1200 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1202 newprefix[0] = '\0';
1204 } else if (!strcasecmp(v->name, "redirect")) {
1205 add_redirect(v->value);
1206 } else if (!strcasecmp(v->name, "sessionlimit")) {
1207 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1208 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1209 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1210 v->name, v->value, v->lineno);
1213 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1217 ast_config_destroy(cfg);
1220 if (strcmp(prefix, newprefix)) {
1221 ast_copy_string(prefix, newprefix, sizeof(prefix));
1223 enablestatic = newenablestatic;
1225 if (num_addrs && enabled) {
1227 for (i = 0; i < num_addrs; ++i) {
1228 ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1229 if (!ast_sockaddr_port(&http_desc.local_address)) {
1230 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1232 ast_tcptls_server_start(&http_desc);
1233 if (http_desc.accept_fd == -1) {
1234 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1235 ast_sockaddr_setnull(&http_desc.local_address);
1237 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1241 /* When no specific TLS bindaddr is specified, we just use
1242 * the non-TLS bindaddress here.
1244 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1245 ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1246 /* Of course, we can't use the same port though.
1247 * Since no bind address was specified, we just use the
1250 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1253 if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1254 ast_tcptls_server_stop(&https_desc);
1255 } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1256 /* We can get here either because a TLS-specific address was specified
1257 * or because we copied the non-TLS address here. In the case where
1258 * we read an explicit address from the config, there may have been
1259 * no port specified, so we'll just use the default TLS port.
1261 if (!ast_sockaddr_port(&https_desc.local_address)) {
1262 ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1264 if (ast_ssl_setup(https_desc.tls_cfg)) {
1265 ast_tcptls_server_start(&https_desc);
1272 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1274 struct ast_http_uri *urih;
1275 struct http_uri_redirect *redirect;
1279 e->command = "http show status";
1281 "Usage: http show status\n"
1282 " Lists status of internal HTTP engine\n";
1289 return CLI_SHOWUSAGE;
1291 ast_cli(a->fd, "HTTP Server Status:\n");
1292 ast_cli(a->fd, "Prefix: %s\n", prefix);
1293 if (ast_sockaddr_isnull(&http_desc.old_address)) {
1294 ast_cli(a->fd, "Server Disabled\n\n");
1296 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1297 ast_sockaddr_stringify(&http_desc.old_address));
1298 if (http_tls_cfg.enabled) {
1299 ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1300 ast_sockaddr_stringify(&https_desc.old_address));
1304 ast_cli(a->fd, "Enabled URI's:\n");
1305 AST_RWLIST_RDLOCK(&uris);
1306 if (AST_RWLIST_EMPTY(&uris)) {
1307 ast_cli(a->fd, "None.\n");
1309 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1310 ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1312 AST_RWLIST_UNLOCK(&uris);
1314 ast_cli(a->fd, "\nEnabled Redirects:\n");
1315 AST_RWLIST_RDLOCK(&uri_redirects);
1316 AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1317 ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
1318 if (AST_RWLIST_EMPTY(&uri_redirects)) {
1319 ast_cli(a->fd, " None.\n");
1321 AST_RWLIST_UNLOCK(&uri_redirects);
1326 int ast_http_reload(void)
1328 return __ast_http_load(1);
1331 static struct ast_cli_entry cli_http[] = {
1332 AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1335 static void http_shutdown(void)
1337 ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1340 int ast_http_init(void)
1342 ast_http_uri_link(&statusuri);
1343 ast_http_uri_link(&staticuri);
1344 ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1345 ast_register_atexit(http_shutdown);
1347 return __ast_http_load(0);