http.c File Reference

http server for AMI access More...

#include "asterisk.h"
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/signal.h>
#include <fcntl.h>
#include "asterisk/paths.h"
#include "asterisk/cli.h"
#include "asterisk/tcptls.h"
#include "asterisk/http.h"
#include "asterisk/utils.h"
#include "asterisk/strings.h"
#include "asterisk/config.h"
#include "asterisk/stringfields.h"
#include "asterisk/ast_version.h"
#include "asterisk/manager.h"
#include "asterisk/_private.h"
#include "asterisk/astobj2.h"
#include "asterisk/netsock2.h"
#include "asterisk/json.h"

Include dependency graph for http.c:

Go to the source code of this file.

Data Structures

struct  ast_cfhttp_methods_text
struct  http_uri_redirect
struct  http_worker_private_data
struct  uri_redirects
struct  uris

Defines

#define BASIC_LEN   6
#define BASIC_PREFIX   "Basic "
#define DEFAULT_PORT   8088
#define DEFAULT_RESPONSE_HEADER_LENGTH   512
#define DEFAULT_SESSION_INACTIVITY   30000
#define DEFAULT_SESSION_KEEP_ALIVE   15000
#define DEFAULT_SESSION_LIMIT   100
#define DEFAULT_TLS_PORT   8089
#define MAX_CONTENT_LENGTH   4096
#define MAX_HTTP_LINE_LENGTH   4096
#define MAX_HTTP_REQUEST_HEADERS   100
#define MAX_PREFIX   80
#define MAX_SERVER_NAME_LENGTH   128
#define MIN_INITIAL_REQUEST_TIMEOUT   10000

Enumerations

enum  http_private_flags { HTTP_FLAG_HAS_BODY = (1 << 0), HTTP_FLAG_BODY_READ = (1 << 1), HTTP_FLAG_CLOSE_ON_COMPLETION = (1 << 2) }

Functions

static int __ast_http_load (int reload)
static void __fini_uri_redirects (void)
static void __fini_uris (void)
static void __init_uri_redirects (void)
static void __init_uris (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 URI handlers.
const char * ast_get_http_method (enum ast_http_method method)
 Return http method name string.
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.
int ast_http_body_discard (struct ast_tcptls_session_instance *ser)
 Read and discard any unread HTTP request body.
void ast_http_body_read_status (struct ast_tcptls_session_instance *ser, int read_success)
 Update the body read success status.
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.
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.
const char * ast_http_ftype2mtype (const char *ftype)
 Return mime type based on extension.
struct ast_http_authast_http_get_auth (struct ast_variable *headers)
 Get HTTP authentication information from headers.
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.
struct ast_variableast_http_get_cookies (struct ast_variable *headers)
 Get cookie from Request headers.
struct ast_jsonast_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.
struct ast_variableast_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-urlencoded.
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.
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 be located in the expected value.
int ast_http_header_parse (char *buf, char **name, char **value)
 Parse a header into the given name/value strings.
int ast_http_init (void)
uint32_t ast_http_manid_from_vars (struct ast_variable *headers)
 Return manager id, if exist, from request headers.
void ast_http_prefix (char *buf, int len)
 Return the current prefix.
int ast_http_reload (void)
void ast_http_request_close_on_completion (struct ast_tcptls_session_instance *ser)
 Request the HTTP connection be closed after this HTTP request.
int ast_http_response_status_line (const char *buf, const char *version, int code)
 Parse the http response status line.
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.
int ast_http_uri_link (struct ast_http_uri *urih)
 Link the new uri into the list.
void ast_http_uri_unlink (struct ast_http_uri *urih)
 Unregister a URI handler.
void ast_http_uri_unlink_all_with_key (const char *key)
 Unregister all handlers with matching key.
static struct ast_http_authauth_create (const char *userid, const char *password)
static int chunked_atoh (const char *s, int len)
static int get_content_length (struct ast_variable *headers)
 Returns the value of the Content-Length header.
static char * get_content_type (struct ast_variable *headers)
 Retrieves the content type specified in the "Content-Type" header.
static const char * get_header (struct ast_variable *headers, const char *field_name)
 Retrieves the header with the given field name.
static const char * get_transfer_encoding (struct ast_variable *headers)
 Returns the value of the Transfer-Encoding header.
static char * handle_show_http (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static int handle_uri (struct ast_tcptls_session_instance *ser, char *uri, enum ast_http_method method, struct ast_variable *headers)
static int http_body_check_chunk_sync (struct ast_tcptls_session_instance *ser)
static int http_body_discard_chunk_trailer_headers (struct ast_tcptls_session_instance *ser)
static int http_body_discard_contents (struct ast_tcptls_session_instance *ser, int length, const char *what_getting)
static int http_body_get_chunk_length (struct ast_tcptls_session_instance *ser)
static int http_body_read_contents (struct ast_tcptls_session_instance *ser, char *buf, int length, const char *what_getting)
static int http_check_connection_close (struct ast_variable *headers)
static int http_request_headers_get (struct ast_tcptls_session_instance *ser, struct ast_variable **headers)
static void http_request_tracking_init (struct http_worker_private_data *request)
static int http_request_tracking_setup (struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
static void http_shutdown (void)
static void * httpd_helper_thread (void *arg)
static int httpd_process_request (struct ast_tcptls_session_instance *ser)
static int httpstatus_callback (struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_vars, struct ast_variable *headers)
static struct ast_variableparse_cookies (const char *cookies)
static void remove_excess_lws (char *s)
static int static_callback (struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_vars, struct ast_variable *headers)

Variables

static struct
ast_cfhttp_methods_text 
ast_http_methods_text []
static struct ast_cli_entry cli_http []
static int enablestatic
static struct
ast_tcptls_session_args 
http_desc
static char http_server_name [MAX_SERVER_NAME_LENGTH]
static struct ast_tls_config http_tls_cfg
static struct
ast_tcptls_session_args 
https_desc
struct {
   const char *   ext
   const char *   mtype
mimetypes []
 Limit the kinds of files we're willing to serve up.
static char prefix [MAX_PREFIX]
static int session_count = 0
static int session_inactivity = DEFAULT_SESSION_INACTIVITY
static int session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE
static int session_limit = DEFAULT_SESSION_LIMIT
static struct ast_http_uri staticuri
static struct ast_http_uri statusuri


Detailed Description

http server for AMI access

Author:
Mark Spencer <markster@digium.com>
This program implements a tiny http server and was inspired by micro-httpd by Jef Poskanzer

GMime http://spruce.sourceforge.net/gmime/

AMI over HTTP support - AMI over the http protocol

Definition in file http.c.


Define Documentation

#define BASIC_LEN   6

strlen(BASIC_PREFIX)

Definition at line 1570 of file http.c.

Referenced by ast_http_get_auth().

#define BASIC_PREFIX   "Basic "

Definition at line 1569 of file http.c.

Referenced by ast_http_get_auth().

#define DEFAULT_PORT   8088

Definition at line 71 of file http.c.

Referenced by __ast_http_load().

#define DEFAULT_RESPONSE_HEADER_LENGTH   512

Max size for the http response header

Definition at line 83 of file http.c.

Referenced by ast_http_auth(), and ast_http_error().

#define DEFAULT_SESSION_INACTIVITY   30000

(ms) Idle time waiting for data.

Definition at line 75 of file http.c.

Referenced by __ast_http_load().

#define DEFAULT_SESSION_KEEP_ALIVE   15000

(ms) Idle time between HTTP requests

Definition at line 79 of file http.c.

Referenced by __ast_http_load().

#define DEFAULT_SESSION_LIMIT   100

Definition at line 73 of file http.c.

Referenced by __ast_http_load().

#define DEFAULT_TLS_PORT   8089

Definition at line 72 of file http.c.

Referenced by __ast_http_load().

#define MAX_CONTENT_LENGTH   4096

Maximum application/json or application/x-www-form-urlencoded body content length.

Definition at line 87 of file http.c.

Referenced by ast_http_create_response(), and ast_http_get_contents().

#define MAX_HTTP_LINE_LENGTH   4096

#define MAX_HTTP_REQUEST_HEADERS   100

Limit the number of request headers in case the sender is being ridiculous.

Definition at line 1737 of file http.c.

Referenced by http_request_headers_get().

#define MAX_PREFIX   80

Definition at line 70 of file http.c.

Referenced by __ast_http_load().

#define MAX_SERVER_NAME_LENGTH   128

Max size for the http server name

Definition at line 81 of file http.c.

Referenced by __ast_http_load(), ast_http_create_response(), and ast_http_send().

#define MIN_INITIAL_REQUEST_TIMEOUT   10000

(ms) Min timeout for initial HTTP request to start coming in.

Definition at line 77 of file http.c.

Referenced by httpd_helper_thread().


Enumeration Type Documentation

Enumerator:
HTTP_FLAG_HAS_BODY  TRUE if the HTTP request has a body.
HTTP_FLAG_BODY_READ  TRUE if the HTTP request body has been read.
HTTP_FLAG_CLOSE_ON_COMPLETION  TRUE if the HTTP request must close when completed.

Definition at line 429 of file http.c.

00429                         {
00430    /*! TRUE if the HTTP request has a body. */
00431    HTTP_FLAG_HAS_BODY = (1 << 0),
00432    /*! TRUE if the HTTP request body has been read. */
00433    HTTP_FLAG_BODY_READ = (1 << 1),
00434    /*! TRUE if the HTTP request must close when completed. */
00435    HTTP_FLAG_CLOSE_ON_COMPLETION = (1 << 2),
00436 };


Function Documentation

static int __ast_http_load ( int  reload  )  [static]

Definition at line 2072 of file http.c.

References ast_tcptls_session_args::accept_fd, add_redirect(), AST_AF_UNSPEC, AST_CERTFILE, ast_config_destroy(), ast_config_load2(), ast_copy_string(), ast_free, ast_get_version(), ast_log, ast_parse_arg(), AST_RWLIST_REMOVE_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_sockaddr_copy(), ast_sockaddr_isnull(), ast_sockaddr_port, ast_sockaddr_resolve(), ast_sockaddr_set_port, ast_sockaddr_setnull(), ast_sockaddr_stringify(), ast_ssl_setup(), ast_strdup, ast_strlen_zero, ast_tcptls_server_start(), ast_tcptls_server_stop(), ast_tls_read_conf(), ast_true(), ast_variable_browse(), ast_verb, ast_tls_config::certfile, ast_tls_config::cipher, CONFIG_FLAG_FILEUNCHANGED, CONFIG_STATUS_FILEINVALID, CONFIG_STATUS_FILEUNCHANGED, DEFAULT_PORT, DEFAULT_SESSION_INACTIVITY, DEFAULT_SESSION_KEEP_ALIVE, DEFAULT_SESSION_LIMIT, DEFAULT_TLS_PORT, ast_tls_config::enabled, enabled, http_tls_cfg, ast_variable::lineno, ast_tcptls_session_args::local_address, LOG_WARNING, MAX_PREFIX, MAX_SERVER_NAME_LENGTH, ast_variable::name, ast_variable::next, NULL, PARSE_DEFAULT, PARSE_IN_RANGE, PARSE_INT32, PARSE_UINT32, ast_tls_config::pvtfile, RAII_VAR, ast_tcptls_session_args::tls_cfg, and ast_variable::value.

Referenced by ast_http_init(), and ast_http_reload().

02073 {
02074    struct ast_config *cfg;
02075    struct ast_variable *v;
02076    int enabled=0;
02077    int newenablestatic=0;
02078    char newprefix[MAX_PREFIX] = "";
02079    char server_name[MAX_SERVER_NAME_LENGTH];
02080    struct http_uri_redirect *redirect;
02081    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
02082    uint32_t bindport = DEFAULT_PORT;
02083    RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
02084    int num_addrs = 0;
02085    int http_tls_was_enabled = 0;
02086 
02087    cfg = ast_config_load2("http.conf", "http", config_flags);
02088    if (!cfg || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
02089       return 0;
02090    }
02091 
02092    http_tls_was_enabled = (reload && http_tls_cfg.enabled);
02093 
02094    http_tls_cfg.enabled = 0;
02095    if (http_tls_cfg.certfile) {
02096       ast_free(http_tls_cfg.certfile);
02097    }
02098    http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
02099 
02100    if (http_tls_cfg.pvtfile) {
02101       ast_free(http_tls_cfg.pvtfile);
02102    }
02103    http_tls_cfg.pvtfile = ast_strdup("");
02104 
02105    if (http_tls_cfg.cipher) {
02106       ast_free(http_tls_cfg.cipher);
02107    }
02108    http_tls_cfg.cipher = ast_strdup("");
02109 
02110    AST_RWLIST_WRLOCK(&uri_redirects);
02111    while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
02112       ast_free(redirect);
02113    }
02114    AST_RWLIST_UNLOCK(&uri_redirects);
02115 
02116    ast_sockaddr_setnull(&https_desc.local_address);
02117 
02118    session_limit = DEFAULT_SESSION_LIMIT;
02119    session_inactivity = DEFAULT_SESSION_INACTIVITY;
02120    session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
02121 
02122    snprintf(server_name, sizeof(server_name), "Asterisk/%s", ast_get_version());
02123 
02124    v = ast_variable_browse(cfg, "general");
02125    for (; v; v = v->next) {
02126       /* read tls config options while preventing unsupported options from being set */
02127       if (strcasecmp(v->name, "tlscafile")
02128          && strcasecmp(v->name, "tlscapath")
02129          && strcasecmp(v->name, "tlscadir")
02130          && strcasecmp(v->name, "tlsverifyclient")
02131          && strcasecmp(v->name, "tlsdontverifyserver")
02132          && strcasecmp(v->name, "tlsclientmethod")
02133          && strcasecmp(v->name, "sslclientmethod")
02134          && strcasecmp(v->name, "tlscipher")
02135          && strcasecmp(v->name, "sslcipher")
02136          && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
02137          continue;
02138       }
02139 
02140       if (!strcasecmp(v->name, "servername")) {
02141          if (!ast_strlen_zero(v->value)) {
02142             ast_copy_string(server_name, v->value, sizeof(server_name));
02143          } else {
02144             server_name[0] = '\0';
02145          }
02146       } else if (!strcasecmp(v->name, "enabled")) {
02147          enabled = ast_true(v->value);
02148       } else if (!strcasecmp(v->name, "enablestatic")) {
02149          newenablestatic = ast_true(v->value);
02150       } else if (!strcasecmp(v->name, "bindport")) {
02151          if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT,
02152             &bindport, DEFAULT_PORT, 0, 65535)) {
02153             ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %" PRId32 "\n",
02154                v->value, DEFAULT_PORT);
02155          }
02156       } else if (!strcasecmp(v->name, "bindaddr")) {
02157          if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
02158             ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
02159          }
02160       } else if (!strcasecmp(v->name, "prefix")) {
02161          if (!ast_strlen_zero(v->value)) {
02162             newprefix[0] = '/';
02163             ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
02164          } else {
02165             newprefix[0] = '\0';
02166          }
02167       } else if (!strcasecmp(v->name, "redirect")) {
02168          add_redirect(v->value);
02169       } else if (!strcasecmp(v->name, "sessionlimit")) {
02170          if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
02171             &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
02172             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
02173                v->name, v->value, v->lineno);
02174          }
02175       } else if (!strcasecmp(v->name, "session_inactivity")) {
02176          if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
02177             &session_inactivity, DEFAULT_SESSION_INACTIVITY, 1, INT_MAX)) {
02178             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
02179                v->name, v->value, v->lineno);
02180          }
02181       } else if (!strcasecmp(v->name, "session_keep_alive")) {
02182          if (sscanf(v->value, "%30d", &session_keep_alive) != 1
02183             || session_keep_alive < 0) {
02184             session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
02185             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
02186                v->name, v->value, v->lineno);
02187          }
02188       } else {
02189          ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
02190       }
02191    }
02192 
02193    ast_config_destroy(cfg);
02194 
02195    if (strcmp(prefix, newprefix)) {
02196       ast_copy_string(prefix, newprefix, sizeof(prefix));
02197    }
02198 
02199    ast_copy_string(http_server_name, server_name, sizeof(http_server_name));
02200    enablestatic = newenablestatic;
02201 
02202    if (num_addrs && enabled) {
02203       int i;
02204       for (i = 0; i < num_addrs; ++i) {
02205          ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
02206          if (!ast_sockaddr_port(&http_desc.local_address)) {
02207             ast_sockaddr_set_port(&http_desc.local_address, bindport);
02208          }
02209          ast_tcptls_server_start(&http_desc);
02210          if (http_desc.accept_fd == -1) {
02211             ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
02212             ast_sockaddr_setnull(&http_desc.local_address);
02213          } else {
02214             ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
02215             break;
02216          }
02217       }
02218       /* When no specific TLS bindaddr is specified, we just use
02219        * the non-TLS bindaddress here.
02220        */
02221       if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
02222          ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
02223          /* Of course, we can't use the same port though.
02224           * Since no bind address was specified, we just use the
02225           * default TLS port
02226           */
02227          ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
02228       }
02229    }
02230    if (http_tls_was_enabled && !http_tls_cfg.enabled) {
02231       ast_tcptls_server_stop(&https_desc);
02232    } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
02233       /* We can get here either because a TLS-specific address was specified
02234        * or because we copied the non-TLS address here. In the case where
02235        * we read an explicit address from the config, there may have been
02236        * no port specified, so we'll just use the default TLS port.
02237        */
02238       if (!ast_sockaddr_port(&https_desc.local_address)) {
02239          ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
02240       }
02241       if (ast_ssl_setup(https_desc.tls_cfg)) {
02242          ast_tcptls_server_start(&https_desc);
02243       }
02244    }
02245 
02246    return 0;
02247 }

