Sat Mar 26 11:24:06 2011

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 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  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)
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 int action_events (struct mansession *s, const struct message *m)
static int action_extensionstate (struct mansession *s, const struct message *m)
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,...)
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)
 Get header from mananger transaction.
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 ()
 Check if AMI is enabled.
static int check_manager_session_inuse (const char *name)
int check_webmanager_enabled ()
 Check if AMI/HTTP is enabled.
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 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 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 int manager_displayconnects (struct mansession_session *session)
 Get displayconnects config option.
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 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 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 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_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_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
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 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 5020 of file manager.c.

05020                    {
05021    FORMAT_RAW,
05022    FORMAT_HTML,
05023    FORMAT_XML,
05024 };


Function Documentation

static int __init_manager ( int  reload  )  [static]

Definition at line 6146 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_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_ssl_setup(), ast_strdup, ast_strdupa, ast_strlen_zero(), ast_tcptls_server_start(), 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_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, inet_aton(), manager_channel_variable::isfunc, ast_manager_user::keep, ast_variable::lineno, ast_tcptls_session_args::local_address, LOG_NOTICE, LOG_WARNING, manager_debug, manager_event, manager_modulecheck(), manager_moduleload(), manager_state_cb(), mansession_cmp_fn(), manager_channel_variable::name, ast_variable::name, eventqent::next, ast_variable::next, OBJ_MULTIPLE, OBJ_NODATA, OBJ_UNLINK, ast_tls_config::pvtfile, ast_manager_user::readperm, S_OR, ast_manager_user::secret, strsep(), 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().

