Fri Jan 18 20:00:17 2013

Asterisk developer's documentation


manager.c File Reference

The Asterisk Management Interface - AMI. More...

#include "asterisk.h"
#include "asterisk/_private.h"
#include "asterisk/paths.h"
#include <ctype.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <regex.h>
#include "asterisk/channel.h"
#include "asterisk/file.h"
#include "asterisk/manager.h"
#include "asterisk/module.h"
#include "asterisk/config.h"
#include "asterisk/callerid.h"
#include "asterisk/lock.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/pbx.h"
#include "asterisk/md5.h"
#include "asterisk/acl.h"
#include "asterisk/utils.h"
#include "asterisk/tcptls.h"
#include "asterisk/http.h"
#include "asterisk/ast_version.h"
#include "asterisk/threadstorage.h"
#include "asterisk/linkedlists.h"
#include "asterisk/term.h"
#include "asterisk/astobj2.h"
#include "asterisk/features.h"
#include "asterisk/security_events.h"
#include "asterisk/aoc.h"
#include "asterisk/stringfields.h"
Include dependency graph for manager.c:

Go to the source code of this file.

Data Structures

struct  actions
 list of actions registered More...
struct  all_events
struct  ast_manager_user
 user descriptor, as read from the config file. More...
struct  channelvars
struct  eventqent
struct  fast_originate_helper
 helper function for originate More...
struct  manager_channel_variable
struct  manager_hooks
 list of hooks registered More...
struct  mansession
struct  mansession_datastores
struct  mansession_session
struct  permalias
struct  users
 list of users found in the config file More...
struct  variable_count

Defines

#define ASTMAN_APPEND_BUF_INITSIZE   256
 initial allocated size for the astman_append_buf
#define DEFAULT_REALM   "asterisk"
#define FORMAT   " %-25.25s %-15.15s\n"
#define FORMAT2   " %-25.25s %-15d\n"
#define GET_HEADER_FIRST_MATCH   0
#define GET_HEADER_LAST_MATCH   1
#define GET_HEADER_SKIP_EMPTY   2
#define HSMC_FORMAT   " %-15.15s %-15.15s %-55.55s\n"
#define HSMCONN_FORMAT1   " %-15.15s %-15.15s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
#define HSMCONN_FORMAT2   " %-15.15s %-15.15s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
#define MANAGER_EVENT_BUF_INITSIZE   256
#define MAX_BLACKLIST_CMD_LEN   2
 Descriptor for a manager session, either on the AMI socket or over HTTP.
#define MSG_MOREDATA   ((char *)astman_send_response)
 send a response with an optional message, and terminate it with an empty line. m is used only to grab the 'ActionID' field.
#define ROW_FMT   "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
#define TEST_STRING   "<form action=\"manager\" method=\"post\">\n\ Action: <select name=\"action\">\n\ <option value=\"\">-----&gt;</option>\n\ <option value=\"login\">login</option>\n\ <option value=\"command\">Command</option>\n\ <option value=\"waitevent\">waitevent</option>\n\ <option value=\"listcommands\">listcommands</option>\n\ </select>\n\ or <input name=\"action\"><br/>\n\ CLI Command <input name=\"command\"><br>\n\ user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\ <input type=\"submit\">\n</form>\n"

Enumerations

enum  error_type {
  UNKNOWN_ACTION = 1, UNKNOWN_CATEGORY, UNSPECIFIED_CATEGORY, UNSPECIFIED_ARGUMENT,
  FAILURE_ALLOCATION, FAILURE_NEWCAT, FAILURE_DELCAT, FAILURE_EMPTYCAT,
  FAILURE_UPDATE, FAILURE_DELETE, FAILURE_APPEND
}
enum  mansession_message_parsing { MESSAGE_OKAY, MESSAGE_LINE_TOO_LONG }
enum  output_format { FORMAT_RAW, FORMAT_HTML, FORMAT_XML }

Functions

int __ast_manager_event_multichan (int category, const char *event, int chancount, struct ast_channel **chans, const char *file, int line, const char *func, const char *fmt,...)
static const char * __astman_get_header (const struct message *m, char *var, int mode)
 Return a matching header value.
static void __init_astman_append_buf (void)
 thread local buffer for astman_append
static int __init_manager (int reload)
static void __init_manager_event_buf (void)
static void __init_manager_event_funcbuf (void)
static void __init_userevent_buf (void)
static int action_aocmessage (struct mansession *s, const struct message *m)
static int action_atxfer (struct mansession *s, const struct message *m)
static int action_challenge (struct mansession *s, const struct message *m)
static int action_command (struct mansession *s, const struct message *m)
 Manager command "command" - execute CLI command.
static int action_coresettings (struct mansession *s, const struct message *m)
 Show PBX core settings information.
static int action_coreshowchannels (struct mansession *s, const struct message *m)
 Manager command "CoreShowChannels" - List currently defined channels and some information about them.
static int action_corestatus (struct mansession *s, const struct message *m)
 Show PBX core status information.
static int action_createconfig (struct mansession *s, const struct message *m)
static void action_destroy (void *obj)
static int action_events (struct mansession *s, const struct message *m)
static int action_extensionstate (struct mansession *s, const struct message *m)
static struct manager_action * action_find (const char *name)
static int action_getconfig (struct mansession *s, const struct message *m)
static int action_getconfigjson (struct mansession *s, const struct message *m)
static int action_getvar (struct mansession *s, const struct message *m)
static int action_hangup (struct mansession *s, const struct message *m)
static int action_listcategories (struct mansession *s, const struct message *m)
static int action_listcommands (struct mansession *s, const struct message *m)
static int action_login (struct mansession *s, const struct message *m)
static int action_logoff (struct mansession *s, const struct message *m)
static int action_mailboxcount (struct mansession *s, const struct message *m)
static int action_mailboxstatus (struct mansession *s, const struct message *m)
static int action_originate (struct mansession *s, const struct message *m)
static int action_ping (struct mansession *s, const struct message *m)
static int action_redirect (struct mansession *s, const struct message *m)
 action_redirect: The redirect manager command
static int action_reload (struct mansession *s, const struct message *m)
 Send a reload event.
static int action_sendtext (struct mansession *s, const struct message *m)
static int action_setvar (struct mansession *s, const struct message *m)
static int action_status (struct mansession *s, const struct message *m)
 Manager "status" command to show channels.
static int action_timeout (struct mansession *s, const struct message *m)
static int action_updateconfig (struct mansession *s, const struct message *m)
static int action_userevent (struct mansession *s, const struct message *m)
static int action_waitevent (struct mansession *s, const struct message *m)
static struct eventqent * advance_event (struct eventqent *e)
static int aocmessage_get_unit_entry (const struct message *m, struct ast_aoc_unit_entry *entry, unsigned int entry_num)
static void append_channel_vars (struct ast_str **pbuf, struct ast_channel *chan)
static int append_event (const char *str, int category)
int ast_hook_send_action (struct manager_custom_hook *hook, const char *msg)
 Registered hooks can call this function to invoke actions and they will receive responses through registered callback.
static int ast_instring (const char *bigstr, const char *smallstr, const char delim)
int ast_manager_register2 (const char *action, int auth, int(*func)(struct mansession *s, const struct message *m), const char *synopsis, const char *description)
 register a new command with manager, including online help. This is the preferred way to register a manager command
void ast_manager_register_hook (struct manager_custom_hook *hook)
 Add a custom hook to be called when an event is fired.
static int ast_manager_register_struct (struct manager_action *act)
int ast_manager_unregister (char *action)
 Unregister a registered manager command.
void ast_manager_unregister_hook (struct manager_custom_hook *hook)
 Delete a custom hook to be called when an event is fired.
void astman_append (struct mansession *s, const char *fmt,...)
static void astman_append_json (struct mansession *s, const char *str)
int astman_datastore_add (struct mansession *s, struct ast_datastore *datastore)
 Add a datastore to a session.
struct ast_datastore * astman_datastore_find (struct mansession *s, const struct ast_datastore_info *info, const char *uid)
 Find a datastore on a session.
int astman_datastore_remove (struct mansession *s, struct ast_datastore *datastore)
 Remove a datastore from a session.
const char * astman_get_header (const struct message *m, char *var)
 Return the first matching variable from an array.
struct ast_variable * astman_get_variables (const struct message *m)
 Get a linked list of the Variable: headers.
int astman_is_authed (uint32_t ident)
 Determinie if a manager session ident is authenticated.
void astman_send_ack (struct mansession *s, const struct message *m, char *msg)
 Send ack in manager transaction.
void astman_send_error (struct mansession *s, const struct message *m, char *error)
 Send error in manager transaction.
void astman_send_listack (struct mansession *s, const struct message *m, char *msg, char *listflag)
 Send ack in manager list transaction.
void astman_send_response (struct mansession *s, const struct message *m, char *resp, char *msg)
 Send response in manager transaction.
static void astman_send_response_full (struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
static void astman_start_ack (struct mansession *s, const struct message *m)
int astman_verify_session_readpermissions (uint32_t ident, int perm)
 Verify a session's read permissions against a permission mask.
int astman_verify_session_writepermissions (uint32_t ident, int perm)
 Verify a session's write permissions against a permission mask.
static int auth_http_callback (struct ast_tcptls_session_instance *ser, enum ast_http_method method, enum output_format format, struct sockaddr_in *remote_address, const char *uri, struct ast_variable *get_params, struct ast_variable *headers)
static int auth_manager_http_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_params, struct ast_variable *headers)
static int auth_mxml_http_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_params, struct ast_variable *headers)
static int auth_rawman_http_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_params, struct ast_variable *headers)
static int authenticate (struct mansession *s, const struct message *m)
static const char * authority_to_str (int authority, struct ast_str **res)
 Convert authority code to a list of options.
static int blackfilter_cmp_fn (void *obj, void *arg, void *data, int flags)
static struct mansession_session * build_mansession (struct sockaddr_in sin)
 Allocate manager session structure and add it to the list of sessions.
static int check_blacklist (const char *cmd)
int check_manager_enabled (void)
 Check if AMI is enabled.
static int check_manager_session_inuse (const char *name)
int check_webmanager_enabled (void)
 Check if AMI/HTTP is enabled.
static void destroy_fast_originate_helper (struct fast_originate_helper *doomed)
static int do_message (struct mansession *s)
static void event_filter_destructor (void *obj)
static void * fast_originate (void *data)
static struct mansession_session * find_session (uint32_t ident, int incinuse)
static struct mansession_session * find_session_by_nonce (const char *username, unsigned long nonce, int *stale)
static void free_channelvars (void)
static int function_capable_string_allowed_with_auths (const char *evaluating, int writepermlist)
 Checks to see if a string which can be used to evaluate functions should be rejected.