static void __fini_uri_redirects ( void   )  [static]

Definition at line 169 of file http.c.

00171 {

static void __fini_uris ( void   )  [static]

Definition at line 133 of file http.c.

00140 {

static void __init_uri_redirects ( void   )  [static]

Definition at line 169 of file http.c.

00171 {

static void __init_uris ( void   )  [static]

Definition at line 133 of file http.c.

00140 {

static void add_redirect ( const char *  value  )  [static]

Add a new URI redirect The entries in the redirect list are sorted by length, just like the list of URI handlers.

Definition at line 2019 of file http.c.

References ast_calloc, ast_log, AST_RWLIST_EMPTY, AST_RWLIST_FIRST, AST_RWLIST_INSERT_AFTER, AST_RWLIST_INSERT_HEAD, AST_RWLIST_INSERT_TAIL, AST_RWLIST_NEXT, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_skip_blanks(), ast_strdupa, http_uri_redirect::dest, LOG_WARNING, strsep(), and http_uri_redirect::target.

Referenced by __ast_http_load().

02020 {
02021    char *target, *dest;
02022    struct http_uri_redirect *redirect, *cur;
02023    unsigned int target_len;
02024    unsigned int total_len;
02025 
02026    dest = ast_strdupa(value);
02027    dest = ast_skip_blanks(dest);
02028    target = strsep(&dest, " ");
02029    target = ast_skip_blanks(target);
02030    target = strsep(&target, " "); /* trim trailing whitespace */
02031 
02032    if (!dest) {
02033       ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
02034       return;
02035    }
02036 
02037    target_len = strlen(target) + 1;
02038    total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
02039 
02040    if (!(redirect = ast_calloc(1, total_len))) {
02041       return;
02042    }
02043    redirect->dest = redirect->target + target_len;
02044    strcpy(redirect->target, target);
02045    strcpy(redirect->dest, dest);
02046 
02047    AST_RWLIST_WRLOCK(&uri_redirects);
02048 
02049    target_len--; /* So we can compare directly with strlen() */
02050    if (AST_RWLIST_EMPTY(&uri_redirects)
02051       || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
02052       AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
02053       AST_RWLIST_UNLOCK(&uri_redirects);
02054 
02055       return;
02056    }
02057 
02058    AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
02059       if (AST_RWLIST_NEXT(cur, entry)
02060          && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
02061          AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
02062          AST_RWLIST_UNLOCK(&uri_redirects);
02063          return;
02064       }
02065    }
02066 
02067    AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
02068 
02069    AST_RWLIST_UNLOCK(&uri_redirects);
02070 }

const char* ast_get_http_method ( enum ast_http_method  method  ) 

Return http method name string.

Since:
1.8

Definition at line 184 of file http.c.

References ARRAY_LEN, ast_http_methods_text, NULL, and ast_cfhttp_methods_text::text.

Referenced by add_allow_header(), ast_ari_invoke(), auth_http_callback(), and handle_options().

00185 {
00186    int x;
00187 
00188    for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
00189       if (ast_http_methods_text[x].method == method) {
00190          return ast_http_methods_text[x].text;
00191       }
00192    }
00193 
00194    return NULL;
00195 }

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 at line 616 of file http.c.

References ast_http_create_response(), ast_str_create(), ast_str_set(), and DEFAULT_RESPONSE_HEADER_LENGTH.

Referenced by auth_http_callback().

00619 {
00620    int status_code = 401;
00621    char *status_title = "Unauthorized";
00622    struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
00623 
00624    if (http_header_data) {
00625       ast_str_set(&http_header_data,
00626                   0,
00627                   "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
00628                   "Content-type: text/html\r\n",
00629                   realm ? realm : "Asterisk",
00630                   nonce,
00631                   opaque,
00632                   stale ? ", stale=true" : "");
00633    }
00634 
00635    ast_http_create_response(ser,
00636                             status_code,
00637                             status_title,
00638                             http_header_data,
00639                             text);
00640 }

int ast_http_body_discard ( struct ast_tcptls_session_instance ser  ) 

Read and discard any unread HTTP request body.

Since:
12.4.0
Parameters:
ser HTTP TCP/TLS session object.
Return values:
0 on success.
-1 on error.

Definition at line 1113 of file http.c.

References ast_assert, ast_debug, ast_set_flag, ast_test_flag, http_worker_private_data::body_length, http_worker_private_data::flags, http_body_check_chunk_sync(), http_body_discard_chunk_trailer_headers(), http_body_discard_contents(), http_body_get_chunk_length(), HTTP_FLAG_BODY_READ, HTTP_FLAG_CLOSE_ON_COMPLETION, HTTP_FLAG_HAS_BODY, ast_tcptls_session_instance::private_data, and request().

Referenced by ast_http_send(), and ast_websocket_uri_cb().

01114 {
01115    struct http_worker_private_data *request;
01116 
01117    request = ser->private_data;
01118    if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
01119       || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
01120       /* No body to read or it has already been read. */
01121       return 0;
01122    }
01123    ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
01124 
01125    ast_debug(1, "HTTP discarding unused request body\n");
01126 
01127    ast_assert(request->body_length != 0);
01128    if (0 < request->body_length) {
01129       if (http_body_discard_contents(ser, request->body_length, "body")) {
01130          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01131          return -1;
01132       }
01133       return 0;
01134    }
01135 
01136    /* parse chunked-body */
01137    for (;;) {
01138       int length;
01139 
01140       length = http_body_get_chunk_length(ser);
01141       if (length < 0) {
01142          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01143          return -1;
01144       }
01145       if (length == 0) {
01146          /* parsed last-chunk */
01147          break;
01148       }
01149 
01150       if (http_body_discard_contents(ser, length, "chunk-data")
01151          || http_body_check_chunk_sync(ser)) {
01152          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01153          return -1;
01154       }
01155    }
01156 
01157    /* Read and discard any trailer entity-header lines. */
01158    if (http_body_discard_chunk_trailer_headers(ser)) {
01159       ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01160       return -1;
01161    }
01162    return 0;
01163 }

void ast_http_body_read_status ( struct ast_tcptls_session_instance ser,
int  read_success 
)

Update the body read success status.

Since:
12.4.0
Parameters:
ser HTTP TCP/TLS session object.
read_success TRUE if body was read successfully.
Returns:
Nothing

Definition at line 891 of file http.c.

References ast_set_flag, ast_test_flag, http_worker_private_data::flags, HTTP_FLAG_BODY_READ, HTTP_FLAG_CLOSE_ON_COMPLETION, HTTP_FLAG_HAS_BODY, ast_tcptls_session_instance::private_data, and request().

Referenced by http_post_callback().

00892 {
00893    struct http_worker_private_data *request;
00894 
00895    request = ser->private_data;
00896    if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
00897       || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
00898       /* No body to read. */
00899       return;
00900    }
00901    ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
00902    if (!read_success) {
00903       ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
00904    }
00905 }

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.