06147 {
06148    struct ast_config *ucfg = NULL, *cfg = NULL;
06149    const char *val;
06150    char *cat = NULL;
06151    int newhttptimeout = DEFAULT_HTTPTIMEOUT;
06152    struct ast_manager_user *user = NULL;
06153    struct ast_variable *var;
06154    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
06155    char a1[256];
06156    char a1_hash[256];
06157    struct sockaddr_in ami_desc_local_address_tmp = { 0, };
06158    struct sockaddr_in amis_desc_local_address_tmp = { 0, };
06159 
06160    if (!registered) {
06161       /* Register default actions */
06162       ast_manager_register_xml("Ping", 0, action_ping);
06163       ast_manager_register_xml("Events", 0, action_events);
06164       ast_manager_register_xml("Logoff", 0, action_logoff);
06165       ast_manager_register_xml("Login", 0, action_login);
06166       ast_manager_register_xml("Challenge", 0, action_challenge);
06167       ast_manager_register_xml("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup);
06168       ast_manager_register_xml("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status);
06169       ast_manager_register_xml("Setvar", EVENT_FLAG_CALL, action_setvar);
06170       ast_manager_register_xml("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar);
06171       ast_manager_register_xml("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig);
06172       ast_manager_register_xml("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson);
06173       ast_manager_register_xml("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig);
06174       ast_manager_register_xml("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig);
06175       ast_manager_register_xml("ListCategories", EVENT_FLAG_CONFIG, action_listcategories);
06176       ast_manager_register_xml("Redirect", EVENT_FLAG_CALL, action_redirect);
06177       ast_manager_register_xml("Atxfer", EVENT_FLAG_CALL, action_atxfer);
06178       ast_manager_register_xml("Originate", EVENT_FLAG_ORIGINATE, action_originate);
06179       ast_manager_register_xml("Command", EVENT_FLAG_COMMAND, action_command);
06180       ast_manager_register_xml("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate);
06181       ast_manager_register_xml("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout);
06182       ast_manager_register_xml("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus);
06183       ast_manager_register_xml("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount);
06184       ast_manager_register_xml("ListCommands", 0, action_listcommands);
06185       ast_manager_register_xml("SendText", EVENT_FLAG_CALL, action_sendtext);
06186       ast_manager_register_xml("UserEvent", EVENT_FLAG_USER, action_userevent);
06187       ast_manager_register_xml("WaitEvent", 0, action_waitevent);
06188       ast_manager_register_xml("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings);
06189       ast_manager_register_xml("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus);
06190       ast_manager_register_xml("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload);
06191       ast_manager_register_xml("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels);
06192       ast_manager_register_xml("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload);
06193       ast_manager_register_xml("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck);
06194       ast_manager_register_xml("AOCMessage", EVENT_FLAG_AOC, action_aocmessage);
06195 
06196       ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
06197       ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
06198       registered = 1;
06199       /* Append placeholder event so master_eventq never runs dry */
06200       append_event("Event: Placeholder\r\n\r\n", 0);
06201    }
06202    if ((cfg = ast_config_load2("manager.conf", "manager", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
06203       return 0;
06204    }
06205 
06206    manager_enabled = DEFAULT_ENABLED;
06207    webmanager_enabled = DEFAULT_WEBENABLED;
06208    displayconnects = DEFAULT_DISPLAYCONNECTS;
06209    broken_events_action = DEFAULT_BROKENEVENTSACTION;
06210    block_sockets = DEFAULT_BLOCKSOCKETS;
06211    timestampevents = DEFAULT_TIMESTAMPEVENTS;
06212    httptimeout = DEFAULT_HTTPTIMEOUT;
06213 
06214    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
06215       ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid. Asterisk management interface (AMI) disabled.\n");
06216       return 0;
06217    }
06218 
06219    /* default values */
06220    ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
06221    memset(&ami_desc.local_address, 0, sizeof(struct sockaddr_in));
06222    memset(&amis_desc.local_address, 0, sizeof(amis_desc.local_address));
06223    amis_desc_local_address_tmp.sin_port = htons(5039);
06224    ami_desc_local_address_tmp.sin_port = htons(DEFAULT_MANAGER_PORT);
06225 
06226    ami_tls_cfg.enabled = 0;
06227    if (ami_tls_cfg.certfile) {
06228       ast_free(ami_tls_cfg.certfile);
06229    }
06230    ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
06231    if (ami_tls_cfg.pvtfile) {
06232       ast_free(ami_tls_cfg.pvtfile);
06233    }
06234    ami_tls_cfg.pvtfile = ast_strdup("");
06235    if (ami_tls_cfg.cipher) {
06236       ast_free(ami_tls_cfg.cipher);
06237    }
06238    ami_tls_cfg.cipher = ast_strdup("");
06239 
06240    free_channelvars();
06241 
06242    for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
06243       val = var->value;
06244 
06245       if (!ast_tls_read_conf(&ami_tls_cfg, &amis_desc, var->name, val)) {
06246          continue;
06247       }
06248 
06249       if (!strcasecmp(var->name, "enabled")) {
06250          manager_enabled = ast_true(val);
06251       } else if (!strcasecmp(var->name, "block-sockets")) {
06252          block_sockets = ast_true(val);
06253       } else if (!strcasecmp(var->name, "webenabled")) {
06254          webmanager_enabled = ast_true(val);
06255       } else if (!strcasecmp(var->name, "port")) {
06256          ami_desc_local_address_tmp.sin_port = htons(atoi(val));
06257       } else if (!strcasecmp(var->name, "bindaddr")) {
06258          if (!inet_aton(val, &ami_desc_local_address_tmp.sin_addr)) {
06259             ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
06260             memset(&ami_desc_local_address_tmp.sin_addr, 0,
06261                    sizeof(ami_desc_local_address_tmp.sin_addr));
06262          }
06263       } else if (!strcasecmp(var->name, "brokeneventsaction")) {
06264          broken_events_action = ast_true(val);
06265       } else if (!strcasecmp(var->name, "allowmultiplelogin")) {
06266          allowmultiplelogin = ast_true(val);
06267       } else if (!strcasecmp(var->name, "displayconnects")) {
06268          displayconnects = ast_true(val);
06269       } else if (!strcasecmp(var->name, "timestampevents")) {
06270          timestampevents = ast_true(val);
06271       } else if (!strcasecmp(var->name, "debug")) {
06272          manager_debug = ast_true(val);
06273       } else if (!strcasecmp(var->name, "httptimeout")) {
06274          newhttptimeout = atoi(val);
06275       } else if (!strcasecmp(var->name, "channelvars")) {
06276          struct manager_channel_variable *mcv;
06277          char *remaining = ast_strdupa(val), *next;
06278          ast_free(manager_channelvars);
06279          manager_channelvars = ast_strdup(val);
06280          AST_RWLIST_WRLOCK(&channelvars);
06281          while ((next = strsep(&remaining, ",|"))) {
06282             if (!(mcv = ast_calloc(1, sizeof(*mcv) + strlen(next) + 1))) {
06283                break;
06284             }
06285             strcpy(mcv->name, next); /* SAFE */
06286             if (strchr(next, '(')) {
06287                mcv->isfunc = 1;
06288             }
06289             AST_RWLIST_INSERT_TAIL(&channelvars, mcv, entry);
06290          }
06291          AST_RWLIST_UNLOCK(&channelvars);
06292       } else {
06293          ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
06294             var->name, val);
06295       }
06296    }
06297 
06298    ami_desc_local_address_tmp.sin_family = AF_INET;
06299    amis_desc_local_address_tmp.sin_family = AF_INET;
06300 
06301    /* if the amis address has not been set, default is the same as non secure ami */
06302    if (!amis_desc_local_address_tmp.sin_addr.s_addr) {
06303       amis_desc_local_address_tmp.sin_addr =
06304           ami_desc_local_address_tmp.sin_addr;
06305    }
06306 
06307    if (manager_enabled) {
06308       ast_sockaddr_from_sin(&ami_desc.local_address, &ami_desc_local_address_tmp);
06309       ast_sockaddr_from_sin(&amis_desc.local_address, &amis_desc_local_address_tmp);
06310    }
06311 
06312    AST_RWLIST_WRLOCK(&users);
06313 
06314    /* First, get users from users.conf */
06315    ucfg = ast_config_load2("users.conf", "manager", config_flags);
06316    if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
06317       const char *hasmanager;
06318       int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
06319 
06320       while ((cat = ast_category_browse(ucfg, cat))) {
06321          if (!strcasecmp(cat, "general")) {
06322             continue;
06323          }
06324 
06325          hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
06326          if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
06327             const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
06328             const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
06329             const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
06330             const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
06331             const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
06332 
06333             /* Look for an existing entry,
06334              * if none found - create one and add it to the list
06335              */
06336             if (!(user = get_manager_by_name_locked(cat))) {
06337                if (!(user = ast_calloc(1, sizeof(*user)))) {
06338                   break;
06339                }
06340 
06341                /* Copy name over */
06342                ast_copy_string(user->username, cat, sizeof(user->username));
06343                /* Insert into list */
06344                AST_LIST_INSERT_TAIL(&users, user, list);
06345                user->ha = NULL;
06346                user->keep = 1;
06347                user->readperm = -1;
06348                user->writeperm = -1;
06349                /* Default displayconnect from [general] */
06350                user->displayconnects = displayconnects;
06351                user->writetimeout = 100;
06352             }
06353 
06354             if (!user_secret) {
06355                user_secret = ast_variable_retrieve(ucfg, "general", "secret");
06356             }
06357             if (!user_read) {
06358                user_read = ast_variable_retrieve(ucfg, "general", "read");
06359             }
06360             if (!user_write) {
06361                user_write = ast_variable_retrieve(ucfg, "general", "write");
06362             }
06363             if (!user_displayconnects) {
06364                user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
06365             }
06366             if (!user_writetimeout) {
06367                user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
06368             }
06369 
06370             if (!ast_strlen_zero(user_secret)) {
06371                if (user->secret) {
06372                   ast_free(user->secret);
06373                }
06374                user->secret = ast_strdup(user_secret);
06375             }
06376 
06377             if (user_read) {
06378                user->readperm = get_perm(user_read);
06379             }
06380             if (user_write) {
06381                user->writeperm = get_perm(user_write);
06382             }
06383             if (user_displayconnects) {
06384                user->displayconnects = ast_true(user_displayconnects);
06385             }
06386             if (user_writetimeout) {
06387                int value = atoi(user_writetimeout);
06388                if (value < 100) {
06389                   ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at users.conf line %d\n", var->value, var->lineno);
06390                } else {
06391                   user->writetimeout = value;
06392                }
06393             }
06394          }
06395       }
06396       ast_config_destroy(ucfg);
06397    }
06398 
06399    /* cat is NULL here in any case */
06400 
06401    while ((cat = ast_category_browse(cfg, cat))) {
06402       struct ast_ha *oldha;
06403 
06404       if (!strcasecmp(cat, "general")) {
06405          continue;
06406       }
06407 
06408       /* Look for an existing entry, if none found - create one and add it to the list */
06409       if (!(user = get_manager_by_name_locked(cat))) {
06410          if (!(user = ast_calloc(1, sizeof(*user)))) {
06411             break;
06412          }
06413          /* Copy name over */
06414          ast_copy_string(user->username, cat, sizeof(user->username));
06415 
06416          user->ha = NULL;
06417          user->readperm = 0;
06418          user->writeperm = 0;
06419          /* Default displayconnect from [general] */
06420          user->displayconnects = displayconnects;
06421          user->writetimeout = 100;
06422          user->whitefilters = ao2_container_alloc(1, NULL, NULL);
06423          user->blackfilters = ao2_container_alloc(1, NULL, NULL);
06424 
06425          /* Insert into list */
06426          AST_RWLIST_INSERT_TAIL(&users, user, list);
06427       } else {
06428          ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
06429          ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
06430       }
06431 
06432       /* Make sure we keep this user and don't destroy it during cleanup */
06433       user->keep = 1;
06434       oldha = user->ha;
06435       user->ha = NULL;
06436 
06437       var = ast_variable_browse(cfg, cat);
06438       for (; var; var = var->next) {
06439          if (!strcasecmp(var->name, "secret")) {
06440             if (user->secret) {
06441                ast_free(user->secret);
06442             }
06443             user->secret = ast_strdup(var->value);
06444          } else if (!strcasecmp(var->name, "deny") ||
06445                    !strcasecmp(var->name, "permit")) {
06446             user->ha = ast_append_ha(var->name, var->value, user->ha, NULL);
06447          }  else if (!strcasecmp(var->name, "read") ) {
06448             user->readperm = get_perm(var->value);
06449          }  else if (!strcasecmp(var->name, "write") ) {
06450             user->writeperm = get_perm(var->value);
06451          }  else if (!strcasecmp(var->name, "displayconnects") ) {
06452             user->displayconnects = ast_true(var->value);
06453          } else if (!strcasecmp(var->name, "writetimeout")) {
06454             int value = atoi(var->value);
06455             if (value < 100) {
06456                ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
06457             } else {
06458                user->writetimeout = value;
06459             }
06460          } else if (!strcasecmp(var->name, "eventfilter")) {
06461             const char *value = var->value;
06462             regex_t *new_filter = ao2_t_alloc(sizeof(*new_filter), event_filter_destructor, "event_filter allocation");
06463             if (new_filter) {
06464                int is_blackfilter;
06465                if (value[0] == '!') {
06466                   is_blackfilter = 1;
06467                   value++;
06468                } else {
06469                   is_blackfilter = 0;
06470                }
06471                if (regcomp(new_filter, value, 0)) {
06472                   ao2_t_ref(new_filter, -1, "failed to make regx");
06473                } else {
06474                   if (is_blackfilter) {
06475                      ao2_t_link(user->blackfilters, new_filter, "link new filter into black user container");
06476                   } else {
06477                      ao2_t_link(user->whitefilters, new_filter, "link new filter into white user container");
06478                   }
06479                }
06480             }
06481          } else {
06482             ast_debug(1, "%s is an unknown option.\n", var->name);
06483          }
06484       }
06485       ast_free_ha(oldha);
06486    }
06487    ast_config_destroy(cfg);
06488 
06489    /* Perform cleanup - essentially prune out old users that no longer exist */
06490    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
06491       if (user->keep) { /* valid record. clear flag for the next round */
06492          user->keep = 0;
06493 
06494          /* Calculate A1 for Digest auth */
06495          snprintf(a1, sizeof(a1), "%s:%s:%s", user->username, global_realm, user->secret);
06496          ast_md5_hash(a1_hash,a1);
06497          if (user->a1_hash) {
06498             ast_free(user->a1_hash);
06499          }
06500          user->a1_hash = ast_strdup(a1_hash);
06501          continue;
06502       }
06503       /* We do not need to keep this user so take them out of the list */
06504       AST_RWLIST_REMOVE_CURRENT(list);
06505       ast_debug(4, "Pruning user '%s'\n", user->username);
06506       /* Free their memory now */
06507       if (user->a1_hash) {
06508          ast_free(user->a1_hash);
06509       }
06510       if (user->secret) {
06511          ast_free(user->secret);
06512       }
06513       ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
06514       ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
06515       ao2_t_ref(user->whitefilters, -1, "decrement ref for white container, should be last one");
06516       ao2_t_ref(user->blackfilters, -1, "decrement ref for black container, should be last one");
06517       ast_free_ha(user->ha);
06518       ast_free(user);
06519    }
06520    AST_RWLIST_TRAVERSE_SAFE_END;
06521 
06522    AST_RWLIST_UNLOCK(&users);
06523 
06524    if (!reload) {
06525       /* If you have a NULL hash fn, you only need a single bucket */
06526       sessions = ao2_container_alloc(1, NULL, mansession_cmp_fn);
06527    }
06528 
06529    if (webmanager_enabled && manager_enabled) {
06530       if (!webregged) {
06531 
06532          ast_http_uri_link(&rawmanuri);
06533          ast_http_uri_link(&manageruri);
06534          ast_http_uri_link(&managerxmluri);
06535 
06536          ast_http_uri_link(&arawmanuri);
06537          ast_http_uri_link(&amanageruri);
06538          ast_http_uri_link(&amanagerxmluri);
06539          webregged = 1;
06540       }
06541    } else {
06542       if (webregged) {
06543          ast_http_uri_unlink(&rawmanuri);
06544          ast_http_uri_unlink(&manageruri);
06545          ast_http_uri_unlink(&managerxmluri);
06546 
06547          ast_http_uri_unlink(&arawmanuri);
06548          ast_http_uri_unlink(&amanageruri);
06549          ast_http_uri_unlink(&amanagerxmluri);
06550          webregged = 0;
06551       }
06552    }
06553 
06554    if (newhttptimeout > 0) {
06555       httptimeout = newhttptimeout;
06556    }
06557 
06558    manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: Manager\r\nStatus: %s\r\nMessage: Manager reload Requested\r\n", manager_enabled ? "Enabled" : "Disabled");
06559 
06560    ast_tcptls_server_start(&ami_desc);
06561    if (ast_ssl_setup(amis_desc.tls_cfg)) {
06562       ast_tcptls_server_start(&amis_desc);
06563    }
06564    return 0;
06565 }

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 6588 of file manager.c.

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

06589 {
06590    AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
06591 
06592    return 0;
06593 }

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 6600 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.

06601 {
06602    struct ast_datastore *datastore = NULL;
06603 
06604    if (info == NULL)
06605       return NULL;
06606 
06607    AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
06608       if (datastore->info != info) {
06609          continue;
06610       }
06611 
06612       if (uid == NULL) {
06613          /* matched by type only */
06614          break;
06615       }
06616 
06617       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
06618          /* Matched by type AND uid */
06619          break;
06620       }
06621    }
06622    AST_LIST_TRAVERSE_SAFE_END;
06623 
06624    return datastore;
06625 }

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 6595 of file manager.c.

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

06596 {
06597    return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
06598 }

int astman_is_authed ( uint32_t  ident  ) 

Determinie if a manager session ident is authenticated.

Definition at line 5096 of file manager.c.

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

Referenced by http_post_callback(), and static_callback().

05097 {
05098    int authed;
05099    struct mansession_session *session;
05100 
05101    if (!(session = find_session(ident, 0)))
05102       return 0;
05103 
05104    authed = (session->authenticated != 0);
05105 
05106    ao2_unlock(session);
05107    unref_mansession(session);
05108 
05109    return authed;
05110 }

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 5112 of file manager.c.

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

05113 {
05114    int result = 0;
05115    struct mansession_session *session;
05116    struct ao2_iterator i;
05117 
05118    if (ident == 0) {
05119       return 0;
05120    }
05121 
05122    i = ao2_iterator_init(sessions, 0);
05123    while ((session = ao2_iterator_next(&i))) {
05124       ao2_lock(session);
05125       if ((session->managerid == ident) && (session->readperm & perm)) {
05126          result = 1;
05127          ao2_unlock(session);
05128          unref_mansession(session);
05129          break;
05130       }
05131       ao2_unlock(session);
05132       unref_mansession(session);
05133    }
05134    ao2_iterator_destroy(&i);
05135    return result;
05136 }

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 5138 of file manager.c.

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

Referenced by http_post_callback().

05139 {
05140    int result = 0;
05141    struct mansession_session *session;
05142    struct ao2_iterator i;
05143 
05144    if (ident == 0) {
05145       return 0;
05146    }
05147 
05148    i = ao2_iterator_init(sessions, 0);
05149    while ((session = ao2_iterator_next(&i))) {
05150       ao2_lock(session);
05151       if ((session->managerid == ident) && (session->writeperm & perm)) {
05152          result = 1;
05153          ao2_unlock(session);
05154          unref_mansession(session);
05155          break;
05156       }
05157       ao2_unlock(session);
05158       unref_mansession(session);
05159    }
05160    ao2_iterator_destroy(&i);
05161    return result;
05162 }

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 5618 of file manager.c.

References ast_manager_user::a1_hash, ao2_lock, ao2_unlock, 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_MAX_MANHEADERS, 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(), 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, ast_manager_user::writetimeout, and xml_translate().

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

05624 {
05625    struct mansession_session *session = NULL;
05626    struct mansession s = { NULL, };
05627    struct ast_variable *v, *params = get_params;
05628    char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
05629    struct ast_str *http_header = NULL, *out = NULL;
05630    size_t result_size = 512;
05631    struct message m = { 0 };
05632    unsigned int x;
05633    size_t hdrlen;
05634 
05635    time_t time_now = time(NULL);
05636    unsigned long nonce = 0, nc;
05637    struct ast_http_digest d = { NULL, };
05638    struct ast_manager_user *user = NULL;
05639    int stale = 0;
05640    char resp_hash[256]="";
05641    /* Cache for user data */
05642    char u_username[80];
05643    int u_readperm;
05644    int u_writeperm;
05645    int u_writetimeout;
05646    int u_displayconnects;
05647    struct ast_sockaddr addr;
05648 
05649    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
05650       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
05651       return -1;
05652    }
05653 
05654    /* Find "Authorization: " header */
05655    for (v = headers; v; v = v->next) {
05656       if (!strcasecmp(v->name, "Authorization")) {
05657          break;
05658       }
05659    }
05660 
05661    if (!v || ast_strlen_zero(v->value)) {
05662       goto out_401; /* Authorization Header not present - send auth request */
05663    }
05664 
05665    /* Digest found - parse */
05666    if (ast_string_field_init(&d, 128)) {
05667       ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05668       return -1;
05669    }
05670 
05671    if (ast_parse_digest(v->value, &d, 0, 1)) {
05672       /* Error in Digest - send new one */
05673       nonce = 0;
05674       goto out_401;
05675    }
05676    if (sscanf(d.nonce, "%30lx", &nonce) != 1) {
05677       ast_log(LOG_WARNING, "Received incorrect nonce in Digest <%s>\n", d.nonce);
05678       nonce = 0;
05679       goto out_401;
05680    }
05681 
05682    AST_RWLIST_WRLOCK(&users);
05683    user = get_manager_by_name_locked(d.username);
05684    if(!user) {
05685       AST_RWLIST_UNLOCK(&users);
05686       ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
05687       nonce = 0;
05688       goto out_401;
05689    }
05690 
05691    ast_sockaddr_from_sin(&addr, remote_address);
05692    /* --- We have User for this auth, now check ACL */
05693    if (user->ha && !ast_apply_ha(user->ha, &addr)) {
05694       AST_RWLIST_UNLOCK(&users);
05695       ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
05696       ast_http_error(ser, 403, "Permission denied", "Permission denied\n");
05697       return -1;
05698    }
05699 
05700    /* --- We have auth, so check it */
05701 
05702    /* compute the expected response to compare with what we received */
05703    {
05704       char a2[256];
05705       char a2_hash[256];
05706       char resp[256];
05707 
05708       /* XXX Now request method are hardcoded in A2 */
05709       snprintf(a2, sizeof(a2), "%s:%s", ast_get_http_method(method), d.uri);
05710       ast_md5_hash(a2_hash, a2);
05711 
05712       if (d.qop) {
05713          /* RFC 2617 */
05714          snprintf(resp, sizeof(resp), "%s:%08lx:%s:%s:auth:%s", user->a1_hash, nonce, d.nc, d.cnonce, a2_hash);
05715       }  else {
05716          /* RFC 2069 */
05717          snprintf(resp, sizeof(resp), "%s:%08lx:%s", user->a1_hash, nonce, a2_hash);
05718       }
05719       ast_md5_hash(resp_hash, resp);
05720    }
05721 
05722    if (!d.nonce  || strncasecmp(d.response, resp_hash, strlen(resp_hash))) {
05723       /* Something was wrong, so give the client to try with a new challenge */
05724       AST_RWLIST_UNLOCK(&users);
05725       nonce = 0;
05726       goto out_401;
05727    }
05728 
05729    /*
05730     * User are pass Digest authentication.
05731     * Now, cache the user data and unlock user list.
05732     */
05733    ast_copy_string(u_username, user->username, sizeof(u_username));
05734    u_readperm = user->readperm;
05735    u_writeperm = user->writeperm;
05736    u_displayconnects = user->displayconnects;
05737    u_writetimeout = user->writetimeout;
05738    AST_RWLIST_UNLOCK(&users);
05739 
05740    if (!(session = find_session_by_nonce(d.username, nonce, &stale))) {
05741       /*
05742        * Create new session.
05743        * While it is not in the list we don't need any locking
05744        */
05745       if (!(session = build_mansession(*remote_address))) {
05746          ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05747          return -1;
05748       }
05749       ao2_lock(session);
05750 
05751       ast_copy_string(session->username, u_username, sizeof(session->username));
05752       session->managerid = nonce;
05753       session->last_ev = grab_last();
05754       AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
05755 
05756       session->readperm = u_readperm;
05757       session->writeperm = u_writeperm;
05758       session->writetimeout = u_writetimeout;
05759 
05760       if (u_displayconnects) {
05761          ast_verb(2, "HTTP Manager '%s' logged in from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05762       }
05763       session->noncetime = session->sessionstart = time_now;
05764       session->authenticated = 1;
05765    } else if (stale) {
05766       /*
05767        * Session found, but nonce is stale.
05768        *
05769        * This could be because an old request (w/old nonce) arrived.
05770        *
05771        * This may be as the result of http proxy usage (separate delay or
05772        * multipath) or in a situation where a page was refreshed too quickly
05773        * (seen in Firefox).
05774        *
05775        * In this situation, we repeat the 401 auth with the current nonce
05776        * value.
05777        */
05778       nonce = session->managerid;
05779       ao2_unlock(session);
05780       stale = 1;
05781       goto out_401;
05782    } else {
05783       sscanf(d.nc, "%30lx", &nc);
05784       if (session->nc >= nc || ((time_now - session->noncetime) > 62) ) {
05785          /*
05786           * Nonce time expired (> 2 minutes) or something wrong with nonce
05787           * counter.
05788           *
05789           * Create new nonce key and resend Digest auth request. Old nonce
05790           * is saved for stale checking...
05791           */
05792          session->nc = 0; /* Reset nonce counter */
05793          session->oldnonce = session->managerid;
05794          nonce = session->managerid = ast_random();
05795          session->noncetime = time_now;
05796          ao2_unlock(session);
05797          stale = 1;
05798          goto out_401;
05799       } else {
05800          session->nc = nc; /* All OK, save nonce counter */
05801       }
05802    }
05803 
05804 
05805    /* Reset session timeout. */
05806    session->sessiontimeout = time(NULL) + (httptimeout > 5 ? httptimeout : 5);
05807    ao2_unlock(session);
05808 
05809    ast_mutex_init(&s.lock);
05810    s.session = session;
05811    s.fd = mkstemp(template);  /* create a temporary file for command output */
05812    unlink(template);
05813    if (s.fd <= -1) {
05814       ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
05815       goto auth_callback_out;
05816    }
05817    s.f = fdopen(s.fd, "w+");
05818    if (!s.f) {
05819       ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
05820       ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
05821       close(s.fd);
05822       goto auth_callback_out;
05823    }
05824 
05825    if (method == AST_HTTP_POST) {
05826       params = ast_http_get_post_vars(ser, headers);
05827    }
05828 
05829    for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
05830       hdrlen = strlen(v->name) + strlen(v->value) + 3;
05831       m.headers[m.hdrcount] = alloca(hdrlen);
05832       snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
05833       ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
05834       m.hdrcount = x + 1;
05835    }
05836 
05837    if (process_message(&s, &m)) {
05838       if (u_displayconnects) {
05839          ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05840       }
05841 
05842       session->needdestroy = 1;
05843    }
05844 
05845    if (s.f) {
05846       result_size = ftell(s.f); /* Calculate approx. size of result */
05847    }
05848 
05849    http_header = ast_str_create(80);
05850    out = ast_str_create(result_size * 2 + 512);
05851 
05852    if (http_header == NULL || out == NULL) {
05853       ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
05854       goto auth_callback_out;
05855    }
05856 
05857    ast_str_append(&http_header, 0, "Content-type: text/%s", contenttype[format]);
05858 
05859    if (format == FORMAT_XML) {
05860       ast_str_append(&out, 0, "<ajax-response>\n");
05861    } else if (format == FORMAT_HTML) {
05862       ast_str_append(&out, 0,
05863       "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
05864       "<html><head>\r\n"
05865       "<title>Asterisk&trade; Manager Interface</title>\r\n"
05866       "</head><body style=\"background-color: #ffffff;\">\r\n"
05867       "<form method=\"POST\">\r\n"
05868       "<table align=\"center\" style=\"background-color: #f1f1f1;\" width=\"500\">\r\n"
05869       "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\"><h1>Manager Tester</h1></th></tr>\r\n"
05870       "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\">Action: <input name=\"action\" /> Cmd: <input name=\"command\" /><br>"
05871       "<input type=\"submit\" value=\"Send request\" /></th></tr>\r\n");
05872    }
05873 
05874    if (s.f != NULL) {   /* have temporary output */
05875       char *buf;
05876       size_t l = ftell(s.f);
05877 
05878       if (l) {
05879          if ((buf = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_SHARED, s.fd, 0))) {
05880             if (format == FORMAT_XML || format == FORMAT_HTML) {
05881                xml_translate(&out, buf, params, format);
05882             } else {
05883                ast_str_append(&out, 0, "%s", buf);
05884             }
05885             munmap(buf, l);
05886          }
05887       } else if (format == FORMAT_XML || format == FORMAT_HTML) {
05888          xml_translate(&out, "", params, format);
05889       }
05890       fclose(s.f);
05891       s.f = NULL;
05892       s.fd = -1;
05893    }
05894 
05895    if (format == FORMAT_XML) {
05896       ast_str_append(&out, 0, "</ajax-response>\n");
05897    } else if (format == FORMAT_HTML) {
05898       ast_str_append(&out, 0, "</table></form></body></html>\r\n");
05899    }
05900 
05901    ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
05902    http_header = out = NULL;
05903 
05904 auth_callback_out:
05905    ast_mutex_destroy(&s.lock);
05906 
05907    /* Clear resources and unlock manager session */
05908    if (method == AST_HTTP_POST && params) {
05909       ast_variables_destroy(params);
05910    }
05911 
05912    ast_free(http_header);
05913    ast_free(out);
05914 
05915    ao2_lock(session);
05916    if (session->f) {
05917       fclose(session->f);
05918    }
05919    session->f = NULL;
05920    session->fd = -1;
05921    ao2_unlock(session);
05922 
05923    if (session->needdestroy) {
05924       ast_debug(1, "Need destroy, doing it now!\n");
05925       session_destroy(session);
05926    }
05927    ast_string_field_free_memory(&d);
05928    return 0;
05929 
05930 out_401:
05931    if (!nonce) {
05932       nonce = ast_random();
05933    }
05934 
05935    ast_http_auth(ser, global_realm, nonce, nonce, stale, NULL);
05936    ast_string_field_free_memory(&d);
05937    return 0;
05938 }

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 5999 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.

06000 {
06001    int retval;
06002    struct sockaddr_in ser_remote_address_tmp;
06003 
06004    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06005    retval = auth_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
06006    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06007    return retval;
06008 }

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 6010 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.

06011 {
06012    int retval;
06013    struct sockaddr_in ser_remote_address_tmp;
06014 
06015    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06016    retval = auth_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
06017    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06018    return retval;
06019 }

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 6021 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.

06022 {
06023    int retval;
06024    struct sockaddr_in ser_remote_address_tmp;
06025 
06026    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06027    retval = auth_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
06028    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06029    return retval;
06030 }

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 5037 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, and unref_mansession().

Referenced by astman_is_authed(), and generic_http_callback().

05038 {
05039    struct mansession_session *session;
05040    struct ao2_iterator i;
05041 
05042    if (ident == 0) {
05043       return NULL;
05044    }
05045 
05046    i = ao2_iterator_init(sessions, 0);
05047    while ((session = ao2_iterator_next(&i))) {
05048       ao2_lock(session);
05049       if (session->managerid == ident && !session->needdestroy) {
05050          ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
05051          break;
05052       }
05053       ao2_unlock(session);
05054       unref_mansession(session);
05055    }
05056    ao2_iterator_destroy(&i);
05057 
05058    return session;
05059 }

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 5070 of file manager.c.

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

Referenced by auth_http_callback().

05071 {
05072    struct mansession_session *session;
05073    struct ao2_iterator i;
05074 
05075    if (nonce == 0 || username == NULL || stale == NULL) {
05076       return NULL;
05077    }
05078 
05079    i = ao2_iterator_init(sessions, 0);
05080    while ((session = ao2_iterator_next(&i))) {
05081       ao2_lock(session);
05082       if (!strcasecmp(session->username, username) && session->managerid == nonce) {
05083          *stale = 0;
05084          break;
05085       } else if (!strcasecmp(session->username, username) && session->oldnonce == nonce) {
05086          *stale = 1;
05087          break;
05088       }
05089       ao2_unlock(session);
05090       unref_mansession(session);
05091    }
05092    ao2_iterator_destroy(&i);
05093    return session;
05094 }

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 5391 of file manager.c.

References ao2_lock, ao2_unlock, 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_MAX_MANHEADERS, 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(), ROW_FMT, mansession_session::send_events, mansession::session, session_destroy(), mansession_session::sessiontimeout, mansession_session::sin, TEST_STRING, mansession_session::username, ast_variable::value, mansession_session::waiting_thread, and xml_translate().

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

05397 {
05398    struct mansession s = { .session = NULL, .tcptls_session = ser };
05399    struct mansession_session *session = NULL;
05400    uint32_t ident = 0;
05401    int blastaway = 0;
05402    struct ast_variable *v, *cookies, *params = get_params;
05403    char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
05404    struct ast_str *http_header = NULL, *out = NULL;
05405    struct message m = { 0 };
05406    unsigned int x;
05407    size_t hdrlen;
05408 
05409    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
05410       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
05411       return -1;
05412    }
05413 
05414    cookies = ast_http_get_cookies(headers);
05415    for (v = cookies; v; v = v->next) {
05416       if (!strcasecmp(v->name, "mansession_id")) {
05417          sscanf(v->value, "%30x", &ident);
05418          break;
05419       }
05420    }
05421    if (cookies) {
05422       ast_variables_destroy(cookies);
05423    }
05424 
05425    if (!(session = find_session(ident, 1))) {
05426 
05427       /**/
05428       /* Create new session.
05429        * While it is not in the list we don't need any locking
05430        */
05431       if (!(session = build_mansession(*remote_address))) {
05432          ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05433          return -1;
05434       }
05435       ao2_lock(session);
05436       session->sin = *remote_address;
05437       session->fd = -1;
05438       session->waiting_thread = AST_PTHREADT_NULL;
05439       session->send_events = 0;
05440       session->inuse = 1;
05441       /*!\note There is approximately a 1 in 1.8E19 chance that the following
05442        * calculation will produce 0, which is an invalid ID, but due to the
05443        * properties of the rand() function (and the constantcy of s), that
05444        * won't happen twice in a row.
05445        */
05446       while ((session->managerid = ast_random() ^ (unsigned long) session) == 0);
05447       session->last_ev = grab_last();
05448       AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
05449    }
05450    ao2_unlock(session);
05451 
05452    http_header = ast_str_create(128);
05453    out = ast_str_create(2048);
05454 
05455    ast_mutex_init(&s.lock);
05456 
05457    if (http_header == NULL || out == NULL) {
05458       ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
05459       goto generic_callback_out;
05460    }
05461 
05462    s.session = session;
05463    s.fd = mkstemp(template);  /* create a temporary file for command output */
05464    unlink(template);
05465    if (s.fd <= -1) {
05466       ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
05467       goto generic_callback_out;
05468    }
05469    s.f = fdopen(s.fd, "w+");
05470    if (!s.f) {
05471       ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
05472       ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
05473       close(s.fd);
05474       goto generic_callback_out;
05475    }
05476 
05477    if (method == AST_HTTP_POST) {
05478       params = ast_http_get_post_vars(ser, headers);
05479    }
05480 
05481    for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
05482       hdrlen = strlen(v->name) + strlen(v->value) + 3;
05483       m.headers[m.hdrcount] = alloca(hdrlen);
05484       snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
05485       ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
05486       m.hdrcount = x + 1;
05487    }
05488 
05489    if (process_message(&s, &m)) {
05490       if (session->authenticated) {
05491          if (manager_displayconnects(session)) {
05492             ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05493          }
05494       } else {
05495          if (displayconnects) {
05496             ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
05497          }
05498       }
05499       session->needdestroy = 1;
05500    }
05501 
05502    ast_str_append(&http_header, 0,
05503       "Content-type: text/%s\r\n"
05504       "Cache-Control: no-cache;\r\n"
05505       "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
05506       "Pragma: SuppressEvents\r\n",
05507       contenttype[format],
05508       session->managerid, httptimeout);
05509 
05510    if (format == FORMAT_XML) {
05511       ast_str_append(&out, 0, "<ajax-response>\n");
05512    } else if (format == FORMAT_HTML) {
05513       /*
05514        * When handling AMI-over-HTTP in HTML format, we provide a simple form for
05515        * debugging purposes. This HTML code should not be here, we
05516        * should read from some config file...
05517        */
05518 
05519 #define ROW_FMT   "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
05520 #define TEST_STRING \
05521    "<form action=\"manager\" method=\"post\">\n\
05522    Action: <select name=\"action\">\n\
05523       <option value=\"\">-----&gt;</option>\n\
05524       <option value=\"login\">login</option>\n\
05525       <option value=\"command\">Command</option>\n\
05526       <option value=\"waitevent\">waitevent</option>\n\
05527       <option value=\"listcommands\">listcommands</option>\n\
05528    </select>\n\
05529    or <input name=\"action\"><br/>\n\
05530    CLI Command <input name=\"command\"><br>\n\
05531    user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
05532    <input type=\"submit\">\n</form>\n"
05533 
05534       ast_str_append(&out, 0, "<title>Asterisk&trade; Manager Interface</title>");
05535       ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
05536       ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
05537       ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
05538    }
05539 
05540    if (s.f != NULL) {   /* have temporary output */
05541       char *buf;
05542       size_t l;
05543 
05544       if ((l = ftell(s.f))) {
05545          if (MAP_FAILED == (buf = mmap(NULL, l + 1, PROT_READ | PROT_WRITE, MAP_PRIVATE, s.fd, 0))) {
05546             ast_log(LOG_WARNING, "mmap failed.  Manager output was not processed\n");
05547          } else {
05548             buf[l] = '\0';
05549             if (format == FORMAT_XML || format == FORMAT_HTML) {
05550                xml_translate(&out, buf, params, format);
05551             } else {
05552                ast_str_append(&out, 0, "%s", buf);
05553             }
05554             munmap(buf, l + 1);
05555          }
05556       } else if (format == FORMAT_XML || format == FORMAT_HTML) {
05557          xml_translate(&out, "", params, format);
05558       }
05559       fclose(s.f);
05560       s.f = NULL;
05561       s.fd = -1;
05562    }
05563 
05564    if (format == FORMAT_XML) {
05565       ast_str_append(&out, 0, "</ajax-response>\n");
05566    } else if (format == FORMAT_HTML) {
05567       ast_str_append(&out, 0, "</table></body>\r\n");
05568    }
05569 
05570    ao2_lock(session);
05571    /* Reset HTTP timeout.  If we're not authenticated, keep it extremely short */
05572    session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
05573 
05574    if (session->needdestroy) {
05575       if (session->inuse == 1) {
05576          ast_debug(1, "Need destroy, doing it now!\n");
05577          blastaway = 1;
05578       } else {
05579          ast_debug(1, "Need destroy, but can't do it yet!\n");
05580          if (session->waiting_thread != AST_PTHREADT_NULL) {
05581             pthread_kill(session->waiting_thread, SIGURG);
05582          }
05583          session->inuse--;
05584       }
05585    } else {
05586       session->inuse--;
05587    }
05588    ao2_unlock(session);
05589 
05590    ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
05591    http_header = out = NULL;
05592 
05593 generic_callback_out:
05594    ast_mutex_destroy(&s.lock);
05595 
05596    /* Clear resource */
05597 
05598    if (method == AST_HTTP_POST && params) {
05599       ast_variables_destroy(params);
05600    }
05601    if (http_header) {
05602       ast_free(http_header);
05603    }
05604    if (out) {
05605       ast_free(out);
05606    }
05607 
05608    if (session && blastaway) {
05609       session_destroy(session);
05610    } else if (session && session->f) {
05611       fclose(session->f);
05612       session->f = NULL;
05613    }
05614 
05615    return 0;
05616 }

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 6094 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, manager_debug, ast_tls_config::pvtfile, S_OR, and ast_cli_entry::usage.

06095 {
06096    switch (cmd) {
06097    case CLI_INIT:
06098       e->command = "manager show settings";
06099       e->usage =
06100          "Usage: manager show settings\n"
06101          "       Provides detailed list of the configuration of the Manager.\n";
06102       return NULL;
06103    case CLI_GENERATE:
06104       return NULL;
06105    }
06106 #define FORMAT "  %-25.25s  %-15.15s\n"
06107 #define FORMAT2 "  %-25.25s  %-15d\n"
06108    if (a->argc != 3) {
06109       return CLI_SHOWUSAGE;
06110    }
06111    ast_cli(a->fd, "\nGlobal Settings:\n");
06112    ast_cli(a->fd, "----------------\n");
06113    ast_cli(a->fd, FORMAT, "Manager (AMI):", AST_CLI_YESNO(manager_enabled));
06114    ast_cli(a->fd, FORMAT, "Web Manager (AMI/HTTP):", AST_CLI_YESNO(webmanager_enabled));
06115    ast_cli(a->fd, FORMAT, "TCP Bindaddress:", ast_sockaddr_stringify(&ami_desc.local_address));
06116    ast_cli(a->fd, FORMAT2, "HTTP Timeout (minutes):", httptimeout);
06117    ast_cli(a->fd, FORMAT, "TLS Enable:", AST_CLI_YESNO(ami_tls_cfg.enabled));
06118    ast_cli(a->fd, FORMAT, "TLS Bindaddress:", ast_sockaddr_stringify(&amis_desc.local_address));
06119    ast_cli(a->fd, FORMAT, "TLS Certfile:", ami_tls_cfg.certfile);
06120    ast_cli(a->fd, FORMAT, "TLS Privatekey:", ami_tls_cfg.pvtfile);
06121    ast_cli(a->fd, FORMAT, "TLS Cipher:", ami_tls_cfg.cipher);
06122    ast_cli(a->fd, FORMAT, "Allow multiple login:", AST_CLI_YESNO(allowmultiplelogin));
06123    ast_cli(a->fd, FORMAT, "Display connects:", AST_CLI_YESNO(displayconnects));
06124    ast_cli(a->fd, FORMAT, "Timestamp events:", AST_CLI_YESNO(timestampevents));
06125    ast_cli(a->fd, FORMAT, "Channel vars:", S_OR(manager_channelvars, ""));
06126    ast_cli(a->fd, FORMAT, "Debug:", AST_CLI_YESNO(manager_debug));
06127    ast_cli(a->fd, FORMAT, "Block sockets:", AST_CLI_YESNO(block_sockets));
06128 #undef FORMAT
06129 #undef FORMAT2
06130 
06131    return CLI_SUCCESS;
06132 }

int init_manager ( void   ) 

Called by Asterisk initialization.

Definition at line 6578 of file manager.c.

References __init_manager().

Referenced by main().

06579 {
06580    return __init_manager(0);
06581 }

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 5940 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.

05941 {
05942    int retval;
05943    struct sockaddr_in ser_remote_address_tmp;
05944 
05945    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05946    retval = generic_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
05947    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05948    return retval;
05949 }

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 5951 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.

05952 {
05953    int retval;
05954    struct sockaddr_in ser_remote_address_tmp;
05955 
05956    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05957    retval = generic_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
05958    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05959    return retval;
05960 }

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 6065 of file manager.c.

References purge_events(), and purge_sessions().

06066 {
06067    purge_sessions(1);
06068    purge_events();
06069 }

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 5962 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.

05963 {
05964    int retval;
05965    struct sockaddr_in ser_remote_address_tmp;
05966 
05967    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05968    retval = generic_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
05969    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05970    return retval;
05971 }

int reload_manager ( void   ) 

Called by Asterisk module functions and the CLI command.

Definition at line 6583 of file manager.c.

References __init_manager().

Referenced by handle_manager_reload().

06584 {
06585    return __init_manager(1);
06586 }

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

Definition at line 5238 of file manager.c.

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

Referenced by xml_translate().

05239 {
05240    /* Due to the simplicity of struct variable_count, it makes no difference
05241     * if you pass in objects or strings, the same operation applies. This is
05242     * due to the fact that the hash occurs on the first element, which means
05243     * the address of both the struct and the string are exactly the same. */
05244    struct variable_count *vc = obj;
05245    char *str = vstr;
05246    return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
05247 }

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

Definition at line 5231 of file manager.c.

References ast_str_hash(), and variable_count::varname.

Referenced by xml_translate().

05232 {
05233    const struct variable_count *vc = vvc;
05234 
05235    return ast_str_hash(vc->varname);
05236 }

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

Definition at line 5169 of file manager.c.

References ast_str_append().

Referenced by xml_translate().

05170 {
05171    /* store in a local buffer to avoid calling ast_str_append too often */
05172    char buf[256];
05173    char *dst = buf;
05174    int space = sizeof(buf);
05175    /* repeat until done and nothing to flush */
05176    for ( ; *src || dst != buf ; src++) {
05177       if (*src == '\0' || space < 10) {   /* flush */
05178          *dst++ = '\0';
05179          ast_str_append(out, 0, "%s", buf);
05180          dst = buf;
05181          space = sizeof(buf);
05182          if (*src == '\0') {
05183             break;
05184          }
05185       }
05186 
05187       if ( (mode & 2) && !isalnum(*src)) {
05188          *dst++ = '_';
05189          space--;
05190          continue;
05191       }
05192       switch (*src) {
05193       case '<':
05194          strcpy(dst, "&lt;");
05195          dst += 4;
05196          space -= 4;
05197          break;
05198       case '>':
05199          strcpy(dst, "&gt;");
05200          dst += 4;
05201          space -= 4;
05202          break;
05203       case '\"':
05204          strcpy(dst, "&quot;");
05205          dst += 6;
05206          space -= 6;
05207          break;
05208       case '\'':
05209          strcpy(dst, "&apos;");
05210          dst += 6;
05211          space -= 6;
05212          break;
05213       case '&':
05214          strcpy(dst, "&amp;");
05215          dst += 5;
05216          space -= 5;
05217          break;
05218 
05219       default:
05220          *dst++ = mode ? tolower(*src) : *src;
05221          space--;
05222       }
05223    }
05224 }

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 5277 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, strsep(), ast_variable::value, var, variable_count_cmp_fn(), variable_count_hash_fn(), variable_count::varname, and xml_copy_escape().

Referenced by auth_http_callback(), and generic_http_callback().

05278 {
05279    struct ast_variable *v;
05280    const char *dest = NULL;
05281    char *var, *val;
05282    const char *objtype = NULL;
05283    int in_data = 0;  /* parsing data */
05284    int inobj = 0;
05285    int xml = (format == FORMAT_XML);
05286    struct variable_count *vc = NULL;
05287    struct ao2_container *vco = NULL;
05288 
05289    if (xml) {
05290       /* dest and objtype need only for XML format */
05291       for (v = get_vars; v; v = v->next) {
05292          if (!strcasecmp(v->name, "ajaxdest")) {
05293             dest = v->value;
05294          } else if (!strcasecmp(v->name, "ajaxobjtype")) {
05295             objtype = v->value;
05296          }
05297       }
05298       if (ast_strlen_zero(dest)) {
05299          dest = "unknown";
05300       }
05301       if (ast_strlen_zero(objtype)) {
05302          objtype = "generic";
05303       }
05304    }
05305 
05306    /* we want to stop when we find an empty line */
05307    while (in && *in) {
05308       val = strsep(&in, "\r\n"); /* mark start and end of line */
05309       if (in && *in == '\n') {   /* remove trailing \n if any */
05310          in++;
05311       }
05312       ast_trim_blanks(val);
05313       ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
05314       if (ast_strlen_zero(val)) {
05315          /* empty line */
05316          if (in_data) {
05317             /* close data in Opaque mode */
05318             ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05319             in_data = 0;
05320          }
05321 
05322          if (inobj) {
05323             /* close block */
05324             ast_str_append(out, 0, xml ? " /></response>\n" :
05325                "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05326             inobj = 0;
05327             ao2_ref(vco, -1);
05328             vco = NULL;
05329          }
05330          continue;
05331       }
05332 
05333       if (!inobj) {
05334          /* start new block */
05335          if (xml) {
05336             ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
05337          }
05338          vco = ao2_container_alloc(37, variable_count_hash_fn, variable_count_cmp_fn);
05339          inobj = 1;
05340       }
05341 
05342       if (in_data) {
05343          /* Process data field in Opaque mode */
05344          xml_copy_escape(out, val, 0);   /* data field */
05345          ast_str_append(out, 0, xml ? "\n" : "<br>\n");
05346          continue;
05347       }
05348 
05349       /* We expect "Name: value" line here */
05350       var = strsep(&val, ":");
05351       if (val) {
05352          /* found the field name */
05353          val = ast_skip_blanks(val);
05354          ast_trim_blanks(var);
05355       } else {
05356          /* field name not found, switch to opaque mode */
05357          val = var;
05358          var = "Opaque-data";
05359          in_data = 1;
05360       }
05361 
05362 
05363       ast_str_append(out, 0, xml ? " " : "<tr><td>");
05364       if ((vc = ao2_find(vco, var, 0))) {
05365          vc->count++;
05366       } else {
05367          /* Create a new entry for this one */
05368          vc = ao2_alloc(sizeof(*vc), NULL);
05369          vc->varname = var;
05370          vc->count = 1;
05371          ao2_link(vco, vc);
05372       }
05373 
05374       xml_copy_escape(out, var, xml ? 1 | 2 : 0); /* data name */
05375       if (vc->count > 1) {
05376          ast_str_append(out, 0, "-%d", vc->count);
05377       }
05378       ao2_ref(vc, -1);
05379       ast_str_append(out, 0, xml ? "='" : "</td><td>");
05380       xml_copy_escape(out, val, 0); /* data field */
05381       ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05382    }
05383 
05384    if (inobj) {
05385       ast_str_append(out, 0, xml ? " /></response>\n" :
05386          "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05387       ao2_ref(vco, -1);
05388    }
05389 }


Variable Documentation

struct ast_http_uri amanageruri [static]

Definition at line 6041 of file manager.c.

struct ast_http_uri amanagerxmluri [static]

Definition at line 6050 of file manager.c.

Definition at line 6072 of file manager.c.

struct ast_tls_config ami_tls_cfg [static]

Definition at line 6071 of file manager.c.

Referenced by __init_manager(), and handle_manager_show_settings().

Definition at line 6083 of file manager.c.

struct ast_http_uri arawmanuri [static]

Definition at line 6032 of file manager.c.

struct ast_cli_entry cli_manager[] [static]

Definition at line 6134 of file manager.c.

const char* const contenttype[] [static]

Initial value:

 {
   [FORMAT_RAW] = "plain",
   [FORMAT_HTML] = "html",
   [FORMAT_XML] =  "xml",
}

Definition at line 5026 of file manager.c.

struct ast_http_uri manageruri [static]

Definition at line 5981 of file manager.c.

struct ast_http_uri managerxmluri [static]

Definition at line 5989 of file manager.c.

struct ast_http_uri rawmanuri [static]

Definition at line 5973 of file manager.c.

int registered = 0 [static]

Definition at line 6059 of file manager.c.

int webregged = 0 [static]

Definition at line 6060 of file manager.c.

const char* words[AST_MAX_CMD_LEN]

Definition at line 892 of file manager.c.

Referenced by check_blacklist().


Generated on Sat Mar 26 11:24:11 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9