69 #define DEFAULT_PORT 8088
70 #define DEFAULT_TLS_PORT 8089
71 #define DEFAULT_SESSION_LIMIT 100
73 #define DEFAULT_SESSION_INACTIVITY 30000
75 #define MIN_INITIAL_REQUEST_TIMEOUT 10000
77 #define DEFAULT_SESSION_KEEP_ALIVE 15000
79 #define MAX_SERVER_NAME_LENGTH 128
81 #define DEFAULT_RESPONSE_HEADER_LENGTH 512
84 #if !defined(LOW_MEMORY)
85 #define MAX_CONTENT_LENGTH 40960
87 #define MAX_CONTENT_LENGTH 1024
91 #if !defined(LOW_MEMORY)
92 #define INITIAL_RESPONSE_BODY_BUFFER 1024
94 #define INITIAL_RESPONSE_BODY_BUFFER 512
98 #if !defined(LOW_MEMORY)
99 #define MAX_HTTP_LINE_LENGTH 4096
101 #define MAX_HTTP_LINE_LENGTH 1024
106 static int session_limit = DEFAULT_SESSION_LIMIT;
109 static int session_count = 0;
113 static void *httpd_helper_thread(
void *arg);
133 .master = AST_PTHREADT_NULL,
134 .tls_cfg = &http_tls_cfg,
136 .name =
"https server",
137 .accept_fn = ast_tcptls_server_root,
138 .worker_fn = httpd_helper_thread,
144 static char prefix[MAX_PREFIX];
145 static int static_uri_enabled;
146 static int status_uri_enabled;
153 {
"png",
"image/png" },
154 {
"xml",
"text/xml" },
155 {
"jpg",
"image/jpeg" },
156 {
"js",
"application/x-javascript" },
157 {
"wav",
"audio/x-wav" },
158 {
"mp3",
"audio/mpeg" },
159 {
"svg",
"image/svg+xml" },
160 {
"svgz",
"image/svg+xml" },
161 {
"gif",
"image/gif" },
162 {
"html",
"text/html" },
163 {
"htm",
"text/html" },
164 {
"css",
"text/css" },
165 {
"cnf",
"text/plain" },
166 {
"cfg",
"text/plain" },
167 {
"bin",
"application/octet-stream" },
168 {
"sbn",
"application/octet-stream" },
169 {
"ld",
"application/octet-stream" },
183 } ast_http_methods_text[] = {
185 { AST_HTTP_GET,
"GET" },
186 { AST_HTTP_POST,
"POST" },
187 { AST_HTTP_HEAD,
"HEAD" },
188 { AST_HTTP_PUT,
"PUT" },
189 { AST_HTTP_DELETE,
"DELETE" },
190 { AST_HTTP_OPTIONS,
"OPTIONS" },
197 for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
198 if (ast_http_methods_text[x].method == method) {
199 return ast_http_methods_text[x].text;
211 for (x = 0; x < ARRAY_LEN(
mimetypes); x++) {
212 if (!strcasecmp(ftype,
mimetypes[x].ext)) {
226 for (v = cookies; v; v = v->
next) {
227 if (!strcasecmp(v->
name,
"mansession_id")) {
228 sscanf(v->
value,
"%30x", &mngid);
258 char timebuf[80], etag[23];
260 int not_modified = 0;
262 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
263 ast_http_error(ser, 501,
"Not Implemented",
"Attempt to use unimplemented / unsupported method");
273 if (ast_strlen_zero(uri)) {
278 if ((uri[0] < 33) || strchr(
"./|~@#$%^&*() \t", uri[0])) {
282 if (strstr(uri,
"/..")) {
286 if ((ftype = strrchr(uri,
'.'))) {
291 snprintf(wkspace,
sizeof(wkspace),
"text/%s",
S_OR(ftype,
"plain"));
296 if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen(
"/static-http/") + 5) > 1024) {
301 sprintf(path,
"%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
302 if (stat(path, &st)) {
306 if (S_ISDIR(st.st_mode)) {
314 fd = open(path, O_RDONLY);
320 snprintf(etag,
sizeof(etag),
"\"%ld\"", (
long)st.st_mtime);
323 tv.tv_sec = st.st_mtime;
328 for (v = headers; v; v = v->
next) {
329 if (!strcasecmp(v->
name,
"If-None-Match")) {
330 if (!strcasecmp(v->
value, etag)) {
345 ast_str_set(&http_header, 0,
"Content-type: %s\r\n"
347 "Last-Modified: %s\r\n",
354 ast_http_send(ser, method, 304,
"Not Modified", http_header, NULL, 0, 1);
356 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1);
362 ast_http_error(ser, 404,
"Not Found",
"The requested URL was not found on this server.");
367 ast_http_error(ser, 403,
"Access Denied",
"You do not have permission to access the requested URL.");
379 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
380 ast_http_error(ser, 501,
"Not Implemented",
"Attempt to use unimplemented / unsupported method");
392 "<html><title>Asterisk HTTP Status</title>\r\n"
393 "<body bgcolor=\"#ffffff\">\r\n"
394 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
395 "<h2> Asterisk™ HTTP Status</h2></td></tr>\r\n");
397 ast_str_append(&out, 0,
"<tr><td><i>Server</i></td><td><b>%s</b></td></tr>\r\n", http_server_name);
398 ast_str_append(&out, 0,
"<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
399 if (global_http_server) {
400 ast_str_append(&out, 0,
"<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
403 if (http_tls_cfg.enabled) {
404 ast_str_append(&out, 0,
"<tr><td><i>TLS Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
407 ast_str_append(&out, 0,
"<tr><td colspan=\"2\"><hr></td></tr>\r\n");
408 for (v = get_vars; v; v = v->
next) {
409 ast_str_append(&out, 0,
"<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->
name, v->
value);
411 ast_str_append(&out, 0,
"<tr><td colspan=\"2\"><hr></td></tr>\r\n");
414 for (v = cookies; v; v = v->
next) {
419 ast_str_append(&out, 0,
"</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body></html>\r\n");
425 .callback = httpstatus_callback,
426 .description =
"Asterisk HTTP General Status",
434 .callback = static_callback,
435 .description =
"Asterisk HTTP Static Delivery",
460 enum ast_http_method method,
int status_code,
const char *status_title,
462 unsigned int static_content)
469 int content_length = 0;
470 int close_connection;
474 if (!ser || !server_header_field) {
476 ast_free(http_header);
478 ast_free(server_header_field);
482 if(!ast_strlen_zero(http_server_name)) {
494 ast_assert(200 <= status_code);
496 if (session_keep_alive <= 0) {
497 close_connection = 1;
505 close_connection = 1;
507 close_connection = 0;
519 content_length += lseek(fd, 0, SEEK_END);
520 lseek(fd, 0, SEEK_SET);
523 send_content = method != AST_HTTP_HEAD || status_code >= 400;
533 "Content-Length: %d\r\n"
536 status_code, status_title ? status_title :
"OK",
539 close_connection ?
"Connection: close\r\n" :
"",
540 static_content ?
"" :
"Cache-Control: no-cache, no-store\r\n",
545 ast_debug(1,
"ast_iostream_printf() failed: %s\n", strerror(errno));
546 close_connection = 1;
547 }
else if (send_content && fd) {
549 while ((len = read(fd, buf,
sizeof(buf))) > 0) {
551 ast_debug(1,
"ast_iostream_write() failed: %s\n", strerror(errno));
552 close_connection = 1;
558 ast_free(http_header);
560 ast_free(server_header_field);
562 if (close_connection) {
563 ast_debug(1,
"HTTP closing session. status_code:%d\n", status_code);
566 ast_debug(1,
"HTTP keeping session open. status_code:%d\n", status_code);
571 const char *status_title,
struct ast_str *http_header_data,
const char *text)
577 if (!http_header_data || !server_address || !out) {
578 ast_free(http_header_data);
579 ast_free(server_address);
582 ast_debug(1,
"HTTP closing session. OOM.\n");
588 if(!ast_strlen_zero(http_server_name)) {
589 ast_xml_escape(http_server_name, server_name,
sizeof(server_name));
592 "<address>%s</address>\r\n",
598 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
600 "<title>%d %s</title>\r\n"
606 "</body></html>\r\n",
613 ast_free(server_address);
626 const unsigned long nonce,
const unsigned long opaque,
int stale,
629 int status_code = 401;
630 char *status_title =
"Unauthorized";
633 if (http_header_data) {
636 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
637 "Content-type: text/html\r\n",
638 realm ? realm :
"Asterisk",
641 stale ?
", stale=true" :
"");
652 const char *status_title,
const char *text)
656 if (http_header_data) {
657 ast_str_set(&http_header_data, 0,
"Content-type: text/html\r\n");
679 int len = strlen(urih->uri);
683 urih->prefix = prefix;
685 if ( AST_RWLIST_EMPTY(&
uris) || strlen(AST_RWLIST_FIRST(&
uris)->uri) <= len ) {
686 AST_RWLIST_INSERT_HEAD(&
uris, urih,
entry);
692 if (AST_RWLIST_NEXT(uri,
entry) &&
693 strlen(AST_RWLIST_NEXT(uri,
entry)->uri) <= len) {
694 AST_RWLIST_INSERT_AFTER(&
uris, uri, urih,
entry);
701 AST_RWLIST_INSERT_TAIL(&
uris, urih,
entry);
719 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&
uris, urih,
entry) {
720 if (!strcmp(urih->
key, key)) {
721 AST_RWLIST_REMOVE_CURRENT(
entry);
723 ast_free(urih->
data);
730 AST_RWLIST_TRAVERSE_SAFE_END;
746 for (v = headers; v; v = v->
next) {
747 if (!strcasecmp(v->
name, field_name)) {
767 const char *content_type =
get_header(headers,
"Content-Type");
775 param = strchr(content_type,
';');
776 size = param ? param - content_type : strlen(content_type);
792 const char *content_length =
get_header(headers,
"Content-Length");
795 if (!content_length) {
801 if (sscanf(content_length,
"%30d", &length) != 1) {
817 return get_header(headers,
"Transfer-Encoding");
829 static int http_check_connection_close(
struct ast_variable *headers)
831 const char *connection =
get_header(headers,
"Connection");
832 int close_connection = 0;
834 if (connection && !strcasecmp(connection,
"close")) {
835 close_connection = -1;
837 return close_connection;
856 ast_set_flags_to(&request->
flags,
876 const char *transfer_encoding;
878 ast_set_flags_to(&request->
flags,
883 if (transfer_encoding && !strcasecmp(transfer_encoding,
"chunked")) {
895 ast_http_error(ser, 400,
"Bad Request",
"Invalid Content-Length in request!");
936 while (total != length) {
945 if (total != length) {
946 ast_log(LOG_WARNING,
"Wrong HTTP content read. Request %s (Wanted %d, Read %d)\n",
947 what_getting, length, res);
972 ast_log(LOG_WARNING,
"Short HTTP request %s (Wanted %d but got %zd)\n",
973 what_getting, length, res);
989 static int chunked_atoh(
const char *s,
int len)
1007 if (*s++ ==
'\x0D') {
1014 if (c >=
'0' && c <=
'9') {
1018 if (c >=
'a' && c <=
'f') {
1019 value += 10 + c -
'a';
1022 if (c >=
'A' && c <=
'F') {
1023 value += 10 + c -
'A';
1050 ast_log(LOG_WARNING,
"Short HTTP read of chunked header\n");
1053 length = chunked_atoh(header_line, strlen(header_line));
1055 ast_log(LOG_WARNING,
"Invalid HTTP chunk size\n");
1078 if (res <
sizeof(chunk_sync)) {
1079 ast_log(LOG_WARNING,
"Short HTTP chunk sync read (Wanted %zu)\n",
1080 sizeof(chunk_sync));
1083 if (chunk_sync[0] != 0x0D || chunk_sync[1] != 0x0A) {
1084 ast_log(LOG_WARNING,
"HTTP chunk sync bytes wrong (0x%02hhX, 0x%02hhX)\n",
1085 (
unsigned char) chunk_sync[0], (
unsigned char) chunk_sync[1]);
1108 ast_log(LOG_WARNING,
"Short HTTP read of chunked trailer header\n");
1114 if (ast_strlen_zero(header_line)) {
1134 ast_debug(1,
"HTTP discarding unused request body\n");
1138 if (http_body_discard_contents(ser, request->
body_length,
"body")) {
1149 length = http_body_get_chunk_length(ser);
1159 if (http_body_discard_contents(ser, length,
"chunk-data")
1160 || http_body_check_chunk_sync(ser)) {
1167 if (http_body_discard_chunk_trailer_headers(ser)) {
1204 ast_debug(2,
"HTTP consuming request body\n");
1211 ast_log(LOG_WARNING,
"Excessively long HTTP content. (%d > %d)\n",
1224 if (http_body_read_contents(ser, buf, content_length,
"body")) {
1231 buf[content_length] = 0;
1232 *return_length = content_length;
1249 chunk_length = http_body_get_chunk_length(ser);
1250 if (chunk_length < 0) {
1256 if (chunk_length == 0) {
1261 ast_log(LOG_WARNING,
1262 "Excessively long HTTP accumulated chunked body. (%d + %d > %d)\n",
1271 if (content_length + chunk_length >= bufsize) {
1277 }
while (content_length + chunk_length >= bufsize);
1288 if (http_body_read_contents(ser, buf + content_length, chunk_length,
"chunk-data")
1289 || http_body_check_chunk_sync(ser)) {
1295 content_length += chunk_length;
1305 if (http_body_discard_chunk_trailer_headers(ser)) {
1312 buf[content_length] = 0;
1313 *return_length = content_length;
1320 int content_length = 0;
1322 RAII_VAR(
char *, buf, NULL, ast_free);
1328 if (ast_strlen_zero(type) || strcasecmp(type,
"application/json")) {
1334 if (!buf || !content_length) {
1359 int content_length = 0;
1362 RAII_VAR(
char *, buf, NULL, ast_free);
1368 if (ast_strlen_zero(type) ||
1369 strcasecmp(type,
"application/x-www-form-urlencoded")) {
1375 if (!buf || !content_length) {
1383 while ((val = strsep(&buf,
"&"))) {
1384 var = strsep(&val,
"=");
1391 if ((v = ast_variable_new(var, val,
""))) {
1412 struct ast_variable *get_vars = NULL, *v, *prev = NULL;
1415 ast_debug(2,
"HTTP Request URI is %s \n", uri);
1417 strsep(¶ms,
"?");
1422 while ((val = strsep(¶ms,
"&"))) {
1423 var = strsep(&val,
"=");
1430 if ((v = ast_variable_new(var, val,
""))) {
1443 if (!strcasecmp(uri, redirect->target)) {
1451 ast_str_set(&http_header, 0,
"Location: %s\r\n", redirect->dest);
1452 ast_http_send(ser, method, 302,
"Moved Temporarily", http_header, NULL, 0, 0);
1463 if (!strncasecmp(uri, prefix, l) && uri[l] ==
'/') {
1467 AST_RWLIST_TRAVERSE(&
uris, urih,
entry) {
1468 l = strlen(urih->uri);
1470 ast_debug(2,
"match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
1471 if (strncasecmp(urih->uri, uri, l)
1472 || (*c && *c !=
'/')) {
1478 if (!*c || urih->has_subtree) {
1486 ast_debug(1,
"Match made with [%s]\n", urih->uri);
1490 res = urih->callback(ser, urih, uri, method, get_vars, headers);
1492 ast_debug(1,
"Requested URI [%s] has no handler\n", uri);
1493 ast_http_error(ser, 404,
"Not Found",
"The requested URL was not found on this server.");
1501 static struct ast_variable *parse_cookies(
const char *cookies)
1507 while ((cur = strsep(&parse,
";"))) {
1513 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1520 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1524 ast_debug(1,
"HTTP Cookie, Name: '%s' Value: '%s'\n", name, val);
1526 var = ast_variable_new(name, val, __FILE__);
1539 for (v = headers; v; v = v->
next) {
1540 if (!strcasecmp(v->
name,
"Cookie")) {
1542 cookies = parse_cookies(v->
value);
1552 size_t password_len;
1554 if (!userid || !password) {
1555 ast_log(LOG_ERROR,
"Invalid userid/password\n");
1559 userid_len = strlen(userid) + 1;
1560 password_len = strlen(password) + 1;
1563 auth = ao2_alloc(
sizeof(*auth) + userid_len + password_len, NULL);
1569 auth->
userid = (
char *)(auth + 1);
1570 strcpy(auth->
userid, userid);
1579 #define BASIC_PREFIX "Basic "
1586 for (v = headers; v; v = v->
next) {
1588 char decoded[256] = {};
1595 if (strcasecmp(
"Authorization", v->
name) != 0) {
1601 "Unsupported Authorization scheme\n");
1622 sizeof(decoded) - 1);
1623 ast_assert(cnt <
sizeof(decoded));
1627 username = strsep(&password,
":");
1629 ast_log(LOG_WARNING,
"Invalid Authorization header\n");
1633 return auth_create(username, password);
1642 size_t size = strlen(version);
1644 if (strncmp(buf, version, size) || buf[size] !=
' ') {
1645 ast_log(LOG_ERROR,
"HTTP version not supported - "
1646 "expected %s\n", version);
1653 if (sscanf(buf,
"%d", &status_code) != 1) {
1654 ast_log(LOG_ERROR,
"Could not read HTTP status code - "
1662 static void remove_excess_lws(
char *s)
1678 if (buf_end != buf) {
1682 memcpy(buf_end, p, s - p);
1694 if (ast_strlen_zero(buf)) {
1699 *name = strsep(value,
":");
1705 if (ast_strlen_zero(*value) || ast_strlen_zero(*name)) {
1709 remove_excess_lws(*value);
1714 const char *value,
const char *expected_value)
1716 if (strcasecmp(name, expected_name)) {
1721 if (strcasecmp(value, expected_value)) {
1722 ast_log(LOG_ERROR,
"Invalid header value - expected %s "
1723 "received %s", value, expected_value);
1730 const char *value,
const char *expected_value)
1732 if (strcasecmp(name, expected_name)) {
1737 if (!strcasestr(expected_value, value)) {
1738 ast_log(LOG_ERROR,
"Header '%s' - could not locate '%s' "
1739 "in '%s'\n", name, value, expected_value);
1747 #define MAX_HTTP_REQUEST_HEADERS 100
1763 int remaining_headers;
1777 if (header_line[len - 1] !=
'\n') {
1780 (len ==
sizeof(header_line) - 1) ?
"Header line too long" :
"Timeout");
1786 if (ast_strlen_zero(header_line)) {
1791 value = header_line;
1792 name = strsep(&value,
":");
1798 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1804 if (!remaining_headers--) {
1806 ast_http_error(ser, 413,
"Request Entity Too Large",
"Too many headers");
1810 *headers = ast_variable_new(name, value, __FILE__);
1813 tail->
next = ast_variable_new(name, value, __FILE__);
1847 const char *transfer_encoding;
1861 http_request_tracking_init(request);
1863 if (request_line[len - 1] !=
'\n') {
1866 (len ==
sizeof(request_line) - 1) ?
"Request line too long" :
"Timeout");
1877 if (!strcasecmp(method,
"GET")) {
1878 http_method = AST_HTTP_GET;
1879 }
else if (!strcasecmp(method,
"POST")) {
1880 http_method = AST_HTTP_POST;
1881 }
else if (!strcasecmp(method,
"HEAD")) {
1882 http_method = AST_HTTP_HEAD;
1883 }
else if (!strcasecmp(method,
"PUT")) {
1884 http_method = AST_HTTP_PUT;
1885 }
else if (!strcasecmp(method,
"DELETE")) {
1886 http_method = AST_HTTP_DELETE;
1887 }
else if (!strcasecmp(method,
"OPTIONS")) {
1888 http_method = AST_HTTP_OPTIONS;
1904 ast_http_error(ser, 503,
"Service Unavailable",
"Shutdown in progress");
1909 if (http_request_headers_get(ser, &headers)) {
1915 if (!transfer_encoding) {
1916 transfer_encoding =
"identity";
1923 if (strcasecmp(transfer_encoding,
"identity") != 0 &&
1924 strcasecmp(transfer_encoding,
"chunked") != 0) {
1926 ast_http_error(ser, 501,
"Unimplemented",
"Unsupported Transfer-Encoding.");
1930 if (http_request_tracking_setup(ser, headers)
1931 || handle_uri(ser, uri, http_method, headers)
1940 static void *httpd_helper_thread(
void *data)
1952 ast_log(LOG_WARNING,
"HTTP session count exceeded %d sessions.\n",
1956 ast_debug(1,
"HTTP opening session. Top level\n");
1964 ast_log(LOG_WARNING,
"Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
1979 timeout = session_keep_alive;
1982 timeout = session_inactivity;
1994 if (httpd_process_request(ser)) {
2003 timeout = session_keep_alive;
2013 ast_debug(1,
"HTTP closing session. Top level\n");
2027 char *target, *dest;
2029 unsigned int target_len;
2030 unsigned int total_len;
2035 target = strsep(&dest,
" ");
2037 target = strsep(&target,
" ");
2040 ast_log(LOG_WARNING,
"Invalid redirect '%s'\n", value);
2044 target_len = strlen(target) + 1;
2045 dest_len = strlen(dest) + 1;
2046 total_len =
sizeof(*redirect) + target_len + dest_len;
2048 if (!(redirect =
ast_calloc(1, total_len))) {
2051 redirect->dest = redirect->target + target_len;
2052 strcpy(redirect->target, target);
2059 || strlen(AST_RWLIST_FIRST(&
uri_redirects)->target) <= target_len ) {
2067 if (AST_RWLIST_NEXT(cur,
entry)
2068 && strlen(AST_RWLIST_NEXT(cur,
entry)->target) <= target_len ) {
2081 #define HTTP_SERVER_BUCKETS 5
2088 static void http_server_destroy(
void *obj)
2094 ast_verb(1,
"Stopped http server '%s' listening at '%s'\n", server->name, server->address);
2096 ast_free(server->name);
2097 ast_free(server->address);
2100 static struct ast_http_server *http_server_create(
const char *name,
const char *address,
2105 server = ao2_alloc(
sizeof(*server), http_server_destroy);
2107 ast_log(LOG_ERROR,
"Unable to allocate HTTP server '%s' at address '%s'\n",
2113 ast_log(LOG_ERROR,
"Unable to complete setup for HTTP server '%s' at address '%s'\n",
2119 server->args.accept_fd = -1;
2120 server->args.
master = AST_PTHREADT_NULL;
2122 server->args.poll_timeout = -1;
2123 server->args.name = server->name;
2124 server->args.
accept_fn = ast_tcptls_server_root;
2125 server->args.
worker_fn = httpd_helper_thread;
2134 if (server->args.accept_fd != -1) {
2140 if (server->args.accept_fd == -1) {
2141 ast_log(LOG_WARNING,
"Failed to start HTTP server '%s' at address '%s'\n",
2142 server->name, server->address);
2147 ast_log(LOG_WARNING,
"Failed to link HTTP server '%s' at address '%s'\n",
2148 server->name, server->address);
2152 ast_verb(1,
"Bound HTTP server '%s' to address %s\n", server->name, server->address);
2180 if (
ao2_ref(server, -1) == 2) {
2205 if (ast_strlen_zero(address)) {
2211 return server ?: http_server_create(name, address, addr);
2236 ast_log(LOG_WARNING,
"Unable to resolve host '%s'\n", host);
2241 port = DEFAULT_PORT;
2244 for (i = 0; i < num_addrs; ++i) {
2285 ao2_lock(http_servers);
2291 if (*replace_me == server) {
2292 ao2_cleanup(server);
2293 ao2_unlock(http_servers);
2301 *replace_me = server;
2304 if (server && http_server_start(server)) {
2313 ao2_unlock(http_servers);
2317 #ifdef TEST_FRAMEWORK
2319 struct ast_http_server *ast_http_test_server_get(
const char *name,
const char *host)
2335 if (ast_strlen_zero(host)) {
2337 if (global_http_server) {
2339 return ao2_bump(global_http_server);
2342 host =
"localhost:8088";
2346 name =
"http test server";
2367 static int __ast_http_load(
int reload)
2372 int new_static_uri_enabled = 0;
2373 int new_status_uri_enabled = 1;
2374 char newprefix[MAX_PREFIX] =
"";
2378 uint32_t bindport = DEFAULT_PORT;
2379 int http_tls_was_enabled = 0;
2380 char *bindaddr = NULL;
2383 if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
2388 if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
2395 http_tls_was_enabled = (reload && http_tls_cfg.enabled);
2397 http_tls_cfg.enabled = 0;
2399 ast_free(http_tls_cfg.certfile);
2402 ast_free(http_tls_cfg.capath);
2405 ast_free(http_tls_cfg.pvtfile);
2411 ast_free(http_tls_cfg.cipher);
2412 http_tls_cfg.cipher =
ast_strdup(
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA");
2422 session_limit = DEFAULT_SESSION_LIMIT;
2426 snprintf(server_name,
sizeof(server_name),
"Asterisk/%s",
ast_get_version());
2428 v = ast_variable_browse(cfg,
"general");
2429 for (; v; v = v->
next) {
2431 if (strcasecmp(v->
name,
"tlscafile")
2432 && strcasecmp(v->
name,
"tlscapath")
2433 && strcasecmp(v->
name,
"tlscadir")
2434 && strcasecmp(v->
name,
"tlsverifyclient")
2435 && strcasecmp(v->
name,
"tlsdontverifyserver")
2436 && strcasecmp(v->
name,
"tlsclientmethod")
2437 && strcasecmp(v->
name,
"sslclientmethod")
2442 if (!strcasecmp(v->
name,
"servername")) {
2443 if (!ast_strlen_zero(v->
value)) {
2446 server_name[0] =
'\0';
2448 }
else if (!strcasecmp(v->
name,
"enabled")) {
2450 }
else if (!strcasecmp(v->
name,
"enablestatic") || !strcasecmp(v->
name,
"enable_static")) {
2452 }
else if (!strcasecmp(v->
name,
"enable_status")) {
2454 }
else if (!strcasecmp(v->
name,
"bindport")) {
2456 &bindport, DEFAULT_PORT, 0, 65535)) {
2457 ast_log(LOG_WARNING,
"Invalid port %s specified. Using default port %" PRId32
"\n",
2458 v->
value, DEFAULT_PORT);
2460 }
else if (!strcasecmp(v->
name,
"bindaddr")) {
2462 }
else if (!strcasecmp(v->
name,
"prefix")) {
2463 if (!ast_strlen_zero(v->
value)) {
2467 newprefix[0] =
'\0';
2469 }
else if (!strcasecmp(v->
name,
"redirect")) {
2471 }
else if (!strcasecmp(v->
name,
"sessionlimit")) {
2473 &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
2474 ast_log(LOG_WARNING,
"Invalid %s '%s' at line %d of http.conf\n",
2477 }
else if (!strcasecmp(v->
name,
"session_inactivity")) {
2480 ast_log(LOG_WARNING,
"Invalid %s '%s' at line %d of http.conf\n",
2483 }
else if (!strcasecmp(v->
name,
"session_keep_alive")) {
2484 if (sscanf(v->
value,
"%30d", &session_keep_alive) != 1
2485 || session_keep_alive < 0) {
2487 ast_log(LOG_WARNING,
"Invalid %s '%s' at line %d of http.conf\n",
2491 ast_log(LOG_WARNING,
"Ignoring unknown option '%s' in http.conf\n", v->
name);
2497 if (strcmp(prefix, newprefix)) {
2501 ast_copy_string(http_server_name, server_name,
sizeof(http_server_name));
2504 http_server_get(
"http server", bindaddr, bindport, &global_http_server);
2505 }
else if (global_http_server) {
2507 global_http_server = NULL;
2514 global_http_server->args.accept_fd != -1) {
2516 ast_sockaddr_copy(&https_desc.local_address, &global_http_server->args.local_address);
2524 if (http_tls_was_enabled && !http_tls_cfg.enabled) {
2540 if (static_uri_enabled && !new_static_uri_enabled) {
2542 }
else if (!static_uri_enabled && new_static_uri_enabled) {
2546 static_uri_enabled = new_static_uri_enabled;
2548 if (status_uri_enabled && !new_status_uri_enabled) {
2550 }
else if (!status_uri_enabled && new_status_uri_enabled) {
2554 status_uri_enabled = new_status_uri_enabled;
2566 e->
command =
"http show status";
2568 "Usage: http show status\n"
2569 " Lists status of internal HTTP engine\n";
2576 return CLI_SHOWUSAGE;
2578 ast_cli(a->fd,
"HTTP Server Status:\n");
2579 ast_cli(a->fd,
"Prefix: %s\n", prefix);
2580 ast_cli(a->fd,
"Server: %s\n", http_server_name);
2581 if (!global_http_server) {
2582 ast_cli(a->fd,
"Server Disabled\n\n");
2584 ast_cli(a->fd,
"Server Enabled and Bound to %s\n\n",
2586 if (http_tls_cfg.enabled) {
2587 ast_cli(a->fd,
"HTTPS Server Enabled and Bound to %s\n\n",
2592 ast_cli(a->fd,
"Enabled URI's:\n");
2594 if (AST_RWLIST_EMPTY(&
uris)) {
2595 ast_cli(a->fd,
"None.\n");
2598 ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
2602 ast_cli(a->fd, "\nEnabled Redirects:\n");
2604 AST_RWLIST_TRAVERSE(&uri_redirects, redirect,
entry)
2605 ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
2606 if (AST_RWLIST_EMPTY(&uri_redirects)) {
2607 ast_cli(a->fd,
" None.\n");
2614 static int reload_module(
void)
2616 return __ast_http_load(1);
2620 AST_CLI_DEFINE(handle_show_http,
"Display HTTP server status"),
2623 static int unload_module(
void)
2628 ao2_cleanup(global_http_server);
2629 ao2_cleanup(http_servers);
2631 if (http_tls_cfg.enabled) {
2634 ast_free(http_tls_cfg.certfile);
2635 ast_free(http_tls_cfg.capath);
2636 ast_free(http_tls_cfg.pvtfile);
2637 ast_free(http_tls_cfg.cipher);
2639 if (status_uri_enabled) {
2643 if (static_uri_enabled) {
2656 static int load_module(
void)
2662 if (!http_servers) {
2666 if (__ast_http_load(0)) {
2667 ao2_cleanup(http_servers);
2668 http_servers = NULL;
2675 AST_MODULE_INFO(
ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER,
"Built-in HTTP Server",
2676 .support_level = AST_MODULE_SUPPORT_CORE,
2677 .load = load_module,
2678 .unload = unload_module,
2679 .reload = reload_module,
2681 .requires =
"extconfig",
void ast_iostream_set_exclusive_input(struct ast_iostream *stream, int exclusive_input)
Set the iostream if it can exclusively depend upon the set timeouts.
void ast_uri_decode(char *s, struct ast_flags spec)
Decode URI, URN, URL (overwrite string)
struct ast_variable * next
static char * ast_http_get_contents(int *return_length, struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
Returns the contents (body) of the HTTP request.
Asterisk main include file. File version handling, generic pbx functions.
AO2_STRING_FIELD_HASH_FN(transport_monitor, key)
Hashing function for struct transport_monitor.
#define ast_realloc(p, len)
A wrapper for realloc()
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *p_result,...)
The argument parsing routine.
void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
This is a generic (re)start routine for a TCP server, which does the socket/bind/listen and starts a ...
String manipulation functions.
struct ast_json * ast_json_load_buf(const char *buffer, size_t buflen, struct ast_json_error *error)
Parse buffer with known length into a JSON object or array.
int ast_http_response_status_line(const char *buf, const char *version, int code)
Parse the http response status line.
void ast_variables_destroy(struct ast_variable *var)
Free variable list.
int ast_ssl_setup(struct ast_tls_config *cfg)
Set up an SSL server.
Asterisk version information.
struct ast_variable * ast_http_get_cookies(struct ast_variable *headers)
Get cookie from Request headers.
int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
Unregister multiple commands.
uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
Return manager id, if exist, from request headers.
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
ssize_t ast_iostream_write(struct ast_iostream *stream, const void *buffer, size_t count)
Write data to an iostream.
Time-related functions and macros.
const char * ast_get_version(void)
Retrieve the Asterisk version string.
static char * get_content_type(struct ast_variable *headers)
Retrieves the content type specified in the "Content-Type" header.
descriptor for a cli entry.
static struct @363 mimetypes[]
Limit the kinds of files we're willing to serve up.
ssize_t ast_iostream_discard(struct ast_iostream *stream, size_t count)
Discard the specified number of bytes from an iostream.
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
void ast_http_uri_unlink(struct ast_http_uri *urih)
Unregister a URI handler.
#define AST_RWLIST_RDLOCK(head)
Read locks a list.
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
struct ast_config * ast_config_load2(const char *filename, const char *who_asked, struct ast_flags flags)
Load a config file.
Structure for variables, used for configurations and for channel variables.
static struct ast_sockaddr address
Address for UDPTL.
Assume that the ao2_container is already locked.
#define INITIAL_RESPONSE_BODY_BUFFER
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
AO2_STRING_FIELD_CMP_FN(transport_monitor, key)
Comparison function for struct transport_monitor.
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
#define ast_cli_register_multiple(e, len)
Register multiple commands.
int ast_iostream_get_fd(struct ast_iostream *stream)
Get an iostream's file descriptor.
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
arguments for the accepting thread
#define ao2_link_flags(container, obj, flags)
Add an object to a container.
static int get_content_length(struct ast_variable *headers)
Returns the value of the Content-Length header.
#define ast_strdup(str)
A wrapper for strdup()
Generic support for tcp/tls servers in Asterisk.
int ast_xml_escape(const char *string, char *outbuf, size_t buflen)
Escape reserved characters for use in XML.
void ast_iostream_set_timeout_idle_inactivity(struct ast_iostream *stream, int timeout, int timeout_reset)
Set the iostream inactivity & idle timeout timers.
const char * ast_get_http_method(enum ast_http_method method)
Return http method name string.
Socket address structure.
char * ast_skip_nonblanks(const char *str)
Gets a pointer to first whitespace character in a string.
void ast_http_uri_unlink_all_with_key(const char *key)
Unregister all handlers with matching key.
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
#define DEFAULT_SESSION_KEEP_ALIVE
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
ssize_t ast_iostream_read(struct ast_iostream *stream, void *buffer, size_t count)
Read data from an iostream.
#define AST_RWLIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a read/write list of specified type, statically initialized...
static int ast_sockaddr_isnull(const struct ast_sockaddr *addr)
Checks if the ast_sockaddr is null. "null" in this sense essentially means uninitialized, or having a 0 length.
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
#define ast_sockaddr_port(addr)
Get the port number of a socket address.
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
#define MAX_SERVER_NAME_LENGTH
Configuration File Parser.
Support for Private Asterisk HTTP Servers.
int ast_base64decode(unsigned char *dst, const char *src, int max)
Decode data from base64.
int ast_http_header_parse(char *buf, char **name, char **value)
Parse a header into the given name/value strings.
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
int astman_is_authed(uint32_t ident)
Determine if a manager session ident is authenticated.
static void cleanup(void)
Clean up any old apps that we don't need any more.
int ast_http_body_discard(struct ast_tcptls_session_instance *ser)
Read and discard any unread HTTP request body.
Asterisk JSON abstraction layer.
Asterisk file paths, configured in asterisk.conf.
#define ast_strdupa(s)
duplicate a string in memory from the stack
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
ssize_t ast_iostream_printf(struct ast_iostream *stream, const char *format,...)
Write a formatted string to an iostream.
#define ast_malloc(len)
A wrapper for malloc()
#define ast_debug(level,...)
Log a DEBUG message.
void ast_http_body_read_status(struct ast_tcptls_session_instance *ser, int read_success)
Update the body read success status.
struct ast_http_server * global_http_server
describes a server instance
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
The AMI - Asterisk Manager Interface - is a TCP protocol created to manage Asterisk with third-party ...
int ast_shutdown_final(void)
static void add_redirect(const char *value)
Add a new URI redirect The entries in the redirect list are sorted by length, just like the list of U...
#define ao2_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn)
Allocate and initialize a hash container with the desired number of buckets.
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1".
Support for dynamic strings.
#define ao2_unlink(container, obj)
Remove an object from a container.
#define ast_sockaddr_set_port(addr, port)
Sets the port number of a socket address.
static const char * get_header(struct ast_variable *headers, const char *field_name)
Retrieves the header with the given field name.
void ast_http_request_close_on_completion(struct ast_tcptls_session_instance *ser)
Request the HTTP connection be closed after this HTTP request.
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
int ast_http_header_match(const char *name, const char *expected_name, const char *value, const char *expected_value)
Check if the header and value match (case insensitive) their associated expected values.
char * ast_skip_blanks(const char *str)
Gets a pointer to the first non-whitespace character in a string.
void ast_http_send(struct ast_tcptls_session_instance *ser, enum ast_http_method method, int status_code, const char *status_title, struct ast_str *http_header, struct ast_str *out, int fd, unsigned int static_content)
Generic function for sending HTTP/1.1 response.
#define ast_strndup(str, len)
A wrapper for strndup()
#define ast_module_ref(mod)
Hold a reference to the module.
char * ast_trim_blanks(char *str)
Trims trailing whitespace characters from a string.
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
#define ast_calloc(num, len)
A wrapper for calloc()
static const char * get_transfer_encoding(struct ast_variable *headers)
Returns the value of the Transfer-Encoding header.
void ast_http_prefix(char *buf, int len)
Return the current prefix.
void *(* worker_fn)(void *)
Module could not be loaded properly.
struct ast_variable * ast_http_get_post_vars(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
Get post variables from client Request Entity-Body, if content type is application/x-www-form-urlenco...
struct ast_http_auth * ast_http_get_auth(struct ast_variable *headers)
Get HTTP authentication information from headers.
struct ast_sockaddr old_address
int ast_strftime(char *buf, size_t len, const char *format, const struct ast_tm *tm)
Special version of strftime(3) that handles fractions of a second. Takes the same arguments as strfti...
#define MIN_INITIAL_REQUEST_TIMEOUT
static void http_server_discard(struct ast_http_server *server)
Discard/Drop a HTTP server.
#define DEFAULT_SESSION_INACTIVITY
Structure used to handle boolean flags.
struct ast_iostream * stream
struct ast_json * ast_http_get_json(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
Get JSON from client Request Entity-Body, if content type is application/json.
#define MAX_CONTENT_LENGTH
#define ast_module_unref(mod)
Release a reference to the module.
ssize_t ast_iostream_gets(struct ast_iostream *stream, char *buffer, size_t size)
Read a LF-terminated string from an iostream.
void ast_http_create_response(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, struct ast_str *http_header_data, const char *text)
Creates and sends a formatted http response message.
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
#define DEFAULT_RESPONSE_HEADER_LENGTH
int ast_http_uri_link(struct ast_http_uri *urih)
Link the new uri into the list.
HTTP authentication information.
Standard Command Line Interface.
static struct ast_http_server * http_server_get(const char *name, const char *host, uint32_t port, struct ast_http_server **replace_me)
Retrieve, or create and start a HTTP server.
static int enabled
Whether or not we are storing history.
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
Closes a tcptls session instance's file and/or file descriptor. The tcptls_session will be set to NUL...
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one...
void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm, const unsigned long nonce, const unsigned long opaque, int stale, const char *text)
Send http "401 Unauthorized" response and close socket.
Definition of a URI handler.
int ast_http_header_match_in(const char *name, const char *expected_name, const char *value, const char *expected_value)
Check if the header name matches the expected header name. If so, then check to see if the value can ...
void ast_iostream_nonblock(struct ast_iostream *stream)
Make an iostream non-blocking.
int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
Used to parse conf files containing tls/ssl options.
static int force_inline attribute_pure ast_begins_with(const char *str, const char *prefix)
Checks whether a string begins with another.
Abstract JSON element (object, array, string, int, ...).
#define HTTP_SERVER_BUCKETS
Number of HTTP server buckets.
#define MAX_HTTP_REQUEST_HEADERS
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
Shutdown a running server if there is one.
struct ast_tls_config * tls_cfg
void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
Send HTTP error message and close socket.
static struct ast_http_server * http_server_get_by_host(const char *name, const char *host, uint32_t port)
Retrieve, or create a HTTP server object by host.
ast_http_method
HTTP Request methods known by Asterisk.
void ast_config_destroy(struct ast_config *cfg)
Destroys a config.
#define ASTERISK_GPL_KEY
The text the key() function should return.
Asterisk module definitions.
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
static struct ast_http_server * http_server_get_by_addr(const char *name, const struct ast_sockaddr *addr)
Retrieve, or create a HTTP server object by sock address.
const char * ast_http_ftype2mtype(const char *ftype)
Return mime type based on extension.
unsigned int no_decode_uri
#define MAX_HTTP_LINE_LENGTH
#define ast_str_create(init_len)
Create a malloc'ed dynamic length string.
int ast_sockaddr_resolve(struct ast_sockaddr **addrs, const char *str, int flags, int family)
Parses a string with an IPv4 or IPv6 address and place results into an array.
void *(* accept_fn)(void *)