Parameters:
ser TCP/TLS session object
status_code HTTP response code (200/401/403/404/500)
status_title English equivalent to the status_code parameter
http_header_data The formatted text to use in the http header
text Additional informational text to use in the response
Note:
Function constructs response headers from the status_code, status_title and http_header_data parameters.
The response body is created as HTML content, from the status_code, status_title, and the text parameters.

The http_header_data parameter will be freed as a result of calling function.

Since:
13.2.0

Definition at line 561 of file http.c.

References ast_debug, ast_free, ast_http_send(), AST_HTTP_UNKNOWN, ast_str_buffer(), ast_str_create(), ast_str_set(), ast_strlen_zero, ast_tcptls_close_session_file(), ast_xml_escape(), ast_tcptls_session_instance::f, MAX_CONTENT_LENGTH, MAX_SERVER_NAME_LENGTH, and out.

Referenced by ast_http_auth(), and ast_http_error().

00563 {
00564    char server_name[MAX_SERVER_NAME_LENGTH];
00565    struct ast_str *server_address = ast_str_create(MAX_SERVER_NAME_LENGTH);
00566    struct ast_str *out = ast_str_create(MAX_CONTENT_LENGTH);
00567 
00568    if (!http_header_data || !server_address || !out) {
00569       ast_free(http_header_data);
00570       ast_free(server_address);
00571       ast_free(out);
00572       if (ser && ser->f) {
00573          ast_debug(1, "HTTP closing session. OOM.\n");
00574          ast_tcptls_close_session_file(ser);
00575       }
00576       return;
00577    }
00578 
00579    if(!ast_strlen_zero(http_server_name)) {
00580       ast_xml_escape(http_server_name, server_name, sizeof(server_name));
00581       ast_str_set(&server_address,
00582                    0,
00583                    "<address>%s</address>\r\n",
00584                    server_name);
00585    }
00586 
00587    ast_str_set(&out,
00588                0,
00589                "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
00590                "<html><head>\r\n"
00591                "<title>%d %s</title>\r\n"
00592                "</head><body>\r\n"
00593                "<h1>%s</h1>\r\n"
00594                "<p>%s</p>\r\n"
00595                "<hr />\r\n"
00596                "%s"
00597                "</body></html>\r\n",
00598                status_code,
00599                status_title,
00600                status_title,
00601                text ? text : "",
00602                ast_str_buffer(server_address));
00603 
00604    ast_free(server_address);
00605 
00606    ast_http_send(ser,
00607                  AST_HTTP_UNKNOWN,
00608                  status_code,
00609                  status_title,
00610                  http_header_data,
00611                  out,
00612                  0,
00613                  0);
00614 }

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.

Definition at line 642 of file http.c.

References ast_http_create_response(), ast_str_create(), ast_str_set(), and DEFAULT_RESPONSE_HEADER_LENGTH.

Referenced by ast_ari_callback(), ast_websocket_uri_cb(), auth_http_callback(), generic_http_callback(), handle_uri(), http_post_callback(), http_request_headers_get(), http_request_tracking_setup(), httpd_helper_thread(), httpd_process_request(), httpstatus_callback(), phoneprov_callback(), static_callback(), and websocket_bad_request().

00644 {
00645    struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
00646 
00647    if (http_header_data) {
00648       ast_str_set(&http_header_data, 0, "Content-type: text/html\r\n");
00649    }
00650 
00651    ast_http_create_response(ser,
00652                             status_code,
00653                             status_title,
00654                             http_header_data,
00655                             text);
00656 }

const char* ast_http_ftype2mtype ( const char *  ftype  ) 

Return mime type based on extension.

Parameters:
ftype filename extension
Returns:
String containing associated MIME type
Since:
1.8

Definition at line 197 of file http.c.

References ARRAY_LEN, ext, mimetypes, and NULL.

Referenced by build_profile(), and static_callback().

00198 {
00199    int x;
00200 
00201    if (ftype) {
00202       for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
00203          if (!strcasecmp(ftype, mimetypes[x].ext)) {
00204             return mimetypes[x].mtype;
00205          }
00206       }
00207    }
00208    return NULL;
00209 }

struct ast_http_auth* ast_http_get_auth ( struct ast_variable headers  )  [read]

Get HTTP authentication information from headers.

The returned object is AO2 managed, so clean up with ao2_cleanup().

Parameters:
headers HTTP request headers.
Returns:
HTTP auth structure.

NULL if no supported HTTP auth headers present.

Since:
12

Definition at line 1572 of file http.c.

References ast_assert, ast_base64decode(), ast_begins_with(), ast_log, auth_create(), base64, BASIC_LEN, BASIC_PREFIX, LOG_DEBUG, LOG_WARNING, ast_variable::name, ast_variable::next, NULL, password, strsep(), and ast_variable::value.

Referenced by authenticate_user().

01573 {
01574    struct ast_variable *v;
01575 
01576    for (v = headers; v; v = v->next) {
01577       const char *base64;
01578       char decoded[256] = {};
01579       char *username;
01580       char *password;
01581 #ifdef AST_DEVMODE
01582       int cnt;
01583 #endif /* AST_DEVMODE */
01584 
01585       if (strcasecmp("Authorization", v->name) != 0) {
01586          continue;
01587       }
01588 
01589       if (!ast_begins_with(v->value, BASIC_PREFIX)) {
01590          ast_log(LOG_DEBUG,
01591             "Unsupported Authorization scheme\n");
01592          continue;
01593       }
01594 
01595       /* Basic auth header parsing. RFC 2617, section 2.
01596        *   credentials = "Basic" basic-credentials
01597        *   basic-credentials = base64-user-pass
01598        *   base64-user-pass  = <base64 encoding of user-pass,
01599        *                        except not limited to 76 char/line>
01600        *   user-pass   = userid ":" password
01601        */
01602 
01603       base64 = v->value + BASIC_LEN;
01604 
01605       /* This will truncate "userid:password" lines to
01606        * sizeof(decoded). The array is long enough that this shouldn't
01607        * be a problem */
01608 #ifdef AST_DEVMODE
01609       cnt =
01610 #endif /* AST_DEVMODE */
01611       ast_base64decode((unsigned char*)decoded, base64,
01612          sizeof(decoded) - 1);
01613       ast_assert(cnt < sizeof(decoded));
01614 
01615       /* Split the string at the colon */
01616       password = decoded;
01617       username = strsep(&password, ":");
01618       if (!password) {
01619          ast_log(LOG_WARNING, "Invalid Authorization header\n");
01620          return NULL;
01621       }
01622 
01623       return auth_create(username, password);
01624    }
01625 
01626    return NULL;
01627 }

static char* ast_http_get_contents ( int *  return_length,
struct ast_tcptls_session_instance ser,
struct ast_variable headers 
) [static]

Returns the contents (body) of the HTTP request.

Parameters:
return_length ptr to int that returns content length
ser HTTP TCP/TLS session object
headers List of HTTP headers
Returns:
ptr to content (zero terminated) or NULL on failure
Note:
Since returned ptr is malloc'd, it should be free'd by caller

Definition at line 1174 of file http.c.

References ast_assert, ast_debug, ast_free, ast_log, ast_malloc, ast_realloc, ast_set_flag, ast_test_flag, http_worker_private_data::body_length, buf, errno, http_worker_private_data::flags, http_body_check_chunk_sync(), http_body_discard_chunk_trailer_headers(), http_body_get_chunk_length(), http_body_read_contents(), HTTP_FLAG_BODY_READ, HTTP_FLAG_CLOSE_ON_COMPLETION, HTTP_FLAG_HAS_BODY, LOG_WARNING, MAX_CONTENT_LENGTH, NULL, ast_tcptls_session_instance::private_data, and request().

Referenced by ast_http_get_json(), and ast_http_get_post_vars().

01176 {
01177    struct http_worker_private_data *request;
01178    int content_length;
01179    int bufsize;
01180    char *buf;
01181 
01182    request = ser->private_data;
01183    if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)) {
01184       /* no content - not an error */
01185       return NULL;
01186    }
01187    if (ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
01188       /* Already read the body.  Cannot read again.  Assume no content. */
01189       ast_assert(0);
01190       return NULL;
01191    }
01192    ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
01193 
01194    ast_debug(2, "HTTP consuming request body\n");
01195 
01196    ast_assert(request->body_length != 0);
01197    if (0 < request->body_length) {
01198       /* handle regular non-chunked content */
01199       content_length = request->body_length;
01200       if (content_length > MAX_CONTENT_LENGTH) {
01201          ast_log(LOG_WARNING, "Excessively long HTTP content. (%d > %d)\n",
01202             content_length, MAX_CONTENT_LENGTH);
01203          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01204          errno = EFBIG;
01205          return NULL;
01206       }
01207       buf = ast_malloc(content_length + 1);
01208       if (!buf) {
01209          /* Malloc sets ENOMEM */
01210          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01211          return NULL;
01212       }
01213 
01214       if (http_body_read_contents(ser, buf, content_length, "body")) {
01215          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01216          errno = EIO;
01217          ast_free(buf);
01218          return NULL;
01219       }
01220 
01221       buf[content_length] = 0;
01222       *return_length = content_length;
01223       return buf;
01224    }
01225 
01226    /* pre-allocate buffer */
01227    bufsize = 250;
01228    buf = ast_malloc(bufsize);
01229    if (!buf) {
01230       ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01231       return NULL;
01232    }
01233 
01234    /* parse chunked-body */
01235    content_length = 0;
01236    for (;;) {
01237       int chunk_length;
01238 
01239       chunk_length = http_body_get_chunk_length(ser);
01240       if (chunk_length < 0) {
01241          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01242          errno = EIO;
01243          ast_free(buf);
01244          return NULL;
01245       }
01246       if (chunk_length == 0) {
01247          /* parsed last-chunk */
01248          break;
01249       }
01250       if (content_length + chunk_length > MAX_CONTENT_LENGTH) {
01251          ast_log(LOG_WARNING,
01252             "Excessively long HTTP accumulated chunked body. (%d + %d > %d)\n",
01253             content_length, chunk_length, MAX_CONTENT_LENGTH);
01254          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01255          errno = EFBIG;
01256          ast_free(buf);
01257          return NULL;
01258       }
01259 
01260       /* insure buffer is large enough +1 */
01261       if (content_length + chunk_length >= bufsize) {
01262          char *new_buf;
01263 
01264          /* Increase bufsize until it can handle the expected data. */
01265          do {
01266             bufsize *= 2;
01267          } while (content_length + chunk_length >= bufsize);
01268 
01269          new_buf = ast_realloc(buf, bufsize);
01270          if (!new_buf) {
01271             ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01272             ast_free(buf);
01273             return NULL;
01274          }
01275          buf = new_buf;
01276       }
01277 
01278       if (http_body_read_contents(ser, buf + content_length, chunk_length, "chunk-data")
01279          || http_body_check_chunk_sync(ser)) {
01280          ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01281          errno = EIO;
01282          ast_free(buf);
01283          return NULL;
01284       }
01285       content_length += chunk_length;
01286    }
01287 
01288    /*
01289     * Read and discard any trailer entity-header lines
01290     * which we don't care about.
01291     *
01292     * XXX In the future we may need to add the trailer headers
01293     * to the passed in headers list rather than discarding them.
01294     */
01295    if (http_body_discard_chunk_trailer_headers(ser)) {
01296       ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
01297       errno = EIO;
01298       ast_free(buf);
01299       return NULL;
01300    }
01301 
01302    buf[content_length] = 0;
01303    *return_length = content_length;
01304    return buf;
01305 }

