2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief The Asterisk Management Interface - AMI
23 * \author Mark Spencer <markster@digium.com>
25 * \extref OpenSSL http://www.openssl.org - for AMI/SSL
27 * At the moment this file contains a number of functions, namely:
29 * - data structures storing AMI state
30 * - AMI-related API functions, used by internal asterisk components
31 * - handlers for AMI-related CLI functions
32 * - handlers for AMI functions (available through the AMI socket)
33 * - the code for the main AMI listener thread and individual session threads
34 * - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
39 /*! \addtogroup Group_AMI AMI functions
46 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48 #include "asterisk/_private.h"
49 #include "asterisk/paths.h" /* use various ast_config_AST_* */
55 #include "asterisk/channel.h"
56 #include "asterisk/file.h"
57 #include "asterisk/manager.h"
58 #include "asterisk/module.h"
59 #include "asterisk/config.h"
60 #include "asterisk/callerid.h"
61 #include "asterisk/lock.h"
62 #include "asterisk/cli.h"
63 #include "asterisk/app.h"
64 #include "asterisk/pbx.h"
65 #include "asterisk/md5.h"
66 #include "asterisk/acl.h"
67 #include "asterisk/utils.h"
68 #include "asterisk/tcptls.h"
69 #include "asterisk/http.h"
70 #include "asterisk/ast_version.h"
71 #include "asterisk/threadstorage.h"
72 #include "asterisk/linkedlists.h"
73 #include "asterisk/term.h"
74 #include "asterisk/astobj2.h"
75 #include "asterisk/features.h"
76 #include "asterisk/security_events.h"
79 <manager name="Ping" language="en_US">
84 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
87 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
88 manager connection open.</para>
91 <manager name="Events" language="en_US">
96 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
97 <parameter name="EventMask" required="true">
100 <para>If all events should be sent.</para>
103 <para>If no events should be sent.</para>
105 <enum name="system,call,log,...">
106 <para>To select which flags events should have to be sent.</para>
112 <para>Enable/Disable sending of events to this manager client.</para>
115 <manager name="Logoff" language="en_US">
120 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
123 <para>Logoff the current manager session.</para>
126 <manager name="Login" language="en_US">
131 <parameter name="ActionID">
132 <para>ActionID for this transaction. Will be returned.</para>
136 <para>Login Manager.</para>
139 <manager name="Challenge" language="en_US">
141 Generate Challenge for MD5 Auth.
144 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
147 <para>Generate a challenge for MD5 authentication.</para>
150 <manager name="Hangup" language="en_US">
155 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
156 <parameter name="Channel" required="true">
157 <para>The channel name to be hangup.</para>
159 <parameter name="Cause">
160 <para>Numeric hangup cause.</para>
164 <para>Hangup a channel.</para>
167 <manager name="Status" language="en_US">
172 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
173 <parameter name="Channel" required="true">
174 <para>The name of the channel to query for status.</para>
176 <parameter name="Variables">
177 <para>Comma <literal>,</literal> separated list of variable to include.</para>
181 <para>Will return the status information of each channel along with the
182 value for the specified channel variables.</para>
185 <manager name="Setvar" language="en_US">
187 Set a channel variable.
190 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
191 <parameter name="Channel">
192 <para>Channel to set variable for.</para>
194 <parameter name="Variable" required="true">
195 <para>Variable name.</para>
197 <parameter name="Value" required="true">
198 <para>Variable value.</para>
202 <para>Set a global or local channel variable.</para>
205 <manager name="Getvar" language="en_US">
207 Gets a channel variable.
210 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
211 <parameter name="Channel">
212 <para>Channel to read variable from.</para>
214 <parameter name="Variable" required="true">
215 <para>Variable name.</para>
219 <para>Get the value of a global or local channel variable.</para>
222 <manager name="GetConfig" language="en_US">
224 Retrieve configuration.
227 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
228 <parameter name="Filename" required="true">
229 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
231 <parameter name="Category">
232 <para>Category in configuration file.</para>
236 <para>This action will dump the contents of a configuration
237 file by category and contents or optionally by specified category only.</para>
240 <manager name="GetConfigJSON" language="en_US">
242 Retrieve configuration (JSON format).
245 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
246 <parameter name="Filename" required="true">
247 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
251 <para>This action will dump the contents of a configuration file by category
252 and contents in JSON format. This only makes sense to be used using rawman over
253 the HTTP interface.</para>
256 <manager name="UpdateConfig" language="en_US">
258 Update basic configuration.
261 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
262 <parameter name="SrcFilename" required="true">
263 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
265 <parameter name="DstFilename" required="true">
266 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
268 <parameter name="Reload">
269 <para>Whether or not a reload should take place (or name of specific module).</para>
271 <parameter name="Action-XXXXXX">
272 <para>Action to take.</para>
273 <para>X's represent 6 digit number beginning with 000000.</para>
275 <enum name="NewCat" />
276 <enum name="RenameCat" />
277 <enum name="DelCat" />
278 <enum name="EmptyCat" />
279 <enum name="Update" />
280 <enum name="Delete" />
281 <enum name="Append" />
282 <enum name="Insert" />
285 <parameter name="Cat-XXXXXX">
286 <para>Category to operate on.</para>
287 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
289 <parameter name="Var-XXXXXX">
290 <para>Variable to work on.</para>
291 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
293 <parameter name="Value-XXXXXX">
294 <para>Value to work on.</para>
295 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
297 <parameter name="Match-XXXXXX">
298 <para>Extra match required to match line.</para>
299 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
301 <parameter name="Line-XXXXXX">
302 <para>Line in category to operate on (used with delete and insert actions).</para>
303 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
307 <para>This action will modify, create, or delete configuration elements
308 in Asterisk configuration files.</para>
311 <manager name="CreateConfig" language="en_US">
313 Creates an empty file in the configuration directory.
316 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
317 <parameter name="Filename" required="true">
318 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
322 <para>This action will create an empty file in the configuration
323 directory. This action is intended to be used before an UpdateConfig
327 <manager name="ListCategories" language="en_US">
329 List categories in configuration file.
332 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
333 <parameter name="Filename" required="true">
334 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
338 <para>This action will dump the categories in a given file.</para>
341 <manager name="Redirect" language="en_US">
343 Redirect (transfer) a call.
346 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
347 <parameter name="Channel" required="true">
348 <para>Channel to redirect.</para>
350 <parameter name="ExtraChannel">
351 <para>Second call leg to transfer (optional).</para>
353 <parameter name="Exten" required="true">
354 <para>Extension to transfer to.</para>
356 <parameter name="Context" required="true">
357 <para>Context to transfer to.</para>
359 <parameter name="Priority" required="true">
360 <para>Priority to transfer to.</para>
364 <para>Redirect (transfer) a call.</para>
367 <manager name="Atxfer" language="en_US">
372 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
373 <parameter name="Channel" required="true">
374 <para>Transferer's channel.</para>
376 <parameter name="Exten" required="true">
377 <para>Extension to transfer to.</para>
379 <parameter name="Context" required="true">
380 <para>Context to transfer to.</para>
382 <parameter name="Priority" required="true">
383 <para>Priority to transfer to.</para>
387 <para>Attended transfer.</para>
390 <manager name="Originate" language="en_US">
395 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
396 <parameter name="Channel" required="true">
397 <para>Channel name to call.</para>
399 <parameter name="Exten">
400 <para>Extension to use (requires <literal>Context</literal> and
401 <literal>Priority</literal>)</para>
403 <parameter name="Context">
404 <para>Context to use (requires <literal>Exten</literal> and
405 <literal>Priority</literal>)</para>
407 <parameter name="Priority">
408 <para>Priority to use (requires <literal>Exten</literal> and
409 <literal>Context</literal>)</para>
411 <parameter name="Application">
412 <para>Application to execute.</para>
414 <parameter name="Data">
415 <para>Data to use (requires <literal>Application</literal>).</para>
417 <parameter name="Timeout" default="30000">
418 <para>How long to wait for call to be answered (in ms.).</para>
420 <parameter name="CallerID">
421 <para>Caller ID to be set on the outgoing channel.</para>
423 <parameter name="Variable">
424 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
426 <parameter name="Account">
427 <para>Account code.</para>
429 <parameter name="Async">
430 <para>Set to <literal>true</literal> for fast origination.</para>
434 <para>Generates an outgoing call to a
435 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
436 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
439 <manager name="Command" language="en_US">
441 Execute Asterisk CLI Command.
444 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
445 <parameter name="Command" required="true">
446 <para>Asterisk CLI command to run.</para>
450 <para>Run a CLI command.</para>
453 <manager name="ExtensionState" language="en_US">
455 Check Extension Status.
458 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
459 <parameter name="Exten" required="true">
460 <para>Extension to check state on.</para>
462 <parameter name="Context" required="true">
463 <para>Context for extension.</para>
467 <para>Report the extension state for given extension. If the extension has a hint,
468 will use devicestate to check the status of the device connected to the extension.</para>
469 <para>Will return an <literal>Extension Status</literal> message. The response will include
470 the hint for the extension and the status.</para>
473 <manager name="AbsoluteTimeout" language="en_US">
475 Set absolute timeout.
478 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
479 <parameter name="Channel" required="true">
480 <para>Channel name to hangup.</para>
482 <parameter name="Timeout" required="true">
483 <para>Maximum duration of the call (sec).</para>
487 <para>Hangup a channel after a certain time. Acknowledges set time with
488 <literal>Timeout Set</literal> message.</para>
491 <manager name="MailboxStatus" language="en_US">
496 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
497 <parameter name="Mailbox" required="true">
498 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
502 <para>Checks a voicemail account for status.</para>
503 <para>Returns number of messages.</para>
504 <para>Message: Mailbox Status.</para>
505 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
506 <para>Waiting: <replaceable>count</replaceable>.</para>
509 <manager name="MailboxCount" language="en_US">
511 Check Mailbox Message Count.
514 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
515 <parameter name="Mailbox" required="true">
516 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
520 <para>Checks a voicemail account for new messages.</para>
521 <para>Returns number of urgent, new and old messages.</para>
522 <para>Message: Mailbox Message Count</para>
523 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
524 <para>UrgentMessages: <replaceable>count</replaceable></para>
525 <para>NewMessages: <replaceable>count</replaceable></para>
526 <para>OldMessages: <replaceable>count</replaceable></para>
529 <manager name="ListCommands" language="en_US">
531 List available manager commands.
534 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
537 <para>Returns the action name and synopsis for every action that
538 is available to the user.</para>
541 <manager name="SendText" language="en_US">
543 Send text message to channel.
546 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
547 <parameter name="Channel" required="true">
548 <para>Channel to send message to.</para>
550 <parameter name="Message" required="true">
551 <para>Message to send.</para>
555 <para>Sends A Text Message to a channel while in a call.</para>
558 <manager name="UserEvent" language="en_US">
560 Send an arbitrary event.
563 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
564 <parameter name="UserEvent" required="true">
565 <para>Event string to send.</para>
567 <parameter name="Header1">
568 <para>Content1.</para>
570 <parameter name="HeaderN">
571 <para>ContentN.</para>
575 <para>Send an event to manager sessions.</para>
578 <manager name="WaitEvent" language="en_US">
580 Wait for an event to occur.
583 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
584 <parameter name="Timeout" required="true">
585 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
589 <para>This action will ellicit a <literal>Success</literal> response. Whenever
590 a manager event is queued. Once WaitEvent has been called on an HTTP manager
591 session, events will be generated and queued.</para>
594 <manager name="CoreSettings" language="en_US">
596 Show PBX core settings (version etc).
599 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
602 <para>Query for Core PBX settings.</para>
605 <manager name="CoreStatus" language="en_US">
607 Show PBX core status variables.
610 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
613 <para>Query for Core PBX status.</para>
616 <manager name="Reload" language="en_US">
621 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
622 <parameter name="Module">
623 <para>Name of the module to reload.</para>
627 <para>Send a reload event.</para>
630 <manager name="CoreShowChannels" language="en_US">
632 List currently active channels.
635 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
638 <para>List currently defined channels and some information about them.</para>
641 <manager name="ModuleLoad" language="en_US">
646 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
647 <parameter name="Module">
648 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
652 <enum name="dnsmgr" />
653 <enum name="extconfig" />
654 <enum name="manager" />
659 <parameter name="LoadType" required="true">
660 <para>The operation to be done on module.</para>
663 <enum name="unload" />
664 <enum name="reload" />
666 <para>If no module is specified for a <literal>reload</literal> loadtype,
667 all modules are reloaded.</para>
671 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
674 <manager name="ModuleCheck" language="en_US">
676 Check if module is loaded.
679 <parameter name="Module" required="true">
680 <para>Asterisk module name (not including extension).</para>
684 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
685 For success returns, the module revision number is included.</para>
693 UNSPECIFIED_CATEGORY,
694 UNSPECIFIED_ARGUMENT,
706 * Linked list of events.
707 * Global events are appended to the list by append_event().
708 * The usecount is the number of stored pointers to the element,
709 * excluding the list pointers. So an element that is only in
710 * the list has a usecount of 0, not 1.
712 * Clients have a pointer to the last event processed, and for each
713 * of these clients we track the usecount of the elements.
714 * If we have a pointer to an entry in the list, it is safe to navigate
715 * it forward because elements will not be deleted, but only appended.
716 * The worst that can happen is seeing the pointer still NULL.
718 * When the usecount of an element drops to 0, and the element is the
719 * first in the list, we can remove it. Removal is done within the
720 * main thread, which is woken up for the purpose.
722 * For simplicity of implementation, we make sure the list is never empty.
725 int usecount; /*!< # of clients who still need the event */
727 unsigned int seq; /*!< sequence number */
728 AST_LIST_ENTRY(eventqent) eq_next;
729 char eventdata[1]; /*!< really variable size, allocated by append_event() */
732 static AST_LIST_HEAD_STATIC(all_events, eventqent);
734 static int displayconnects = 1;
735 static int allowmultiplelogin = 1;
736 static int timestampevents;
737 static int httptimeout = 60;
738 static int manager_enabled = 0;
739 static int webmanager_enabled = 0;
741 #define DEFAULT_REALM "asterisk"
742 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
744 static int block_sockets;
746 static int manager_debug; /*!< enable some debugging code in the manager */
749 * Descriptor for a manager session, either on the AMI socket or over HTTP.
752 * AMI session have managerid == 0; the entry is created upon a connect,
753 * and destroyed with the socket.
754 * HTTP sessions have managerid != 0, the value is used as a search key
755 * to lookup sessions (using the mansession_id cookie, or nonce key from
756 * Digest Authentication http header).
758 #define MAX_BLACKLIST_CMD_LEN 2
759 static const struct {
760 const char *words[AST_MAX_CMD_LEN];
761 } command_blacklist[] = {
762 {{ "module", "load", NULL }},
763 {{ "module", "unload", NULL }},
764 {{ "restart", "gracefully", NULL }},
767 /* In order to understand what the heck is going on with the
768 * mansession_session and mansession structs, we need to have a bit of a history
771 * In the beginning, there was the mansession. The mansession contained data that was
772 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
773 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
774 * sessions, these were used to represent the TCP socket over which the AMI session was taking
775 * place. It makes perfect sense for these fields to be a part of the session-specific data since
776 * the session actually defines this information.
778 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
779 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
780 * but rather to the action that is being executed. Because a single session may execute many commands
781 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
782 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
783 * has had a chance to properly close its handles.
785 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
786 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
787 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
788 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
789 * part of the action instead.
791 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
792 * contain the action-specific information, such as which file to write to. In order to maintain expectations
793 * of action handlers and not have to change the public API of the manager code, we would need to name this
794 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
795 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
796 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
799 struct mansession_session {
800 pthread_t ms_t; /*!< Execution thread, basically useless */
801 /* XXX need to document which fields it is protecting */
802 struct sockaddr_in sin; /*!< address we are connecting from */
803 FILE *f; /*!< fdopen() on the underlying fd */
804 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
805 int inuse; /*!< number of HTTP sessions using this entry */
806 int needdestroy; /*!< Whether an HTTP session should be destroyed */
807 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
808 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
809 time_t sessionstart; /*!< Session start time */
810 struct timeval sessionstart_tv; /*!< Session start time */
811 time_t sessiontimeout; /*!< Session timeout if HTTP */
812 char username[80]; /*!< Logged in username */
813 char challenge[10]; /*!< Authentication challenge */
814 int authenticated; /*!< Authentication status */
815 int readperm; /*!< Authorization for reading */
816 int writeperm; /*!< Authorization for writing */
817 char inbuf[1025]; /*!< Buffer */
818 /* we use the extra byte to add a '\0' and simplify parsing */
819 int inlen; /*!< number of buffered bytes */
820 int send_events; /*!< XXX what ? */
821 struct eventqent *last_ev; /*!< last event processed. */
822 int writetimeout; /*!< Timeout for ast_carefulwrite() */
823 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
824 time_t noncetime; /*!< Timer for nonce value expiration */
825 unsigned long oldnonce; /*!< Stale nonce value */
826 unsigned long nc; /*!< incremental nonce counter */
827 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
828 AST_LIST_ENTRY(mansession_session) list;
831 /* In case you didn't read that giant block of text above the mansession_session struct, the
832 * 'mansession' struct is named this solely to keep the API the same in Asterisk. This structure really
833 * represents data that is different from Manager action to Manager action. The mansession_session pointer
834 * contained within points to session-specific data.
837 struct mansession_session *session;
838 struct ast_tcptls_session_instance *tcptls_session;
844 static struct ao2_container *sessions = NULL;
846 #define NEW_EVENT(m) (AST_LIST_NEXT(m->session->last_ev, eq_next))
848 /*! \brief user descriptor, as read from the config file.
850 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
851 * lines which are not supported here, and readperm/writeperm/writetimeout
854 struct ast_manager_user {
857 struct ast_ha *ha; /*!< ACL setting */
858 int readperm; /*! Authorization for reading */
859 int writeperm; /*! Authorization for writing */
860 int writetimeout; /*! Per user Timeout for ast_carefulwrite() */
861 int displayconnects; /*!< XXX unused */
862 int keep; /*!< mark entries created on a reload */
863 char *a1_hash; /*!< precalculated A1 for Digest auth */
864 AST_RWLIST_ENTRY(ast_manager_user) list;
867 /*! \brief list of users found in the config file */
868 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
870 /*! \brief list of actions registered */
871 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
873 /*! \brief list of hooks registered */
874 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
876 static struct eventqent *unref_event(struct eventqent *e);
877 static void ref_event(struct eventqent *e);
879 /*! \brief Add a custom hook to be called when an event is fired */
880 void ast_manager_register_hook(struct manager_custom_hook *hook)
882 AST_RWLIST_WRLOCK(&manager_hooks);
883 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
884 AST_RWLIST_UNLOCK(&manager_hooks);
887 /*! \brief Delete a custom hook to be called when an event is fired */
888 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
890 AST_RWLIST_WRLOCK(&manager_hooks);
891 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
892 AST_RWLIST_UNLOCK(&manager_hooks);
895 int check_manager_enabled()
897 return manager_enabled;
900 int check_webmanager_enabled()
902 return (webmanager_enabled && manager_enabled);
906 * Grab a reference to the last event, update usecount as needed.
907 * Can handle a NULL pointer.
909 static struct eventqent *grab_last(void)
911 struct eventqent *ret;
913 AST_LIST_LOCK(&all_events);
914 ret = AST_LIST_LAST(&all_events);
915 /* the list is never empty now, but may become so when
916 * we optimize it in the future, so be prepared.
919 ast_atomic_fetchadd_int(&ret->usecount, 1);
921 AST_LIST_UNLOCK(&all_events);
926 * Purge unused events. Remove elements from the head
927 * as long as their usecount is 0 and there is a next element.
929 static void purge_events(void)
931 struct eventqent *ev;
933 AST_LIST_LOCK(&all_events);
934 while ( (ev = AST_LIST_FIRST(&all_events)) &&
935 ev->usecount == 0 && AST_LIST_NEXT(ev, eq_next)) {
936 AST_LIST_REMOVE_HEAD(&all_events, eq_next);
939 AST_LIST_UNLOCK(&all_events);
943 * helper functions to convert back and forth between
944 * string and numeric representation of set of flags
946 static const struct permalias {
950 { EVENT_FLAG_SYSTEM, "system" },
951 { EVENT_FLAG_CALL, "call" },
952 { EVENT_FLAG_LOG, "log" },
953 { EVENT_FLAG_VERBOSE, "verbose" },
954 { EVENT_FLAG_COMMAND, "command" },
955 { EVENT_FLAG_AGENT, "agent" },
956 { EVENT_FLAG_USER, "user" },
957 { EVENT_FLAG_CONFIG, "config" },
958 { EVENT_FLAG_DTMF, "dtmf" },
959 { EVENT_FLAG_REPORTING, "reporting" },
960 { EVENT_FLAG_CDR, "cdr" },
961 { EVENT_FLAG_DIALPLAN, "dialplan" },
962 { EVENT_FLAG_ORIGINATE, "originate" },
963 { EVENT_FLAG_AGI, "agi" },
968 /*! \brief Convert authority code to a list of options */
969 static const char *authority_to_str(int authority, struct ast_str **res)
975 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
976 if (authority & perms[i].num) {
977 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
982 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
983 ast_str_append(res, 0, "<none>");
985 return ast_str_buffer(*res);
988 /*! Tells you if smallstr exists inside bigstr
989 which is delim by delim and uses no buf or stringsep
990 ast_instring("this|that|more","this",'|') == 1;
992 feel free to move this to app.c -anthm */
993 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
995 const char *val = bigstr, *next;
998 if ((next = strchr(val, delim))) {
999 if (!strncmp(val, smallstr, (next - val))) {
1005 return !strcmp(smallstr, val);
1007 } while (*(val = (next + 1)));
1012 static int get_perm(const char *instr)
1020 for (x = 0; x < ARRAY_LEN(perms); x++) {
1021 if (ast_instring(instr, perms[x].label, ',')) {
1022 ret |= perms[x].num;
1030 * A number returns itself, false returns 0, true returns all flags,
1031 * other strings return the flags that are set.
1033 static int strings_to_mask(const char *string)
1037 if (ast_strlen_zero(string)) {
1041 for (p = string; *p; p++) {
1042 if (*p < '0' || *p > '9') {
1046 if (!p) { /* all digits */
1047 return atoi(string);
1049 if (ast_false(string)) {
1052 if (ast_true(string)) { /* all permissions */
1054 for (x = 0; x < ARRAY_LEN(perms); x++) {
1055 ret |= perms[x].num;
1059 return get_perm(string);
1062 /*! \brief Unreference manager session object.
1063 If no more references, then go ahead and delete it */
1064 static struct mansession_session *unref_mansession(struct mansession_session *s)
1066 int refcount = ao2_ref(s, -1);
1067 if (manager_debug) {
1068 ast_log(LOG_DEBUG, "Mansession: %p refcount now %d\n", s, refcount - 1);
1073 static void session_destructor(void *obj)
1075 struct mansession_session *session = obj;
1076 struct eventqent *eqe = session->last_ev;
1077 struct ast_datastore *datastore;
1079 /* Get rid of each of the data stores on the session */
1080 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1081 /* Free the data store */
1082 ast_datastore_free(datastore);
1085 if (session->f != NULL) {
1091 /*! \brief Allocate manager session structure and add it to the list of sessions */
1092 static struct mansession_session *build_mansession(struct sockaddr_in sin)
1094 struct mansession_session *newsession;
1096 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1099 newsession->fd = -1;
1100 newsession->waiting_thread = AST_PTHREADT_NULL;
1101 newsession->writetimeout = 100;
1102 newsession->send_events = -1;
1103 newsession->sin = sin;
1105 ao2_link(sessions, newsession);
1110 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1112 struct mansession_session *s = obj;
1114 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1117 static void session_destroy(struct mansession_session *s)
1119 unref_mansession(s);
1120 ao2_unlink(sessions, s);
1124 static int check_manager_session_inuse(const char *name)
1126 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1131 unref_mansession(session);
1138 * lookup an entry in the list of registered users.
1139 * must be called with the list lock held.
1141 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1143 struct ast_manager_user *user = NULL;
1145 AST_RWLIST_TRAVERSE(&users, user, list)
1146 if (!strcasecmp(user->username, name)) {
1152 /*! \brief Get displayconnects config option.
1153 * \param session manager session to get parameter from.
1154 * \return displayconnects config option value.
1156 static int manager_displayconnects (struct mansession_session *session)
1158 struct ast_manager_user *user = NULL;
1161 AST_RWLIST_RDLOCK(&users);
1162 if ((user = get_manager_by_name_locked (session->username))) {
1163 ret = user->displayconnects;
1165 AST_RWLIST_UNLOCK(&users);
1170 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1172 struct manager_action *cur;
1173 struct ast_str *authority;
1177 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
1182 e->command = "manager show command";
1184 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1185 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1188 l = strlen(a->word);
1190 AST_RWLIST_RDLOCK(&actions);
1191 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1192 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1193 ret = ast_strdup(cur->action);
1194 break; /* make sure we exit even if ast_strdup() returns NULL */
1197 AST_RWLIST_UNLOCK(&actions);
1200 authority = ast_str_alloca(80);
1202 return CLI_SHOWUSAGE;
1206 /* setup the titles */
1207 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1208 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1209 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1210 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1211 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1214 AST_RWLIST_RDLOCK(&actions);
1215 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1216 for (num = 3; num < a->argc; num++) {
1217 if (!strcasecmp(cur->action, a->argv[num])) {
1219 if (cur->docsrc == AST_XML_DOC) {
1220 ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
1222 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1224 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1226 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1228 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1230 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1));
1233 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1234 cur->action, cur->synopsis,
1235 authority_to_str(cur->authority, &authority),
1236 S_OR(cur->description, ""));
1243 AST_RWLIST_UNLOCK(&actions);
1248 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1252 e->command = "manager set debug [on|off]";
1253 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1260 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1261 } else if (a->argc == 4) {
1262 if (!strcasecmp(a->argv[3], "on")) {
1264 } else if (!strcasecmp(a->argv[3], "off")) {
1267 return CLI_SHOWUSAGE;
1273 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1275 struct ast_manager_user *user = NULL;
1278 struct ast_str *rauthority = ast_str_alloca(128);
1279 struct ast_str *wauthority = ast_str_alloca(128);
1283 e->command = "manager show user";
1285 " Usage: manager show user <user>\n"
1286 " Display all information related to the manager user specified.\n";
1289 l = strlen(a->word);
1294 AST_RWLIST_RDLOCK(&users);
1295 AST_RWLIST_TRAVERSE(&users, user, list) {
1296 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1297 ret = ast_strdup(user->username);
1301 AST_RWLIST_UNLOCK(&users);
1306 return CLI_SHOWUSAGE;
1309 AST_RWLIST_RDLOCK(&users);
1311 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1312 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1313 AST_RWLIST_UNLOCK(&users);
1317 ast_cli(a->fd, "\n");
1324 "displayconnects: %s\n",
1325 (user->username ? user->username : "(N/A)"),
1326 (user->secret ? "<Set>" : "(N/A)"),
1327 (user->ha ? "yes" : "no"),
1328 authority_to_str(user->readperm, &rauthority),
1329 authority_to_str(user->writeperm, &wauthority),
1330 (user->displayconnects ? "yes" : "no"));
1332 AST_RWLIST_UNLOCK(&users);
1338 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1340 struct ast_manager_user *user = NULL;
1344 e->command = "manager show users";
1346 "Usage: manager show users\n"
1347 " Prints a listing of all managers that are currently configured on that\n"
1354 return CLI_SHOWUSAGE;
1357 AST_RWLIST_RDLOCK(&users);
1359 /* If there are no users, print out something along those lines */
1360 if (AST_RWLIST_EMPTY(&users)) {
1361 ast_cli(a->fd, "There are no manager users.\n");
1362 AST_RWLIST_UNLOCK(&users);
1366 ast_cli(a->fd, "\nusername\n--------\n");
1368 AST_RWLIST_TRAVERSE(&users, user, list) {
1369 ast_cli(a->fd, "%s\n", user->username);
1373 AST_RWLIST_UNLOCK(&users);
1375 ast_cli(a->fd,"-------------------\n"
1376 "%d manager users configured.\n", count_amu);
1381 /*! \brief CLI command manager list commands */
1382 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1384 struct manager_action *cur;
1385 struct ast_str *authority;
1386 #define HSMC_FORMAT " %-15.15s %-15.15s %-55.55s\n"
1389 e->command = "manager show commands";
1391 "Usage: manager show commands\n"
1392 " Prints a listing of all the available Asterisk manager interface commands.\n";
1397 authority = ast_str_alloca(80);
1398 ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
1399 ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
1401 AST_RWLIST_RDLOCK(&actions);
1402 AST_RWLIST_TRAVERSE(&actions, cur, list)
1403 ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
1404 AST_RWLIST_UNLOCK(&actions);
1409 /*! \brief CLI command manager list connected */
1410 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1412 struct mansession_session *session;
1413 time_t now = time(NULL);
1414 #define HSMCONN_FORMAT1 " %-15.15s %-15.15s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
1415 #define HSMCONN_FORMAT2 " %-15.15s %-15.15s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
1417 struct ao2_iterator i;
1421 e->command = "manager show connected";
1423 "Usage: manager show connected\n"
1424 " Prints a listing of the users that are currently connected to the\n"
1425 "Asterisk manager interface.\n";
1431 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1433 i = ao2_iterator_init(sessions, 0);
1434 while ((session = ao2_iterator_next(&i))) {
1436 ast_cli(a->fd, HSMCONN_FORMAT2, session->username, ast_inet_ntoa(session->sin.sin_addr), (int)(session->sessionstart), (int)(now - session->sessionstart), session->fd, session->inuse, session->readperm, session->writeperm);
1438 ao2_unlock(session);
1439 unref_mansession(session);
1442 ast_cli(a->fd, "%d users connected.\n", count);
1447 /*! \brief CLI command manager list eventq */
1448 /* Should change to "manager show connected" */
1449 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1451 struct eventqent *s;
1454 e->command = "manager show eventq";
1456 "Usage: manager show eventq\n"
1457 " Prints a listing of all events pending in the Asterisk manger\n"
1463 AST_LIST_LOCK(&all_events);
1464 AST_LIST_TRAVERSE(&all_events, s, eq_next) {
1465 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1466 ast_cli(a->fd, "Category: %d\n", s->category);
1467 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1469 AST_LIST_UNLOCK(&all_events);
1474 /*! \brief CLI command manager reload */
1475 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1479 e->command = "manager reload";
1481 "Usage: manager reload\n"
1482 " Reloads the manager configuration.\n";
1488 return CLI_SHOWUSAGE;
1495 static struct ast_cli_entry cli_manager[] = {
1496 AST_CLI_DEFINE(handle_showmancmd, "Show a manager interface command"),
1497 AST_CLI_DEFINE(handle_showmancmds, "List manager interface commands"),
1498 AST_CLI_DEFINE(handle_showmanconn, "List connected manager interface users"),
1499 AST_CLI_DEFINE(handle_showmaneventq, "List manager interface queued events"),
1500 AST_CLI_DEFINE(handle_showmanagers, "List configured manager users"),
1501 AST_CLI_DEFINE(handle_showmanager, "Display information on a specific manager user"),
1502 AST_CLI_DEFINE(handle_mandebug, "Show, enable, disable debugging of the manager code"),
1503 AST_CLI_DEFINE(handle_manager_reload, "Reload manager configurations"),
1506 static struct eventqent *unref_event(struct eventqent *e)
1508 ast_atomic_fetchadd_int(&e->usecount, -1);
1509 return AST_LIST_NEXT(e, eq_next);
1512 static void ref_event(struct eventqent *e)
1514 ast_atomic_fetchadd_int(&e->usecount, 1);
1518 * Generic function to return either the first or the last matching header
1519 * from a list of variables, possibly skipping empty strings.
1520 * At the moment there is only one use of this function in this file,
1521 * so we make it static.
1523 #define GET_HEADER_FIRST_MATCH 0
1524 #define GET_HEADER_LAST_MATCH 1
1525 #define GET_HEADER_SKIP_EMPTY 2
1526 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1528 int x, l = strlen(var);
1529 const char *result = "";
1531 for (x = 0; x < m->hdrcount; x++) {
1532 const char *h = m->headers[x];
1533 if (!strncasecmp(var, h, l) && h[l] == ':' && h[l+1] == ' ') {
1534 const char *value = h + l + 2;
1535 /* found a potential candidate */
1536 if (mode & GET_HEADER_SKIP_EMPTY && ast_strlen_zero(value))
1537 continue; /* not interesting */
1538 if (mode & GET_HEADER_LAST_MATCH)
1539 result = value; /* record the last match so far */
1549 * Return the first matching variable from an array.
1550 * This is the legacy function and is implemented in therms of
1551 * __astman_get_header().
1553 const char *astman_get_header(const struct message *m, char *var)
1555 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
1559 struct ast_variable *astman_get_variables(const struct message *m)
1562 struct ast_variable *head = NULL, *cur;
1564 AST_DECLARE_APP_ARGS(args,
1565 AST_APP_ARG(vars)[32];
1568 varlen = strlen("Variable: ");
1570 for (x = 0; x < m->hdrcount; x++) {
1571 char *parse, *var, *val;
1573 if (strncasecmp("Variable: ", m->headers[x], varlen)) {
1576 parse = ast_strdupa(m->headers[x] + varlen);
1578 AST_STANDARD_APP_ARGS(args, parse);
1582 for (y = 0; y < args.argc; y++) {
1583 if (!args.vars[y]) {
1586 var = val = ast_strdupa(args.vars[y]);
1588 if (!val || ast_strlen_zero(var)) {
1591 cur = ast_variable_new(var, val, "");
1601 * helper function to send a string to the socket.
1602 * Return -1 on error (e.g. buffer full).
1604 static int send_string(struct mansession *s, char *string)
1607 return ast_careful_fwrite(s->f, s->fd, string, strlen(string), s->session->writetimeout);
1609 return ast_careful_fwrite(s->session->f, s->session->fd, string, strlen(string), s->session->writetimeout);
1614 * \brief thread local buffer for astman_append
1616 * \note This can not be defined within the astman_append() function
1617 * because it declares a couple of functions that get used to
1618 * initialize the thread local storage key.
1620 AST_THREADSTORAGE(astman_append_buf);
1621 AST_THREADSTORAGE(userevent_buf);
1623 /*! \brief initial allocated size for the astman_append_buf */
1624 #define ASTMAN_APPEND_BUF_INITSIZE 256
1627 * utility functions for creating AMI replies
1629 void astman_append(struct mansession *s, const char *fmt, ...)
1632 struct ast_str *buf;
1634 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
1639 ast_str_set_va(&buf, 0, fmt, ap);
1642 if (s->f != NULL || s->session->f != NULL) {
1643 send_string(s, ast_str_buffer(buf));
1645 ast_verbose("fd == -1 in astman_append, should not happen\n");
1649 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
1650 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
1651 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
1652 be non-zero). In either of these cases, there is no need to lock-protect the session's
1653 fd, since no other output will be sent (events will be queued), and no input will
1654 be read until either the current action finishes or get_input() obtains the session
1658 /*! \brief send a response with an optional message,
1659 * and terminate it with an empty line.
1660 * m is used only to grab the 'ActionID' field.
1662 * Use the explicit constant MSG_MOREDATA to remove the empty line.
1663 * XXX MSG_MOREDATA should go to a header file.
1665 #define MSG_MOREDATA ((char *)astman_send_response)
1666 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
1668 const char *id = astman_get_header(m, "ActionID");
1670 astman_append(s, "Response: %s\r\n", resp);
1671 if (!ast_strlen_zero(id)) {
1672 astman_append(s, "ActionID: %s\r\n", id);
1675 astman_append(s, "Eventlist: %s\r\n", listflag); /* Start, complete, cancelled */
1677 if (msg == MSG_MOREDATA) {
1680 astman_append(s, "Message: %s\r\n\r\n", msg);
1682 astman_append(s, "\r\n");
1686 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
1688 astman_send_response_full(s, m, resp, msg, NULL);
1691 void astman_send_error(struct mansession *s, const struct message *m, char *error)
1693 astman_send_response_full(s, m, "Error", error, NULL);
1696 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
1698 astman_send_response_full(s, m, "Success", msg, NULL);
1701 static void astman_start_ack(struct mansession *s, const struct message *m)
1703 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
1706 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
1708 astman_send_response_full(s, m, "Success", msg, listflag);
1711 /*! \brief Lock the 'mansession' structure. */
1712 static void mansession_lock(struct mansession *s)
1714 ast_mutex_lock(&s->lock);
1717 /*! \brief Unlock the 'mansession' structure. */
1718 static void mansession_unlock(struct mansession *s)
1720 ast_mutex_unlock(&s->lock);
1724 Rather than braindead on,off this now can also accept a specific int mask value
1725 or a ',' delim list of mask strings (the same as manager.conf) -anthm
1727 static int set_eventmask(struct mansession *s, const char *eventmask)
1729 int maskint = strings_to_mask(eventmask);
1733 s->session->send_events = maskint;
1735 mansession_unlock(s);
1740 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
1742 return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
1743 AST_SECURITY_EVENT_TRANSPORT_TCP;
1746 static struct sockaddr_in *mansession_encode_sin_local(const struct mansession *s,
1747 struct sockaddr_in *sin_local)
1749 *sin_local = s->tcptls_session->parent->local_address;
1754 static void report_invalid_user(const struct mansession *s, const char *username)
1756 struct sockaddr_in sin_local;
1757 char session_id[32];
1758 struct ast_security_event_inval_acct_id inval_acct_id = {
1759 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
1760 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
1761 .common.service = "AMI",
1762 .common.account_id = username,
1763 .common.session_tv = &s->session->sessionstart_tv,
1764 .common.local_addr = {
1765 .sin = mansession_encode_sin_local(s, &sin_local),
1766 .transport = mansession_get_transport(s),
1768 .common.remote_addr = {
1769 .sin = &s->session->sin,
1770 .transport = mansession_get_transport(s),
1772 .common.session_id = session_id,
1775 snprintf(session_id, sizeof(session_id), "%p", s);
1777 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
1780 static void report_failed_acl(const struct mansession *s, const char *username)
1782 struct sockaddr_in sin_local;
1783 char session_id[32];
1784 struct ast_security_event_failed_acl failed_acl_event = {
1785 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
1786 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
1787 .common.service = "AMI",
1788 .common.account_id = username,
1789 .common.session_tv = &s->session->sessionstart_tv,
1790 .common.local_addr = {
1791 .sin = mansession_encode_sin_local(s, &sin_local),
1792 .transport = mansession_get_transport(s),
1794 .common.remote_addr = {
1795 .sin = &s->session->sin,
1796 .transport = mansession_get_transport(s),
1798 .common.session_id = session_id,
1801 snprintf(session_id, sizeof(session_id), "%p", s->session);
1803 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
1806 static void report_inval_password(const struct mansession *s, const char *username)
1808 struct sockaddr_in sin_local;
1809 char session_id[32];
1810 struct ast_security_event_inval_password inval_password = {
1811 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
1812 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
1813 .common.service = "AMI",
1814 .common.account_id = username,
1815 .common.session_tv = &s->session->sessionstart_tv,
1816 .common.local_addr = {
1817 .sin = mansession_encode_sin_local(s, &sin_local),
1818 .transport = mansession_get_transport(s),
1820 .common.remote_addr = {
1821 .sin = &s->session->sin,
1822 .transport = mansession_get_transport(s),
1824 .common.session_id = session_id,
1827 snprintf(session_id, sizeof(session_id), "%p", s->session);
1829 ast_security_event_report(AST_SEC_EVT(&inval_password));
1832 static void report_auth_success(const struct mansession *s)
1834 struct sockaddr_in sin_local;
1835 char session_id[32];
1836 struct ast_security_event_successful_auth successful_auth = {
1837 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
1838 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
1839 .common.service = "AMI",
1840 .common.account_id = s->session->username,
1841 .common.session_tv = &s->session->sessionstart_tv,
1842 .common.local_addr = {
1843 .sin = mansession_encode_sin_local(s, &sin_local),
1844 .transport = mansession_get_transport(s),
1846 .common.remote_addr = {
1847 .sin = &s->session->sin,
1848 .transport = mansession_get_transport(s),
1850 .common.session_id = session_id,
1853 snprintf(session_id, sizeof(session_id), "%p", s->session);
1855 ast_security_event_report(AST_SEC_EVT(&successful_auth));
1858 static void report_req_not_allowed(const struct mansession *s, const char *action)
1860 struct sockaddr_in sin_local;
1861 char session_id[32];
1862 char request_type[64];
1863 struct ast_security_event_req_not_allowed req_not_allowed = {
1864 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
1865 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
1866 .common.service = "AMI",
1867 .common.account_id = s->session->username,
1868 .common.session_tv = &s->session->sessionstart_tv,
1869 .common.local_addr = {
1870 .sin = mansession_encode_sin_local(s, &sin_local),
1871 .transport = mansession_get_transport(s),
1873 .common.remote_addr = {
1874 .sin = &s->session->sin,
1875 .transport = mansession_get_transport(s),
1877 .common.session_id = session_id,
1879 .request_type = request_type,
1882 snprintf(session_id, sizeof(session_id), "%p", s->session);
1883 snprintf(request_type, sizeof(request_type), "Action: %s", action);
1885 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
1888 static void report_req_bad_format(const struct mansession *s, const char *action)
1890 struct sockaddr_in sin_local;
1891 char session_id[32];
1892 char request_type[64];
1893 struct ast_security_event_req_bad_format req_bad_format = {
1894 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
1895 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
1896 .common.service = "AMI",
1897 .common.account_id = s->session->username,
1898 .common.session_tv = &s->session->sessionstart_tv,
1899 .common.local_addr = {
1900 .sin = mansession_encode_sin_local(s, &sin_local),
1901 .transport = mansession_get_transport(s),
1903 .common.remote_addr = {
1904 .sin = &s->session->sin,
1905 .transport = mansession_get_transport(s),
1907 .common.session_id = session_id,
1909 .request_type = request_type,
1912 snprintf(session_id, sizeof(session_id), "%p", s->session);
1913 snprintf(request_type, sizeof(request_type), "Action: %s", action);
1915 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
1918 static void report_failed_challenge_response(const struct mansession *s,
1919 const char *response, const char *expected_response)
1921 struct sockaddr_in sin_local;
1922 char session_id[32];
1923 struct ast_security_event_chal_resp_failed chal_resp_failed = {
1924 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
1925 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
1926 .common.service = "AMI",
1927 .common.account_id = s->session->username,
1928 .common.session_tv = &s->session->sessionstart_tv,
1929 .common.local_addr = {
1930 .sin = mansession_encode_sin_local(s, &sin_local),
1931 .transport = mansession_get_transport(s),
1933 .common.remote_addr = {
1934 .sin = &s->session->sin,
1935 .transport = mansession_get_transport(s),
1937 .common.session_id = session_id,
1939 .challenge = s->session->challenge,
1940 .response = response,
1941 .expected_response = expected_response,
1944 snprintf(session_id, sizeof(session_id), "%p", s->session);
1946 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
1949 static void report_session_limit(const struct mansession *s)
1951 struct sockaddr_in sin_local;
1952 char session_id[32];
1953 struct ast_security_event_session_limit session_limit = {
1954 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
1955 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
1956 .common.service = "AMI",
1957 .common.account_id = s->session->username,
1958 .common.session_tv = &s->session->sessionstart_tv,
1959 .common.local_addr = {
1960 .sin = mansession_encode_sin_local(s, &sin_local),
1961 .transport = mansession_get_transport(s),
1963 .common.remote_addr = {
1964 .sin = &s->session->sin,
1965 .transport = mansession_get_transport(s),
1967 .common.session_id = session_id,
1970 snprintf(session_id, sizeof(session_id), "%p", s->session);
1972 ast_security_event_report(AST_SEC_EVT(&session_limit));
1976 * Here we start with action_ handlers for AMI actions,
1977 * and the internal functions used by them.
1978 * Generally, the handlers are called action_foo()
1981 /* helper function for action_login() */
1982 static int authenticate(struct mansession *s, const struct message *m)
1984 const char *username = astman_get_header(m, "Username");
1985 const char *password = astman_get_header(m, "Secret");
1987 struct ast_manager_user *user = NULL;
1989 if (ast_strlen_zero(username)) { /* missing username */
1993 /* locate user in locked state */
1994 AST_RWLIST_WRLOCK(&users);
1996 if (!(user = get_manager_by_name_locked(username))) {
1997 report_invalid_user(s, username);
1998 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
1999 } else if (user->ha && !ast_apply_ha(user->ha, &(s->session->sin))) {
2000 report_failed_acl(s, username);
2001 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2002 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2003 const char *key = astman_get_header(m, "Key");
2004 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2007 char md5key[256] = "";
2008 struct MD5Context md5;
2009 unsigned char digest[16];
2012 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2013 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2014 MD5Final(digest, &md5);
2015 for (x = 0; x < 16; x++)
2016 len += sprintf(md5key + len, "%2.2x", digest[x]);
2017 if (!strcmp(md5key, key)) {
2020 report_failed_challenge_response(s, key, md5key);
2023 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2024 S_OR(s->session->challenge, ""));
2026 } else if (user->secret) {
2027 if (!strcmp(password, user->secret)) {
2030 report_inval_password(s, username);
2035 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2036 AST_RWLIST_UNLOCK(&users);
2042 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2043 s->session->readperm = user->readperm;
2044 s->session->writeperm = user->writeperm;
2045 s->session->writetimeout = user->writetimeout;
2046 s->session->sessionstart = time(NULL);
2047 s->session->sessionstart_tv = ast_tvnow();
2048 set_eventmask(s, astman_get_header(m, "Events"));
2050 report_auth_success(s);
2052 AST_RWLIST_UNLOCK(&users);
2056 static int action_ping(struct mansession *s, const struct message *m)
2058 const char *actionid = astman_get_header(m, "ActionID");
2059 struct timeval now = ast_tvnow();
2061 astman_append(s, "Response: Success\r\n");
2062 if (!ast_strlen_zero(actionid)){
2063 astman_append(s, "ActionID: %s\r\n", actionid);
2068 "Timestamp: %ld.%06lu\r\n"
2070 now.tv_sec, (unsigned long) now.tv_usec);
2074 static int action_getconfig(struct mansession *s, const struct message *m)
2076 struct ast_config *cfg;
2077 const char *fn = astman_get_header(m, "Filename");
2078 const char *category = astman_get_header(m, "Category");
2081 char *cur_category = NULL;
2082 struct ast_variable *v;
2083 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2085 if (ast_strlen_zero(fn)) {
2086 astman_send_error(s, m, "Filename not specified");
2089 cfg = ast_config_load2(fn, "manager", config_flags);
2090 if (cfg == CONFIG_STATUS_FILEMISSING) {
2091 astman_send_error(s, m, "Config file not found");
2093 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2094 astman_send_error(s, m, "Config file has invalid format");
2098 astman_start_ack(s, m);
2099 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2100 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2102 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2103 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2104 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2109 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2110 astman_append(s, "No categories found\r\n");
2112 ast_config_destroy(cfg);
2113 astman_append(s, "\r\n");
2118 static int action_listcategories(struct mansession *s, const struct message *m)
2120 struct ast_config *cfg;
2121 const char *fn = astman_get_header(m, "Filename");
2122 char *category = NULL;
2123 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2126 if (ast_strlen_zero(fn)) {
2127 astman_send_error(s, m, "Filename not specified");
2130 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2131 astman_send_error(s, m, "Config file not found");
2133 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2134 astman_send_error(s, m, "Config file has invalid format");
2137 astman_start_ack(s, m);
2138 while ((category = ast_category_browse(cfg, category))) {
2139 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2142 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2143 astman_append(s, "Error: no categories found\r\n");
2145 ast_config_destroy(cfg);
2146 astman_append(s, "\r\n");
2154 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2155 static void json_escape(char *out, const char *in)
2158 if (*in == '\\' || *in == '\"') {
2166 static int action_getconfigjson(struct mansession *s, const struct message *m)
2168 struct ast_config *cfg;
2169 const char *fn = astman_get_header(m, "Filename");
2170 char *category = NULL;
2171 struct ast_variable *v;
2174 unsigned int buf_len = 0;
2175 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2177 if (ast_strlen_zero(fn)) {
2178 astman_send_error(s, m, "Filename not specified");
2182 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2183 astman_send_error(s, m, "Config file not found");
2185 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2186 astman_send_error(s, m, "Config file has invalid format");
2191 buf = alloca(buf_len);
2193 astman_start_ack(s, m);
2194 astman_append(s, "JSON: {");
2195 while ((category = ast_category_browse(cfg, category))) {
2197 if (buf_len < 2 * strlen(category) + 1) {
2199 buf = alloca(buf_len);
2201 json_escape(buf, category);
2202 astman_append(s, "%s\"%s\":[", comma1 ? "," : "", buf);
2206 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2208 astman_append(s, ",");
2210 if (buf_len < 2 * strlen(v->name) + 1) {
2212 buf = alloca(buf_len);
2214 json_escape(buf, v->name);
2215 astman_append(s, "\"%s", buf);
2216 if (buf_len < 2 * strlen(v->value) + 1) {
2218 buf = alloca(buf_len);
2220 json_escape(buf, v->value);
2221 astman_append(s, "%s\"", buf);
2226 astman_append(s, "]");
2228 astman_append(s, "}\r\n\r\n");
2230 ast_config_destroy(cfg);
2235 /* helper function for action_updateconfig */
2236 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2240 const char *action, *cat, *var, *value, *match, *line;
2241 struct ast_category *category;
2242 struct ast_variable *v;
2243 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2244 enum error_type result = 0;
2246 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2247 unsigned int object = 0;
2249 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2250 action = astman_get_header(m, hdr);
2251 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2252 break; /* this could cause problems if actions come in misnumbered */
2254 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2255 cat = astman_get_header(m, hdr);
2256 if (ast_strlen_zero(cat)) { /* every action needs a category */
2257 result = UNSPECIFIED_CATEGORY;
2261 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2262 var = astman_get_header(m, hdr);
2264 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2265 value = astman_get_header(m, hdr);
2267 if (!ast_strlen_zero(value) && *value == '>') {
2272 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2273 match = astman_get_header(m, hdr);
2275 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2276 line = astman_get_header(m, hdr);
2278 if (!strcasecmp(action, "newcat")) {
2279 if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
2280 result = FAILURE_NEWCAT; /* already exist */
2283 if (!(category = ast_category_new(cat, dfn, -1))) {
2284 result = FAILURE_ALLOCATION;
2287 if (ast_strlen_zero(match)) {
2288 ast_category_append(cfg, category);
2290 ast_category_insert(cfg, category, match);
2292 } else if (!strcasecmp(action, "renamecat")) {
2293 if (ast_strlen_zero(value)) {
2294 result = UNSPECIFIED_ARGUMENT;
2297 if (!(category = ast_category_get(cfg, cat))) {
2298 result = UNKNOWN_CATEGORY;
2301 ast_category_rename(category, value);
2302 } else if (!strcasecmp(action, "delcat")) {
2303 if (ast_category_delete(cfg, cat)) {
2304 result = FAILURE_DELCAT;
2307 } else if (!strcasecmp(action, "emptycat")) {
2308 if (ast_category_empty(cfg, cat)) {
2309 result = FAILURE_EMPTYCAT;
2312 } else if (!strcasecmp(action, "update")) {
2313 if (ast_strlen_zero(var)) {
2314 result = UNSPECIFIED_ARGUMENT;
2317 if (!(category = ast_category_get(cfg,cat))) {
2318 result = UNKNOWN_CATEGORY;
2321 if (ast_variable_update(category, var, value, match, object)) {
2322 result = FAILURE_UPDATE;
2325 } else if (!strcasecmp(action, "delete")) {
2326 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2327 result = UNSPECIFIED_ARGUMENT;
2330 if (!(category = ast_category_get(cfg, cat))) {
2331 result = UNKNOWN_CATEGORY;
2334 if (ast_variable_delete(category, var, match, line)) {
2335 result = FAILURE_DELETE;
2338 } else if (!strcasecmp(action, "append")) {
2339 if (ast_strlen_zero(var)) {
2340 result = UNSPECIFIED_ARGUMENT;
2343 if (!(category = ast_category_get(cfg, cat))) {
2344 result = UNKNOWN_CATEGORY;
2347 if (!(v = ast_variable_new(var, value, dfn))) {
2348 result = FAILURE_ALLOCATION;
2351 if (object || (match && !strcasecmp(match, "object"))) {
2354 ast_variable_append(category, v);
2355 } else if (!strcasecmp(action, "insert")) {
2356 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2357 result = UNSPECIFIED_ARGUMENT;
2360 if (!(category = ast_category_get(cfg, cat))) {
2361 result = UNKNOWN_CATEGORY;
2364 if (!(v = ast_variable_new(var, value, dfn))) {
2365 result = FAILURE_ALLOCATION;
2368 ast_variable_insert(category, v, line);
2371 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
2372 result = UNKNOWN_ACTION;
2381 static int action_updateconfig(struct mansession *s, const struct message *m)
2383 struct ast_config *cfg;
2384 const char *sfn = astman_get_header(m, "SrcFilename");
2385 const char *dfn = astman_get_header(m, "DstFilename");
2387 const char *rld = astman_get_header(m, "Reload");
2388 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2389 enum error_type result;
2391 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
2392 astman_send_error(s, m, "Filename not specified");
2395 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
2396 astman_send_error(s, m, "Config file not found");
2398 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2399 astman_send_error(s, m, "Config file has invalid format");
2402 result = handle_updates(s, m, cfg, dfn);
2404 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
2405 res = ast_config_text_file_save(dfn, cfg, "Manager");
2406 ast_config_destroy(cfg);
2408 astman_send_error(s, m, "Save of config failed");
2411 astman_send_ack(s, m, NULL);
2412 if (!ast_strlen_zero(rld)) {
2413 if (ast_true(rld)) {
2416 ast_module_reload(rld);
2419 ast_config_destroy(cfg);
2421 case UNKNOWN_ACTION:
2422 astman_send_error(s, m, "Unknown action command");
2424 case UNKNOWN_CATEGORY:
2425 astman_send_error(s, m, "Given category does not exist");
2427 case UNSPECIFIED_CATEGORY:
2428 astman_send_error(s, m, "Category not specified");
2430 case UNSPECIFIED_ARGUMENT:
2431 astman_send_error(s, m, "Problem with category, value, or line (if required)");
2433 case FAILURE_ALLOCATION:
2434 astman_send_error(s, m, "Memory allocation failure, this should not happen");
2436 case FAILURE_NEWCAT:
2437 astman_send_error(s, m, "Create category did not complete successfully");
2439 case FAILURE_DELCAT:
2440 astman_send_error(s, m, "Delete category did not complete successfully");
2442 case FAILURE_EMPTYCAT:
2443 astman_send_error(s, m, "Empty category did not complete successfully");
2445 case FAILURE_UPDATE:
2446 astman_send_error(s, m, "Update did not complete successfully");
2448 case FAILURE_DELETE:
2449 astman_send_error(s, m, "Delete did not complete successfully");
2451 case FAILURE_APPEND:
2452 astman_send_error(s, m, "Append did not complete successfully");
2459 static int action_createconfig(struct mansession *s, const struct message *m)
2462 const char *fn = astman_get_header(m, "Filename");
2463 struct ast_str *filepath = ast_str_alloca(PATH_MAX);
2464 ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
2465 ast_str_append(&filepath, 0, "%s", fn);
2467 if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
2469 astman_send_ack(s, m, "New configuration file created successfully");
2471 astman_send_error(s, m, strerror(errno));
2477 static int action_waitevent(struct mansession *s, const struct message *m)
2479 const char *timeouts = astman_get_header(m, "Timeout");
2483 const char *id = astman_get_header(m, "ActionID");
2486 if (!ast_strlen_zero(id)) {
2487 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
2492 if (!ast_strlen_zero(timeouts)) {
2493 sscanf(timeouts, "%30i", &timeout);
2497 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
2501 if (s->session->waiting_thread != AST_PTHREADT_NULL) {
2502 pthread_kill(s->session->waiting_thread, SIGURG);
2505 if (s->session->managerid) { /* AMI-over-HTTP session */
2507 * Make sure the timeout is within the expire time of the session,
2508 * as the client will likely abort the request if it does not see
2509 * data coming after some amount of time.
2511 time_t now = time(NULL);
2512 int max = s->session->sessiontimeout - now - 10;
2514 if (max < 0) { /* We are already late. Strange but possible. */
2517 if (timeout < 0 || timeout > max) {
2520 if (!s->session->send_events) { /* make sure we record events */
2521 s->session->send_events = -1;
2524 mansession_unlock(s);
2526 /* XXX should this go inside the lock ? */
2527 s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
2528 ast_debug(1, "Starting waiting for an event!\n");
2530 for (x = 0; x < timeout || timeout < 0; x++) {
2535 /* We can have multiple HTTP session point to the same mansession entry.
2536 * The way we deal with it is not very nice: newcomers kick out the previous
2537 * HTTP session. XXX this needs to be improved.
2539 if (s->session->waiting_thread != pthread_self()) {
2542 if (s->session->needdestroy) {
2545 mansession_unlock(s);
2549 if (s->session->managerid == 0) { /* AMI session */
2550 if (ast_wait_for_input(s->session->fd, 1000)) {
2553 } else { /* HTTP session */
2557 ast_debug(1, "Finished waiting for an event!\n");
2560 if (s->session->waiting_thread == pthread_self()) {
2561 struct eventqent *eqe;
2562 astman_send_response(s, m, "Success", "Waiting for Event completed.");
2563 while ( (eqe = NEW_EVENT(s)) ) {
2565 if (((s->session->readperm & eqe->category) == eqe->category) &&
2566 ((s->session->send_events & eqe->category) == eqe->category)) {
2567 astman_append(s, "%s", eqe->eventdata);
2569 s->session->last_ev = unref_event(s->session->last_ev);
2572 "Event: WaitEventComplete\r\n"
2575 s->session->waiting_thread = AST_PTHREADT_NULL;
2577 ast_debug(1, "Abandoning event request!\n");
2579 mansession_unlock(s);
2583 /*! \note The actionlock is read-locked by the caller of this function */
2584 static int action_listcommands(struct mansession *s, const struct message *m)
2586 struct manager_action *cur;
2587 struct ast_str *temp = ast_str_alloca(BUFSIZ); /* XXX very large ? */
2589 astman_start_ack(s, m);
2590 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2591 if (s->session->writeperm & cur->authority || cur->authority == 0) {
2592 astman_append(s, "%s: %s (Priv: %s)\r\n",
2593 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
2596 astman_append(s, "\r\n");
2601 static int action_events(struct mansession *s, const struct message *m)
2603 const char *mask = astman_get_header(m, "EventMask");
2606 res = set_eventmask(s, mask);
2608 astman_append(s, "Response: Success\r\n"
2611 astman_append(s, "Response: Success\r\n"
2616 static int action_logoff(struct mansession *s, const struct message *m)
2618 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
2622 static int action_login(struct mansession *s, const struct message *m)
2625 /* still authenticated - don't process again */
2626 if (s->session->authenticated) {
2627 astman_send_ack(s, m, "Already authenticated");
2631 if (authenticate(s, m)) {
2633 astman_send_error(s, m, "Authentication failed");
2636 s->session->authenticated = 1;
2637 if (manager_displayconnects(s->session)) {
2638 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_inet_ntoa(s->session->sin.sin_addr));
2640 astman_send_ack(s, m, "Authentication accepted");
2644 static int action_challenge(struct mansession *s, const struct message *m)
2646 const char *authtype = astman_get_header(m, "AuthType");
2648 if (!strcasecmp(authtype, "MD5")) {
2649 if (ast_strlen_zero(s->session->challenge)) {
2650 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
2653 astman_start_ack(s, m);
2654 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
2655 mansession_unlock(s);
2657 astman_send_error(s, m, "Must specify AuthType");
2662 static int action_hangup(struct mansession *s, const struct message *m)
2664 struct ast_channel *c = NULL;
2665 int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
2666 const char *name = astman_get_header(m, "Channel");
2667 const char *cause = astman_get_header(m, "Cause");
2669 if (ast_strlen_zero(name)) {
2670 astman_send_error(s, m, "No channel specified");
2674 if (!ast_strlen_zero(cause)) {
2676 causecode = strtol(cause, &endptr, 10);
2677 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
2678 ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
2679 /* keep going, better to hangup without cause than to not hang up at all */
2680 causecode = 0; /* do not set channel's hangupcause */
2684 if (!(c = ast_channel_get_by_name(name))) {
2685 astman_send_error(s, m, "No such channel");
2689 ast_channel_lock(c);
2690 if (causecode > 0) {
2691 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
2692 c->name, causecode, c->hangupcause);
2693 c->hangupcause = causecode;
2695 ast_softhangup_nolock(c, AST_SOFTHANGUP_EXPLICIT);
2696 ast_channel_unlock(c);
2698 c = ast_channel_unref(c);
2700 astman_send_ack(s, m, "Channel Hungup");
2705 static int action_setvar(struct mansession *s, const struct message *m)
2707 struct ast_channel *c = NULL;
2708 const char *name = astman_get_header(m, "Channel");
2709 const char *varname = astman_get_header(m, "Variable");
2710 const char *varval = astman_get_header(m, "Value");
2712 if (ast_strlen_zero(varname)) {
2713 astman_send_error(s, m, "No variable specified");
2717 if (!ast_strlen_zero(name)) {
2718 if (!(c = ast_channel_get_by_name(name))) {
2719 astman_send_error(s, m, "No such channel");
2724 pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
2727 c = ast_channel_unref(c);
2730 astman_send_ack(s, m, "Variable Set");
2735 static int action_getvar(struct mansession *s, const struct message *m)
2737 struct ast_channel *c = NULL;
2738 const char *name = astman_get_header(m, "Channel");
2739 const char *varname = astman_get_header(m, "Variable");
2741 char workspace[1024] = "";
2743 if (ast_strlen_zero(varname)) {
2744 astman_send_error(s, m, "No variable specified");
2748 if (!ast_strlen_zero(name)) {
2749 if (!(c = ast_channel_get_by_name(name))) {
2750 astman_send_error(s, m, "No such channel");
2755 if (varname[strlen(varname) - 1] == ')') {
2757 c = ast_dummy_channel_alloc();
2759 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
2760 c = ast_channel_release(c);
2762 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
2764 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
2768 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
2772 c = ast_channel_unref(c);
2775 astman_start_ack(s, m);
2776 astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, varval);
2781 /*! \brief Manager "status" command to show channels */
2782 /* Needs documentation... */
2783 static int action_status(struct mansession *s, const struct message *m)
2785 const char *name = astman_get_header(m, "Channel");
2786 const char *cvariables = astman_get_header(m, "Variables");
2787 char *variables = ast_strdupa(S_OR(cvariables, ""));
2788 struct ast_channel *c;
2790 struct timeval now = ast_tvnow();
2791 long elapsed_seconds = 0;
2793 int all = ast_strlen_zero(name); /* set if we want all channels */
2794 const char *id = astman_get_header(m, "ActionID");
2796 AST_DECLARE_APP_ARGS(vars,
2797 AST_APP_ARG(name)[100];
2799 struct ast_str *str = ast_str_create(1000);
2800 struct ast_channel_iterator *iter = NULL;
2802 if (!ast_strlen_zero(id)) {
2803 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
2809 if (!(iter = ast_channel_iterator_all_new())) {
2811 astman_send_error(s, m, "Memory Allocation Failure");
2814 c = ast_channel_iterator_next(iter);
2816 if (!(c = ast_channel_get_by_name(name))) {
2817 astman_send_error(s, m, "No such channel");
2823 astman_send_ack(s, m, "Channel status will follow");
2825 if (!ast_strlen_zero(cvariables)) {
2826 AST_STANDARD_APP_ARGS(vars, variables);
2829 /* if we look by name, we break after the first iteration */
2830 for (; c; c = ast_channel_iterator_next(iter)) {
2831 ast_channel_lock(c);
2833 if (!ast_strlen_zero(cvariables)) {
2836 for (i = 0; i < vars.argc; i++) {
2837 char valbuf[512], *ret = NULL;
2839 if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
2840 if (ast_func_read(c, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
2845 pbx_retrieve_variable(c, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);
2848 ast_str_append(&str, 0, "Variable: %s=%s\r\n", vars.name[i], ret);
2854 snprintf(bridge, sizeof(bridge), "BridgedChannel: %s\r\nBridgedUniqueid: %s\r\n", c->_bridge->name, c->_bridge->uniqueid);
2860 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
2864 "Privilege: Call\r\n"
2866 "CallerIDNum: %s\r\n"
2867 "CallerIDName: %s\r\n"
2868 "Accountcode: %s\r\n"
2869 "ChannelState: %d\r\n"
2870 "ChannelStateDesc: %s\r\n"
2881 S_OR(c->cid.cid_num, ""),
2882 S_OR(c->cid.cid_name, ""),
2885 ast_state2str(c->_state), c->context,
2886 c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, ast_str_buffer(str), idText);
2890 "Privilege: Call\r\n"
2892 "CallerIDNum: %s\r\n"
2893 "CallerIDName: %s\r\n"
2902 S_OR(c->cid.cid_num, "<unknown>"),
2903 S_OR(c->cid.cid_name, "<unknown>"),
2905 ast_state2str(c->_state), bridge, c->uniqueid,
2906 ast_str_buffer(str), idText);
2909 ast_channel_unlock(c);
2910 c = ast_channel_unref(c);
2918 ast_channel_iterator_destroy(iter);
2922 "Event: StatusComplete\r\n"
2925 "\r\n", idText, channels);
2932 static int action_sendtext(struct mansession *s, const struct message *m)
2934 struct ast_channel *c = NULL;
2935 const char *name = astman_get_header(m, "Channel");
2936 const char *textmsg = astman_get_header(m, "Message");
2939 if (ast_strlen_zero(name)) {
2940 astman_send_error(s, m, "No channel specified");
2944 if (ast_strlen_zero(textmsg)) {
2945 astman_send_error(s, m, "No Message specified");
2949 if (!(c = ast_channel_get_by_name(name))) {
2950 astman_send_error(s, m, "No such channel");
2954 ast_channel_lock(c);
2955 res = ast_sendtext(c, textmsg);
2956 ast_channel_unlock(c);
2957 c = ast_channel_unref(c);
2960 astman_send_ack(s, m, "Success");
2962 astman_send_error(s, m, "Failure");
2968 /*! \brief action_redirect: The redirect manager command */
2969 static int action_redirect(struct mansession *s, const struct message *m)
2971 const char *name = astman_get_header(m, "Channel");
2972 const char *name2 = astman_get_header(m, "ExtraChannel");
2973 const char *exten = astman_get_header(m, "Exten");
2974 const char *context = astman_get_header(m, "Context");
2975 const char *priority = astman_get_header(m, "Priority");
2976 struct ast_channel *chan, *chan2 = NULL;
2980 if (ast_strlen_zero(name)) {
2981 astman_send_error(s, m, "Channel not specified");
2985 if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
2986 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
2987 astman_send_error(s, m, "Invalid priority");
2992 if (!(chan = ast_channel_get_by_name(name))) {
2994 snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
2995 astman_send_error(s, m, buf);
2999 if (ast_check_hangup_locked(chan)) {
3000 astman_send_error(s, m, "Redirect failed, channel not up.");
3001 chan = ast_channel_unref(chan);
3005 if (!ast_strlen_zero(name2)) {
3006 chan2 = ast_channel_get_by_name(name2);
3009 if (chan2 && ast_check_hangup_locked(chan2)) {
3010 astman_send_error(s, m, "Redirect failed, extra channel not up.");
3011 chan = ast_channel_unref(chan);
3012 chan2 = ast_channel_unref(chan2);
3017 ast_channel_lock(chan);
3018 ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
3019 ast_channel_unlock(chan);
3022 res = ast_async_goto(chan, context, exten, pi);
3024 if (!ast_strlen_zero(name2)) {
3027 ast_channel_lock(chan2);
3028 ast_set_flag(chan2, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
3029 ast_channel_unlock(chan2);
3031 res = ast_async_goto(chan2, context, exten, pi);
3036 astman_send_ack(s, m, "Dual Redirect successful");
3038 astman_send_error(s, m, "Secondary redirect failed");
3041 astman_send_ack(s, m, "Redirect successful");
3044 astman_send_error(s, m, "Redirect failed");
3048 chan = ast_channel_unref(chan);
3052 chan2 = ast_channel_unref(chan2);
3058 static int action_atxfer(struct mansession *s, const struct message *m)
3060 const char *name = astman_get_header(m, "Channel");
3061 const char *exten = astman_get_header(m, "Exten");
3062 const char *context = astman_get_header(m, "Context");
3063 struct ast_channel *chan = NULL;
3064 struct ast_call_feature *atxfer_feature = NULL;
3065 char *feature_code = NULL;
3067 if (ast_strlen_zero(name)) {
3068 astman_send_error(s, m, "No channel specified");
3071 if (ast_strlen_zero(exten)) {
3072 astman_send_error(s, m, "No extension specified");
3076 if (!(atxfer_feature = ast_find_call_feature("atxfer"))) {
3077 astman_send_error(s, m, "No attended transfer feature found");
3081 if (!(chan = ast_channel_get_by_name(name))) {
3082 astman_send_error(s, m, "Channel specified does not exist");
3086 if (!ast_strlen_zero(context)) {
3087 pbx_builtin_setvar_helper(chan, "TRANSFER_CONTEXT", context);
3090 for (feature_code = atxfer_feature->exten; feature_code && *feature_code; ++feature_code) {
3091 struct ast_frame f = { AST_FRAME_DTMF, *feature_code };
3092 ast_queue_frame(chan, &f);