Wed Mar 2 18:57:33 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 "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/version.h"
#include "asterisk/term.h"
#include "asterisk/astobj2.h"
#include "asterisk/features.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  eventqent
struct  fast_originate_helper
 helper function for originate More...
struct  manager_hooks
 list of hooks registered More...
struct  mansession
struct  mansession_datastores
struct  mansession_session
struct  permalias
struct  sessions
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 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\">\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

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_userevent_buf (void)
int __manager_event (int category, const char *event, const char *file, int line, const char *func, const char *fmt,...)
 manager_event: Send AMI event to client
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 append_event (const char *str, int category)
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 authenticate (struct mansession *s, const struct message *m)
static char * authority_to_str (int authority, struct ast_str **res)
 Convert authority code to a list of options.
static int check_blacklist (const char *cmd)
int check_manager_enabled ()
 Event list management functions. We assume that the event list always has at least one element, and the delete code will not remove the last entry even if the.
static int check_manager_session_inuse (const char *name)
int check_webmanager_enabled ()
 Check if AMI/HTTP is enabled.
static int compress_char (char c)
static void destroy_session (struct mansession_session *session)
static int do_message (struct mansession *s)
static void * fast_originate (void *data)
static struct mansession_session * find_session (uint32_t ident, int incinuse)
static void free_session (struct mansession_session *session)
static struct ast_str * generic_http_callback (enum output_format format, struct sockaddr_in *remote_address, const char *uri, enum ast_http_method method, struct ast_variable *params, int *status, char **title, int *contentlength)
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_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 struct ast_str * 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 *params, struct ast_variable *headers, int *status, char **title, int *contentlength)
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 struct ast_str * 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 *params, struct ast_variable *headers, int *status, char **title, int *contentlength)
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 struct ast_str * 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 *params, struct ast_variable *headers, int *status, char **title, int *contentlength)
int reload_manager (void)
 Called by Asterisk module functions and the CLI command.
static int send_string (struct mansession *s, char *string)
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 int variable_count_cmp_fn (void *obj, void *vstr, int flags)
static int variable_count_hash_fn (const void *vvc, const 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 *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_tcptls_session_args 
ami_desc
struct ast_tls_config ami_tls_cfg
static struct
ast_tcptls_session_args 
amis_desc
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 {
   char *   words [AST_MAX_CMD_LEN]
} command_blacklist []
static char * 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 int httptimeout
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 , }
struct ast_http_uri manageruri
struct ast_http_uri managerxmluri
static char mandescr_atxfer []
static char mandescr_command []
static char mandescr_coresettings []
static char mandescr_coreshowchannels []
static char mandescr_corestatus []
static char mandescr_createconfig []
static char mandescr_events []
static char mandescr_extensionstate []
static char mandescr_getconfig []
static char mandescr_getconfigjson []
static char mandescr_getvar []
static char mandescr_hangup []
static char mandescr_listcategories []
static char mandescr_listcommands []
static char mandescr_logoff []
static char mandescr_mailboxcount []
static char mandescr_mailboxstatus []
 Help text for manager command mailboxstatus.
static char mandescr_modulecheck []
static char mandescr_moduleload []
static char mandescr_originate []
static char mandescr_ping []
 Manager PING.
static char mandescr_redirect []
static char mandescr_reload []
static char mandescr_sendtext []
static char mandescr_setvar []
static char mandescr_status []
static char mandescr_timeout []
static char mandescr_updateconfig []
static char mandescr_userevent []
static char mandescr_waitevent []
 Manager WAITEVENT.
static int num_sessions
static struct permalias perms []
struct ast_http_uri rawmanuri
static int registered = 0
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 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\">\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 3536 of file manager.c.

03536                    {
03537    FORMAT_RAW,
03538    FORMAT_HTML,
03539    FORMAT_XML,
03540 };


Function Documentation

static int __init_manager ( int  reload  )  [static]

Definition at line 4115 of file manager.c.

References 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(), ahp, ami_desc, ami_tls_cfg, amis_desc, append_event(), ARRAY_LEN, ast_append_ha(), ast_calloc, ast_category_browse(), AST_CERTFILE, ast_cli_register_multiple(), ast_config_destroy(), ast_config_load2(), ast_copy_string(), ast_debug, ast_extension_state_add(), ast_free, ast_free_ha(), ast_gethostbyname(), ast_http_uri_link(), ast_http_uri_unlink(), AST_LIST_INSERT_TAIL, ast_log(), ast_manager_register2(), 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_ssl_setup(), ast_strdup, ast_strlen_zero(), ast_tcptls_server_start(), ast_true(), ast_variable_browse(), ast_variable_retrieve(), ast_tls_config::certfile, ast_tls_config::cipher, cli_manager, CONFIG_FLAG_FILEUNCHANGED, config_flags, CONFIG_STATUS_FILEINVALID, CONFIG_STATUS_FILEUNCHANGED, DEFAULT_MANAGER_PORT, ast_manager_user::displayconnects, ast_tls_config::enabled, EVENT_FLAG_CALL, EVENT_FLAG_COMMAND, EVENT_FLAG_CONFIG, EVENT_FLAG_ORIGINATE, EVENT_FLAG_REPORTING, EVENT_FLAG_SYSTEM, EVENT_FLAG_USER, get_manager_by_name_locked(), get_perm(), ast_manager_user::ha, hp, inet_aton(), ast_manager_user::keep, ast_variable::lineno, ast_tcptls_session_args::local_address, LOG_NOTICE, LOG_WARNING, manager_event, manager_modulecheck(), manager_moduleload(), manager_state_cb(), manageruri, managerxmluri, mandescr_atxfer, mandescr_command, mandescr_coresettings, mandescr_coreshowchannels, mandescr_corestatus, mandescr_createconfig, mandescr_events, mandescr_extensionstate, mandescr_getconfig, mandescr_getconfigjson, mandescr_getvar, mandescr_hangup, mandescr_listcategories, mandescr_listcommands, mandescr_logoff, mandescr_mailboxcount, mandescr_mailboxstatus, mandescr_modulecheck, mandescr_moduleload, mandescr_originate, mandescr_ping, mandescr_redirect, mandescr_reload, mandescr_sendtext, mandescr_setvar, mandescr_status, mandescr_timeout, mandescr_updateconfig, mandescr_userevent, mandescr_waitevent, ast_variable::name, ast_variable::next, rawmanuri, ast_manager_user::readperm, registered, ast_manager_user::secret, ast_tcptls_session_args::tls_cfg, ast_manager_user::username, ast_variable::value, var, webregged, ast_manager_user::writeperm, and ast_manager_user::writetimeout.