struct ast_variable* ast_http_get_cookies ( struct ast_variable headers  )  [read]

Get cookie from Request headers.

Definition at line 1525 of file http.c.

References ast_variables_destroy(), ast_variable::name, ast_variable::next, NULL, parse_cookies(), and ast_variable::value.

Referenced by ast_http_manid_from_vars(), and httpstatus_callback().

01526 {
01527    struct ast_variable *v, *cookies = NULL;
01528 
01529    for (v = headers; v; v = v->next) {
01530       if (!strcasecmp(v->name, "Cookie")) {
01531          ast_variables_destroy(cookies);
01532          cookies = parse_cookies(v->value);
01533       }
01534    }
01535    return cookies;
01536 }

struct ast_json* ast_http_get_json ( struct ast_tcptls_session_instance ser,
struct ast_variable headers 
) [read]

Get JSON from client Request Entity-Body, if content type is application/json.

Parameters:
ser TCP/TLS session object
headers List of HTTP headers
Returns:
Parsed JSON content body

NULL on error, if no content, or if different content type.

Since:
12

Definition at line 1307 of file http.c.

References ast_free, ast_http_get_contents(), ast_json_load_buf(), ast_strlen_zero, buf, errno, get_content_type(), NULL, RAII_VAR, and type.

Referenced by ast_ari_applications_subscribe_cb(), ast_ari_applications_unsubscribe_cb(), ast_ari_asterisk_get_global_var_cb(), ast_ari_asterisk_get_info_cb(), ast_ari_asterisk_set_global_var_cb(), ast_ari_bridges_add_channel_cb(), ast_ari_bridges_create_cb(), ast_ari_bridges_create_with_id_cb(), ast_ari_bridges_play_cb(), ast_ari_bridges_play_with_id_cb(), ast_ari_bridges_record_cb(), ast_ari_bridges_remove_channel_cb(), ast_ari_bridges_start_moh_cb(), ast_ari_channels_continue_in_dialplan_cb(), ast_ari_channels_get_channel_var_cb(), ast_ari_channels_hangup_cb(), ast_ari_channels_mute_cb(), ast_ari_channels_originate_cb(), ast_ari_channels_originate_with_id_cb(), ast_ari_channels_play_cb(), ast_ari_channels_play_with_id_cb(), ast_ari_channels_record_cb(), ast_ari_channels_redirect_cb(), ast_ari_channels_send_dtmf_cb(), ast_ari_channels_set_channel_var_cb(), ast_ari_channels_snoop_channel_cb(), ast_ari_channels_snoop_channel_with_id_cb(), ast_ari_channels_start_moh_cb(), ast_ari_channels_unmute_cb(), ast_ari_device_states_update_cb(), ast_ari_endpoints_send_message_cb(), ast_ari_endpoints_send_message_to_endpoint_cb(), ast_ari_events_user_event_cb(), ast_ari_mailboxes_update_cb(), ast_ari_playbacks_control_cb(), ast_ari_recordings_copy_stored_cb(), and ast_ari_sounds_list_cb().

01309 {
01310    int content_length = 0;
01311    struct ast_json *body;
01312    RAII_VAR(char *, buf, NULL, ast_free);
01313    RAII_VAR(char *, type, get_content_type(headers), ast_free);
01314 
01315    /* Use errno to distinguish errors from no body */
01316    errno = 0;
01317 
01318    if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
01319       /* Content type is not JSON.  Don't read the body. */
01320       return NULL;
01321    }
01322 
01323    buf = ast_http_get_contents(&content_length, ser, headers);
01324    if (!buf || !content_length) {
01325       /*
01326        * errno already set
01327        * or it is not an error to have zero content
01328        */
01329       return NULL;
01330    }
01331 
01332    body = ast_json_load_buf(buf, content_length, NULL);
01333    if (!body) {
01334       /* Failed to parse JSON; treat as an I/O error */
01335       errno = EIO;
01336       return NULL;
01337    }
01338 
01339    return body;
01340 }

struct ast_variable* ast_http_get_post_vars ( struct ast_tcptls_session_instance ser,
struct ast_variable headers 
) [read]

Get post variables from client Request Entity-Body, if content type is application/x-www-form-urlencoded.

Parameters:
ser TCP/TLS session object
headers List of HTTP headers
Returns:
List of variables within the POST body
Note:
Since returned list is malloc'd, list should be free'd by the calling function
Since:
1.8

Definition at line 1346 of file http.c.

References ast_free, ast_http_get_contents(), ast_strlen_zero, ast_uri_decode(), ast_uri_http_legacy, ast_variable_new(), buf, errno, get_content_type(), NULL, RAII_VAR, strsep(), type, and var.

Referenced by ast_ari_callback(), auth_http_callback(), and generic_http_callback().

01348 {
01349    int content_length = 0;
01350    struct ast_variable *v, *post_vars=NULL, *prev = NULL;
01351    char *var, *val;
01352    RAII_VAR(char *, buf, NULL, ast_free);
01353    RAII_VAR(char *, type, get_content_type(headers), ast_free);
01354 
01355    /* Use errno to distinguish errors from no params */
01356    errno = 0;
01357 
01358    if (ast_strlen_zero(type) ||
01359        strcasecmp(type, "application/x-www-form-urlencoded")) {
01360       /* Content type is not form data.  Don't read the body. */
01361       return NULL;
01362    }
01363 
01364    buf = ast_http_get_contents(&content_length, ser, headers);
01365    if (!buf || !content_length) {
01366       /*
01367        * errno already set
01368        * or it is not an error to have zero content
01369        */
01370       return NULL;
01371    }
01372 
01373    while ((val = strsep(&buf, "&"))) {
01374       var = strsep(&val, "=");
01375       if (val) {
01376          ast_uri_decode(val, ast_uri_http_legacy);
01377       } else  {
01378          val = "";
01379       }
01380       ast_uri_decode(var, ast_uri_http_legacy);
01381       if ((v = ast_variable_new(var, val, ""))) {
01382          if (post_vars) {
01383             prev->next = v;
01384          } else {
01385             post_vars = v;
01386          }
01387          prev = v;
01388       }
01389    }
01390 
01391    return post_vars;
01392 }

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.

Parameters:
name header name to check
expected_name the expected name of the header
value header value to check
expected_value the expected value of the header
Returns:
0 if the name and expected name do not match

-1 if the value and expected value do not match

1 if the both the name and value match their expected value

Since:
13

Definition at line 1703 of file http.c.

References ast_log, and LOG_ERROR.

Referenced by websocket_client_handshake_get_response().

01705 {
01706    if (strcasecmp(name, expected_name)) {
01707       /* no value to validate if names don't match */
01708       return 0;
01709    }
01710 
01711    if (strcasecmp(value, expected_value)) {
01712       ast_log(LOG_ERROR, "Invalid header value - expected %s "
01713          "received %s", value, expected_value);
01714       return -1;
01715    }
01716    return 1;
01717 }

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 be located in the expected value.

Note:
Both header and value checks are case insensitive.
Parameters:
name header name to check
expected_name the expected name of the header
value header value to check if in expected value
expected_value the expected value(s)
Returns:
0 if the name and expected name do not match

-1 if the value and is not in the expected value

1 if the name matches expected name and value is in expected value

Since:
13

Definition at line 1719 of file http.c.

References ast_log, LOG_ERROR, and strcasestr().

Referenced by websocket_client_handshake_get_response().

01721 {
01722    if (strcasecmp(name, expected_name)) {
01723       /* no value to validate if names don't match */
01724       return 0;
01725    }
01726 
01727    if (!strcasestr(expected_value, value)) {
01728       ast_log(LOG_ERROR, "Header '%s' - could not locate '%s' "
01729          "in '%s'\n", name, value, expected_value);
01730       return -1;
01731 
01732    }
01733    return 1;
01734 }

int ast_http_header_parse ( char *  buf,
char **  name,
char **  value 
)

Parse a header into the given name/value strings.

Note:
This modifies the given buffer and the out parameters point (not allocated) to the start of the header name and header value, respectively.
Parameters:
buf a string containing the name/value to point to
name out parameter pointing to the header name
value out parameter pointing to header value
Returns:
-1 if buf is empty

0 if buf could be separated into into name and value

1 if name or value portion don't exist

Since:
13

Definition at line 1681 of file http.c.

References ast_skip_blanks(), ast_strlen_zero, ast_trim_blanks(), remove_excess_lws(), and strsep().

Referenced by websocket_client_handshake_get_response().

01682 {
01683    ast_trim_blanks(buf);
01684    if (ast_strlen_zero(buf)) {
01685       return -1;
01686    }
01687 
01688    *value = buf;
01689    *name = strsep(value, ":");
01690    if (!*value) {
01691       return 1;
01692    }
01693 
01694    *value = ast_skip_blanks(*value);
01695    if (ast_strlen_zero(*value) || ast_strlen_zero(*name)) {
01696       return 1;
01697    }
01698 
01699    remove_excess_lws(*value);
01700    return 0;
01701 }

int ast_http_init ( void   ) 

uint32_t ast_http_manid_from_vars ( struct ast_variable headers  ) 

Return manager id, if exist, from request headers.

Parameters:
headers List of HTTP headers
Returns:
32-bit associated manager session identifier
Since:
1.8

Definition at line 211 of file http.c.

References ast_http_get_cookies(), ast_variables_destroy(), ast_variable::name, ast_variable::next, and ast_variable::value.

Referenced by generic_http_callback(), http_post_callback(), and static_callback().

00212 {
00213    uint32_t mngid = 0;
00214    struct ast_variable *v, *cookies;
00215 
00216    cookies = ast_http_get_cookies(headers);
00217    for (v = cookies; v; v = v->next) {
00218       if (!strcasecmp(v->name, "mansession_id")) {
00219          sscanf(v->value, "%30x", &mngid);
00220          break;
00221       }
00222    }
00223    ast_variables_destroy(cookies);
00224    return mngid;
00225 }

void ast_http_prefix ( char *  buf,
int  len 
)

Return the current prefix.

Parameters:
[out] buf destination buffer for previous
[in] len length of prefix to copy
Since:
1.6.1

Definition at line 227 of file http.c.

References ast_copy_string().

00228 {
00229    if (buf) {
00230       ast_copy_string(buf, prefix, len);
00231    }
00232 }

int ast_http_reload ( void   ) 

Provided by http.c

Definition at line 2304 of file http.c.

References __ast_http_load().

02305 {
02306    return __ast_http_load(1);
02307 }

void ast_http_request_close_on_completion ( struct ast_tcptls_session_instance ser  ) 

Request the HTTP connection be closed after this HTTP request.

Since:
12.4.0
Parameters:
ser HTTP TCP/TLS session object.
Note:
Call before ast_http_error() to make the connection close.
Returns:
Nothing

Definition at line 828 of file http.c.

References ast_set_flag, http_worker_private_data::flags, HTTP_FLAG_CLOSE_ON_COMPLETION, ast_tcptls_session_instance::private_data, and request().

Referenced by ast_ari_callback(), auth_http_callback(), generic_http_callback(), handle_uri(), http_post_callback(), httpstatus_callback(), static_callback(), and websocket_bad_request().

00829 {
00830    struct http_worker_private_data *request = ser->private_data;
00831 
00832    ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
00833 }

int ast_http_response_status_line ( const char *  buf,
const char *  version,
int  code 
)

Parse the http response status line.

Parameters:
buf the http response line information
version the expected http version (e.g. HTTP/1.1)
code the expected status code
Returns:
-1 if version didn't match or status code conversion fails.

status code (>0)

Since:
13

Definition at line 1629 of file http.c.