static int generic_http_callback (struct ast_tcptls_session_instance *ser, enum ast_http_method method, enum output_format format, struct sockaddr_in *remote_address, const char *uri, struct ast_variable *get_params, struct ast_variable *headers)
static int get_input (struct mansession *s, char *output)
static struct ast_manager_user * get_manager_by_name_locked (const char *name)
static int get_perm (const char *instr)
static struct eventqent * grab_last (void)
static char * handle_manager_reload (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI command manager reload.
static char * handle_manager_show_settings (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI command manager show settings.
static char * handle_mandebug (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static void handle_parse_error (struct mansession *s, struct message *m, char *error)
static char * handle_showmanager (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_showmanagers (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_showmancmd (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_showmancmds (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI command manager list commands.
static char * handle_showmanconn (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI command manager list connected.
static char * handle_showmaneventq (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI command manager list eventq.
static enum error_type handle_updates (struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
int init_manager (void)
 Called by Asterisk initialization.
static void json_escape (char *out, const char *in)
static void load_channelvars (struct ast_variable *var)
static struct ast_variable * man_do_variable_value (struct ast_variable *head, const char *hdr_val)
static int manager_displayconnects (struct mansession_session *session)
 Get displayconnects config option.
static void manager_free_user (struct ast_manager_user *user)
static int manager_http_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_params, struct ast_variable *headers)
static int manager_modulecheck (struct mansession *s, const struct message *m)
static int manager_moduleload (struct mansession *s, const struct message *m)
static void manager_shutdown (void)
static int manager_state_cb (char *context, char *exten, int state, void *data)
static int mansession_cmp_fn (void *obj, void *arg, int flags)
static struct sockaddr_in * mansession_encode_sin_local (const struct mansession *s, struct sockaddr_in *sin_local)
static enum
ast_security_event_transport_type 
mansession_get_transport (const struct mansession *s)
static void mansession_lock (struct mansession *s)
 Lock the 'mansession' structure.
static void mansession_unlock (struct mansession *s)
 Unlock the 'mansession' structure.
static int match_filter (struct mansession *s, char *eventdata)
static int mxml_http_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_params, struct ast_variable *headers)
static int process_events (struct mansession *s)
static int process_message (struct mansession *s, const struct message *m)
static void process_output (struct mansession *s, struct ast_str **out, struct ast_variable *params, enum output_format format)
static void purge_events (void)
static void purge_old_stuff (void *data)
 cleanup code called at each iteration of server_root, guaranteed to happen every 5 seconds at most
static void purge_sessions (int n_max)
 remove at most n_max stale session from the list.
static int rawman_http_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_params, struct ast_variable *headers)
int reload_manager (void)
 Called by Asterisk module functions and the CLI command.
static void report_auth_success (const struct mansession *s)
static void report_failed_acl (const struct mansession *s, const char *username)
static void report_failed_challenge_response (const struct mansession *s, const char *response, const char *expected_response)
static void report_inval_password (const struct mansession *s, const char *username)
static void report_invalid_user (const struct mansession *s, const char *username)
static void report_req_bad_format (const struct mansession *s, const char *action)
static void report_req_not_allowed (const struct mansession *s, const char *action)
static void report_session_limit (const struct mansession *s)
static int send_string (struct mansession *s, char *string)
static void session_destroy (struct mansession_session *s)
static void session_destructor (void *obj)
static void * session_do (void *data)
 The body of the individual manager session. Call get_input() to read one line at a time (or be woken up on new events), collect the lines in a message until found an empty line, and execute the request. In any case, deliver events asynchronously through process_events() (called from here if no line is available, or at the end of process_message(). ).
static int set_eventmask (struct mansession *s, const char *eventmask)
 Rather than braindead on,off this now can also accept a specific int mask value or a ',' delim list of mask strings (the same as manager.conf) -anthm.
static int strings_to_mask (const char *string)
static struct mansession_session * unref_mansession (struct mansession_session *s)
 Unreference manager session object. If no more references, then go ahead and delete it.
static int variable_count_cmp_fn (void *obj, void *vstr, int flags)
static int variable_count_hash_fn (const void *vvc, const int flags)
static int whitefilter_cmp_fn (void *obj, void *arg, void *data, int flags)
static void xml_copy_escape (struct ast_str **out, const char *src, int mode)
static void xml_translate (struct ast_str **out, char *in, struct ast_variable *get_vars, enum output_format format)
 Convert the input into XML or HTML. The input is supposed to be a sequence of lines of the form Name: value optionally followed by a blob of unformatted text. A blank line is a section separator. Basically, this is a mixture of the format of Manager Interface and CLI commands. The unformatted text is considered as a single value of a field named 'Opaque-data'.

Variables

static int allowmultiplelogin = 1
static struct ast_http_uri amanageruri
static struct ast_http_uri amanagerxmluri
static struct
ast_tcptls_session_args 
ami_desc
static struct ast_tls_config ami_tls_cfg
static struct
ast_tcptls_session_args 
amis_desc
static struct ast_http_uri arawmanuri
static struct ast_threadstorage astman_append_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_astman_append_buf , .custom_init = NULL , }
static int authlimit
static int authtimeout
static int block_sockets
static int broken_events_action
static struct ast_cli_entry cli_manager []
struct {
   const char *   words [AST_MAX_CMD_LEN]
} command_blacklist []
static const char *const contenttype []
static const int DEFAULT_AUTHLIMIT = 50
static const int DEFAULT_AUTHTIMEOUT = 30
static const int DEFAULT_BLOCKSOCKETS = 0
static const int DEFAULT_BROKENEVENTSACTION = 0
static const int DEFAULT_DISPLAYCONNECTS = 1
static const int DEFAULT_ENABLED = 0
static const int DEFAULT_HTTPTIMEOUT = 60
static const int DEFAULT_MANAGERDEBUG = 0
static const int DEFAULT_TIMESTAMPEVENTS = 0
static const int DEFAULT_WEBENABLED = 0
static int displayconnects
static char global_realm [MAXHOSTNAMELEN]
static int httptimeout
static char * manager_channelvars
static int manager_debug = 0
static int manager_enabled = 0
static struct ast_threadstorage manager_event_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_manager_event_buf , .custom_init = NULL , }
static struct ast_threadstorage manager_event_funcbuf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_manager_event_funcbuf , .custom_init = NULL , }
static struct ast_http_uri manageruri
static struct ast_http_uri managerxmluri
static struct permalias perms []
static struct ast_http_uri rawmanuri
static int registered = 0
static struct ao2_container * sessions = NULL
static int timestampevents
static int unauth_sessions = 0
static struct ast_threadstorage userevent_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_userevent_buf , .custom_init = NULL , }
static int webmanager_enabled = 0
static int webregged = 0

Detailed Description

The Asterisk Management Interface - AMI.

Author:
Mark Spencer <markster@digium.com>
ExtRef:
OpenSSL http://www.openssl.org - for AMI/SSL

At the moment this file contains a number of functions, namely:

manager.conf

Definition in file manager.c.


Define Documentation

#define FORMAT   " %-25.25s %-15.15s\n"
#define FORMAT2   " %-25.25s %-15d\n"
#define HSMC_FORMAT   " %-15.15s %-15.15s %-55.55s\n"

Referenced by handle_showmancmds().

#define HSMCONN_FORMAT1   " %-15.15s %-15.15s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"

Referenced by handle_showmanconn().

#define HSMCONN_FORMAT2   " %-15.15s %-15.15s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"

Referenced by handle_showmanconn().

#define ROW_FMT   "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"

Referenced by generic_http_callback().

#define TEST_STRING   "<form action=\"manager\" method=\"post\">\n\ Action: <select name=\"action\">\n\ <option value=\"\">-----&gt;</option>\n\ <option value=\"login\">login</option>\n\ <option value=\"command\">Command</option>\n\ <option value=\"waitevent\">waitevent</option>\n\ <option value=\"listcommands\">listcommands</option>\n\ </select>\n\ or <input name=\"action\"><br/>\n\ CLI Command <input name=\"command\"><br>\n\ user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\ <input type=\"submit\">\n</form>\n"

Referenced by generic_http_callback().


Enumeration Type Documentation

END Doxygen group

Enumerator:
FORMAT_RAW 
FORMAT_HTML 
FORMAT_XML 

Definition at line 5435 of file manager.c.

05435                    {
05436    FORMAT_RAW,
05437    FORMAT_HTML,
05438    FORMAT_XML,
05439 };


Function Documentation

static int __init_manager ( int  reload  )  [static]

Definition at line 6709 of file manager.c.

References ast_manager_user::a1_hash, action_aocmessage(), action_atxfer(), action_challenge(), action_command(), action_coresettings(), action_coreshowchannels(), action_corestatus(), action_createconfig(), action_events(), action_extensionstate(), action_getconfig(), action_getconfigjson(), action_getvar(), action_hangup(), action_listcategories(), action_listcommands(), action_login(), action_logoff(), action_mailboxcount(), action_mailboxstatus(), action_originate(), action_ping(), action_redirect(), action_reload(), action_sendtext(), action_setvar(), action_status(), action_timeout(), action_updateconfig(), action_userevent(), action_waitevent(), ami_tls_cfg, ao2_container_alloc, ao2_t_alloc, ao2_t_callback, ao2_t_link, ao2_t_ref, append_event(), ARRAY_LEN, ast_append_ha(), ast_calloc, ast_category_browse(), AST_CERTFILE, ast_cli_register_multiple(), ast_config_AST_SYSTEM_NAME, ast_config_destroy(), ast_config_load2(), ast_copy_string(), ast_debug, ast_extension_state_add(), ast_free, ast_free_ha(), ast_http_uri_link(), ast_http_uri_unlink(), AST_LIST_INSERT_TAIL, ast_log(), ast_manager_register_xml, ast_md5_hash(), ast_register_atexit(), AST_RWLIST_INSERT_TAIL, AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_sockaddr_from_sin, ast_sockaddr_setnull(), ast_sockaddr_to_sin, 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_variable_retrieve(), ast_manager_user::blackfilters, block_sockets, ast_tls_config::certfile, ast_tls_config::cipher, CONFIG_FLAG_FILEUNCHANGED, CONFIG_STATUS_FILEINVALID, CONFIG_STATUS_FILEUNCHANGED, DEFAULT_MANAGER_PORT, DEFAULT_MANAGER_TLS_PORT, DEFAULT_REALM, ast_manager_user::displayconnects, ast_tls_config::enabled, event_filter_destructor(), EVENT_FLAG_AOC, EVENT_FLAG_CALL, EVENT_FLAG_COMMAND, EVENT_FLAG_CONFIG, EVENT_FLAG_ORIGINATE, EVENT_FLAG_REPORTING, EVENT_FLAG_SYSTEM, EVENT_FLAG_USER, free_channelvars(), get_manager_by_name_locked(), get_perm(), global_realm, ast_manager_user::ha, ast_manager_user::keep, ast_variable::lineno, load_channelvars(), ast_tcptls_session_args::local_address, LOG_NOTICE, LOG_WARNING, manager_event, manager_free_user(), manager_modulecheck(), manager_moduleload(), manager_shutdown(), manager_state_cb(), mansession_cmp_fn(), ast_variable::name, ast_variable::next, OBJ_MULTIPLE, OBJ_NODATA, OBJ_UNLINK, ast_tls_config::pvtfile, ast_manager_user::readperm, S_OR, ast_manager_user::secret, sessions, ast_tcptls_session_args::tls_cfg, ast_manager_user::username, value, ast_variable::value, var, ast_manager_user::whitefilters, ast_manager_user::writeperm, and ast_manager_user::writetimeout.

Referenced by init_manager(), and reload_manager().

06710 {
06711    struct ast_config *ucfg = NULL, *cfg = NULL;
06712    const char *val;
06713    char *cat = NULL;
06714    int newhttptimeout = DEFAULT_HTTPTIMEOUT;
06715    struct ast_manager_user *user = NULL;
06716    struct ast_variable *var;
06717    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
06718    char a1[256];
06719    char a1_hash[256];
06720    struct sockaddr_in ami_desc_local_address_tmp = { 0, };
06721    struct sockaddr_in amis_desc_local_address_tmp = { 0, };
06722    int tls_was_enabled = 0;
06723 
06724    if (!registered) {
06725       /* Register default actions */
06726       ast_manager_register_xml("Ping", 0, action_ping);
06727       ast_manager_register_xml("Events", 0, action_events);
06728       ast_manager_register_xml("Logoff", 0, action_logoff);
06729       ast_manager_register_xml("Login", 0, action_login);
06730       ast_manager_register_xml("Challenge", 0, action_challenge);
06731       ast_manager_register_xml("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup);
06732       ast_manager_register_xml("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status);
06733       ast_manager_register_xml("Setvar", EVENT_FLAG_CALL, action_setvar);
06734       ast_manager_register_xml("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar);
06735       ast_manager_register_xml("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig);
06736       ast_manager_register_xml("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson);
06737       ast_manager_register_xml("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig);
06738       ast_manager_register_xml("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig);
06739       ast_manager_register_xml("ListCategories", EVENT_FLAG_CONFIG, action_listcategories);
06740       ast_manager_register_xml("Redirect", EVENT_FLAG_CALL, action_redirect);
06741       ast_manager_register_xml("Atxfer", EVENT_FLAG_CALL, action_atxfer);
06742       ast_manager_register_xml("Originate", EVENT_FLAG_ORIGINATE, action_originate);
06743       ast_manager_register_xml("Command", EVENT_FLAG_COMMAND, action_command);
06744       ast_manager_register_xml("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate);
06745       ast_manager_register_xml("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout);
06746       ast_manager_register_xml("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus);
06747       ast_manager_register_xml("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount);
06748       ast_manager_register_xml("ListCommands", 0, action_listcommands);
06749       ast_manager_register_xml("SendText", EVENT_FLAG_CALL, action_sendtext);
06750       ast_manager_register_xml("UserEvent", EVENT_FLAG_USER, action_userevent);
06751       ast_manager_register_xml("WaitEvent", 0, action_waitevent);
06752       ast_manager_register_xml("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings);
06753       ast_manager_register_xml("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus);
06754       ast_manager_register_xml("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload);
06755       ast_manager_register_xml("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels);
06756       ast_manager_register_xml("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload);
06757       ast_manager_register_xml("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck);
06758       ast_manager_register_xml("AOCMessage", EVENT_FLAG_AOC, action_aocmessage);
06759 
06760       ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
06761       ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
06762       registered = 1;
06763       /* Append placeholder event so master_eventq never runs dry */
06764       append_event("Event: Placeholder\r\n\r\n", 0);
06765    }
06766 
06767    ast_register_atexit(manager_shutdown);
06768 
06769    if ((cfg = ast_config_load2("manager.conf", "manager", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
06770       return 0;
06771    }
06772 
06773    manager_enabled = DEFAULT_ENABLED;
06774    webmanager_enabled = DEFAULT_WEBENABLED;
06775    manager_debug = DEFAULT_MANAGERDEBUG;
06776    displayconnects = DEFAULT_DISPLAYCONNECTS;
06777    broken_events_action = DEFAULT_BROKENEVENTSACTION;
06778    block_sockets = DEFAULT_BLOCKSOCKETS;
06779    timestampevents = DEFAULT_TIMESTAMPEVENTS;
06780    httptimeout = DEFAULT_HTTPTIMEOUT;
06781    authtimeout = DEFAULT_AUTHTIMEOUT;
06782    authlimit = DEFAULT_AUTHLIMIT;
06783 
06784    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
06785       ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid. Asterisk management interface (AMI) disabled.\n");
06786       return 0;
06787    }
06788 
06789    /* default values */
06790    ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
06791    ast_sockaddr_setnull(&ami_desc.local_address);
06792    ast_sockaddr_setnull(&amis_desc.local_address);
06793 
06794    ami_desc_local_address_tmp.sin_family = AF_INET;
06795    amis_desc_local_address_tmp.sin_family = AF_INET;
06796 
06797    ami_desc_local_address_tmp.sin_port = htons(DEFAULT_MANAGER_PORT);
06798 
06799    tls_was_enabled = (reload && ami_tls_cfg.enabled);
06800 
06801    ami_tls_cfg.enabled = 0;
06802    if (ami_tls_cfg.certfile) {
06803       ast_free(ami_tls_cfg.certfile);
06804    }
06805    ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
06806    if (ami_tls_cfg.pvtfile) {
06807       ast_free(ami_tls_cfg.pvtfile);
06808    }
06809    ami_tls_cfg.pvtfile = ast_strdup("");
06810    if (ami_tls_cfg.cipher) {
06811       ast_free(ami_tls_cfg.cipher);
06812    }
06813    ami_tls_cfg.cipher = ast_strdup("");
06814 
06815    free_channelvars();
06816 
06817    for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
06818       val = var->value;
06819 
06820       if (!ast_tls_read_conf(&ami_tls_cfg, &amis_desc, var->name, val)) {
06821          continue;
06822       }
06823 
06824       if (!strcasecmp(var->name, "enabled")) {
06825          manager_enabled = ast_true(val);
06826       } else if (!strcasecmp(var->name, "block-sockets")) {
06827          block_sockets = ast_true(val);
06828       } else if (!strcasecmp(var->name, "webenabled")) {
06829          webmanager_enabled = ast_true(val);
06830       } else if (!strcasecmp(var->name, "port")) {
06831          ami_desc_local_address_tmp.sin_port = htons(atoi(val));
06832       } else if (!strcasecmp(var->name, "bindaddr")) {
06833          if (!inet_aton(val, &ami_desc_local_address_tmp.sin_addr)) {
06834             ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
06835             memset(&ami_desc_local_address_tmp.sin_addr, 0,
06836                    sizeof(ami_desc_local_address_tmp.sin_addr));
06837          }
06838       } else if (!strcasecmp(var->name, "brokeneventsaction")) {
06839          broken_events_action = ast_true(val);
06840       } else if (!strcasecmp(var->name, "allowmultiplelogin")) {
06841          allowmultiplelogin = ast_true(val);
06842       } else if (!strcasecmp(var->name, "displayconnects")) {
06843          displayconnects = ast_true(val);
06844       } else if (!strcasecmp(var->name, "timestampevents")) {
06845          timestampevents = ast_true(val);
06846       } else if (!strcasecmp(var->name, "debug")) {
06847          manager_debug = ast_true(val);
06848       } else if (!strcasecmp(var->name, "httptimeout")) {
06849          newhttptimeout = atoi(val);
06850       } else if (!strcasecmp(var->name, "authtimeout")) {
06851          int timeout = atoi(var->value);
06852 
06853          if (timeout < 1) {
06854             ast_log(LOG_WARNING, "Invalid authtimeout value '%s', using default value\n", var->value);
06855          } else {
06856             authtimeout = timeout;
06857          }
06858       } else if (!strcasecmp(var->name, "authlimit")) {
06859          int limit = atoi(var->value);
06860 
06861          if (limit < 1) {
06862             ast_log(LOG_WARNING, "Invalid authlimit value '%s', using default value\n", var->value);
06863          } else {
06864             authlimit = limit;
06865          }
06866       } else if (!strcasecmp(var->name, "channelvars")) {
06867          load_channelvars(var);
06868       } else {
06869          ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
06870             var->name, val);
06871       }
06872    }
06873 
06874    ast_sockaddr_to_sin(&amis_desc.local_address, &amis_desc_local_address_tmp);
06875 
06876    /* if the amis address has not been set, default is the same as non secure ami */
06877    if (!amis_desc_local_address_tmp.sin_addr.s_addr) {
06878       amis_desc_local_address_tmp.sin_addr =
06879           ami_desc_local_address_tmp.sin_addr;
06880    }
06881 
06882    if (!amis_desc_local_address_tmp.sin_port) {
06883       amis_desc_local_address_tmp.sin_port = htons(DEFAULT_MANAGER_TLS_PORT);
06884    }
06885 
06886    if (manager_enabled) {
06887       ast_sockaddr_from_sin(&ami_desc.local_address, &ami_desc_local_address_tmp);
06888       ast_sockaddr_from_sin(&amis_desc.local_address, &amis_desc_local_address_tmp);
06889    }
06890 
06891    AST_RWLIST_WRLOCK(&users);
06892 
06893    /* First, get users from users.conf */
06894    ucfg = ast_config_load2("users.conf", "manager", config_flags);
06895    if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
06896       const char *hasmanager;
06897       int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
06898 
06899       while ((cat = ast_category_browse(ucfg, cat))) {
06900          if (!strcasecmp(cat, "general")) {
06901             continue;
06902          }
06903 
06904          hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
06905          if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
06906             const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
06907             const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
06908             const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
06909             const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
06910             const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
06911 
06912             /* Look for an existing entry,
06913              * if none found - create one and add it to the list
06914              */
06915             if (!(user = get_manager_by_name_locked(cat))) {
06916                if (!(user = ast_calloc(1, sizeof(*user)))) {
06917                   break;
06918                }
06919 
06920                /* Copy name over */
06921                ast_copy_string(user->username, cat, sizeof(user->username));
06922                /* Insert into list */
06923                AST_LIST_INSERT_TAIL(&users, user, list);
06924                user->ha = NULL;
06925                user->keep = 1;
06926                user->readperm = -1;
06927                user->writeperm = -1;
06928                /* Default displayconnect from [general] */
06929                user->displayconnects = displayconnects;
06930                user->writetimeout = 100;
06931             }
06932 
06933             if (!user_secret) {
06934                user_secret = ast_variable_retrieve(ucfg, "general", "secret");
06935             }
06936             if (!user_read) {
06937                user_read = ast_variable_retrieve(ucfg, "general", "read");
06938             }
06939             if (!user_write) {
06940                user_write = ast_variable_retrieve(ucfg, "general", "write");
06941             }
06942             if (!user_displayconnects) {
06943                user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
06944             }
06945             if (!user_writetimeout) {
06946                user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
06947             }
06948 
06949             if (!ast_strlen_zero(user_secret)) {
06950                if (user->secret) {
06951                   ast_free(user->secret);
06952                }
06953                user->secret = ast_strdup(user_secret);
06954             }
06955 
06956             if (user_read) {
06957                user->readperm = get_perm(user_read);
06958             }
06959             if (user_write) {
06960                user->writeperm = get_perm(user_write);
06961             }
06962             if (user_displayconnects) {
06963                user->displayconnects = ast_true(user_displayconnects);
06964             }
06965             if (user_writetimeout) {
06966                int value = atoi(user_writetimeout);
06967                if (value < 100) {
06968                   ast_log(LOG_WARNING, "Invalid writetimeout value '%d' in users.conf\n", value);
06969                } else {
06970                   user->writetimeout = value;
06971                }
06972             }
06973          }
06974       }
06975       ast_config_destroy(ucfg);
06976    }
06977 
06978    /* cat is NULL here in any case */
06979 
06980    while ((cat = ast_category_browse(cfg, cat))) {
06981       struct ast_ha *oldha;
06982 
06983       if (!strcasecmp(cat, "general")) {
06984          continue;
06985       }
06986 
06987       /* Look for an existing entry, if none found - create one and add it to the list */
06988       if (!(user = get_manager_by_name_locked(cat))) {
06989          if (!(user = ast_calloc(1, sizeof(*user)))) {
06990             break;
06991          }
06992          /* Copy name over */
06993          ast_copy_string(user->username, cat, sizeof(user->username));
06994 
06995          user->ha = NULL;
06996          user->readperm = 0;
06997          user->writeperm = 0;
06998          /* Default displayconnect from [general] */
06999          user->displayconnects = displayconnects;
07000          user->writetimeout = 100;
07001          user->whitefilters = ao2_container_alloc(1, NULL, NULL);
07002          user->blackfilters = ao2_container_alloc(1, NULL, NULL);
07003 
07004          /* Insert into list */
07005          AST_RWLIST_INSERT_TAIL(&users, user, list);
07006       } else {
07007          ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
07008          ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
07009       }
07010 
07011       /* Make sure we keep this user and don't destroy it during cleanup */
07012       user->keep = 1;
07013       oldha = user->ha;
07014       user->ha = NULL;
07015 
07016       var = ast_variable_browse(cfg, cat);
07017       for (; var; var = var->next) {
07018          if (!strcasecmp(var->name, "secret")) {
07019             if (user->secret) {
07020                ast_free(user->secret);
07021             }
07022             user->secret = ast_strdup(var->value);
07023          } else if (!strcasecmp(var->name, "deny") ||
07024                    !strcasecmp(var->name, "permit")) {
07025             user->ha = ast_append_ha(var->name, var->value, user->ha, NULL);
07026          }  else if (!strcasecmp(var->name, "read") ) {
07027             user->readperm = get_perm(var->value);
07028          }  else if (!strcasecmp(var->name, "write") ) {
07029             user->writeperm = get_perm(var->value);
07030          }  else if (!strcasecmp(var->name, "displayconnects") ) {
07031             user->displayconnects = ast_true(var->value);
07032          } else if (!strcasecmp(var->name, "writetimeout")) {
07033             int value = atoi(var->value);
07034             if (value < 100) {
07035                ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
07036             } else {
07037                user->writetimeout = value;
07038             }
07039          } else if (!strcasecmp(var->name, "eventfilter")) {
07040             const char *value = var->value;
07041             regex_t *new_filter = ao2_t_alloc(sizeof(*new_filter), event_filter_destructor, "event_filter allocation");
07042             if (new_filter) {
07043                int is_blackfilter;
07044                if (value[0] == '!') {
07045                   is_blackfilter = 1;
07046                   value++;
07047                } else {
07048                   is_blackfilter = 0;
07049                }
07050                if (regcomp(new_filter, value, 0)) {
07051                   ao2_t_ref(new_filter, -1, "failed to make regx");
07052                } else {
07053                   if (is_blackfilter) {
07054                      ao2_t_link(user->blackfilters, new_filter, "link new filter into black user container");
07055                   } else {
07056                      ao2_t_link(user->whitefilters, new_filter, "link new filter into white user container");
07057                   }
07058                }
07059             }
07060          } else {
07061             ast_debug(1, "%s is an unknown option.\n", var->name);
07062          }
07063       }
07064       ast_free_ha(oldha);
07065    }
07066    ast_config_destroy(cfg);
07067 
07068    /* Perform cleanup - essentially prune out old users that no longer exist */
07069    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
07070       if (user->keep) { /* valid record. clear flag for the next round */
07071          user->keep = 0;
07072 
07073          /* Calculate A1 for Digest auth */
07074          snprintf(a1, sizeof(a1), "%s:%s:%s", user->username, global_realm, user->secret);
07075          ast_md5_hash(a1_hash,a1);
07076          if (user->a1_hash) {
07077             ast_free(user->a1_hash);
07078          }
07079          user->a1_hash = ast_strdup(a1_hash);
07080          continue;
07081       }
07082       /* We do not need to keep this user so take them out of the list */
07083       AST_RWLIST_REMOVE_CURRENT(list);
07084       ast_debug(4, "Pruning user '%s'\n", user->username);
07085       manager_free_user(user);
07086    }
07087    AST_RWLIST_TRAVERSE_SAFE_END;
07088 
07089    AST_RWLIST_UNLOCK(&users);
07090 
07091    if (!reload) {
07092       /* If you have a NULL hash fn, you only need a single bucket */
07093       sessions = ao2_container_alloc(1, NULL, mansession_cmp_fn);
07094    }
07095 
07096    if (webmanager_enabled && manager_enabled) {
07097       if (!webregged) {
07098 
07099          ast_http_uri_link(&rawmanuri);
07100          ast_http_uri_link(&manageruri);
07101          ast_http_uri_link(&managerxmluri);
07102 
07103          ast_http_uri_link(&arawmanuri);
07104          ast_http_uri_link(&amanageruri);
07105          ast_http_uri_link(&amanagerxmluri);
07106          webregged = 1;
07107       }
07108    } else {
07109       if (webregged) {
07110          ast_http_uri_unlink(&rawmanuri);
07111          ast_http_uri_unlink(&manageruri);
07112          ast_http_uri_unlink(&managerxmluri);
07113 
07114          ast_http_uri_unlink(&arawmanuri);
07115          ast_http_uri_unlink(&amanageruri);
07116          ast_http_uri_unlink(&amanagerxmluri);
07117          webregged = 0;
07118       }
07119    }
07120 
07121    if (newhttptimeout > 0) {
07122       httptimeout = newhttptimeout;
07123    }
07124 
07125    manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: Manager\r\nStatus: %s\r\nMessage: Manager reload Requested\r\n", manager_enabled ? "Enabled" : "Disabled");
07126 
07127    ast_tcptls_server_start(&ami_desc);
07128    if (tls_was_enabled && !ami_tls_cfg.enabled) {
07129       ast_tcptls_server_stop(&amis_desc);
07130    } else if (ast_ssl_setup(amis_desc.tls_cfg)) {
07131       ast_tcptls_server_start(&amis_desc);
07132    }
07133 
07134    return 0;
07135 }

int astman_datastore_add ( struct mansession *  s,
struct ast_datastore *  datastore 
)

Add a datastore to a session.

Return values:
0 success
non-zero failure
Since:
1.6.1

Definition at line 7158 of file manager.c.

References AST_LIST_INSERT_HEAD, mansession_session::datastores, and mansession::session.

07159 {
07160    AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
07161 
07162    return 0;
07163 }

struct ast_datastore* astman_datastore_find ( struct mansession *  s,
const struct ast_datastore_info *  info,
const char *  uid 
) [read]

Find a datastore on a session.

Return values:
pointer to the datastore if found
NULL if not found
Since:
1.6.1

Definition at line 7170 of file manager.c.

References AST_LIST_TRAVERSE_SAFE_BEGIN, AST_LIST_TRAVERSE_SAFE_END, mansession_session::datastores, ast_datastore::info, mansession::session, and ast_datastore::uid.

07171 {
07172    struct ast_datastore *datastore = NULL;
07173 
07174    if (info == NULL)
07175       return NULL;
07176 
07177    AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
07178       if (datastore->info != info) {
07179          continue;
07180       }
07181 
07182       if (uid == NULL) {
07183          /* matched by type only */
07184          break;
07185       }
07186 
07187       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
07188          /* Matched by type AND uid */
07189          break;
07190       }
07191    }
07192    AST_LIST_TRAVERSE_SAFE_END;
07193 
07194    return datastore;
07195 }

int astman_datastore_remove ( struct mansession *  s,
struct ast_datastore *  datastore 
)

Remove a datastore from a session.

Return values:
0 success
non-zero failure
Since:
1.6.1

Definition at line 7165 of file manager.c.

References AST_LIST_REMOVE, mansession_session::datastores, and mansession::session.

07166 {
07167    return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
07168 }

int astman_is_authed ( uint32_t  ident  ) 

Determinie if a manager session ident is authenticated.

Definition at line 5511 of file manager.c.

References ao2_unlock, mansession_session::authenticated, find_session(), and unref_mansession().

Referenced by http_post_callback(), and static_callback().

05512 {
05513    int authed;
05514    struct mansession_session *session;
05515 
05516    if (!(session = find_session(ident, 0)))
05517       return 0;
05518 
05519    authed = (session->authenticated != 0);
05520 
05521    ao2_unlock(session);
05522    unref_mansession(session);
05523 
05524    return authed;
05525 }

int astman_verify_session_readpermissions ( uint32_t  ident,
int  perm 
)

Verify a session's read permissions against a permission mask.

Parameters:
ident session identity
perm permission mask to verify
Return values:
1 if the session has the permission mask capabilities
0 otherwise

Definition at line 5527 of file manager.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_lock, ao2_unlock, mansession_session::managerid, mansession_session::readperm, sessions, and unref_mansession().

05528 {
05529    int result = 0;
05530    struct mansession_session *session;
05531    struct ao2_iterator i;
05532 
05533    if (ident == 0) {
05534       return 0;
05535    }
05536 
05537    i = ao2_iterator_init(sessions, 0);
05538    while ((session = ao2_iterator_next(&i))) {
05539       ao2_lock(session);
05540       if ((session->managerid == ident) && (session->readperm & perm)) {
05541          result = 1;
05542          ao2_unlock(session);
05543          unref_mansession(session);
05544          break;
05545       }
05546       ao2_unlock(session);
05547       unref_mansession(session);
05548    }
05549    ao2_iterator_destroy(&i);
05550    return result;
05551 }

int astman_verify_session_writepermissions ( uint32_t  ident,
int  perm 
)

Verify a session's write permissions against a permission mask.

Parameters:
ident session identity
perm permission mask to verify
Return values:
1 if the session has the permission mask capabilities, otherwise 0
0 otherwise

Definition at line 5553 of file manager.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_lock, ao2_unlock, mansession_session::managerid, sessions, unref_mansession(), and mansession_session::writeperm.

Referenced by http_post_callback().

05554 {
05555    int result = 0;
05556    struct mansession_session *session;
05557    struct ao2_iterator i;
05558 
05559    if (ident == 0) {
05560       return 0;
05561    }
05562 
05563    i = ao2_iterator_init(sessions, 0);
05564    while ((session = ao2_iterator_next(&i))) {
05565       ao2_lock(session);
05566       if ((session->managerid == ident) && (session->writeperm & perm)) {
05567          result = 1;
05568          ao2_unlock(session);
05569          unref_mansession(session);
05570          break;
05571       }
05572       ao2_unlock(session);
05573       unref_mansession(session);
05574    }
05575    ao2_iterator_destroy(&i);
05576    return result;
05577 }

static int auth_http_callback ( struct ast_tcptls_session_instance *  ser,
enum ast_http_method  method,
enum output_format  format,
struct sockaddr_in *  remote_address,
const char *  uri,
struct ast_variable *  get_params,
struct ast_variable *  headers 
) [static]

Definition at line 6067 of file manager.c.

References ast_manager_user::a1_hash, ao2_lock, ao2_unlock, ARRAY_LEN, ast_apply_ha(), ast_copy_string(), ast_debug, ast_free, ast_get_http_method(), ast_http_auth(), ast_http_error(), AST_HTTP_GET, ast_http_get_post_vars(), AST_HTTP_HEAD, AST_HTTP_POST, ast_http_send(), ast_inet_ntoa(), AST_LIST_HEAD_INIT_NOLOCK, ast_log(), ast_malloc, ast_md5_hash(), ast_mutex_destroy, ast_mutex_init, ast_parse_digest(), ast_random(), AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_sockaddr_from_sin, ast_str_append(), ast_str_create(), ast_string_field_free_memory, ast_string_field_init, ast_strlen_zero(), ast_variables_destroy(), ast_verb, mansession_session::authenticated, build_mansession(), ast_http_digest::cnonce, mansession_session::datastores, ast_manager_user::displayconnects, errno, mansession_session::f, mansession::f, mansession_session::fd, mansession::fd, find_session_by_nonce(), FORMAT_HTML, FORMAT_XML, get_manager_by_name_locked(), global_realm, grab_last(), ast_manager_user::ha, message::hdrcount, message::headers, mansession_session::last_ev, mansession::lock, LOG_NOTICE, LOG_WARNING, mansession_session::managerid, ast_variable::name, mansession_session::nc, ast_http_digest::nc, mansession_session::needdestroy, ast_variable::next, ast_http_digest::nonce, mansession_session::noncetime, mansession_session::oldnonce, process_message(), process_output(), ast_http_digest::qop, mansession_session::readperm, ast_manager_user::readperm, ast_http_digest::response, mansession::session, session_destroy(), mansession_session::sessionstart, mansession_session::sessiontimeout, mansession_session::sin, ast_http_digest::uri, mansession_session::username, ast_manager_user::username, ast_http_digest::username, ast_variable::value, mansession_session::writeperm, ast_manager_user::writeperm, mansession_session::writetimeout, and ast_manager_user::writetimeout.

Referenced by auth_manager_http_callback(), auth_mxml_http_callback(), and auth_rawman_http_callback().

06073 {
06074    struct mansession_session *session = NULL;
06075    struct mansession s = { .session = NULL, .tcptls_session = ser };
06076    struct ast_variable *v, *params = get_params;
06077    char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
06078    struct ast_str *http_header = NULL, *out = NULL;
06079    size_t result_size = 512;
06080    struct message m = { 0 };
06081    unsigned int idx;
06082    size_t hdrlen;
06083 
06084    time_t time_now = time(NULL);
06085    unsigned long nonce = 0, nc;
06086    struct ast_http_digest d = { NULL, };
06087    struct ast_manager_user *user = NULL;
06088    int stale = 0;
06089    char resp_hash[256]="";
06090    /* Cache for user data */
06091    char u_username[80];
06092    int u_readperm;
06093    int u_writeperm;
06094    int u_writetimeout;
06095    int u_displayconnects;
06096    struct ast_sockaddr addr;
06097 
06098    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
06099       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
06100       return -1;
06101    }
06102 
06103    /* Find "Authorization: " header */
06104    for (v = headers; v; v = v->next) {
06105       if (!strcasecmp(v->name, "Authorization")) {
06106          break;
06107       }
06108    }
06109 
06110    if (!v || ast_strlen_zero(v->value)) {
06111       goto out_401; /* Authorization Header not present - send auth request */
06112    }
06113 
06114    /* Digest found - parse */
06115    if (ast_string_field_init(&d, 128)) {
06116       ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
06117       return -1;
06118    }
06119 
06120    if (ast_parse_digest(v->value, &d, 0, 1)) {
06121       /* Error in Digest - send new one */
06122       nonce = 0;
06123       goto out_401;
06124    }
06125    if (sscanf(d.nonce, "%30lx", &nonce) != 1) {
06126       ast_log(LOG_WARNING, "Received incorrect nonce in Digest <%s>\n", d.nonce);
06127       nonce = 0;
06128       goto out_401;
06129    }
06130 
06131    AST_RWLIST_WRLOCK(&users);
06132    user = get_manager_by_name_locked(d.username);
06133    if(!user) {
06134       AST_RWLIST_UNLOCK(&users);
06135       ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
06136       nonce = 0;
06137       goto out_401;
06138    }
06139 
06140    ast_sockaddr_from_sin(&addr, remote_address);
06141    /* --- We have User for this auth, now check ACL */
06142    if (user->ha && !ast_apply_ha(user->ha, &addr)) {
06143       AST_RWLIST_UNLOCK(&users);
06144       ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
06145       ast_http_error(ser, 403, "Permission denied", "Permission denied\n");
06146       return -1;
06147    }
06148 
06149    /* --- We have auth, so check it */
06150 
06151    /* compute the expected response to compare with what we received */
06152    {
06153       char a2[256];
06154       char a2_hash[256];
06155       char resp[256];
06156 
06157       /* XXX Now request method are hardcoded in A2 */
06158       snprintf(a2, sizeof(a2), "%s:%s", ast_get_http_method(method), d.uri);
06159       ast_md5_hash(a2_hash, a2);
06160 
06161       if (d.qop) {
06162          /* RFC 2617 */
06163          snprintf(resp, sizeof(resp), "%s:%08lx:%s:%s:auth:%s", user->a1_hash, nonce, d.nc, d.cnonce, a2_hash);
06164       }  else {
06165          /* RFC 2069 */
06166          snprintf(resp, sizeof(resp), "%s:%08lx:%s", user->a1_hash, nonce, a2_hash);
06167       }
06168       ast_md5_hash(resp_hash, resp);
06169    }
06170 
06171    if (strncasecmp(d.response, resp_hash, strlen(resp_hash))) {
06172       /* Something was wrong, so give the client to try with a new challenge */
06173       AST_RWLIST_UNLOCK(&users);
06174       nonce = 0;
06175       goto out_401;
06176    }
06177 
06178    /*
06179     * User are pass Digest authentication.
06180     * Now, cache the user data and unlock user list.
06181     */
06182    ast_copy_string(u_username, user->username, sizeof(u_username));
06183    u_readperm = user->readperm;
06184    u_writeperm = user->writeperm;
06185    u_displayconnects = user->displayconnects;
06186    u_writetimeout = user->writetimeout;
06187    AST_RWLIST_UNLOCK(&users);
06188 
06189    if (!(session = find_session_by_nonce(d.username, nonce, &stale))) {
06190       /*
06191        * Create new session.
06192        * While it is not in the list we don't need any locking
06193        */
06194       if (!(session = build_mansession(*remote_address))) {
06195          ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
06196          return -1;
06197       }
06198       ao2_lock(session);
06199 
06200       ast_copy_string(session->username, u_username, sizeof(session->username));
06201       session->managerid = nonce;
06202       session->last_ev = grab_last();
06203       AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
06204 
06205       session->readperm = u_readperm;
06206       session->writeperm = u_writeperm;
06207       session->writetimeout = u_writetimeout;
06208 
06209       if (u_displayconnects) {
06210          ast_verb(2, "HTTP Manager '%s' logged in from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
06211       }
06212       session->noncetime = session->sessionstart = time_now;
06213       session->authenticated = 1;
06214    } else if (stale) {
06215       /*
06216        * Session found, but nonce is stale.
06217        *
06218        * This could be because an old request (w/old nonce) arrived.
06219        *
06220        * This may be as the result of http proxy usage (separate delay or
06221        * multipath) or in a situation where a page was refreshed too quickly
06222        * (seen in Firefox).
06223        *
06224        * In this situation, we repeat the 401 auth with the current nonce
06225        * value.
06226        */
06227       nonce = session->managerid;
06228       ao2_unlock(session);
06229       stale = 1;
06230       goto out_401;
06231    } else {
06232       sscanf(d.nc, "%30lx", &nc);
06233       if (session->nc >= nc || ((time_now - session->noncetime) > 62) ) {
06234          /*
06235           * Nonce time expired (> 2 minutes) or something wrong with nonce
06236           * counter.
06237           *
06238           * Create new nonce key and resend Digest auth request. Old nonce
06239           * is saved for stale checking...
06240           */
06241          session->nc = 0; /* Reset nonce counter */
06242          session->oldnonce = session->managerid;
06243          nonce = session->managerid = ast_random();
06244          session->noncetime = time_now;
06245          ao2_unlock(session);
06246          stale = 1;
06247          goto out_401;
06248       } else {
06249          session->nc = nc; /* All OK, save nonce counter */
06250       }
06251    }
06252 
06253 
06254    /* Reset session timeout. */
06255    session->sessiontimeout = time(NULL) + (httptimeout > 5 ? httptimeout : 5);
06256    ao2_unlock(session);
06257 
06258    ast_mutex_init(&s.lock);
06259    s.session = session;
06260    s.fd = mkstemp(template);  /* create a temporary file for command output */
06261    unlink(template);
06262    if (s.fd <= -1) {
06263       ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
06264       goto auth_callback_out;
06265    }
06266    s.f = fdopen(s.fd, "w+");
06267    if (!s.f) {
06268       ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
06269       ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
06270       close(s.fd);
06271       goto auth_callback_out;
06272    }
06273 
06274    if (method == AST_HTTP_POST) {
06275       params = ast_http_get_post_vars(ser, headers);
06276    }
06277 
06278    for (v = params; v && m.hdrcount < ARRAY_LEN(m.headers); v = v->next) {
06279       hdrlen = strlen(v->name) + strlen(v->value) + 3;
06280       m.headers[m.hdrcount] = ast_malloc(hdrlen);
06281       if (!m.headers[m.hdrcount]) {
06282          /* Allocation failure */
06283          continue;
06284       }
06285       snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
06286       ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
06287       ++m.hdrcount;
06288    }
06289 
06290    if (process_message(&s, &m)) {
06291       if (u_displayconnects) {
06292          ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
06293       }
06294 
06295       session->needdestroy = 1;
06296    }
06297 
06298    /* Free request headers. */
06299    for (idx = 0; idx < m.hdrcount; ++idx) {
06300       ast_free((void *) m.headers[idx]);
06301       m.headers[idx] = NULL;
06302    }
06303 
06304    if (s.f) {
06305       result_size = ftell(s.f); /* Calculate approx. size of result */
06306    }
06307 
06308    http_header = ast_str_create(80);
06309    out = ast_str_create(result_size * 2 + 512);
06310 
06311    if (http_header == NULL || out == NULL) {
06312       ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
06313       goto auth_callback_out;
06314    }
06315 
06316    ast_str_append(&http_header, 0, "Content-type: text/%s\r\n", contenttype[format]);
06317 
06318    if (format == FORMAT_XML) {
06319       ast_str_append(&out, 0, "<ajax-response>\n");
06320    } else if (format == FORMAT_HTML) {
06321       ast_str_append(&out, 0,
06322       "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
06323       "<html><head>\r\n"
06324       "<title>Asterisk&trade; Manager Interface</title>\r\n"
06325       "</head><body style=\"background-color: #ffffff;\">\r\n"
06326       "<form method=\"POST\">\r\n"
06327       "<table align=\"center\" style=\"background-color: #f1f1f1;\" width=\"500\">\r\n"
06328       "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\"><h1>Manager Tester</h1></th></tr>\r\n"
06329       "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\">Action: <input name=\"action\" /> Cmd: <input name=\"command\" /><br>"
06330       "<input type=\"submit\" value=\"Send request\" /></th></tr>\r\n");
06331    }
06332 
06333    process_output(&s, &out, params, format);
06334 
06335    if (format == FORMAT_XML) {
06336       ast_str_append(&out, 0, "</ajax-response>\n");
06337    } else if (format == FORMAT_HTML) {
06338       ast_str_append(&out, 0, "</table></form></body></html>\r\n");
06339    }
06340 
06341    ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
06342    http_header = out = NULL;
06343 
06344 auth_callback_out:
06345    ast_mutex_destroy(&s.lock);
06346 
06347    /* Clear resources and unlock manager session */
06348    if (method == AST_HTTP_POST && params) {
06349       ast_variables_destroy(params);
06350    }
06351 
06352    ast_free(http_header);
06353    ast_free(out);
06354 
06355    ao2_lock(session);
06356    if (session->f) {
06357       fclose(session->f);
06358    }
06359    session->f = NULL;
06360    session->fd = -1;
06361    ao2_unlock(session);
06362 
06363    if (session->needdestroy) {
06364       ast_debug(1, "Need destroy, doing it now!\n");
06365       session_destroy(session);
06366    }
06367    ast_string_field_free_memory(&d);
06368    return 0;
06369 
06370 out_401:
06371    if (!nonce) {
06372       nonce = ast_random();
06373    }
06374 
06375    ast_http_auth(ser, global_realm, nonce, nonce, stale, NULL);
06376    ast_string_field_free_memory(&d);
06377    return 0;
06378 }

static int auth_manager_http_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_params,
struct ast_variable *  headers 
) [static]

Definition at line 6439 of file manager.c.

References ast_sockaddr_from_sin, ast_sockaddr_to_sin, auth_http_callback(), FORMAT_HTML, and ast_tcptls_session_instance::remote_address.

06440 {
06441    int retval;
06442    struct sockaddr_in ser_remote_address_tmp;
06443 
06444    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06445    retval = auth_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
06446    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06447    return retval;
06448 }

static int auth_mxml_http_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_params,
struct ast_variable *  headers 
) [static]

Definition at line 6450 of file manager.c.

References ast_sockaddr_from_sin, ast_sockaddr_to_sin, auth_http_callback(), FORMAT_XML, and ast_tcptls_session_instance::remote_address.

06451 {
06452    int retval;
06453    struct sockaddr_in ser_remote_address_tmp;
06454 
06455    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06456    retval = auth_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
06457    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06458    return retval;
06459 }

static int auth_rawman_http_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_params,
struct ast_variable *  headers 
) [static]

Definition at line 6461 of file manager.c.

References ast_sockaddr_from_sin, ast_sockaddr_to_sin, auth_http_callback(), FORMAT_RAW, and ast_tcptls_session_instance::remote_address.

06462 {
06463    int retval;
06464    struct sockaddr_in ser_remote_address_tmp;
06465 
06466    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06467    retval = auth_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
06468    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06469    return retval;
06470 }

static struct mansession_session* find_session ( uint32_t  ident,
int  incinuse 
) [static, read]

locate an http session in the list. The search key (ident) is the value of the mansession_id cookie (0 is not valid and means a session on the AMI socket).

Definition at line 5452 of file manager.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_lock, ao2_unlock, ast_atomic_fetchadd_int(), mansession_session::inuse, mansession_session::managerid, mansession_session::needdestroy, sessions, and unref_mansession().

Referenced by astman_is_authed(), and generic_http_callback().

05453 {
05454    struct mansession_session *session;
05455    struct ao2_iterator i;
05456 
05457    if (ident == 0) {
05458       return NULL;
05459    }
05460 
05461    i = ao2_iterator_init(sessions, 0);
05462    while ((session = ao2_iterator_next(&i))) {
05463       ao2_lock(session);
05464       if (session->managerid == ident && !session->needdestroy) {
05465          ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
05466          break;
05467       }
05468       ao2_unlock(session);
05469       unref_mansession(session);
05470    }
05471    ao2_iterator_destroy(&i);
05472 
05473    return session;
05474 }

static struct mansession_session* find_session_by_nonce ( const char *  username,
unsigned long  nonce,
int *  stale 
) [static, read]

locate an http session in the list. The search keys (nonce) and (username) is value from received "Authorization" http header. As well as in find_session() function, the value of the nonce can't be zero. (0 meansi, that the session used for AMI socket connection). Flag (stale) is set, if client used valid, but old, nonce value.

Definition at line 5485 of file manager.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_lock, ao2_unlock, mansession_session::managerid, mansession_session::oldnonce, sessions, unref_mansession(), and mansession_session::username.

Referenced by auth_http_callback().

05486 {
05487    struct mansession_session *session;
05488    struct ao2_iterator i;
05489 
05490    if (nonce == 0 || username == NULL || stale == NULL) {
05491       return NULL;
05492    }
05493 
05494    i = ao2_iterator_init(sessions, 0);
05495    while ((session = ao2_iterator_next(&i))) {
05496       ao2_lock(session);
05497       if (!strcasecmp(session->username, username) && session->managerid == nonce) {
05498          *stale = 0;
05499          break;
05500       } else if (!strcasecmp(session->username, username) && session->oldnonce == nonce) {
05501          *stale = 1;
05502          break;
05503       }
05504       ao2_unlock(session);
05505       unref_mansession(session);
05506    }
05507    ao2_iterator_destroy(&i);
05508    return session;
05509 }

static int generic_http_callback ( struct ast_tcptls_session_instance *  ser,
enum ast_http_method  method,
enum output_format  format,
struct sockaddr_in *  remote_address,
const char *  uri,
struct ast_variable *  get_params,
struct ast_variable *  headers 
) [static]

Note:
There is approximately a 1 in 1.8E19 chance that the following calculation will produce 0, which is an invalid ID, but due to the properties of the rand() function (and the constantcy of s), that won't happen twice in a row.

Definition at line 5852 of file manager.c.

References ao2_lock, ao2_unlock, ARRAY_LEN, ast_debug, ast_free, ast_http_error(), AST_HTTP_GET, ast_http_get_cookies(), ast_http_get_post_vars(), AST_HTTP_HEAD, AST_HTTP_POST, ast_http_send(), ast_inet_ntoa(), AST_LIST_HEAD_INIT_NOLOCK, ast_log(), ast_malloc, ast_mutex_destroy, ast_mutex_init, AST_PTHREADT_NULL, ast_random(), ast_str_append(), ast_str_create(), ast_variables_destroy(), ast_verb, mansession_session::authenticated, build_mansession(), errno, mansession_session::f, mansession::f, mansession::fd, mansession_session::fd, find_session(), FORMAT_HTML, FORMAT_XML, grab_last(), message::hdrcount, message::headers, mansession_session::inuse, mansession::lock, LOG_WARNING, manager_displayconnects(), mansession_session::managerid, ast_variable::name, mansession_session::needdestroy, ast_variable::next, process_message(), process_output(), ROW_FMT, mansession_session::send_events, mansession::session, session_destroy(), mansession_session::sessiontimeout, mansession_session::sin, TEST_STRING, mansession_session::username, ast_variable::value, and mansession_session::waiting_thread.

Referenced by manager_http_callback(), mxml_http_callback(), and rawman_http_callback().

05858 {
05859    struct mansession s = { .session = NULL, .tcptls_session = ser };
05860    struct mansession_session *session = NULL;
05861    uint32_t ident = 0;
05862    int blastaway = 0;
05863    struct ast_variable *v, *cookies, *params = get_params;
05864    char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
05865    struct ast_str *http_header = NULL, *out = NULL;
05866    struct message m = { 0 };
05867    unsigned int idx;
05868    size_t hdrlen;
05869 
05870    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
05871       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
05872       return -1;
05873    }
05874 
05875    cookies = ast_http_get_cookies(headers);
05876    for (v = cookies; v; v = v->next) {
05877       if (!strcasecmp(v->name, "mansession_id")) {
05878          sscanf(v->value, "%30x", &ident);
05879          break;
05880       }
05881    }
05882    if (cookies) {
05883       ast_variables_destroy(cookies);
05884    }
05885 
05886    if (!(session = find_session(ident, 1))) {
05887 
05888       /**/
05889       /* Create new session.
05890        * While it is not in the list we don't need any locking
05891        */
05892       if (!(session = build_mansession(*remote_address))) {
05893          ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05894          return -1;
05895       }
05896       ao2_lock(session);
05897       session->sin = *remote_address;
05898       session->fd = -1;
05899       session->waiting_thread = AST_PTHREADT_NULL;
05900       session->send_events = 0;
05901       session->inuse = 1;
05902       /*!\note There is approximately a 1 in 1.8E19 chance that the following
05903        * calculation will produce 0, which is an invalid ID, but due to the
05904        * properties of the rand() function (and the constantcy of s), that
05905        * won't happen twice in a row.
05906        */
05907       while ((session->managerid = ast_random() ^ (unsigned long) session) == 0);
05908       session->last_ev = grab_last();
05909       AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
05910    }
05911    ao2_unlock(session);
05912 
05913    http_header = ast_str_create(128);
05914    out = ast_str_create(2048);
05915 
05916    ast_mutex_init(&s.lock);
05917 
05918    if (http_header == NULL || out == NULL) {
05919       ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
05920       goto generic_callback_out;
05921    }
05922 
05923    s.session = session;
05924    s.fd = mkstemp(template);  /* create a temporary file for command output */
05925    unlink(template);
05926    if (s.fd <= -1) {
05927       ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
05928       goto generic_callback_out;
05929    }
05930    s.f = fdopen(s.fd, "w+");
05931    if (!s.f) {
05932       ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
05933       ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
05934       close(s.fd);
05935       goto generic_callback_out;
05936    }
05937 
05938    if (method == AST_HTTP_POST) {
05939       params = ast_http_get_post_vars(ser, headers);
05940    }
05941 
05942    for (v = params; v && m.hdrcount < ARRAY_LEN(m.headers); v = v->next) {
05943       hdrlen = strlen(v->name) + strlen(v->value) + 3;
05944       m.headers[m.hdrcount] = ast_malloc(hdrlen);
05945       if (!m.headers[m.hdrcount]) {
05946          /* Allocation failure */
05947          continue;
05948       }
05949       snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
05950       ast_debug(1, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
05951       ++m.hdrcount;
05952    }
05953 
05954    if (process_message(&s, &m)) {
05955       if (session->authenticated) {
05956          if (manager_displayconnects(session)) {
05957             ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05958          }
05959       } else {
05960          if (displayconnects) {
05961             ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
05962          }
05963       }
05964       session->needdestroy = 1;
05965    }
05966 
05967    /* Free request headers. */
05968    for (idx = 0; idx < m.hdrcount; ++idx) {
05969       ast_free((void *) m.headers[idx]);
05970       m.headers[idx] = NULL;
05971    }
05972 
05973    ast_str_append(&http_header, 0,
05974       "Content-type: text/%s\r\n"
05975       "Cache-Control: no-cache;\r\n"
05976       "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
05977       "Pragma: SuppressEvents\r\n",
05978       contenttype[format],
05979       session->managerid, httptimeout);
05980 
05981    if (format == FORMAT_XML) {
05982       ast_str_append(&out, 0, "<ajax-response>\n");
05983    } else if (format == FORMAT_HTML) {
05984       /*
05985        * When handling AMI-over-HTTP in HTML format, we provide a simple form for
05986        * debugging purposes. This HTML code should not be here, we
05987        * should read from some config file...
05988        */
05989 
05990 #define ROW_FMT   "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
05991 #define TEST_STRING \
05992    "<form action=\"manager\" method=\"post\">\n\
05993    Action: <select name=\"action\">\n\
05994       <option value=\"\">-----&gt;</option>\n\
05995       <option value=\"login\">login</option>\n\
05996       <option value=\"command\">Command</option>\n\
05997       <option value=\"waitevent\">waitevent</option>\n\
05998       <option value=\"listcommands\">listcommands</option>\n\
05999    </select>\n\
06000    or <input name=\"action\"><br/>\n\
06001    CLI Command <input name=\"command\"><br>\n\
06002    user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
06003    <input type=\"submit\">\n</form>\n"
06004 
06005       ast_str_append(&out, 0, "<title>Asterisk&trade; Manager Interface</title>");
06006       ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
06007       ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
06008       ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
06009    }
06010 
06011    process_output(&s, &out, params, format);
06012 
06013    if (format == FORMAT_XML) {
06014       ast_str_append(&out, 0, "</ajax-response>\n");
06015    } else if (format == FORMAT_HTML) {
06016       ast_str_append(&out, 0, "</table></body>\r\n");
06017    }
06018 
06019    ao2_lock(session);
06020    /* Reset HTTP timeout.  If we're not authenticated, keep it extremely short */
06021    session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
06022 
06023    if (session->needdestroy) {
06024       if (session->inuse == 1) {
06025          ast_debug(1, "Need destroy, doing it now!\n");
06026          blastaway = 1;
06027       } else {
06028          ast_debug(1, "Need destroy, but can't do it yet!\n");
06029          if (session->waiting_thread != AST_PTHREADT_NULL) {
06030             pthread_kill(session->waiting_thread, SIGURG);
06031          }
06032          session->inuse--;
06033       }
06034    } else {
06035       session->inuse--;
06036    }
06037    ao2_unlock(session);
06038 
06039    ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
06040    http_header = out = NULL;
06041 
06042 generic_callback_out:
06043    ast_mutex_destroy(&s.lock);
06044 
06045    /* Clear resource */
06046 
06047    if (method == AST_HTTP_POST && params) {
06048       ast_variables_destroy(params);
06049    }
06050    if (http_header) {
06051       ast_free(http_header);
06052    }
06053    if (out) {
06054       ast_free(out);
06055    }
06056 
06057    if (session && blastaway) {
06058       session_destroy(session);
06059    } else if (session && session->f) {
06060       fclose(session->f);
06061       session->f = NULL;
06062    }
06063 
06064    return 0;
06065 }

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

CLI command manager show settings.

Definition at line 6534 of file manager.c.

References ami_tls_cfg, ast_cli_args::argc, ast_cli(), AST_CLI_YESNO, ast_sockaddr_stringify(), block_sockets, ast_tls_config::certfile, ast_tls_config::cipher, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_tls_config::enabled, ast_cli_args::fd, FORMAT, FORMAT2, ast_tcptls_session_args::local_address, ast_tls_config::pvtfile, S_OR, and ast_cli_entry::usage.

06535 {
06536    switch (cmd) {
06537    case CLI_INIT:
06538       e->command = "manager show settings";
06539       e->usage =
06540          "Usage: manager show settings\n"
06541          "       Provides detailed list of the configuration of the Manager.\n";
06542       return NULL;
06543    case CLI_GENERATE:
06544       return NULL;
06545    }
06546 #define FORMAT "  %-25.25s  %-15.15s\n"
06547 #define FORMAT2 "  %-25.25s  %-15d\n"
06548    if (a->argc != 3) {
06549       return CLI_SHOWUSAGE;
06550    }
06551    ast_cli(a->fd, "\nGlobal Settings:\n");
06552    ast_cli(a->fd, "----------------\n");
06553    ast_cli(a->fd, FORMAT, "Manager (AMI):", AST_CLI_YESNO(manager_enabled));
06554    ast_cli(a->fd, FORMAT, "Web Manager (AMI/HTTP):", AST_CLI_YESNO(webmanager_enabled));
06555    ast_cli(a->fd, FORMAT, "TCP Bindaddress:", manager_enabled != 0 ? ast_sockaddr_stringify(&ami_desc.local_address) : "Disabled");
06556    ast_cli(a->fd, FORMAT2, "HTTP Timeout (minutes):", httptimeout);
06557    ast_cli(a->fd, FORMAT, "TLS Enable:", AST_CLI_YESNO(ami_tls_cfg.enabled));
06558    ast_cli(a->fd, FORMAT, "TLS Bindaddress:", ami_tls_cfg.enabled != 0 ? ast_sockaddr_stringify(&amis_desc.local_address) : "Disabled");
06559    ast_cli(a->fd, FORMAT, "TLS Certfile:", ami_tls_cfg.certfile);
06560    ast_cli(a->fd, FORMAT, "TLS Privatekey:", ami_tls_cfg.pvtfile);
06561    ast_cli(a->fd, FORMAT, "TLS Cipher:", ami_tls_cfg.cipher);
06562    ast_cli(a->fd, FORMAT, "Allow multiple login:", AST_CLI_YESNO(allowmultiplelogin));
06563    ast_cli(a->fd, FORMAT, "Display connects:", AST_CLI_YESNO(displayconnects));
06564    ast_cli(a->fd, FORMAT, "Timestamp events:", AST_CLI_YESNO(timestampevents));
06565    ast_cli(a->fd, FORMAT, "Channel vars:", S_OR(manager_channelvars, ""));
06566    ast_cli(a->fd, FORMAT, "Debug:", AST_CLI_YESNO(manager_debug));
06567    ast_cli(a->fd, FORMAT, "Block sockets:", AST_CLI_YESNO(block_sockets));
06568 #undef FORMAT
06569 #undef FORMAT2
06570 
06571    return CLI_SUCCESS;
06572 }

int init_manager ( void   ) 

Called by Asterisk initialization.

Definition at line 7148 of file manager.c.

References __init_manager().

Referenced by main().

07149 {
07150    return __init_manager(0);
07151 }

static void load_channelvars ( struct ast_variable *  var  )  [static]

Definition at line 6594 of file manager.c.

References ast_calloc, ast_free, AST_RWLIST_INSERT_TAIL, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_strdup, ast_strdupa, free_channelvars(), manager_channel_variable::isfunc, manager_channel_variable::name, eventqent::next, and ast_variable::value.

Referenced by __init_manager().

06595 {
06596    struct manager_channel_variable *mcv;
06597    char *remaining = ast_strdupa(var->value);
06598    char *next;
06599 
06600    ast_free(manager_channelvars);
06601    manager_channelvars = ast_strdup(var->value);
06602 
06603    /*
06604     * XXX TODO: To allow dialplan functions to have more than one
06605     * parameter requires eliminating the '|' as a separator so we
06606     * could use AST_STANDARD_APP_ARGS() to separate items.
06607     */
06608    free_channelvars();
06609    AST_RWLIST_WRLOCK(&channelvars);
06610    while ((next = strsep(&remaining, ",|"))) {
06611       if (!(mcv = ast_calloc(1, sizeof(*mcv) + strlen(next) + 1))) {
06612          break;
06613       }
06614       strcpy(mcv->name, next); /* SAFE */
06615       if (strchr(next, '(')) {
06616          mcv->isfunc = 1;
06617       }
06618       AST_RWLIST_INSERT_TAIL(&channelvars, mcv, entry);
06619    }
06620    AST_RWLIST_UNLOCK(&channelvars);
06621 }

static void manager_free_user ( struct ast_manager_user *  user  )  [static]

Definition at line 6624 of file manager.c.

References ast_manager_user::a1_hash, ao2_t_callback, ao2_t_ref, ast_free, ast_free_ha(), ast_manager_user::blackfilters, ast_manager_user::ha, OBJ_MULTIPLE, OBJ_NODATA, OBJ_UNLINK, ast_manager_user::secret, and ast_manager_user::whitefilters.

Referenced by __init_manager(), and manager_shutdown().

06625 {
06626    if (user->a1_hash) {
06627       ast_free(user->a1_hash);
06628    }
06629    if (user->secret) {
06630       ast_free(user->secret);
06631    }
06632    ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
06633    ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
06634    ao2_t_ref(user->whitefilters, -1, "decrement ref for white container, should be last one");
06635    ao2_t_ref(user->blackfilters, -1, "decrement ref for black container, should be last one");
06636    ast_free_ha(user->ha);
06637    ast_free(user);
06638 }

static int manager_http_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_params,
struct ast_variable *  headers 
) [static]

Definition at line 6380 of file manager.c.

References ast_sockaddr_from_sin, ast_sockaddr_to_sin, FORMAT_HTML, generic_http_callback(), and ast_tcptls_session_instance::remote_address.

06381 {
06382    int retval;
06383    struct sockaddr_in ser_remote_address_tmp;
06384 
06385    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06386    retval = generic_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
06387    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06388    return retval;
06389 }

static void manager_shutdown ( void   )  [static]

Definition at line 6641 of file manager.c.

References ami_tls_cfg, ao2_ref, ARRAY_LEN, ast_cli_unregister_multiple(), ast_free, AST_LIST_REMOVE_HEAD, ast_manager_unregister(), ast_tcptls_server_stop(), ast_tls_config::certfile, ast_tls_config::cipher, ast_manager_user::list, manager_free_user(), ast_tls_config::pvtfile, and sessions.

Referenced by __init_manager().

06642 {
06643    struct ast_manager_user *user;
06644 
06645    if (registered) {
06646       ast_manager_unregister("Ping");
06647       ast_manager_unregister("Events");
06648       ast_manager_unregister("Logoff");
06649       ast_manager_unregister("Login");
06650       ast_manager_unregister("Challenge");
06651       ast_manager_unregister("Hangup");
06652       ast_manager_unregister("Status");
06653       ast_manager_unregister("Setvar");
06654       ast_manager_unregister("Getvar");
06655       ast_manager_unregister("GetConfig");
06656       ast_manager_unregister("GetConfigJSON");
06657       ast_manager_unregister("UpdateConfig");
06658       ast_manager_unregister("CreateConfig");
06659       ast_manager_unregister("ListCategories");
06660       ast_manager_unregister("Redirect");
06661       ast_manager_unregister("Atxfer");
06662       ast_manager_unregister("Originate");
06663       ast_manager_unregister("Command");
06664       ast_manager_unregister("ExtensionState");
06665       ast_manager_unregister("AbsoluteTimeout");
06666       ast_manager_unregister("MailboxStatus");
06667       ast_manager_unregister("MailboxCount");
06668       ast_manager_unregister("ListCommands");
06669       ast_manager_unregister("SendText");
06670       ast_manager_unregister("UserEvent");
06671       ast_manager_unregister("WaitEvent");
06672       ast_manager_unregister("CoreSettings");
06673       ast_manager_unregister("CoreStatus");
06674       ast_manager_unregister("Reload");
06675       ast_manager_unregister("CoreShowChannels");
06676       ast_manager_unregister("ModuleLoad");
06677       ast_manager_unregister("ModuleCheck");
06678       ast_manager_unregister("AOCMessage");
06679       ast_manager_unregister("Filter");
06680       ast_cli_unregister_multiple(cli_manager, ARRAY_LEN(cli_manager));
06681    }
06682 
06683    ast_tcptls_server_stop(&ami_desc);
06684    ast_tcptls_server_stop(&amis_desc);
06685 
06686    if (ami_tls_cfg.certfile) {
06687       ast_free(ami_tls_cfg.certfile);
06688       ami_tls_cfg.certfile = NULL;
06689    }
06690    if (ami_tls_cfg.pvtfile) {
06691       ast_free(ami_tls_cfg.pvtfile);
06692       ami_tls_cfg.pvtfile = NULL;
06693    }
06694    if (ami_tls_cfg.cipher) {
06695       ast_free(ami_tls_cfg.cipher);
06696       ami_tls_cfg.cipher = NULL;
06697    }
06698 
06699    if (sessions) {
06700       ao2_ref(sessions, -1);
06701       sessions = NULL;
06702    }
06703 
06704    while ((user = AST_LIST_REMOVE_HEAD(&users, list))) {
06705       manager_free_user(user);
06706    }
06707 }

static int mxml_http_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_params,
struct ast_variable *  headers 
) [static]

Definition at line 6391 of file manager.c.

References ast_sockaddr_from_sin, ast_sockaddr_to_sin, FORMAT_XML, generic_http_callback(), and ast_tcptls_session_instance::remote_address.

06392 {
06393    int retval;
06394    struct sockaddr_in ser_remote_address_tmp;
06395 
06396    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06397    retval = generic_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
06398    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06399    return retval;
06400 }

static void process_output ( struct mansession *  s,
struct ast_str **  out,
struct ast_variable *  params,
enum output_format  format 
) [static]

Definition at line 5809 of file manager.c.

References ast_log(), ast_str_append(), errno, mansession::f, mansession::fd, FORMAT_HTML, FORMAT_XML, LOG_ERROR, LOG_WARNING, and xml_translate().

Referenced by auth_http_callback(), and generic_http_callback().

05810 {
05811    char *buf;
05812    size_t l;
05813 
05814    if (!s->f)
05815       return;
05816 
05817    /* Ensure buffer is NULL-terminated */
05818    fprintf(s->f, "%c", 0);
05819    fflush(s->f);
05820 
05821    if ((l = ftell(s->f)) > 0) {
05822       if (MAP_FAILED == (buf = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, s->fd, 0))) {
05823          ast_log(LOG_WARNING, "mmap failed.  Manager output was not processed\n");
05824       } else {
05825          if (format == FORMAT_XML || format == FORMAT_HTML) {
05826             xml_translate(out, buf, params, format);
05827          } else {
05828             ast_str_append(out, 0, "%s", buf);
05829          }
05830          munmap(buf, l);
05831       }
05832    } else if (format == FORMAT_XML || format == FORMAT_HTML) {
05833       xml_translate(out, "", params, format);
05834    }
05835 
05836    if (s->f) {
05837       if (fclose(s->f)) {
05838          ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
05839       }
05840       s->f = NULL;
05841       s->fd = -1;
05842    } else if (s->fd != -1) {
05843       if (close(s->fd)) {
05844          ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
05845       }
05846       s->fd = -1;
05847    } else {
05848       ast_log(LOG_ERROR, "process output attempted to close file/file descriptor on mansession without a valid file or file descriptor.\n");
05849    }
05850 }

static void purge_old_stuff ( void *  data  )  [static]

cleanup code called at each iteration of server_root, guaranteed to happen every 5 seconds at most

Definition at line 6505 of file manager.c.

References purge_events(), and purge_sessions().

06506 {
06507    purge_sessions(1);
06508    purge_events();
06509 }

static int rawman_http_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_params,
struct ast_variable *  headers 
) [static]

Definition at line 6402 of file manager.c.

References ast_sockaddr_from_sin, ast_sockaddr_to_sin, FORMAT_RAW, generic_http_callback(), and ast_tcptls_session_instance::remote_address.

06403 {
06404    int retval;
06405    struct sockaddr_in ser_remote_address_tmp;
06406 
06407    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06408    retval = generic_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
06409    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06410    return retval;
06411 }

int reload_manager ( void   ) 

Called by Asterisk module functions and the CLI command.

Definition at line 7153 of file manager.c.

References __init_manager().

Referenced by handle_manager_reload().

07154 {
07155    return __init_manager(1);
07156 }

static int variable_count_cmp_fn ( void *  obj,
void *  vstr,
int  flags 
) [static]

Definition at line 5653 of file manager.c.

References CMP_MATCH, CMP_STOP, str, and variable_count::varname.

Referenced by xml_translate().

05654 {
05655    /* Due to the simplicity of struct variable_count, it makes no difference
05656     * if you pass in objects or strings, the same operation applies. This is
05657     * due to the fact that the hash occurs on the first element, which means
05658     * the address of both the struct and the string are exactly the same. */
05659    struct variable_count *vc = obj;
05660    char *str = vstr;
05661    return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
05662 }

static int variable_count_hash_fn ( const void *  vvc,
const int  flags 
) [static]

Definition at line 5646 of file manager.c.

References ast_str_hash(), and variable_count::varname.

Referenced by xml_translate().

05647 {
05648    const struct variable_count *vc = vvc;
05649 
05650    return ast_str_hash(vc->varname);
05651 }

static void xml_copy_escape ( struct ast_str **  out,
const char *  src,
int  mode 
) [static]

Definition at line 5584 of file manager.c.

References ast_str_append().

Referenced by xml_translate().

05585 {
05586    /* store in a local buffer to avoid calling ast_str_append too often */
05587    char buf[256];
05588    char *dst = buf;
05589    int space = sizeof(buf);
05590    /* repeat until done and nothing to flush */
05591    for ( ; *src || dst != buf ; src++) {
05592       if (*src == '\0' || space < 10) {   /* flush */
05593          *dst++ = '\0';
05594          ast_str_append(out, 0, "%s", buf);
05595          dst = buf;
05596          space = sizeof(buf);
05597          if (*src == '\0') {
05598             break;
05599          }
05600       }
05601 
05602       if ( (mode & 2) && !isalnum(*src)) {
05603          *dst++ = '_';
05604          space--;
05605          continue;
05606       }
05607       switch (*src) {
05608       case '<':
05609          strcpy(dst, "&lt;");
05610          dst += 4;
05611          space -= 4;
05612          break;
05613       case '>':
05614          strcpy(dst, "&gt;");
05615          dst += 4;
05616          space -= 4;
05617          break;
05618       case '\"':
05619          strcpy(dst, "&quot;");
05620          dst += 6;
05621          space -= 6;
05622          break;
05623       case '\'':
05624          strcpy(dst, "&apos;");
05625          dst += 6;
05626          space -= 6;
05627          break;
05628       case '&':
05629          strcpy(dst, "&amp;");
05630          dst += 5;
05631          space -= 5;
05632          break;
05633 
05634       default:
05635          *dst++ = mode ? tolower(*src) : *src;
05636          space--;
05637       }
05638    }
05639 }

static void xml_translate ( struct ast_str **  out,
char *  in,
struct ast_variable *  get_vars,
enum output_format  format 
) [static]

Convert the input into XML or HTML. The input is supposed to be a sequence of lines of the form Name: value optionally followed by a blob of unformatted text. A blank line is a section separator. Basically, this is a mixture of the format of Manager Interface and CLI commands. The unformatted text is considered as a single value of a field named 'Opaque-data'.

At the moment the output format is the following (but it may change depending on future requirements so don't count too much on it when writing applications):

General: the unformatted text is used as a value of XML output: to be completed

 *   Each section is within <response type="object" id="xxx">
 *   where xxx is taken from ajaxdest variable or defaults to unknown
 *   Each row is reported as an attribute Name="value" of an XML
 *   entity named from the variable ajaxobjtype, default to "generic"
 * 

HTML output: each Name-value pair is output as a single row of a two-column table. Sections (blank lines in the input) are separated by a


Definition at line 5692 of file manager.c.

References ao2_alloc, ao2_container_alloc, ao2_find, ao2_link, ao2_ref, ast_debug, ast_skip_blanks(), ast_str_append(), ast_strlen_zero(), ast_trim_blanks(), variable_count::count, FORMAT_XML, ast_variable::name, ast_variable::next, ast_variable::value, var, variable_count_cmp_fn(), variable_count_hash_fn(), variable_count::varname, and xml_copy_escape().

Referenced by process_output().

05693 {
05694    struct ast_variable *v;
05695    const char *dest = NULL;
05696    char *var, *val;
05697    const char *objtype = NULL;
05698    int in_data = 0;  /* parsing data */
05699    int inobj = 0;
05700    int xml = (format == FORMAT_XML);
05701    struct variable_count *vc = NULL;
05702    struct ao2_container *vco = NULL;
05703 
05704    if (xml) {
05705       /* dest and objtype need only for XML format */
05706       for (v = get_vars; v; v = v->next) {
05707          if (!strcasecmp(v->name, "ajaxdest")) {
05708             dest = v->value;
05709          } else if (!strcasecmp(v->name, "ajaxobjtype")) {
05710             objtype = v->value;
05711          }
05712       }
05713       if (ast_strlen_zero(dest)) {
05714          dest = "unknown";
05715       }
05716       if (ast_strlen_zero(objtype)) {
05717          objtype = "generic";
05718       }
05719    }
05720 
05721    /* we want to stop when we find an empty line */
05722    while (in && *in) {
05723       val = strsep(&in, "\r\n"); /* mark start and end of line */
05724       if (in && *in == '\n') {   /* remove trailing \n if any */
05725          in++;
05726       }
05727       ast_trim_blanks(val);
05728       ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
05729       if (ast_strlen_zero(val)) {
05730          /* empty line */
05731          if (in_data) {
05732             /* close data in Opaque mode */
05733             ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05734             in_data = 0;
05735          }
05736 
05737          if (inobj) {
05738             /* close block */
05739             ast_str_append(out, 0, xml ? " /></response>\n" :
05740                "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05741             inobj = 0;
05742             ao2_ref(vco, -1);
05743             vco = NULL;
05744          }
05745          continue;
05746       }
05747 
05748       if (!inobj) {
05749          /* start new block */
05750          if (xml) {
05751             ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
05752          }
05753          vco = ao2_container_alloc(37, variable_count_hash_fn, variable_count_cmp_fn);
05754          inobj = 1;
05755       }
05756 
05757       if (in_data) {
05758          /* Process data field in Opaque mode. This is a
05759           * followup, so we re-add line feeds. */
05760          ast_str_append(out, 0, xml ? "\n" : "<br>\n");
05761          xml_copy_escape(out, val, 0);   /* data field */
05762          continue;
05763       }
05764 
05765       /* We expect "Name: value" line here */
05766       var = strsep(&val, ":");
05767       if (val) {
05768          /* found the field name */
05769          val = ast_skip_blanks(val);
05770          ast_trim_blanks(var);
05771       } else {
05772          /* field name not found, switch to opaque mode */
05773          val = var;
05774          var = "Opaque-data";
05775          in_data = 1;
05776       }
05777 
05778 
05779       ast_str_append(out, 0, xml ? " " : "<tr><td>");
05780       if ((vc = ao2_find(vco, var, 0))) {
05781          vc->count++;
05782       } else {
05783          /* Create a new entry for this one */
05784          vc = ao2_alloc(sizeof(*vc), NULL);
05785          vc->varname = var;
05786          vc->count = 1;
05787          ao2_link(vco, vc);
05788       }
05789 
05790       xml_copy_escape(out, var, xml ? 1 | 2 : 0); /* data name */
05791       if (vc->count > 1) {
05792          ast_str_append(out, 0, "-%d", vc->count);
05793       }
05794       ao2_ref(vc, -1);
05795       ast_str_append(out, 0, xml ? "='" : "</td><td>");
05796       xml_copy_escape(out, val, 0); /* data field */
05797       if (!in_data || !*in) {
05798          ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05799       }
05800    }
05801 
05802    if (inobj) {
05803       ast_str_append(out, 0, xml ? " /></response>\n" :
05804          "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05805       ao2_ref(vco, -1);
05806    }
05807 }


Variable Documentation

struct ast_http_uri amanageruri [static]

Definition at line 6481 of file manager.c.

struct ast_http_uri amanagerxmluri [static]

Definition at line 6490 of file manager.c.

Definition at line 6512 of file manager.c.

struct ast_tls_config ami_tls_cfg [static]

Definition at line 6511 of file manager.c.

Referenced by __init_manager(), handle_manager_show_settings(), and manager_shutdown().

Definition at line 6523 of file manager.c.

struct ast_http_uri arawmanuri [static]

Definition at line 6472 of file manager.c.

struct ast_cli_entry cli_manager[] [static]

Definition at line 6574 of file manager.c.

const char* const contenttype[] [static]
Initial value:
 {
   [FORMAT_RAW] = "plain",
   [FORMAT_HTML] = "html",
   [FORMAT_XML] =  "xml",
}

Definition at line 5441 of file manager.c.

struct ast_http_uri manageruri [static]

Definition at line 6421 of file manager.c.

struct ast_http_uri managerxmluri [static]

Definition at line 6429 of file manager.c.

struct ast_http_uri rawmanuri [static]

Definition at line 6413 of file manager.c.

int registered = 0 [static]

Definition at line 6499 of file manager.c.

int webregged = 0 [static]

Definition at line 6500 of file manager.c.

const char* words[AST_MAX_CMD_LEN]

Definition at line 929 of file manager.c.

Referenced by check_blacklist().


Generated on 18 Jan 2013 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1