Referenced by init_manager(), and reload_manager().

04116 {
04117    struct ast_config *ucfg = NULL, *cfg = NULL;
04118    const char *val;
04119    char *cat = NULL;
04120    int newhttptimeout = DEFAULT_HTTPTIMEOUT;
04121    int have_sslbindaddr = 0;
04122    struct hostent *hp;
04123    struct ast_hostent ahp;
04124    struct ast_manager_user *user = NULL;
04125    struct ast_variable *var;
04126    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
04127    
04128    if (!registered) {
04129       /* Register default actions */
04130       ast_manager_register2("Ping", 0, action_ping, "Keepalive command", mandescr_ping);
04131       ast_manager_register2("Events", 0, action_events, "Control Event Flow", mandescr_events);
04132       ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
04133       ast_manager_register2("Login", 0, action_login, "Login Manager", NULL);
04134       ast_manager_register2("Challenge", 0, action_challenge, "Generate Challenge for MD5 Auth", NULL);
04135       ast_manager_register2("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
04136       ast_manager_register2("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status, "Lists channel status", mandescr_status);
04137       ast_manager_register2("Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable", mandescr_setvar);
04138       ast_manager_register2("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar, "Gets a Channel Variable", mandescr_getvar);
04139       ast_manager_register2("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig, "Retrieve configuration", mandescr_getconfig);
04140       ast_manager_register2("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson, "Retrieve configuration (JSON format)", mandescr_getconfigjson);
04141       ast_manager_register2("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig, "Update basic configuration", mandescr_updateconfig);
04142       ast_manager_register2("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig, "Creates an empty file in the configuration directory", mandescr_createconfig);
04143       ast_manager_register2("ListCategories", EVENT_FLAG_CONFIG, action_listcategories, "List categories in configuration file", mandescr_listcategories);
04144       ast_manager_register2("Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect (transfer) a call", mandescr_redirect );
04145       ast_manager_register2("Atxfer", EVENT_FLAG_CALL, action_atxfer, "Attended transfer", mandescr_atxfer);
04146       ast_manager_register2("Originate", EVENT_FLAG_ORIGINATE, action_originate, "Originate Call", mandescr_originate);
04147       ast_manager_register2("Command", EVENT_FLAG_COMMAND, action_command, "Execute Asterisk CLI Command", mandescr_command );
04148       ast_manager_register2("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate, "Check Extension Status", mandescr_extensionstate );
04149       ast_manager_register2("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout", mandescr_timeout );
04150       ast_manager_register2("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus, "Check Mailbox", mandescr_mailboxstatus );
04151       ast_manager_register2("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount, "Check Mailbox Message Count", mandescr_mailboxcount );
04152       ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
04153       ast_manager_register2("SendText", EVENT_FLAG_CALL, action_sendtext, "Send text message to channel", mandescr_sendtext);
04154       ast_manager_register2("UserEvent", EVENT_FLAG_USER, action_userevent, "Send an arbitrary event", mandescr_userevent);
04155       ast_manager_register2("WaitEvent", 0, action_waitevent, "Wait for an event to occur", mandescr_waitevent);
04156       ast_manager_register2("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings, "Show PBX core settings (version etc)", mandescr_coresettings);
04157       ast_manager_register2("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus, "Show PBX core status variables", mandescr_corestatus);
04158       ast_manager_register2("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload, "Send a reload event", mandescr_reload);
04159       ast_manager_register2("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels, "List currently active channels", mandescr_coreshowchannels);
04160       ast_manager_register2("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload, "Module management", mandescr_moduleload);
04161       ast_manager_register2("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck, "Check if module is loaded", mandescr_modulecheck);
04162 
04163       ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
04164       ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
04165       registered = 1;
04166       /* Append placeholder event so master_eventq never runs dry */
04167       append_event("Event: Placeholder\r\n\r\n", 0);
04168    }
04169    if ((cfg = ast_config_load2("manager.conf", "manager", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
04170       return 0;
04171 
04172    manager_enabled = DEFAULT_ENABLED;
04173    webmanager_enabled = DEFAULT_WEBENABLED;
04174    displayconnects = DEFAULT_DISPLAYCONNECTS;
04175    broken_events_action = DEFAULT_BROKENEVENTSACTION;
04176    block_sockets = DEFAULT_BLOCKSOCKETS;
04177    timestampevents = DEFAULT_TIMESTAMPEVENTS;
04178    httptimeout = DEFAULT_HTTPTIMEOUT;
04179 
04180    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
04181       ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid. Asterisk management interface (AMI) disabled.\n");
04182       return 0;
04183    }
04184 
04185    /* default values */
04186    memset(&ami_desc.local_address, 0, sizeof(struct sockaddr_in));
04187    memset(&amis_desc.local_address, 0, sizeof(amis_desc.local_address));
04188    amis_desc.local_address.sin_port = htons(5039);
04189    ami_desc.local_address.sin_port = htons(DEFAULT_MANAGER_PORT);
04190 
04191    ami_tls_cfg.enabled = 0;
04192    if (ami_tls_cfg.certfile)
04193       ast_free(ami_tls_cfg.certfile);
04194    ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
04195    if (ami_tls_cfg.cipher)
04196       ast_free(ami_tls_cfg.cipher);
04197    ami_tls_cfg.cipher = ast_strdup("");
04198 
04199    for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
04200       val = var->value;
04201       if (!strcasecmp(var->name, "sslenable"))
04202          ami_tls_cfg.enabled = ast_true(val);
04203       else if (!strcasecmp(var->name, "sslbindport"))
04204          amis_desc.local_address.sin_port = htons(atoi(val));
04205       else if (!strcasecmp(var->name, "sslbindaddr")) {
04206          if ((hp = ast_gethostbyname(val, &ahp))) {
04207             memcpy(&amis_desc.local_address.sin_addr, hp->h_addr, sizeof(amis_desc.local_address.sin_addr));
04208             have_sslbindaddr = 1;
04209          } else {
04210             ast_log(LOG_WARNING, "Invalid bind address '%s'\n", val);
04211          }
04212       } else if (!strcasecmp(var->name, "sslcert")) {
04213          ast_free(ami_tls_cfg.certfile);
04214          ami_tls_cfg.certfile = ast_strdup(val);
04215       } else if (!strcasecmp(var->name, "sslcipher")) {
04216          ast_free(ami_tls_cfg.cipher);
04217          ami_tls_cfg.cipher = ast_strdup(val);
04218       } else if (!strcasecmp(var->name, "enabled")) {
04219          manager_enabled = ast_true(val);
04220       } else if (!strcasecmp(var->name, "block-sockets")) {
04221          block_sockets = ast_true(val);
04222       } else if (!strcasecmp(var->name, "webenabled")) {
04223          webmanager_enabled = ast_true(val);
04224       } else if (!strcasecmp(var->name, "port")) {
04225          ami_desc.local_address.sin_port = htons(atoi(val));
04226       } else if (!strcasecmp(var->name, "bindaddr")) {
04227          if (!inet_aton(val, &ami_desc.local_address.sin_addr)) {
04228             ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
04229             memset(&ami_desc.local_address.sin_addr, 0, sizeof(ami_desc.local_address.sin_addr));
04230          }
04231       } else if (!strcasecmp(var->name, "brokeneventsaction")) {
04232          broken_events_action = ast_true(val);
04233       } else if (!strcasecmp(var->name, "allowmultiplelogin")) { 
04234          allowmultiplelogin = ast_true(val);
04235       } else if (!strcasecmp(var->name, "displayconnects")) {
04236          displayconnects = ast_true(val);
04237       } else if (!strcasecmp(var->name, "timestampevents")) {
04238          timestampevents = ast_true(val);
04239       } else if (!strcasecmp(var->name, "debug")) {
04240          manager_debug = ast_true(val);
04241       } else if (!strcasecmp(var->name, "httptimeout")) {
04242          newhttptimeout = atoi(val);
04243       } else {
04244          ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
04245             var->name, val);
04246       }  
04247    }
04248 
04249    if (manager_enabled)
04250       ami_desc.local_address.sin_family = AF_INET;
04251    if (!have_sslbindaddr)
04252       amis_desc.local_address.sin_addr = ami_desc.local_address.sin_addr;
04253    if (ami_tls_cfg.enabled)
04254       amis_desc.local_address.sin_family = AF_INET;
04255 
04256    
04257    AST_RWLIST_WRLOCK(&users);
04258 
04259    /* First, get users from users.conf */
04260    ucfg = ast_config_load2("users.conf", "manager", config_flags);
04261    if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
04262       const char *hasmanager;
04263       int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
04264 
04265       while ((cat = ast_category_browse(ucfg, cat))) {
04266          if (!strcasecmp(cat, "general"))
04267             continue;
04268          
04269          hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
04270          if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
04271             const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
04272             const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
04273             const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
04274             const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
04275             const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
04276             
04277             /* Look for an existing entry,
04278              * if none found - create one and add it to the list
04279              */
04280             if (!(user = get_manager_by_name_locked(cat))) {
04281                if (!(user = ast_calloc(1, sizeof(*user))))
04282                   break;
04283 
04284                /* Copy name over */
04285                ast_copy_string(user->username, cat, sizeof(user->username));
04286                /* Insert into list */
04287                AST_LIST_INSERT_TAIL(&users, user, list);
04288                user->ha = NULL;
04289                user->keep = 1;
04290                user->readperm = -1;
04291                user->writeperm = -1;
04292                /* Default displayconnect from [general] */
04293                user->displayconnects = displayconnects;
04294                user->writetimeout = 100;
04295             }
04296 
04297             if (!user_secret)
04298                user_secret = ast_variable_retrieve(ucfg, "general", "secret");
04299             if (!user_read)
04300                user_read = ast_variable_retrieve(ucfg, "general", "read");
04301             if (!user_write)
04302                user_write = ast_variable_retrieve(ucfg, "general", "write");
04303             if (!user_displayconnects)
04304                user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
04305             if (!user_writetimeout)
04306                user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
04307 
04308             if (!ast_strlen_zero(user_secret)) {
04309                if (user->secret)
04310                   ast_free(user->secret);
04311                user->secret = ast_strdup(user_secret);
04312             }
04313 
04314             if (user_read)
04315                user->readperm = get_perm(user_read);
04316             if (user_write)
04317                user->writeperm = get_perm(user_write);
04318             if (user_displayconnects)
04319                user->displayconnects = ast_true(user_displayconnects);
04320 
04321             if (user_writetimeout) {
04322                int value = atoi(user_writetimeout);
04323                if (value < 100)
04324                   ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at users.conf line %d\n", var->value, var->lineno);
04325                else
04326                   user->writetimeout = value;
04327             }
04328          }
04329       }
04330       ast_config_destroy(ucfg);
04331    }
04332 
04333    /* cat is NULL here in any case */
04334 
04335    while ((cat = ast_category_browse(cfg, cat))) {
04336       struct ast_ha *oldha;
04337 
04338       if (!strcasecmp(cat, "general"))
04339          continue;
04340 
04341       /* Look for an existing entry, if none found - create one and add it to the list */
04342       if (!(user = get_manager_by_name_locked(cat))) {
04343          if (!(user = ast_calloc(1, sizeof(*user))))
04344             break;
04345          /* Copy name over */
04346          ast_copy_string(user->username, cat, sizeof(user->username));
04347 
04348          user->ha = NULL;
04349          user->readperm = 0;
04350          user->writeperm = 0;
04351          /* Default displayconnect from [general] */
04352          user->displayconnects = displayconnects;
04353          user->writetimeout = 100;
04354 
04355          /* Insert into list */
04356          AST_RWLIST_INSERT_TAIL(&users, user, list);
04357       }
04358 
04359       /* Make sure we keep this user and don't destroy it during cleanup */
04360       user->keep = 1;
04361       oldha = user->ha;
04362       user->ha = NULL;
04363 
04364       var = ast_variable_browse(cfg, cat);
04365       for (; var; var = var->next) {
04366          if (!strcasecmp(var->name, "secret")) {
04367             if (user->secret)
04368                ast_free(user->secret);
04369             user->secret = ast_strdup(var->value);
04370          } else if (!strcasecmp(var->name, "deny") ||
04371                    !strcasecmp(var->name, "permit")) {
04372             user->ha = ast_append_ha(var->name, var->value, user->ha, NULL);
04373          }  else if (!strcasecmp(var->name, "read") ) {
04374             user->readperm = get_perm(var->value);
04375          }  else if (!strcasecmp(var->name, "write") ) {
04376             user->writeperm = get_perm(var->value);
04377          }  else if (!strcasecmp(var->name, "displayconnects") ) {
04378             user->displayconnects = ast_true(var->value);
04379          } else if (!strcasecmp(var->name, "writetimeout")) {
04380             int value = atoi(var->value);
04381             if (value < 100)
04382                ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
04383             else
04384                user->writetimeout = value;
04385          } else
04386             ast_debug(1, "%s is an unknown option.\n", var->name);
04387       }
04388       ast_free_ha(oldha);
04389    }
04390    ast_config_destroy(cfg);
04391 
04392    /* Perform cleanup - essentially prune out old users that no longer exist */
04393    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
04394       if (user->keep) { /* valid record. clear flag for the next round */
04395          user->keep = 0;
04396          continue;
04397       }
04398       /* We do not need to keep this user so take them out of the list */
04399       AST_RWLIST_REMOVE_CURRENT(list);
04400       /* Free their memory now */
04401       if (user->secret)
04402          ast_free(user->secret);
04403       ast_free_ha(user->ha);
04404       ast_free(user);
04405    }
04406    AST_RWLIST_TRAVERSE_SAFE_END;
04407 
04408    AST_RWLIST_UNLOCK(&users);
04409 
04410    if (webmanager_enabled && manager_enabled) {
04411       if (!webregged) {
04412          ast_http_uri_link(&rawmanuri);
04413          ast_http_uri_link(&manageruri);
04414          ast_http_uri_link(&managerxmluri);
04415          webregged = 1;
04416       }
04417    } else {
04418       if (webregged) {
04419          ast_http_uri_unlink(&rawmanuri);
04420          ast_http_uri_unlink(&manageruri);
04421          ast_http_uri_unlink(&managerxmluri);
04422          webregged = 0;
04423       }
04424    }
04425 
04426    if (newhttptimeout > 0)
04427       httptimeout = newhttptimeout;
04428 
04429    manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: Manager\r\nStatus: %s\r\nMessage: Manager reload Requested\r\n", manager_enabled ? "Enabled" : "Disabled");
04430 
04431    ast_tcptls_server_start(&ami_desc);
04432    if (ast_ssl_setup(amis_desc.tls_cfg))
04433       ast_tcptls_server_start(&amis_desc);
04434    return 0;
04435 }

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

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

04448 {
04449    AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
04450 
04451    return 0;
04452 }

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

04460 {
04461    struct ast_datastore *datastore = NULL;
04462    
04463    if (info == NULL)
04464       return NULL;
04465 
04466    AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
04467       if (datastore->info != info) {
04468          continue;
04469       }
04470 
04471       if (uid == NULL) {
04472          /* matched by type only */
04473          break;
04474       }
04475 
04476       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
04477          /* Matched by type AND uid */
04478          break;
04479       }
04480    }
04481    AST_LIST_TRAVERSE_SAFE_END;
04482 
04483    return datastore;
04484 }

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

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

04455 {
04456    return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
04457 }

int astman_is_authed ( uint32_t  ident  ) 

Determinie if a manager session ident is authenticated.

Definition at line 3574 of file manager.c.

References mansession_session::__lock, ast_mutex_unlock(), mansession_session::authenticated, and find_session().

Referenced by handle_uri(), and static_callback().

03575 {
03576    int authed;
03577    struct mansession_session *session;
03578 
03579    if (!(session = find_session(ident, 0)))
03580       return 0;
03581 
03582    authed = (session->authenticated != 0);
03583 
03584    ast_mutex_unlock(&session->__lock);
03585 
03586    return authed;
03587 }

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

References mansession_session::__lock, AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_mutex_lock(), ast_mutex_unlock(), mansession_session::managerid, and mansession_session::readperm.

03590 {
03591    int result = 0;
03592    struct mansession_session *session;
03593 
03594    AST_LIST_LOCK(&sessions);
03595    AST_LIST_TRAVERSE(&sessions, session, list) {
03596       ast_mutex_lock(&session->__lock);
03597       if ((session->managerid == ident) && (session->readperm & perm)) {
03598          result = 1;
03599          ast_mutex_unlock(&session->__lock);
03600          break;
03601       }
03602       ast_mutex_unlock(&session->__lock);
03603    }
03604    AST_LIST_UNLOCK(&sessions);
03605    return result;
03606 }

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

References mansession_session::__lock, AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_mutex_lock(), ast_mutex_unlock(), mansession_session::managerid, and mansession_session::writeperm.

Referenced by http_post_callback().

03609 {
03610    int result = 0;
03611    struct mansession_session *session;
03612 
03613    AST_LIST_LOCK(&sessions);
03614    AST_LIST_TRAVERSE(&sessions, session, list) {
03615       ast_mutex_lock(&session->__lock);
03616       if ((session->managerid == ident) && (session->writeperm & perm)) {
03617          result = 1;
03618          ast_mutex_unlock(&session->__lock);
03619          break;
03620       }
03621       ast_mutex_unlock(&session->__lock);
03622    }
03623    AST_LIST_UNLOCK(&sessions);
03624    return result;
03625 }

static int compress_char ( char  c  )  [static]

Definition at line 3693 of file manager.c.

Referenced by variable_count_hash_fn().

03694 {
03695    c &= 0x7f;
03696    if (c < 32)
03697       return 0;
03698    else if (c >= 'a' && c <= 'z')
03699       return c - 64;
03700    else if (c > 'z')
03701       return '_';
03702    else
03703       return c - 32;
03704 }

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

References mansession_session::__lock, ast_atomic_fetchadd_int(), AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_mutex_lock(), ast_mutex_unlock(), mansession_session::inuse, mansession_session::managerid, and mansession_session::needdestroy.

Referenced by astman_is_authed(), and generic_http_callback().

03554 {
03555    struct mansession_session *session;
03556 
03557    if (ident == 0)
03558       return NULL;
03559 
03560    AST_LIST_LOCK(&sessions);
03561    AST_LIST_TRAVERSE(&sessions, session, list) {
03562       ast_mutex_lock(&session->__lock);
03563       if (session->managerid == ident && !session->needdestroy) {
03564          ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
03565          break;
03566       }
03567       ast_mutex_unlock(&session->__lock);
03568    }
03569    AST_LIST_UNLOCK(&sessions);
03570 
03571    return session;
03572 }

static struct ast_str* generic_http_callback ( enum output_format  format,
struct sockaddr_in *  remote_address,
const char *  uri,
enum ast_http_method  method,
struct ast_variable *  params,
int *  status,
char **  title,
int *  contentlength 
) [static, read]

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

References mansession_session::__lock, ast_atomic_fetchadd_int(), ast_calloc, ast_debug, ast_http_error(), ast_inet_ntoa(), AST_LIST_HEAD_INIT_NOLOCK, AST_LIST_INSERT_HEAD, AST_LIST_LOCK, AST_LIST_UNLOCK, ast_log(), AST_MAX_MANHEADERS, ast_mutex_init(), ast_mutex_lock(), ast_mutex_unlock(), AST_PTHREADT_NULL, ast_random(), ast_str_append(), ast_str_create(), ast_verb, mansession_session::authenticated, buf, contenttype, destroy_session(), mansession::f, mansession::fd, mansession_session::fd, find_session(), FORMAT_HTML, FORMAT_XML, grab_last(), message::hdrcount, message::headers, mansession_session::inuse, LOG_EVENT, LOG_WARNING, manager_displayconnects(), mansession_session::managerid, ast_variable::name, mansession_session::needdestroy, ast_variable::next, process_message(), ROW_FMT, s, mansession_session::send_events, mansession::session, 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().

03861 {
03862    struct mansession s = {.session = NULL, };
03863    struct mansession_session *session = NULL;
03864    uint32_t ident = 0;
03865    int blastaway = 0;
03866    struct ast_variable *v;
03867    char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
03868    struct ast_str *out = NULL;
03869    struct message m = { 0 };
03870    unsigned int x;
03871    size_t hdrlen;
03872 
03873    for (v = params; v; v = v->next) {
03874       if (!strcasecmp(v->name, "mansession_id")) {
03875          sscanf(v->value, "%30x", &ident);
03876          break;
03877       }
03878    }
03879 
03880    if (!(session = find_session(ident, 1))) {
03881       /* Create new session.
03882        * While it is not in the list we don't need any locking
03883        */
03884       if (!(session = ast_calloc(1, sizeof(*session)))) {
03885          *status = 500;
03886          goto generic_callback_out;
03887       }
03888       session->sin = *remote_address;
03889       session->fd = -1;
03890       session->waiting_thread = AST_PTHREADT_NULL;
03891       session->send_events = 0;
03892       ast_mutex_init(&session->__lock);
03893       ast_mutex_lock(&session->__lock);
03894       session->inuse = 1;
03895       /*!\note There is approximately a 1 in 1.8E19 chance that the following
03896        * calculation will produce 0, which is an invalid ID, but due to the
03897        * properties of the rand() function (and the constantcy of s), that
03898        * won't happen twice in a row.
03899        */
03900       while ((session->managerid = ast_random() ^ (unsigned long) session) == 0);
03901       session->last_ev = grab_last();
03902       AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
03903       AST_LIST_LOCK(&sessions);
03904       AST_LIST_INSERT_HEAD(&sessions, session, list);
03905       ast_atomic_fetchadd_int(&num_sessions, 1);
03906       AST_LIST_UNLOCK(&sessions);
03907    }
03908 
03909    s.session = session;
03910 
03911    ast_mutex_unlock(&session->__lock);
03912 
03913    if (!(out = ast_str_create(1024))) {
03914       *status = 500;
03915       goto generic_callback_out;
03916    }
03917 
03918    s.fd = mkstemp(template);  /* create a temporary file for command output */
03919    unlink(template);
03920    s.f = fdopen(s.fd, "w+");
03921 
03922    for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
03923       hdrlen = strlen(v->name) + strlen(v->value) + 3;
03924       m.headers[m.hdrcount] = alloca(hdrlen);
03925       snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
03926       ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
03927       m.hdrcount = x + 1;
03928    }
03929 
03930    if (process_message(&s, &m)) {
03931       if (session->authenticated) {
03932          if (manager_displayconnects(session)) {
03933             ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
03934          }
03935          ast_log(LOG_EVENT, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
03936       } else {
03937          if (displayconnects) {
03938             ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
03939          }
03940          ast_log(LOG_EVENT, "HTTP Failed attempt from %s\n", ast_inet_ntoa(session->sin.sin_addr));
03941       }
03942       session->needdestroy = 1;
03943    }
03944 
03945    ast_str_append(&out, 0,
03946              "Content-type: text/%s\r\n"
03947              "Cache-Control: no-cache;\r\n"
03948              "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
03949              "Pragma: SuppressEvents\r\n"
03950              "\r\n",
03951          contenttype[format],
03952          session->managerid, httptimeout);
03953 
03954    if (format == FORMAT_XML) {
03955       ast_str_append(&out, 0, "<ajax-response>\n");
03956    } else if (format == FORMAT_HTML) {
03957       /*
03958        * When handling AMI-over-HTTP in HTML format, we provide a simple form for
03959        * debugging purposes. This HTML code should not be here, we
03960        * should read from some config file...
03961        */
03962 
03963 #define ROW_FMT   "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
03964 #define TEST_STRING \
03965    "<form action=\"manager\">\n\
03966    Action: <select name=\"action\">\n\
03967       <option value=\"\">-----&gt;</option>\n\
03968       <option value=\"login\">login</option>\n\
03969       <option value=\"command\">Command</option>\n\
03970       <option value=\"waitevent\">waitevent</option>\n\
03971       <option value=\"listcommands\">listcommands</option>\n\
03972    </select>\n\
03973    or <input name=\"action\"><br/>\n\
03974    CLI Command <input name=\"command\"><br>\n\
03975    user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
03976    <input type=\"submit\">\n</form>\n"
03977 
03978       ast_str_append(&out, 0, "<title>Asterisk&trade; Manager Interface</title>");
03979       ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
03980       ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
03981       ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
03982    }
03983 
03984    if (s.f != NULL) {   /* have temporary output */
03985       char *buf;
03986       size_t l;
03987 
03988       if ((l = ftell(s.f))) {
03989          if (MAP_FAILED == (buf = mmap(NULL, l + 1, PROT_READ | PROT_WRITE, MAP_PRIVATE, s.fd, 0))) {
03990             ast_log(LOG_WARNING, "mmap failed.  Manager output was not processed\n");
03991          } else {
03992             buf[l] = '\0';
03993             if (format == FORMAT_XML || format == FORMAT_HTML) {
03994                xml_translate(&out, buf, params, format);
03995             } else {
03996                ast_str_append(&out, 0, "%s", buf);
03997             }
03998             munmap(buf, l + 1);
03999          }
04000       } else if (format == FORMAT_XML || format == FORMAT_HTML) {
04001          xml_translate(&out, "", params, format);
04002       }
04003       fclose(s.f);
04004       s.f = NULL;
04005       s.fd = -1;
04006    }
04007 
04008    if (format == FORMAT_XML) {
04009       ast_str_append(&out, 0, "</ajax-response>\n");
04010    } else if (format == FORMAT_HTML)
04011       ast_str_append(&out, 0, "</table></body>\r\n");
04012 
04013    ast_mutex_lock(&session->__lock);
04014    /* Reset HTTP timeout.  If we're not authenticated, keep it extremely short */
04015    session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
04016 
04017    if (session->needdestroy) {
04018       if (session->inuse == 1) {
04019          ast_debug(1, "Need destroy, doing it now!\n");
04020          blastaway = 1;
04021       } else {
04022          ast_debug(1, "Need destroy, but can't do it yet!\n");
04023          if (session->waiting_thread != AST_PTHREADT_NULL)
04024             pthread_kill(session->waiting_thread, SIGURG);
04025          session->inuse--;
04026       }
04027    } else
04028       session->inuse--;
04029    ast_mutex_unlock(&session->__lock);
04030 
04031    if (blastaway)
04032       destroy_session(session);
04033 generic_callback_out:
04034    if (*status != 200)
04035       return ast_http_error(500, "Server Error", NULL, "Internal Server Error (out of memory)\n");
04036    return out;
04037 }

int init_manager ( void   ) 

Called by Asterisk initialization.

Definition at line 4437 of file manager.c.

References __init_manager().

Referenced by main().

04438 {
04439    return __init_manager(0);
04440 }

static struct ast_str* 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 *  params,
struct ast_variable *  headers,
int *  status,
char **  title,
int *  contentlength 
) [static, read]

Definition at line 4039 of file manager.c.

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

04040 {
04041    return generic_http_callback(FORMAT_HTML, &ser->remote_address, uri, method, params, status, title, contentlength);
04042 }

static struct ast_str* 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 *  params,
struct ast_variable *  headers,
int *  status,
char **  title,
int *  contentlength 
) [static, read]

Definition at line 4044 of file manager.c.

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

04045 {
04046    return generic_http_callback(FORMAT_XML, &ser->remote_address, uri, method, params, status, title, contentlength);
04047 }

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

References purge_events(), and purge_sessions().

04088 {
04089    purge_sessions(1);
04090    purge_events();
04091 }

static struct ast_str* 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 *  params,
struct ast_variable *  headers,
int *  status,
char **  title,
int *  contentlength 
) [static, read]

Definition at line 4049 of file manager.c.

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

04050 {
04051    return generic_http_callback(FORMAT_RAW, &ser->remote_address, uri, method, params, status, title, contentlength);
04052 }

int reload_manager ( void   ) 

Called by Asterisk module functions and the CLI command.

Definition at line 4442 of file manager.c.

References __init_manager().

Referenced by handle_manager_reload().

04443 {
04444    return __init_manager(1);
04445 }

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

Definition at line 3718 of file manager.c.

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

Referenced by xml_translate().

03719 {
03720    /* Due to the simplicity of struct variable_count, it makes no difference
03721     * if you pass in objects or strings, the same operation applies. This is
03722     * due to the fact that the hash occurs on the first element, which means
03723     * the address of both the struct and the string are exactly the same. */
03724    struct variable_count *vc = obj;
03725    char *str = vstr;
03726    return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
03727 }

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

Definition at line 3706 of file manager.c.

References compress_char(), and variable_count::varname.

Referenced by xml_translate().

03707 {
03708    const struct variable_count *vc = vvc;
03709    int res = 0, i;
03710    for (i = 0; i < 5; i++) {
03711       if (vc->varname[i] == '\0')
03712          break;
03713       res += compress_char(vc->varname[i]) << (i * 6);
03714    }
03715    return res;
03716 }

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

Definition at line 3632 of file manager.c.

References ast_str_append(), and buf.

Referenced by xml_translate().

03633 {
03634    /* store in a local buffer to avoid calling ast_str_append too often */
03635    char buf[256];
03636    char *dst = buf;
03637    int space = sizeof(buf);
03638    /* repeat until done and nothing to flush */
03639    for ( ; *src || dst != buf ; src++) {
03640       if (*src == '\0' || space < 10) {   /* flush */
03641          *dst++ = '\0';
03642          ast_str_append(out, 0, "%s", buf);
03643          dst = buf;
03644          space = sizeof(buf);
03645          if (*src == '\0')
03646             break;
03647       }
03648          
03649       if ( (mode & 2) && !isalnum(*src)) {
03650          *dst++ = '_';
03651          space--;
03652          continue;
03653       }
03654       switch (*src) {
03655       case '<':
03656          strcpy(dst, "&lt;");
03657          dst += 4;
03658          space -= 4;
03659          break;
03660       case '>':
03661          strcpy(dst, "&gt;");
03662          dst += 4;
03663          space -= 4;
03664          break;
03665       case '\"':
03666          strcpy(dst, "&quot;");
03667          dst += 6;
03668          space -= 6;
03669          break;
03670       case '\'':
03671          strcpy(dst, "&apos;");
03672          dst += 6;
03673          space -= 6;
03674          break;
03675       case '&':
03676          strcpy(dst, "&amp;");
03677          dst += 5;
03678          space -= 5;
03679          break;
03680 
03681       default:
03682          *dst++ = mode ? tolower(*src) : *src;
03683          space--;
03684       }
03685    }
03686 }

static void xml_translate ( struct ast_str **  out,
char *  in,
struct ast_variable *  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 3757 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 generic_http_callback().

03758 {
03759    struct ast_variable *v;
03760    const char *dest = NULL;
03761    char *var, *val;
03762    const char *objtype = NULL;
03763    int in_data = 0;  /* parsing data */
03764    int inobj = 0;
03765    int xml = (format == FORMAT_XML);
03766    struct variable_count *vc = NULL;
03767    struct ao2_container *vco = NULL;
03768 
03769    for (v = vars; v; v = v->next) {
03770       if (!dest && !strcasecmp(v->name, "ajaxdest"))
03771          dest = v->value;
03772       else if (!objtype && !strcasecmp(v->name, "ajaxobjtype"))
03773          objtype = v->value;
03774    }
03775    if (!dest)
03776       dest = "unknown";
03777    if (!objtype)
03778       objtype = "generic";
03779 
03780    /* we want to stop when we find an empty line */
03781    while (in && *in) {
03782       val = strsep(&in, "\r\n"); /* mark start and end of line */
03783       if (in && *in == '\n')     /* remove trailing \n if any */
03784          in++;
03785       ast_trim_blanks(val);
03786       ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
03787       if (ast_strlen_zero(val)) {
03788          if (in_data) { /* close data */
03789             ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
03790             in_data = 0;
03791          }
03792          if (inobj) {
03793             ast_str_append(out, 0, xml ? " /></response>\n" :
03794                "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
03795             inobj = 0;
03796             ao2_ref(vco, -1);
03797             vco = NULL;
03798          }
03799          continue;
03800       }
03801 
03802       /* we expect Name: value lines */
03803       if (in_data) {
03804          var = NULL;
03805       } else {
03806          var = strsep(&val, ":");
03807          if (val) {  /* found the field name */
03808             val = ast_skip_blanks(val);
03809             ast_trim_blanks(var);
03810          } else {    /* field name not found, move to opaque mode */
03811             val = var;
03812             var = "Opaque-data";
03813          }
03814       }
03815 
03816       if (!inobj) {
03817          if (xml)
03818             ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
03819          else
03820             ast_str_append(out, 0, "<body>\n");
03821          vco = ao2_container_alloc(37, variable_count_hash_fn, variable_count_cmp_fn);
03822          inobj = 1;
03823       }
03824 
03825       if (!in_data) {   /* build appropriate line start */
03826          ast_str_append(out, 0, xml ? " " : "<tr><td>");
03827          if ((vc = ao2_find(vco, var, 0)))
03828             vc->count++;
03829          else {
03830             /* Create a new entry for this one */
03831             vc = ao2_alloc(sizeof(*vc), NULL);
03832             vc->varname = var;
03833             vc->count = 1;
03834             ao2_link(vco, vc);
03835          }
03836          xml_copy_escape(out, var, xml ? 1 | 2 : 0);
03837          if (vc->count > 1)
03838             ast_str_append(out, 0, "-%d", vc->count);
03839          ao2_ref(vc, -1);
03840          ast_str_append(out, 0, xml ? "='" : "</td><td>");
03841          if (!strcmp(var, "Opaque-data"))
03842             in_data = 1;
03843       }
03844       xml_copy_escape(out, val, 0); /* data field */
03845       if (!in_data)
03846          ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
03847       else
03848          ast_str_append(out, 0, xml ? "\n" : "<br>\n");
03849    }
03850    if (inobj) {
03851       ast_str_append(out, 0, xml ? " /></response>\n" :
03852          "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
03853       ao2_ref(vco, -1);
03854    }
03855 }


Variable Documentation

Definition at line 4094 of file manager.c.

Referenced by __init_manager().

Definition at line 4093 of file manager.c.

Referenced by __init_manager().

Definition at line 4105 of file manager.c.

Referenced by __init_manager().

char* contenttype[] [static]

Initial value:

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

Definition at line 3542 of file manager.c.

Referenced by generic_http_callback().

Definition at line 4063 of file manager.c.

Referenced by __init_manager().

Definition at line 4072 of file manager.c.

Referenced by __init_manager().

Definition at line 4054 of file manager.c.

Referenced by __init_manager().

int registered = 0 [static]

Definition at line 4081 of file manager.c.

Referenced by __init_manager().

int webregged = 0 [static]

Definition at line 4082 of file manager.c.

Referenced by __init_manager().

char* words[AST_MAX_CMD_LEN]

Definition at line 155 of file manager.c.

Referenced by check_blacklist().


Generated on Wed Mar 2 18:57:34 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9