References ast_log, and LOG_ERROR.

Referenced by websocket_client_handshake_get_response().

01630 {
01631    int status_code;
01632    size_t size = strlen(version);
01633 
01634    if (strncmp(buf, version, size) || buf[size] != ' ') {
01635       ast_log(LOG_ERROR, "HTTP version not supported - "
01636          "expected %s\n", version);
01637       return -1;
01638    }
01639 
01640    /* skip to status code (version + space) */
01641    buf += size + 1;
01642 
01643    if (sscanf(buf, "%d", &status_code) != 1) {
01644       ast_log(LOG_ERROR, "Could not read HTTP status code - "
01645          "%s\n", buf);
01646       return -1;
01647    }
01648 
01649    return status_code;
01650 }

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.

Parameters:
ser TCP/TLS session object
method GET/POST/HEAD
status_code HTTP response code (200/401/403/404/500)
status_title English equivalent to the status_code parameter
http_header An ast_str object containing all headers
out An ast_str object containing the body of the response
fd If out is NULL, a file descriptor where the body of the response is held (otherwise -1)
static_content Zero if the content is dynamically generated and should not be cached; nonzero otherwise
Note:
Function determines the HTTP response header from status_code, status_header, and http_header.
Extra HTTP headers MUST be present only in the http_header argument. The argument "out" should contain only content of the response (no headers!).

HTTP content can be constructed from the argument "out", if it is not NULL; otherwise, the function will read content from FD.

This function calculates the content-length http header itself.

Both the http_header and out arguments will be freed by this function; however, if FD is open, it will remain open.

Since:
1.8

Definition at line 446 of file http.c.

References ast_assert, ast_debug, ast_free, ast_http_body_discard(), AST_HTTP_HEAD, ast_localtime(), ast_log, ast_str_buffer(), ast_str_create(), ast_str_set(), ast_str_strlen(), ast_strftime(), ast_strlen_zero, ast_tcptls_close_session_file(), ast_test_flag, ast_tvnow(), buf, errno, ast_tcptls_session_instance::f, http_worker_private_data::flags, HTTP_FLAG_CLOSE_ON_COMPLETION, len(), LOG_ERROR, LOG_WARNING, MAX_SERVER_NAME_LENGTH, ast_tcptls_session_instance::private_data, and request().

Referenced by ast_ari_callback(), ast_http_create_response(), auth_http_callback(), generic_http_callback(), handle_uri(), httpstatus_callback(), phoneprov_callback(), static_callback(), and websocket_bad_request().

00450 {
00451    struct timeval now = ast_tvnow();
00452    struct ast_tm tm;
00453    char timebuf[80];
00454    int content_length = 0;
00455    int close_connection;
00456    struct ast_str *server_header_field = ast_str_create(MAX_SERVER_NAME_LENGTH);
00457 
00458    if (!ser || !ser->f || !server_header_field) {
00459       /* The connection is not open. */
00460       ast_free(http_header);
00461       ast_free(out);
00462       ast_free(server_header_field);
00463       return;
00464    }
00465 
00466    if(!ast_strlen_zero(http_server_name)) {
00467       ast_str_set(&server_header_field,
00468                    0,
00469                    "Server: %s\r\n",
00470                    http_server_name);
00471    }
00472 
00473    /*
00474     * We shouldn't be sending non-final status codes to this
00475     * function because we may close the connection before
00476     * returning.
00477     */
00478    ast_assert(200 <= status_code);
00479 
00480    if (session_keep_alive <= 0) {
00481       close_connection = 1;
00482    } else {
00483       struct http_worker_private_data *request;
00484 
00485       request = ser->private_data;
00486       if (!request
00487          || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)
00488          || ast_http_body_discard(ser)) {
00489          close_connection = 1;
00490       } else {
00491          close_connection = 0;
00492       }
00493    }
00494 
00495    ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
00496 
00497    /* calc content length */
00498    if (out) {
00499       content_length += ast_str_strlen(out);
00500    }
00501 
00502    if (fd) {
00503       content_length += lseek(fd, 0, SEEK_END);
00504       lseek(fd, 0, SEEK_SET);
00505    }
00506 
00507    /* send http header */
00508    fprintf(ser->f,
00509       "HTTP/1.1 %d %s\r\n"
00510       "%s"
00511       "Date: %s\r\n"
00512       "%s"
00513       "%s"
00514       "%s"
00515       "Content-Length: %d\r\n"
00516       "\r\n",
00517       status_code, status_title ? status_title : "OK",
00518       ast_str_buffer(server_header_field),
00519       timebuf,
00520       close_connection ? "Connection: close\r\n" : "",
00521       static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
00522       http_header ? ast_str_buffer(http_header) : "",
00523       content_length
00524       );
00525 
00526    /* send content */
00527    if (method != AST_HTTP_HEAD || status_code >= 400) {
00528       if (out && ast_str_strlen(out)) {
00529          if (fwrite(ast_str_buffer(out), ast_str_strlen(out), 1, ser->f) != 1) {
00530             ast_log(LOG_ERROR, "fwrite() failed: %s\n", strerror(errno));
00531             close_connection = 1;
00532          }
00533       }
00534 
00535       if (fd) {
00536          char buf[256];
00537          int len;
00538 
00539          while ((len = read(fd, buf, sizeof(buf))) > 0) {
00540             if (fwrite(buf, len, 1, ser->f) != 1) {
00541                ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
00542                close_connection = 1;
00543                break;
00544             }
00545          }
00546       }
00547    }
00548 
00549    ast_free(http_header);
00550    ast_free(out);
00551    ast_free(server_header_field);
00552 
00553    if (close_connection) {
00554       ast_debug(1, "HTTP closing session.  status_code:%d\n", status_code);
00555       ast_tcptls_close_session_file(ser);
00556    } else {
00557       ast_debug(1, "HTTP keeping session open.  status_code:%d\n", status_code);
00558    }
00559 }

int ast_http_uri_link ( struct ast_http_uri urih  ) 

Link the new uri into the list.

Register a URI handler.

They are sorted by length of the string, not alphabetically. Duplicate entries are not replaced, but the insertion order (using <= and not just <) makes sure that more recent insertions hide older ones. On a lookup, we just scan the list and stop at the first matching entry.

Definition at line 667 of file http.c.

References AST_RWLIST_EMPTY, AST_RWLIST_FIRST, AST_RWLIST_INSERT_AFTER, AST_RWLIST_INSERT_HEAD, AST_RWLIST_INSERT_TAIL, AST_RWLIST_NEXT, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, len(), and ast_http_uri::uri.

Referenced by __ast_http_post_load(), __init_manager(), ast_http_init(), load_module(), and reload_module().

00668 {
00669    struct ast_http_uri *uri;
00670    int len = strlen(urih->uri);
00671 
00672    AST_RWLIST_WRLOCK(&uris);
00673 
00674    if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
00675       AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
00676       AST_RWLIST_UNLOCK(&uris);
00677       return 0;
00678    }
00679 
00680    AST_RWLIST_TRAVERSE(&uris, uri, entry) {
00681       if (AST_RWLIST_NEXT(uri, entry) &&
00682          strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
00683          AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
00684          AST_RWLIST_UNLOCK(&uris);
00685 
00686          return 0;
00687       }
00688    }
00689 
00690    AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
00691 
00692    AST_RWLIST_UNLOCK(&uris);
00693 
00694    return 0;
00695 }

void ast_http_uri_unlink ( struct ast_http_uri urih  ) 

Unregister a URI handler.

Definition at line 697 of file http.c.

References AST_RWLIST_REMOVE, AST_RWLIST_UNLOCK, and AST_RWLIST_WRLOCK.

Referenced by __init_manager(), http_shutdown(), reload_module(), and unload_module().

00698 {
00699    AST_RWLIST_WRLOCK(&uris);
00700    AST_RWLIST_REMOVE(&uris, urih, entry);
00701    AST_RWLIST_UNLOCK(&uris);
00702 }

void ast_http_uri_unlink_all_with_key ( const char *  key  ) 

Unregister all handlers with matching key.

Definition at line 704 of file http.c.

References ast_free, AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_http_uri::data, ast_http_uri::dmallocd, ast_http_uri::key, and ast_http_uri::mallocd.

Referenced by __ast_http_post_load(), and unload_module().

00705 {
00706    struct ast_http_uri *urih;
00707    AST_RWLIST_WRLOCK(&uris);
00708    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
00709       if (!strcmp(urih->key, key)) {
00710          AST_RWLIST_REMOVE_CURRENT(entry);
00711          if (urih->dmallocd) {
00712             ast_free(urih->data);
00713          }
00714          if (urih->mallocd) {
00715             ast_free(urih);
00716          }
00717       }
00718    }
00719    AST_RWLIST_TRAVERSE_SAFE_END;
00720    AST_RWLIST_UNLOCK(&uris);
00721 }

static struct ast_http_auth* auth_create ( const char *  userid,
const char *  password 
) [static, read]

Definition at line 1538 of file http.c.

References ao2_alloc, ast_log, LOG_ERROR, NULL, ast_http_auth::password, and ast_http_auth::userid.

Referenced by ast_http_get_auth().

01539 {
01540    struct ast_http_auth *auth;
01541    size_t userid_len;
01542    size_t password_len;
01543 
01544    if (!userid || !password) {
01545       ast_log(LOG_ERROR, "Invalid userid/password\n");
01546       return NULL;
01547    }
01548 
01549    userid_len = strlen(userid) + 1;
01550    password_len = strlen(password) + 1;
01551 
01552    /* Allocate enough room to store everything in one memory block */
01553    auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
01554    if (!auth) {
01555       return NULL;
01556    }
01557 
01558    /* Put the userid right after the struct */
01559    auth->userid = (char *)(auth + 1);
01560    strcpy(auth->userid, userid);
01561 
01562    /* Put the password right after the userid */
01563    auth->password = auth->userid + userid_len;
01564    strcpy(auth->password, password);
01565 
01566    return auth;
01567 }

static int chunked_atoh ( const char *  s,
int  len 
) [static]

Definition at line 980 of file http.c.

References c, and value.

Referenced by http_body_get_chunk_length().

00981 {
00982    int value = 0;
00983    char c;
00984 
00985    if (*s < '0') {
00986       /* zero value must be 0\n not just \n */
00987       return -1;
00988    }
00989 
00990    while (len--) {
00991       c = *s++;
00992       if (c == '\x0D') {
00993          return value;
00994       }
00995       if (c == ';') {
00996          /* We have a chunk-extension that we don't care about. */
00997          while (len--) {
00998             if (*s++ == '\x0D') {
00999                return value;
01000             }
01001          }
01002          break;
01003       }
01004       value <<= 4;
01005       if (c >= '0' && c <= '9') {
01006          value += c - '0';
01007          continue;
01008       }
01009       if (c >= 'a' && c <= 'f') {
01010          value += 10 + c - 'a';
01011          continue;
01012       }
01013       if (c >= 'A' && c <= 'F') {
01014          value += 10 + c - 'A';
01015          continue;
01016       }
01017       /* invalid character */
01018       return -1;
01019    }
01020    /* end of string */
01021    return -1;
01022 }

static int get_content_length ( struct ast_variable headers  )  [static]

Returns the value of the Content-Length header.

Parameters:
headers HTTP headers.
Return values:
length Value of the Content-Length header.
0 if header is not present.
-1 if header is invalid.

Definition at line 778 of file http.c.

References get_header().

Referenced by http_request_tracking_setup().

00779 {
00780    const char *content_length = get_header(headers, "Content-Length");
00781    int length;
00782 
00783    if (!content_length) {
00784       /* Missing content length; assume zero */
00785       return 0;
00786    }
00787 
00788    length = 0;
00789    if (sscanf(content_length, "%30d", &length) != 1) {
00790       /* Invalid Content-Length value */
00791       length = -1;
00792    }
00793    return length;
00794 }

static char* get_content_type ( struct ast_variable headers  )  [static]

Retrieves the content type specified in the "Content-Type" header.

This function only returns the "type/subtype" and any trailing parameter is not included.

Note:
the return value is an allocated string that needs to be freed.
Return values:
the content type/subtype or NULL if the header is not found.

Definition at line 753 of file http.c.

References ast_strndup, get_header(), and NULL.

Referenced by ast_http_get_json(), and ast_http_get_post_vars().

00754 {
00755    const char *content_type = get_header(headers, "Content-Type");
00756    const char *param;
00757    size_t size;
00758 
00759    if (!content_type) {
00760       return NULL;
00761    }
00762 
00763    param = strchr(content_type, ';');
00764    size = param ? param - content_type : strlen(content_type);
00765 
00766    return ast_strndup(content_type, size);
00767 }

static const char* get_header ( struct ast_variable headers,
const char *  field_name 
) [static]

Retrieves the header with the given field name.

Parameters:
headers Headers to search.
field_name Name of the header to find.
Returns:
Associated header value.

NULL if header is not present.

Definition at line 731 of file http.c.

References ast_variable::name, ast_variable::next, NULL, and ast_variable::value.

00732 {
00733    struct ast_variable *v;
00734 
00735    for (v = headers; v; v = v->next) {
00736       if (!strcasecmp(v->name, field_name)) {
00737          return v->value;
00738       }
00739    }
00740    return NULL;
00741 }

static const char* get_transfer_encoding ( struct ast_variable headers  )  [static]

Returns the value of the Transfer-Encoding header.

Parameters:
headers HTTP headers.
Return values:
string Value of the Transfer-Encoding header.
NULL if header is not present.

Definition at line 803 of file http.c.

References get_header().

Referenced by http_request_tracking_setup(), and httpd_process_request().

00804 {
00805    return get_header(headers, "Transfer-Encoding");
00806 }

static char* handle_show_http ( struct ast_cli_entry e,
int  cmd,
struct ast_cli_args a 
) [static]

Definition at line 2249 of file http.c.

References ast_cli_args::argc, ast_cli(), AST_RWLIST_EMPTY, AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, ast_sockaddr_isnull(), ast_sockaddr_stringify(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_http_uri::description, http_uri_redirect::dest, ast_tls_config::enabled, ast_cli_args::fd, ast_http_uri::has_subtree, http_tls_cfg, NULL, ast_tcptls_session_args::old_address, http_uri_redirect::target, ast_http_uri::uri, and ast_cli_entry::usage.

02250 {
02251    struct ast_http_uri *urih;
02252    struct http_uri_redirect *redirect;
02253 
02254    switch (cmd) {
02255    case CLI_INIT:
02256       e->command = "http show status";
02257       e->usage =
02258          "Usage: http show status\n"
02259          "       Lists status of internal HTTP engine\n";
02260       return NULL;
02261    case CLI_GENERATE:
02262       return NULL;
02263    }
02264 
02265    if (a->argc != 3) {
02266       return CLI_SHOWUSAGE;
02267    }
02268    ast_cli(a->fd, "HTTP Server Status:\n");
02269    ast_cli(a->fd, "Prefix: %s\n", prefix);
02270    ast_cli(a->fd, "Server: %s\n", http_server_name);
02271    if (ast_sockaddr_isnull(&http_desc.old_address)) {
02272       ast_cli(a->fd, "Server Disabled\n\n");
02273    } else {
02274       ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
02275          ast_sockaddr_stringify(&http_desc.old_address));
02276       if (http_tls_cfg.enabled) {
02277          ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
02278             ast_sockaddr_stringify(&https_desc.old_address));
02279       }
02280    }
02281 
02282    ast_cli(a->fd, "Enabled URI's:\n");
02283    AST_RWLIST_RDLOCK(&uris);
02284    if (AST_RWLIST_EMPTY(&uris)) {
02285       ast_cli(a->fd, "None.\n");
02286    } else {
02287       AST_RWLIST_TRAVERSE(&uris, urih, entry)
02288          ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
02289    }
02290    AST_RWLIST_UNLOCK(&uris);
02291 
02292    ast_cli(a->fd, "\nEnabled Redirects:\n");
02293    AST_RWLIST_RDLOCK(&uri_redirects);
02294    AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
02295       ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
02296    if (AST_RWLIST_EMPTY(&uri_redirects)) {
02297       ast_cli(a->fd, "  None.\n");
02298    }
02299    AST_RWLIST_UNLOCK(&uri_redirects);
02300 
02301    return CLI_SUCCESS;
02302 }

static int handle_uri ( struct ast_tcptls_session_instance ser,
char *  uri,
enum ast_http_method  method,
struct ast_variable headers 
) [static]

Definition at line 1394 of file http.c.

References ast_debug, ast_http_error(), ast_http_request_close_on_completion(), ast_http_send(), AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, ast_str_create(), ast_str_set(), ast_uri_decode(), ast_uri_http_legacy, ast_variable_new(), ast_variables_destroy(), c, ast_http_uri::callback, cleanup(), http_uri_redirect::dest, ast_http_uri::has_subtree, ast_http_uri::no_decode_uri, NULL, strsep(), http_uri_redirect::target, ast_http_uri::uri, and var.

Referenced by httpd_process_request().

01396 {
01397    char *c;
01398    int res = 0;
01399    char *params = uri;
01400    struct ast_http_uri *urih = NULL;
01401    int l;
01402    struct ast_variable *get_vars = NULL, *v, *prev = NULL;
01403    struct http_uri_redirect *redirect;
01404 
01405    ast_debug(2, "HTTP Request URI is %s \n", uri);
01406 
01407    strsep(&params, "?");
01408    /* Extract arguments from the request and store them in variables. */
01409    if (params) {
01410       char *var, *val;
01411 
01412       while ((val = strsep(&params, "&"))) {
01413          var = strsep(&val, "=");
01414          if (val) {
01415             ast_uri_decode(val, ast_uri_http_legacy);
01416          } else  {
01417             val = "";
01418          }
01419          ast_uri_decode(var, ast_uri_http_legacy);
01420          if ((v = ast_variable_new(var, val, ""))) {
01421             if (get_vars) {
01422                prev->next = v;
01423             } else {
01424                get_vars = v;
01425             }
01426             prev = v;
01427          }
01428       }
01429    }
01430 
01431    AST_RWLIST_RDLOCK(&uri_redirects);
01432    AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
01433       if (!strcasecmp(uri, redirect->target)) {
01434          struct ast_str *http_header = ast_str_create(128);
01435 
01436          if (!http_header) {
01437             ast_http_request_close_on_completion(ser);
01438             ast_http_error(ser, 500, "Server Error", "Out of memory");
01439             break;
01440          }
01441          ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
01442          ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
01443          break;
01444       }
01445    }
01446    AST_RWLIST_UNLOCK(&uri_redirects);
01447    if (redirect) {
01448       goto cleanup;
01449    }
01450 
01451    /* We want requests to start with the (optional) prefix and '/' */
01452    l = strlen(prefix);
01453    if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
01454       uri += l + 1;
01455       /* scan registered uris to see if we match one. */
01456       AST_RWLIST_RDLOCK(&uris);
01457       AST_RWLIST_TRAVERSE(&uris, urih, entry) {
01458          l = strlen(urih->uri);
01459          c = uri + l;   /* candidate */
01460          ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
01461          if (strncasecmp(urih->uri, uri, l) /* no match */
01462              || (*c && *c != '/')) { /* substring */
01463             continue;
01464          }
01465          if (*c == '/') {
01466             c++;
01467          }
01468          if (!*c || urih->has_subtree) {
01469             uri = c;
01470             break;
01471          }
01472       }
01473       AST_RWLIST_UNLOCK(&uris);
01474    }
01475    if (urih) {
01476       ast_debug(1, "Match made with [%s]\n", urih->uri);
01477       if (!urih->no_decode_uri) {
01478          ast_uri_decode(uri, ast_uri_http_legacy);
01479       }
01480       res = urih->callback(ser, urih, uri, method, get_vars, headers);
01481    } else {
01482       ast_debug(1, "Requested URI [%s] has no handler\n", uri);
01483       ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
01484    }
01485 
01486 cleanup:
01487    ast_variables_destroy(get_vars);
01488    return res;
01489 }

static int http_body_check_chunk_sync ( struct ast_tcptls_session_instance ser  )  [static]

Definition at line 1062 of file http.c.

References ast_log, ast_tcptls_session_instance::f, and LOG_WARNING.

Referenced by ast_http_body_discard(), and ast_http_get_contents().

01063 {
01064    int res;
01065    char chunk_sync[2];
01066 
01067    /* Stay in fread until get the expected CRLF or timeout. */
01068    res = fread(chunk_sync, sizeof(chunk_sync), 1, ser->f);
01069    if (res < 1) {
01070       ast_log(LOG_WARNING, "Short HTTP chunk sync read (Wanted %zu)\n",
01071          sizeof(chunk_sync));
01072       return -1;
01073    }
01074    if (chunk_sync[0] != 0x0D || chunk_sync[1] != 0x0A) {
01075       ast_log(LOG_WARNING, "HTTP chunk sync bytes wrong (0x%02hhX, 0x%02hhX)\n",
01076          (unsigned char) chunk_sync[0], (unsigned char) chunk_sync[1]);
01077       return -1;
01078    }
01079 
01080    return 0;
01081 }

static int http_body_discard_chunk_trailer_headers ( struct ast_tcptls_session_instance ser  )  [static]

Definition at line 1093 of file http.c.

References ast_log, ast_strlen_zero, ast_trim_blanks(), ast_tcptls_session_instance::f, LOG_WARNING, and MAX_HTTP_LINE_LENGTH.

Referenced by ast_http_body_discard(), and ast_http_get_contents().

01094 {
01095    char header_line[MAX_HTTP_LINE_LENGTH];
01096 
01097    for (;;) {
01098       if (!fgets(header_line, sizeof(header_line), ser->f)) {
01099          ast_log(LOG_WARNING, "Short HTTP read of chunked trailer header\n");
01100          return -1;
01101       }
01102 
01103       /* Trim trailing whitespace */
01104       ast_trim_blanks(header_line);
01105       if (ast_strlen_zero(header_line)) {
01106          /* A blank line ends the chunked-body */
01107          break;
01108       }
01109    }
01110    return 0;
01111 }

static int http_body_discard_contents ( struct ast_tcptls_session_instance ser,
int  length,
const char *  what_getting 
) [static]

Definition at line 946 of file http.c.

References ast_log, buf, ast_tcptls_session_instance::f, LOG_WARNING, and MAX_HTTP_LINE_LENGTH.

Referenced by ast_http_body_discard().

00947 {
00948    int res;
00949    char buf[MAX_HTTP_LINE_LENGTH];/* Discard buffer */
00950 
00951    /* Stay in fread until get all the expected data or timeout. */
00952    while (sizeof(buf) < length) {
00953       res = fread(buf, sizeof(buf), 1, ser->f);
00954       if (res < 1) {
00955          ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %zu of remaining %d)\n",
00956             what_getting, sizeof(buf), length);
00957          return -1;
00958       }
00959       length -= sizeof(buf);
00960    }
00961    res = fread(buf, length, 1, ser->f);
00962    if (res < 1) {
00963       ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d of remaining %d)\n",
00964          what_getting, length, length);
00965       return -1;
00966    }
00967    return 0;
00968 }

static int http_body_get_chunk_length ( struct ast_tcptls_session_instance ser  )  [static]

Definition at line 1034 of file http.c.

References ast_log, chunked_atoh(), ast_tcptls_session_instance::f, LOG_WARNING, and MAX_HTTP_LINE_LENGTH.

Referenced by ast_http_body_discard(), and ast_http_get_contents().

01035 {
01036    int length;
01037    char header_line[MAX_HTTP_LINE_LENGTH];
01038 
01039    /* get the line of hexadecimal giving chunk-size w/ optional chunk-extension */
01040    if (!fgets(header_line, sizeof(header_line), ser->f)) {
01041       ast_log(LOG_WARNING, "Short HTTP read of chunked header\n");
01042       return -1;
01043    }
01044    length = chunked_atoh(header_line, strlen(header_line));
01045    if (length < 0) {
01046       ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
01047       return -1;
01048    }
01049    return length;
01050 }

static int http_body_read_contents ( struct ast_tcptls_session_instance ser,
char *  buf,
int  length,
const char *  what_getting 
) [static]

Definition at line 920 of file http.c.

References ast_log, ast_tcptls_session_instance::f, and LOG_WARNING.

Referenced by ast_http_get_contents().

00921 {
00922    int res;
00923 
00924    /* Stay in fread until get all the expected data or timeout. */
00925    res = fread(buf, length, 1, ser->f);
00926    if (res < 1) {
00927       ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d)\n",
00928          what_getting, length);
00929       return -1;
00930    }
00931    return 0;
00932 }

static int http_check_connection_close ( struct ast_variable headers  )  [static]

Definition at line 817 of file http.c.

References get_header().

Referenced by http_request_tracking_setup().

00818 {
00819    const char *connection = get_header(headers, "Connection");
00820    int close_connection = 0;
00821 
00822    if (connection && !strcasecmp(connection, "close")) {
00823       close_connection = -1;
00824    }
00825    return close_connection;
00826 }

static int http_request_headers_get ( struct ast_tcptls_session_instance ser,
struct ast_variable **  headers 
) [static]

Definition at line 1750 of file http.c.

References ast_http_error(), ast_skip_blanks(), ast_strlen_zero, ast_trim_blanks(), ast_variable_new(), ast_variables_destroy(), ast_tcptls_session_instance::f, MAX_HTTP_LINE_LENGTH, MAX_HTTP_REQUEST_HEADERS, name, ast_variable::next, NULL, strsep(), and value.

Referenced by httpd_process_request().

01751 {
01752    struct ast_variable *tail = *headers;
01753    int remaining_headers;
01754    char header_line[MAX_HTTP_LINE_LENGTH];
01755 
01756    remaining_headers = MAX_HTTP_REQUEST_HEADERS;
01757    for (;;) {
01758       char *name;
01759       char *value;
01760 
01761       if (!fgets(header_line, sizeof(header_line), ser->f)) {
01762          ast_http_error(ser, 400, "Bad Request", "Timeout");
01763          return -1;
01764       }
01765 
01766       /* Trim trailing characters */
01767       ast_trim_blanks(header_line);
01768       if (ast_strlen_zero(header_line)) {
01769          /* A blank line ends the request header section. */
01770          break;
01771       }
01772 
01773       value = header_line;
01774       name = strsep(&value, ":");
01775       if (!value) {
01776          continue;
01777       }
01778 
01779       value = ast_skip_blanks(value);
01780       if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
01781          continue;
01782       }
01783 
01784       ast_trim_blanks(name);
01785 
01786       if (!remaining_headers--) {
01787          /* Too many headers. */
01788          ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
01789          return -1;
01790       }
01791       if (!*headers) {
01792          *headers = ast_variable_new(name, value, __FILE__);
01793          tail = *headers;
01794       } else {
01795          tail->next = ast_variable_new(name, value, __FILE__);
01796          tail = tail->next;
01797       }
01798       if (!tail) {
01799          /*
01800           * Variable allocation failure.
01801           * Try to make some room.
01802           */
01803          ast_variables_destroy(*headers);
01804          *headers = NULL;
01805 
01806          ast_http_error(ser, 500, "Server Error", "Out of memory");
01807          return -1;
01808       }
01809    }
01810 
01811    return 0;
01812 }

static void http_request_tracking_init ( struct http_worker_private_data request  )  [static]

Definition at line 844 of file http.c.

References ast_set_flags_to, http_worker_private_data::flags, HTTP_FLAG_BODY_READ, HTTP_FLAG_CLOSE_ON_COMPLETION, and HTTP_FLAG_HAS_BODY.

Referenced by httpd_helper_thread(), and httpd_process_request().

00845 {
00846    ast_set_flags_to(&request->flags,
00847       HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
00848       /* Assume close in case request fails early */
00849       HTTP_FLAG_CLOSE_ON_COMPLETION);
00850 }

static int http_request_tracking_setup ( struct ast_tcptls_session_instance ser,
struct ast_variable headers 
) [static]

Definition at line 863 of file http.c.

References ast_http_error(), ast_set_flag, ast_set_flags_to, http_worker_private_data::body_length, http_worker_private_data::flags, get_content_length(), get_transfer_encoding(), http_check_connection_close(), HTTP_FLAG_BODY_READ, HTTP_FLAG_CLOSE_ON_COMPLETION, HTTP_FLAG_HAS_BODY, ast_tcptls_session_instance::private_data, and request().

Referenced by httpd_process_request().

00864 {
00865    struct http_worker_private_data *request = ser->private_data;
00866    const char *transfer_encoding;
00867 
00868    ast_set_flags_to(&request->flags,
00869       HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
00870       http_check_connection_close(headers) ? HTTP_FLAG_CLOSE_ON_COMPLETION : 0);
00871 
00872    transfer_encoding = get_transfer_encoding(headers);
00873    if (transfer_encoding && !strcasecmp(transfer_encoding, "chunked")) {
00874       request->body_length = -1;
00875       ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
00876       return 0;
00877    }
00878 
00879    request->body_length = get_content_length(headers);
00880    if (0 < request->body_length) {
00881       ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
00882    } else if (request->body_length < 0) {
00883       /* Invalid Content-Length */
00884       ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
00885       ast_http_error(ser, 400, "Bad Request", "Invalid Content-Length in request!");
00886       return -1;
00887    }
00888    return 0;
00889 }

static void http_shutdown ( void   )  [static]

static void * httpd_helper_thread ( void *  arg  )  [static]

Definition at line 1913 of file http.c.

References AO2_ALLOC_OPT_LOCK_NOLOCK, ao2_alloc_options, ao2_cleanup, ao2_ref, ast_atomic_fetchadd_int(), ast_debug, ast_http_error(), ast_log, ast_tcptls_close_session_file(), ast_tcptls_stream_set_exclusive_input(), ast_tcptls_stream_set_timeout_inactivity(), errno, ast_tcptls_session_instance::f, ast_tcptls_session_instance::fd, http_request_tracking_init(), httpd_process_request(), LOG_WARNING, MIN_INITIAL_REQUEST_TIMEOUT, NULL, ast_tcptls_session_instance::private_data, ast_tcptls_session_instance::stream_cookie, and timeout.

01914 {
01915    struct ast_tcptls_session_instance *ser = data;
01916    struct protoent *p;
01917    int flags;
01918    int timeout;
01919 
01920    if (!ser || !ser->f) {
01921       ao2_cleanup(ser);
01922       return NULL;
01923    }
01924 
01925    if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
01926       ast_log(LOG_WARNING, "HTTP session count exceeded %d sessions.\n",
01927          session_limit);
01928       goto done;
01929    }
01930    ast_debug(1, "HTTP opening session.  Top level\n");
01931 
01932    /*
01933     * Here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
01934     * This is necessary to prevent delays (caused by buffering) as we
01935     * write to the socket in bits and pieces.
01936     */
01937    p = getprotobyname("tcp");
01938    if (p) {
01939       int arg = 1;
01940 
01941       if (setsockopt(ser->fd, p->p_proto, TCP_NODELAY, (char *) &arg, sizeof(arg) ) < 0) {
01942          ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
01943          ast_log(LOG_WARNING, "Some HTTP requests may be slow to respond.\n");
01944       }
01945    } else {
01946       ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection, getprotobyname(\"tcp\") failed\n");
01947       ast_log(LOG_WARNING, "Some HTTP requests may be slow to respond.\n");
01948    }
01949 
01950    /* make sure socket is non-blocking */
01951    flags = fcntl(ser->fd, F_GETFL);
01952    flags |= O_NONBLOCK;
01953    fcntl(ser->fd, F_SETFL, flags);
01954 
01955    /* Setup HTTP worker private data to keep track of request body reading. */
01956    ao2_cleanup(ser->private_data);
01957    ser->private_data = ao2_alloc_options(sizeof(struct http_worker_private_data), NULL,
01958       AO2_ALLOC_OPT_LOCK_NOLOCK);
01959    if (!ser->private_data) {
01960       ast_http_error(ser, 500, "Server Error", "Out of memory");
01961       goto done;
01962    }
01963    http_request_tracking_init(ser->private_data);
01964 
01965    /* Determine initial HTTP request wait timeout. */
01966    timeout = session_keep_alive;
01967    if (timeout <= 0) {
01968       /* Persistent connections not enabled. */
01969       timeout = session_inactivity;
01970    }
01971    if (timeout < MIN_INITIAL_REQUEST_TIMEOUT) {
01972       timeout = MIN_INITIAL_REQUEST_TIMEOUT;
01973    }
01974 
01975    /* We can let the stream wait for data to arrive. */
01976    ast_tcptls_stream_set_exclusive_input(ser->stream_cookie, 1);
01977 
01978    for (;;) {
01979       int ch;
01980 
01981       /* Wait for next potential HTTP request message. */
01982       ast_tcptls_stream_set_timeout_inactivity(ser->stream_cookie, timeout);
01983       ch = fgetc(ser->f);
01984       if (ch == EOF || ungetc(ch, ser->f) == EOF) {
01985          /* Between request idle timeout */
01986          ast_debug(1, "HTTP idle timeout or peer closed connection.\n");
01987          break;
01988       }
01989 
01990       ast_tcptls_stream_set_timeout_inactivity(ser->stream_cookie, session_inactivity);
01991       if (httpd_process_request(ser) || !ser->f || feof(ser->f)) {
01992          /* Break the connection or the connection closed */
01993          break;
01994       }
01995 
01996       timeout = session_keep_alive;
01997       if (timeout <= 0) {
01998          /* Persistent connections not enabled. */
01999          break;
02000       }
02001    }
02002 
02003 done:
02004    ast_atomic_fetchadd_int(&session_count, -1);
02005 
02006    if (ser->f) {
02007       ast_debug(1, "HTTP closing session.  Top level\n");
02008       ast_tcptls_close_session_file(ser);
02009    }
02010    ao2_ref(ser, -1);
02011    return NULL;
02012 }

static int httpd_process_request ( struct ast_tcptls_session_instance ser  )  [static]

Definition at line 1824 of file http.c.

References AST_HTTP_DELETE, ast_http_error(), AST_HTTP_GET, AST_HTTP_HEAD, AST_HTTP_OPTIONS, AST_HTTP_POST, AST_HTTP_PUT, AST_HTTP_UNKNOWN, ast_shutdown_final(), ast_skip_blanks(), ast_skip_nonblanks(), ast_test_flag, ast_variables_destroy(), c, ast_tcptls_session_instance::f, http_worker_private_data::flags, get_transfer_encoding(), handle_uri(), HTTP_FLAG_CLOSE_ON_COMPLETION, http_request_headers_get(), http_request_tracking_init(), http_request_tracking_setup(), MAX_HTTP_LINE_LENGTH, method, NULL, ast_tcptls_session_instance::private_data, RAII_VAR, and request().

Referenced by httpd_helper_thread().

01825 {
01826    RAII_VAR(struct ast_variable *, headers, NULL, ast_variables_destroy);
01827    char *uri;
01828    char *method;
01829    const char *transfer_encoding;
01830    struct http_worker_private_data *request;
01831    enum ast_http_method http_method = AST_HTTP_UNKNOWN;
01832    int res;
01833    char request_line[MAX_HTTP_LINE_LENGTH];
01834 
01835    if (!fgets(request_line, sizeof(request_line), ser->f)) {
01836       return -1;
01837    }
01838 
01839    /* Re-initialize the request body tracking data. */
01840    request = ser->private_data;
01841    http_request_tracking_init(request);
01842 
01843    /* Get method */
01844    method = ast_skip_blanks(request_line);
01845    uri = ast_skip_nonblanks(method);
01846    if (*uri) {
01847       *uri++ = '\0';
01848    }
01849 
01850    if (!strcasecmp(method,"GET")) {
01851       http_method = AST_HTTP_GET;
01852    } else if (!strcasecmp(method,"POST")) {
01853       http_method = AST_HTTP_POST;
01854    } else if (!strcasecmp(method,"HEAD")) {
01855       http_method = AST_HTTP_HEAD;
01856    } else if (!strcasecmp(method,"PUT")) {
01857       http_method = AST_HTTP_PUT;
01858    } else if (!strcasecmp(method,"DELETE")) {
01859       http_method = AST_HTTP_DELETE;
01860    } else if (!strcasecmp(method,"OPTIONS")) {
01861       http_method = AST_HTTP_OPTIONS;
01862    }
01863 
01864    uri = ast_skip_blanks(uri);   /* Skip white space */
01865    if (*uri) {       /* terminate at the first blank */
01866       char *c = ast_skip_nonblanks(uri);
01867 
01868       if (*c) {
01869          *c = '\0';
01870       }
01871    } else {
01872       ast_http_error(ser, 400, "Bad Request", "Invalid Request");
01873       return -1;
01874    }
01875 
01876    if (ast_shutdown_final()) {
01877       ast_http_error(ser, 503, "Service Unavailable", "Shutdown in progress");
01878       return -1;
01879    }
01880 
01881    /* process "Request Headers" lines */
01882    if (http_request_headers_get(ser, &headers)) {
01883       return -1;
01884    }
01885 
01886    transfer_encoding = get_transfer_encoding(headers);
01887    /* Transfer encoding defaults to identity */
01888    if (!transfer_encoding) {
01889       transfer_encoding = "identity";
01890    }
01891 
01892    /*
01893     * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
01894     * codings we don't understand.
01895     */
01896    if (strcasecmp(transfer_encoding, "identity") != 0 &&
01897       strcasecmp(transfer_encoding, "chunked") != 0) {
01898       /* Transfer encodings not supported */
01899       ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
01900       return -1;
01901    }
01902 
01903    if (http_request_tracking_setup(ser, headers)
01904       || handle_uri(ser, uri, http_method, headers)
01905       || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)) {
01906       res = -1;
01907    } else {
01908       res = 0;
01909    }
01910    return res;
01911 }

static int httpstatus_callback ( struct ast_tcptls_session_instance ser,
const struct ast_http_uri urih,
const char *  uri,
enum ast_http_method  method,
struct ast_variable get_vars,
struct ast_variable headers 
) [static]

Definition at line 358 of file http.c.

References ast_http_error(), AST_HTTP_GET, ast_http_get_cookies(), AST_HTTP_HEAD, ast_http_request_close_on_completion(), ast_http_send(), ast_sockaddr_stringify_addr(), ast_sockaddr_stringify_port(), ast_str_append(), ast_str_create(), ast_variables_destroy(), ast_tls_config::enabled, http_tls_cfg, ast_variable::name, ast_variable::next, NULL, ast_tcptls_session_args::old_address, out, and ast_variable::value.

00362 {
00363    struct ast_str *out;
00364    struct ast_variable *v, *cookies = NULL;
00365 
00366    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
00367       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
00368       return 0;
00369    }
00370 
00371    out = ast_str_create(512);
00372    if (!out) {
00373       ast_http_request_close_on_completion(ser);
00374       ast_http_error(ser, 500, "Server Error", "Out of memory");
00375       return 0;
00376    }
00377 
00378    ast_str_append(&out, 0,
00379       "<html><title>Asterisk HTTP Status</title>\r\n"
00380       "<body bgcolor=\"#ffffff\">\r\n"
00381       "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
00382       "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
00383 
00384    ast_str_append(&out, 0, "<tr><td><i>Server</i></td><td><b>%s</b></td></tr>\r\n", http_server_name);
00385    ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
00386    ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
00387              ast_sockaddr_stringify_addr(&http_desc.old_address));
00388    ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
00389              ast_sockaddr_stringify_port(&http_desc.old_address));
00390    if (http_tls_cfg.enabled) {
00391       ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
00392                 ast_sockaddr_stringify_port(&https_desc.old_address));
00393    }
00394    ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
00395    for (v = get_vars; v; v = v->next) {
00396       ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
00397    }
00398    ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
00399 
00400    cookies = ast_http_get_cookies(headers);
00401    for (v = cookies; v; v = v->next) {
00402       ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
00403    }
00404    ast_variables_destroy(cookies);
00405 
00406    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");
00407    ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
00408    return 0;
00409 }

static struct ast_variable* parse_cookies ( const char *  cookies  )  [static, read]

Definition at line 1491 of file http.c.

References ast_debug, ast_strdupa, ast_strip(), ast_strip_quoted(), ast_strlen_zero, ast_variable_new(), name, NULL, parse(), strsep(), and var.

Referenced by ast_http_get_cookies().

01492 {
01493    char *parse = ast_strdupa(cookies);
01494    char *cur;
01495    struct ast_variable *vars = NULL, *var;
01496 
01497    while ((cur = strsep(&parse, ";"))) {
01498       char *name, *val;
01499 
01500       name = val = cur;
01501       strsep(&val, "=");
01502 
01503       if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
01504          continue;
01505       }
01506 
01507       name = ast_strip(name);
01508       val = ast_strip_quoted(val, "\"", "\"");
01509 
01510       if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
01511          continue;
01512       }
01513 
01514       ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
01515 
01516       var = ast_variable_new(name, val, __FILE__);
01517       var->next = vars;
01518       vars = var;
01519    }
01520 
01521    return vars;
01522 }

static void remove_excess_lws ( char *  s  )  [static]

Definition at line 1652 of file http.c.

References ast_free, ast_malloc, ast_skip_blanks(), ast_skip_nonblanks(), and buf.

Referenced by ast_http_header_parse().

01653 {
01654    char *p, *res = s;
01655    char *buf = ast_malloc(strlen(s) + 1);
01656    char *buf_end;
01657 
01658    if (!buf) {
01659       return;
01660    }
01661 
01662    buf_end = buf;
01663 
01664    while (*s && *(s = ast_skip_blanks(s))) {
01665       p = s;
01666       s = ast_skip_nonblanks(s);
01667 
01668       if (buf_end != buf) {
01669          *buf_end++ = ' ';
01670       }
01671 
01672       memcpy(buf_end, p, s - p);
01673       buf_end += s - p;
01674    }
01675    *buf_end = '\0';
01676    /* safe since buf will always be less than or equal to res */
01677    strcpy(res, buf);
01678    ast_free(buf);
01679 }

static int static_callback ( struct ast_tcptls_session_instance ser,
const struct ast_http_uri urih,
const char *  uri,
enum ast_http_method  method,
struct ast_variable get_vars,
struct ast_variable headers 
) [static]

Definition at line 234 of file http.c.

References ast_alloca, ast_config_AST_DATA_DIR, ast_http_error(), ast_http_ftype2mtype(), AST_HTTP_GET, AST_HTTP_HEAD, ast_http_manid_from_vars(), ast_http_request_close_on_completion(), ast_http_send(), ast_localtime(), ast_str_create(), ast_str_set(), ast_strftime(), ast_strlen_zero, astman_is_authed(), len(), mtype, ast_variable::name, ast_variable::next, NULL, S_OR, and ast_variable::value.

00238 {
00239    char *path;
00240    const char *ftype;
00241    const char *mtype;
00242    char wkspace[80];
00243    struct stat st;
00244    int len;
00245    int fd;
00246    struct ast_str *http_header;
00247    struct timeval tv;
00248    struct ast_tm tm;
00249    char timebuf[80], etag[23];
00250    struct ast_variable *v;
00251    int not_modified = 0;
00252 
00253    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
00254       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
00255       return 0;
00256    }
00257 
00258    /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
00259       substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
00260    if (!enablestatic || ast_strlen_zero(uri)) {
00261       goto out403;
00262    }
00263 
00264    /* Disallow any funny filenames at all (checking first character only??) */
00265    if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
00266       goto out403;
00267    }
00268 
00269    if (strstr(uri, "/..")) {
00270       goto out403;
00271    }
00272 
00273    if ((ftype = strrchr(uri, '.'))) {
00274       ftype++;
00275    }
00276 
00277    if (!(mtype = ast_http_ftype2mtype(ftype))) {
00278       snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
00279       mtype = wkspace;
00280    }
00281 
00282    /* Cap maximum length */
00283    if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
00284       goto out403;
00285    }
00286 
00287    path = ast_alloca(len);
00288    sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
00289    if (stat(path, &st)) {
00290       goto out404;
00291    }
00292 
00293    if (S_ISDIR(st.st_mode)) {
00294       goto out404;
00295    }
00296 
00297    if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
00298       goto out403;
00299    }
00300 
00301    fd = open(path, O_RDONLY);
00302    if (fd < 0) {
00303       goto out403;
00304    }
00305 
00306    /* make "Etag:" http header value */
00307    snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
00308 
00309    /* make "Last-Modified:" http header value */
00310    tv.tv_sec = st.st_mtime;
00311    tv.tv_usec = 0;
00312    ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
00313 
00314    /* check received "If-None-Match" request header and Etag value for file */
00315    for (v = headers; v; v = v->next) {
00316       if (!strcasecmp(v->name, "If-None-Match")) {
00317          if (!strcasecmp(v->value, etag)) {
00318             not_modified = 1;
00319          }
00320          break;
00321       }
00322    }
00323 
00324    http_header = ast_str_create(255);
00325    if (!http_header) {
00326       ast_http_request_close_on_completion(ser);
00327       ast_http_error(ser, 500, "Server Error", "Out of memory");
00328       close(fd);
00329       return 0;
00330    }
00331 
00332    ast_str_set(&http_header, 0, "Content-type: %s\r\n"
00333       "ETag: %s\r\n"
00334       "Last-Modified: %s\r\n",
00335       mtype,
00336       etag,
00337       timebuf);
00338 
00339    /* ast_http_send() frees http_header, so we don't need to do it before returning */
00340    if (not_modified) {
00341       ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
00342    } else {
00343       ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
00344    }
00345    close(fd);
00346    return 0;
00347 
00348 out404:
00349    ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
00350    return 0;
00351 
00352 out403:
00353    ast_http_request_close_on_completion(ser);
00354    ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
00355    return 0;
00356 }


Variable Documentation

Referenced by ast_get_http_method().

struct ast_cli_entry cli_http[] [static]

Initial value:

 {
   AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
}

Definition at line 2309 of file http.c.

int enablestatic [static]

Definition at line 137 of file http.c.

const char* ext

we have up to two accepting threads, one for http, one for https

Definition at line 113 of file http.c.

char http_server_name[MAX_SERVER_NAME_LENGTH] [static]

Definition at line 99 of file http.c.

struct ast_tls_config http_tls_cfg [static]

Definition at line 106 of file http.c.

Referenced by __ast_http_load(), handle_show_http(), http_shutdown(), and httpstatus_callback().

Definition at line 123 of file http.c.

struct { ... } mimetypes[] [static]

Limit the kinds of files we're willing to serve up.

Referenced by ast_http_ftype2mtype().

const char* mtype

Definition at line 142 of file http.c.

Referenced by static_callback().

char prefix[MAX_PREFIX] [static]

int session_count = 0 [static]

Definition at line 104 of file http.c.

Referenced by cli_fax_show_sessions(), and manager_fax_sessions().

int session_inactivity = DEFAULT_SESSION_INACTIVITY [static]

Definition at line 102 of file http.c.

int session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE [static]

Definition at line 103 of file http.c.

int session_limit = DEFAULT_SESSION_LIMIT [static]

Definition at line 101 of file http.c.

struct ast_http_uri staticuri [static]

Definition at line 420 of file http.c.

Referenced by ast_http_init(), and http_shutdown().

struct ast_http_uri statusuri [static]

Definition at line 411 of file http.c.

Referenced by ast_http_init(), and http_shutdown().


Generated on Thu Apr 16 06:31:37 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6