Sat Mar 26 11:07:49 2011

Asterisk developer's documentation


manager.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief The Asterisk Management Interface - AMI
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * \extref OpenSSL http://www.openssl.org - for AMI/SSL
00026  *
00027  * At the moment this file contains a number of functions, namely:
00028  *
00029  * - data structures storing AMI state
00030  * - AMI-related API functions, used by internal asterisk components
00031  * - handlers for AMI-related CLI functions
00032  * - handlers for AMI functions (available through the AMI socket)
00033  * - the code for the main AMI listener thread and individual session threads
00034  * - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
00035  *
00036  * \ref amiconf
00037  */
00038 
00039 /*! \addtogroup Group_AMI AMI functions
00040 */
00041 /*! @{
00042  Doxygen group */
00043 
00044 #include "asterisk.h"
00045 
00046 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 291227 $")
00047 
00048 #include "asterisk/_private.h"
00049 #include "asterisk/paths.h"   /* use various ast_config_AST_* */
00050 #include <ctype.h>
00051 #include <sys/time.h>
00052 #include <signal.h>
00053 #include <sys/mman.h>
00054 #include <sys/types.h>
00055 #include <regex.h>
00056 
00057 #include "asterisk/channel.h"
00058 #include "asterisk/file.h"
00059 #include "asterisk/manager.h"
00060 #include "asterisk/module.h"
00061 #include "asterisk/config.h"
00062 #include "asterisk/callerid.h"
00063 #include "asterisk/lock.h"
00064 #include "asterisk/cli.h"
00065 #include "asterisk/app.h"
00066 #include "asterisk/pbx.h"
00067 #include "asterisk/md5.h"
00068 #include "asterisk/acl.h"
00069 #include "asterisk/utils.h"
00070 #include "asterisk/tcptls.h"
00071 #include "asterisk/http.h"
00072 #include "asterisk/ast_version.h"
00073 #include "asterisk/threadstorage.h"
00074 #include "asterisk/linkedlists.h"
00075 #include "asterisk/term.h"
00076 #include "asterisk/astobj2.h"
00077 #include "asterisk/features.h"
00078 #include "asterisk/security_events.h"
00079 #include "asterisk/aoc.h"
00080 
00081 /*** DOCUMENTATION
00082    <manager name="Ping" language="en_US">
00083       <synopsis>
00084          Keepalive command.
00085       </synopsis>
00086       <syntax>
00087          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00088       </syntax>
00089       <description>
00090          <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
00091          manager connection open.</para>
00092       </description>
00093    </manager>
00094    <manager name="Events" language="en_US">
00095       <synopsis>
00096          Control Event Flow.
00097       </synopsis>
00098       <syntax>
00099          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00100          <parameter name="EventMask" required="true">
00101             <enumlist>
00102                <enum name="on">
00103                   <para>If all events should be sent.</para>
00104                </enum>
00105                <enum name="off">
00106                   <para>If no events should be sent.</para>
00107                </enum>
00108                <enum name="system,call,log,...">
00109                   <para>To select which flags events should have to be sent.</para>
00110                </enum>
00111             </enumlist>
00112          </parameter>
00113       </syntax>
00114       <description>
00115          <para>Enable/Disable sending of events to this manager client.</para>
00116       </description>
00117    </manager>
00118    <manager name="Logoff" language="en_US">
00119       <synopsis>
00120          Logoff Manager.
00121       </synopsis>
00122       <syntax>
00123          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00124       </syntax>
00125       <description>
00126          <para>Logoff the current manager session.</para>
00127       </description>
00128    </manager>
00129    <manager name="Login" language="en_US">
00130       <synopsis>
00131          Login Manager.
00132       </synopsis>
00133       <syntax>
00134          <parameter name="ActionID">
00135             <para>ActionID for this transaction. Will be returned.</para>
00136          </parameter>
00137       </syntax>
00138       <description>
00139          <para>Login Manager.</para>
00140       </description>
00141    </manager>
00142    <manager name="Challenge" language="en_US">
00143       <synopsis>
00144          Generate Challenge for MD5 Auth.
00145       </synopsis>
00146       <syntax>
00147          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00148       </syntax>
00149       <description>
00150          <para>Generate a challenge for MD5 authentication.</para>
00151       </description>
00152    </manager>
00153    <manager name="Hangup" language="en_US">
00154       <synopsis>
00155          Hangup channel.
00156       </synopsis>
00157       <syntax>
00158          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00159          <parameter name="Channel" required="true">
00160             <para>The channel name to be hangup.</para>
00161          </parameter>
00162          <parameter name="Cause">
00163             <para>Numeric hangup cause.</para>
00164          </parameter>
00165       </syntax>
00166       <description>
00167          <para>Hangup a channel.</para>
00168       </description>
00169    </manager>
00170    <manager name="Status" language="en_US">
00171       <synopsis>
00172          List channel status.
00173       </synopsis>
00174       <syntax>
00175          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00176          <parameter name="Channel" required="true">
00177             <para>The name of the channel to query for status.</para>
00178          </parameter>
00179          <parameter name="Variables">
00180             <para>Comma <literal>,</literal> separated list of variable to include.</para>
00181          </parameter>
00182       </syntax>
00183       <description>
00184          <para>Will return the status information of each channel along with the
00185          value for the specified channel variables.</para>
00186       </description>
00187    </manager>
00188    <manager name="Setvar" language="en_US">
00189       <synopsis>
00190          Set a channel variable.
00191       </synopsis>
00192       <syntax>
00193          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00194          <parameter name="Channel">
00195             <para>Channel to set variable for.</para>
00196          </parameter>
00197          <parameter name="Variable" required="true">
00198             <para>Variable name.</para>
00199          </parameter>
00200          <parameter name="Value" required="true">
00201             <para>Variable value.</para>
00202          </parameter>
00203       </syntax>
00204       <description>
00205          <para>Set a global or local channel variable.</para>
00206       </description>
00207    </manager>
00208    <manager name="Getvar" language="en_US">
00209       <synopsis>
00210          Gets a channel variable.
00211       </synopsis>
00212       <syntax>
00213          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00214          <parameter name="Channel">
00215             <para>Channel to read variable from.</para>
00216          </parameter>
00217          <parameter name="Variable" required="true">
00218             <para>Variable name.</para>
00219          </parameter>
00220       </syntax>
00221       <description>
00222          <para>Get the value of a global or local channel variable.</para>
00223       </description>
00224    </manager>
00225    <manager name="GetConfig" language="en_US">
00226       <synopsis>
00227          Retrieve configuration.
00228       </synopsis>
00229       <syntax>
00230          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00231          <parameter name="Filename" required="true">
00232             <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
00233          </parameter>
00234          <parameter name="Category">
00235             <para>Category in configuration file.</para>
00236          </parameter>
00237       </syntax>
00238       <description>
00239          <para>This action will dump the contents of a configuration
00240          file by category and contents or optionally by specified category only.</para>
00241       </description>
00242    </manager>
00243    <manager name="GetConfigJSON" language="en_US">
00244       <synopsis>
00245          Retrieve configuration (JSON format).
00246       </synopsis>
00247       <syntax>
00248          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00249          <parameter name="Filename" required="true">
00250             <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
00251          </parameter>
00252       </syntax>
00253       <description>
00254          <para>This action will dump the contents of a configuration file by category
00255          and contents in JSON format. This only makes sense to be used using rawman over
00256          the HTTP interface.</para>
00257       </description>
00258    </manager>
00259    <manager name="UpdateConfig" language="en_US">
00260       <synopsis>
00261          Update basic configuration.
00262       </synopsis>
00263       <syntax>
00264          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00265          <parameter name="SrcFilename" required="true">
00266             <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
00267          </parameter>
00268          <parameter name="DstFilename" required="true">
00269             <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
00270          </parameter>
00271          <parameter name="Reload">
00272             <para>Whether or not a reload should take place (or name of specific module).</para>
00273          </parameter>
00274          <parameter name="Action-XXXXXX">
00275             <para>Action to take.</para>
00276             <para>X's represent 6 digit number beginning with 000000.</para>
00277             <enumlist>
00278                <enum name="NewCat" />
00279                <enum name="RenameCat" />
00280                <enum name="DelCat" />
00281                <enum name="EmptyCat" />
00282                <enum name="Update" />
00283                <enum name="Delete" />
00284                <enum name="Append" />
00285                <enum name="Insert" />
00286             </enumlist>
00287          </parameter>
00288          <parameter name="Cat-XXXXXX">
00289             <para>Category to operate on.</para>
00290             <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
00291          </parameter>
00292          <parameter name="Var-XXXXXX">
00293             <para>Variable to work on.</para>
00294             <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
00295          </parameter>
00296          <parameter name="Value-XXXXXX">
00297             <para>Value to work on.</para>
00298             <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
00299          </parameter>
00300          <parameter name="Match-XXXXXX">
00301             <para>Extra match required to match line.</para>
00302             <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
00303          </parameter>
00304          <parameter name="Line-XXXXXX">
00305             <para>Line in category to operate on (used with delete and insert actions).</para>
00306             <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
00307          </parameter>
00308       </syntax>
00309       <description>
00310          <para>This action will modify, create, or delete configuration elements
00311          in Asterisk configuration files.</para>
00312       </description>
00313    </manager>
00314    <manager name="CreateConfig" language="en_US">
00315       <synopsis>
00316          Creates an empty file in the configuration directory.
00317       </synopsis>
00318       <syntax>
00319          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00320          <parameter name="Filename" required="true">
00321             <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
00322          </parameter>
00323       </syntax>
00324       <description>
00325          <para>This action will create an empty file in the configuration
00326          directory. This action is intended to be used before an UpdateConfig
00327          action.</para>
00328       </description>
00329    </manager>
00330    <manager name="ListCategories" language="en_US">
00331       <synopsis>
00332          List categories in configuration file.
00333       </synopsis>
00334       <syntax>
00335          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00336          <parameter name="Filename" required="true">
00337             <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
00338          </parameter>
00339       </syntax>
00340       <description>
00341          <para>This action will dump the categories in a given file.</para>
00342       </description>
00343    </manager>
00344    <manager name="Redirect" language="en_US">
00345       <synopsis>
00346          Redirect (transfer) a call.
00347       </synopsis>
00348       <syntax>
00349          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00350          <parameter name="Channel" required="true">
00351             <para>Channel to redirect.</para>
00352          </parameter>
00353          <parameter name="ExtraChannel">
00354             <para>Second call leg to transfer (optional).</para>
00355          </parameter>
00356          <parameter name="Exten" required="true">
00357             <para>Extension to transfer to.</para>
00358          </parameter>
00359          <parameter name="ExtraExten">
00360             <para>Extension to transfer extrachannel to (optional).</para>
00361          </parameter>
00362          <parameter name="Context" required="true">
00363             <para>Context to transfer to.</para>
00364          </parameter>
00365          <parameter name="ExtraContext">
00366             <para>Context to transfer extrachannel to (optional).</para>
00367          </parameter>
00368          <parameter name="Priority" required="true">
00369             <para>Priority to transfer to.</para>
00370          </parameter>
00371          <parameter name="ExtraPriority">
00372             <para>Priority to transfer extrachannel to (optional).</para>
00373          </parameter>
00374       </syntax>
00375       <description>
00376          <para>Redirect (transfer) a call.</para>
00377       </description>
00378    </manager>
00379    <manager name="Atxfer" language="en_US">
00380       <synopsis>
00381          Attended transfer.
00382       </synopsis>
00383       <syntax>
00384          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00385          <parameter name="Channel" required="true">
00386             <para>Transferer's channel.</para>
00387          </parameter>
00388          <parameter name="Exten" required="true">
00389             <para>Extension to transfer to.</para>
00390          </parameter>
00391          <parameter name="Context" required="true">
00392             <para>Context to transfer to.</para>
00393          </parameter>
00394          <parameter name="Priority" required="true">
00395             <para>Priority to transfer to.</para>
00396          </parameter>
00397       </syntax>
00398       <description>
00399          <para>Attended transfer.</para>
00400       </description>
00401    </manager>
00402    <manager name="Originate" language="en_US">
00403       <synopsis>
00404          Originate a call.
00405       </synopsis>
00406       <syntax>
00407          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00408          <parameter name="Channel" required="true">
00409             <para>Channel name to call.</para>
00410          </parameter>
00411          <parameter name="Exten">
00412             <para>Extension to use (requires <literal>Context</literal> and
00413             <literal>Priority</literal>)</para>
00414          </parameter>
00415          <parameter name="Context">
00416             <para>Context to use (requires <literal>Exten</literal> and
00417             <literal>Priority</literal>)</para>
00418          </parameter>
00419          <parameter name="Priority">
00420             <para>Priority to use (requires <literal>Exten</literal> and
00421             <literal>Context</literal>)</para>
00422          </parameter>
00423          <parameter name="Application">
00424             <para>Application to execute.</para>
00425          </parameter>
00426          <parameter name="Data">
00427             <para>Data to use (requires <literal>Application</literal>).</para>
00428          </parameter>
00429          <parameter name="Timeout" default="30000">
00430             <para>How long to wait for call to be answered (in ms.).</para>
00431          </parameter>
00432          <parameter name="CallerID">
00433             <para>Caller ID to be set on the outgoing channel.</para>
00434          </parameter>
00435          <parameter name="Variable">
00436             <para>Channel variable to set, multiple Variable: headers are allowed.</para>
00437          </parameter>
00438          <parameter name="Account">
00439             <para>Account code.</para>
00440          </parameter>
00441          <parameter name="Async">
00442             <para>Set to <literal>true</literal> for fast origination.</para>
00443          </parameter>
00444          <parameter name="Codecs">
00445             <para>Comma-separated list of codecs to use for this call.</para>
00446          </parameter>
00447       </syntax>
00448       <description>
00449          <para>Generates an outgoing call to a
00450          <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
00451          or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
00452       </description>
00453    </manager>
00454    <manager name="Command" language="en_US">
00455       <synopsis>
00456          Execute Asterisk CLI Command.
00457       </synopsis>
00458       <syntax>
00459          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00460          <parameter name="Command" required="true">
00461             <para>Asterisk CLI command to run.</para>
00462          </parameter>
00463       </syntax>
00464       <description>
00465          <para>Run a CLI command.</para>
00466       </description>
00467    </manager>
00468    <manager name="ExtensionState" language="en_US">
00469       <synopsis>
00470          Check Extension Status.
00471       </synopsis>
00472       <syntax>
00473          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00474          <parameter name="Exten" required="true">
00475             <para>Extension to check state on.</para>
00476          </parameter>
00477          <parameter name="Context" required="true">
00478             <para>Context for extension.</para>
00479          </parameter>
00480       </syntax>
00481       <description>
00482          <para>Report the extension state for given extension. If the extension has a hint,
00483          will use devicestate to check the status of the device connected to the extension.</para>
00484          <para>Will return an <literal>Extension Status</literal> message. The response will include
00485          the hint for the extension and the status.</para>
00486       </description>
00487    </manager>
00488    <manager name="AbsoluteTimeout" language="en_US">
00489       <synopsis>
00490          Set absolute timeout.
00491       </synopsis>
00492       <syntax>
00493          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00494          <parameter name="Channel" required="true">
00495             <para>Channel name to hangup.</para>
00496          </parameter>
00497          <parameter name="Timeout" required="true">
00498             <para>Maximum duration of the call (sec).</para>
00499          </parameter>
00500       </syntax>
00501       <description>
00502          <para>Hangup a channel after a certain time. Acknowledges set time with
00503          <literal>Timeout Set</literal> message.</para>
00504       </description>
00505    </manager>
00506    <manager name="MailboxStatus" language="en_US">
00507       <synopsis>
00508          Check mailbox.
00509       </synopsis>
00510       <syntax>
00511          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00512          <parameter name="Mailbox" required="true">
00513             <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
00514          </parameter>
00515       </syntax>
00516       <description>
00517          <para>Checks a voicemail account for status.</para>
00518          <para>Returns number of messages.</para>
00519          <para>Message: Mailbox Status.</para>
00520          <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
00521          <para>Waiting: <replaceable>count</replaceable>.</para>
00522       </description>
00523    </manager>
00524    <manager name="MailboxCount" language="en_US">
00525       <synopsis>
00526          Check Mailbox Message Count.
00527       </synopsis>
00528       <syntax>
00529          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00530          <parameter name="Mailbox" required="true">
00531             <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
00532          </parameter>
00533       </syntax>
00534       <description>
00535          <para>Checks a voicemail account for new messages.</para>
00536          <para>Returns number of urgent, new and old messages.</para>
00537          <para>Message: Mailbox Message Count</para>
00538          <para>Mailbox: <replaceable>mailboxid</replaceable></para>
00539          <para>UrgentMessages: <replaceable>count</replaceable></para>
00540          <para>NewMessages: <replaceable>count</replaceable></para>
00541          <para>OldMessages: <replaceable>count</replaceable></para>
00542       </description>
00543    </manager>
00544    <manager name="ListCommands" language="en_US">
00545       <synopsis>
00546          List available manager commands.
00547       </synopsis>
00548       <syntax>
00549          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00550       </syntax>
00551       <description>
00552          <para>Returns the action name and synopsis for every action that
00553          is available to the user.</para>
00554       </description>
00555    </manager>
00556    <manager name="SendText" language="en_US">
00557       <synopsis>
00558          Send text message to channel.
00559       </synopsis>
00560       <syntax>
00561          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00562          <parameter name="Channel" required="true">
00563             <para>Channel to send message to.</para>
00564          </parameter>
00565          <parameter name="Message" required="true">
00566             <para>Message to send.</para>
00567          </parameter>
00568       </syntax>
00569       <description>
00570          <para>Sends A Text Message to a channel while in a call.</para>
00571       </description>
00572    </manager>
00573    <manager name="UserEvent" language="en_US">
00574       <synopsis>
00575          Send an arbitrary event.
00576       </synopsis>
00577       <syntax>
00578          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00579          <parameter name="UserEvent" required="true">
00580             <para>Event string to send.</para>
00581          </parameter>
00582          <parameter name="Header1">
00583             <para>Content1.</para>
00584          </parameter>
00585          <parameter name="HeaderN">
00586             <para>ContentN.</para>
00587          </parameter>
00588       </syntax>
00589       <description>
00590          <para>Send an event to manager sessions.</para>
00591       </description>
00592    </manager>
00593    <manager name="WaitEvent" language="en_US">
00594       <synopsis>
00595          Wait for an event to occur.
00596       </synopsis>
00597       <syntax>
00598          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00599          <parameter name="Timeout" required="true">
00600             <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
00601          </parameter>
00602       </syntax>
00603       <description>
00604          <para>This action will ellicit a <literal>Success</literal> response. Whenever
00605          a manager event is queued. Once WaitEvent has been called on an HTTP manager
00606          session, events will be generated and queued.</para>
00607       </description>
00608    </manager>
00609    <manager name="CoreSettings" language="en_US">
00610       <synopsis>
00611          Show PBX core settings (version etc).
00612       </synopsis>
00613       <syntax>
00614          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00615       </syntax>
00616       <description>
00617          <para>Query for Core PBX settings.</para>
00618       </description>
00619    </manager>
00620    <manager name="CoreStatus" language="en_US">
00621       <synopsis>
00622          Show PBX core status variables.
00623       </synopsis>
00624       <syntax>
00625          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00626       </syntax>
00627       <description>
00628          <para>Query for Core PBX status.</para>
00629       </description>
00630    </manager>
00631    <manager name="Reload" language="en_US">
00632       <synopsis>
00633          Send a reload event.
00634       </synopsis>
00635       <syntax>
00636          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00637          <parameter name="Module">
00638             <para>Name of the module to reload.</para>
00639          </parameter>
00640       </syntax>
00641       <description>
00642          <para>Send a reload event.</para>
00643       </description>
00644    </manager>
00645    <manager name="CoreShowChannels" language="en_US">
00646       <synopsis>
00647          List currently active channels.
00648       </synopsis>
00649       <syntax>
00650          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00651       </syntax>
00652       <description>
00653          <para>List currently defined channels and some information about them.</para>
00654       </description>
00655    </manager>
00656    <manager name="ModuleLoad" language="en_US">
00657       <synopsis>
00658          Module management.
00659       </synopsis>
00660       <syntax>
00661          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00662          <parameter name="Module">
00663             <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
00664             <enumlist>
00665                <enum name="cdr" />
00666                <enum name="enum" />
00667                <enum name="dnsmgr" />
00668                <enum name="extconfig" />
00669                <enum name="manager" />
00670                <enum name="rtp" />
00671                <enum name="http" />
00672             </enumlist>
00673          </parameter>
00674          <parameter name="LoadType" required="true">
00675             <para>The operation to be done on module.</para>
00676             <enumlist>
00677                <enum name="load" />
00678                <enum name="unload" />
00679                <enum name="reload" />
00680             </enumlist>
00681             <para>If no module is specified for a <literal>reload</literal> loadtype,
00682             all modules are reloaded.</para>
00683          </parameter>
00684       </syntax>
00685       <description>
00686          <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
00687       </description>
00688    </manager>
00689    <manager name="ModuleCheck" language="en_US">
00690       <synopsis>
00691          Check if module is loaded.
00692       </synopsis>
00693       <syntax>
00694          <parameter name="Module" required="true">
00695             <para>Asterisk module name (not including extension).</para>
00696          </parameter>
00697       </syntax>
00698       <description>
00699          <para>Checks if Asterisk module is loaded. Will return Success/Failure.
00700          For success returns, the module revision number is included.</para>
00701       </description>
00702    </manager>
00703    <manager name="AOCMessage" language="en_US">
00704       <synopsis>
00705          Generate an Advice of Charge message on a channel.
00706       </synopsis>
00707       <syntax>
00708          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00709          <parameter name="Channel" required="true">
00710             <para>Channel name to generate the AOC message on.</para>
00711          </parameter>
00712          <parameter name="ChannelPrefix">
00713             <para>Partial channel prefix.  By using this option one can match the beginning part
00714             of a channel name without having to put the entire name in.  For example
00715             if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
00716             that channel matches and the message will be sent.  Note however that only
00717             the first matched channel has the message sent on it. </para>
00718          </parameter>
00719          <parameter name="MsgType" required="true">
00720             <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
00721             <enumlist>
00722                <enum name="D" />
00723                <enum name="E" />
00724             </enumlist>
00725          </parameter>
00726          <parameter name="ChargeType" required="true">
00727             <para>Defines what kind of charge this message represents.</para>
00728             <enumlist>
00729                <enum name="NA" />
00730                <enum name="FREE" />
00731                <enum name="Currency" />
00732                <enum name="Unit" />
00733             </enumlist>
00734          </parameter>
00735          <parameter name="UnitAmount(0)">
00736             <para>This represents the amount of units charged. The ETSI AOC standard specifies that
00737             this value along with the optional UnitType value are entries in a list.  To accommodate this
00738             these values take an index value starting at 0 which can be used to generate this list of
00739             unit entries.  For Example, If two unit entires were required this could be achieved by setting the
00740             paramter UnitAmount(0)=1234 and UnitAmount(1)=5678.  Note that UnitAmount at index 0 is
00741             required when ChargeType=Unit, all other entries in the list are optional.
00742             </para>
00743          </parameter>
00744          <parameter name="UnitType(0)">
00745             <para>Defines the type of unit.  ETSI AOC standard specifies this as an integer
00746             value between 1 and 16, but this value is left open to accept any positive
00747             integer.  Like the UnitAmount parameter, this value represents a list entry
00748             and has an index parameter that starts at 0.
00749             </para>
00750          </parameter>
00751          <parameter name="CurrencyName">
00752             <para>Specifies the currency's name.  Note that this value is truncated after 10 characters.</para>
00753          </parameter>
00754          <parameter name="CurrencyAmount">
00755             <para>Specifies the charge unit amount as a positive integer.  This value is required
00756             when ChargeType==Currency.</para>
00757          </parameter>
00758          <parameter name="CurrencyMultiplier">
00759             <para>Specifies the currency multiplier.  This value is required when ChargeType==Currency.</para>
00760             <enumlist>
00761                <enum name="OneThousandth" />
00762                <enum name="OneHundredth" />
00763                <enum name="OneTenth" />
00764                <enum name="One" />
00765                <enum name="Ten" />
00766                <enum name="Hundred" />
00767                <enum name="Thousand" />
00768             </enumlist>
00769          </parameter>
00770          <parameter name="TotalType" default="Total">
00771             <para>Defines what kind of AOC-D total is represented.</para>
00772             <enumlist>
00773                <enum name="Total" />
00774                <enum name="SubTotal" />
00775             </enumlist>
00776          </parameter>
00777          <parameter name="AOCBillingId">
00778             <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
00779             that only the first 3 items of the enum are valid AOC-D billing IDs</para>
00780             <enumlist>
00781                <enum name="Normal" />
00782                <enum name="ReverseCharge" />
00783                <enum name="CreditCard" />
00784                <enum name="CallFwdUnconditional" />
00785                <enum name="CallFwdBusy" />
00786                <enum name="CallFwdNoReply" />
00787                <enum name="CallDeflection" />
00788                <enum name="CallTransfer" />
00789             </enumlist>
00790          </parameter>
00791          <parameter name="ChargingAssociationId">
00792             <para>Charging association identifier.  This is optional for AOC-E and can be
00793             set to any value between -32768 and 32767</para>
00794          </parameter>
00795          <parameter name="ChargingAssociationNumber">
00796             <para>Represents the charging association party number.  This value is optional
00797             for AOC-E.</para>
00798          </parameter>
00799          <parameter name="ChargingAssociationPlan">
00800             <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
00801             The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
00802             numbering-plan-identification fields.</para>
00803          </parameter>
00804       </syntax>
00805       <description>
00806          <para>Generates an AOC-D or AOC-E message on a channel.</para>
00807       </description>
00808    </manager>
00809  ***/
00810 
00811 enum error_type {
00812    UNKNOWN_ACTION = 1,
00813    UNKNOWN_CATEGORY,
00814    UNSPECIFIED_CATEGORY,
00815    UNSPECIFIED_ARGUMENT,
00816    FAILURE_ALLOCATION,
00817    FAILURE_NEWCAT,
00818    FAILURE_DELCAT,
00819    FAILURE_EMPTYCAT,
00820    FAILURE_UPDATE,
00821    FAILURE_DELETE,
00822    FAILURE_APPEND
00823 };
00824 
00825 
00826 /*!
00827  * Linked list of events.
00828  * Global events are appended to the list by append_event().
00829  * The usecount is the number of stored pointers to the element,
00830  * excluding the list pointers. So an element that is only in
00831  * the list has a usecount of 0, not 1.
00832  *
00833  * Clients have a pointer to the last event processed, and for each
00834  * of these clients we track the usecount of the elements.
00835  * If we have a pointer to an entry in the list, it is safe to navigate
00836  * it forward because elements will not be deleted, but only appended.
00837  * The worst that can happen is seeing the pointer still NULL.
00838  *
00839  * When the usecount of an element drops to 0, and the element is the
00840  * first in the list, we can remove it. Removal is done within the
00841  * main thread, which is woken up for the purpose.
00842  *
00843  * For simplicity of implementation, we make sure the list is never empty.
00844  */
00845 struct eventqent {
00846    int usecount;     /*!< # of clients who still need the event */
00847    int category;
00848    unsigned int seq; /*!< sequence number */
00849    struct timeval tv;  /*!< When event was allocated */
00850    AST_RWLIST_ENTRY(eventqent) eq_next;
00851    char eventdata[1];   /*!< really variable size, allocated by append_event() */
00852 };
00853 
00854 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
00855 
00856 static const int DEFAULT_ENABLED       = 0;  /*!< Default setting for manager to be enabled */
00857 static const int DEFAULT_WEBENABLED       = 0;  /*!< Default setting for the web interface to be enabled */
00858 static const int DEFAULT_BLOCKSOCKETS     = 0;  /*!< Default setting for block-sockets */
00859 static const int DEFAULT_DISPLAYCONNECTS  = 1;  /*!< Default setting for displaying manager connections */
00860 static const int DEFAULT_TIMESTAMPEVENTS  = 0;  /*!< Default setting for timestampevents */  
00861 static const int DEFAULT_HTTPTIMEOUT      = 60; /*!< Default manager http timeout */
00862 static const int DEFAULT_BROKENEVENTSACTION  = 0;  /*!< Default setting for brokeneventsaction */
00863 
00864 static int displayconnects;
00865 static int allowmultiplelogin = 1;
00866 static int timestampevents;
00867 static int httptimeout;
00868 static int broken_events_action;
00869 static int manager_enabled = 0;
00870 static int webmanager_enabled = 0;
00871 static char *manager_channelvars;
00872 
00873 #define DEFAULT_REALM      "asterisk"
00874 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
00875 
00876 static int block_sockets;
00877 
00878 static int manager_debug;  /*!< enable some debugging code in the manager */
00879 
00880 /*! \brief
00881  * Descriptor for a manager session, either on the AMI socket or over HTTP.
00882  *
00883  * \note
00884  * AMI session have managerid == 0; the entry is created upon a connect,
00885  * and destroyed with the socket.
00886  * HTTP sessions have managerid != 0, the value is used as a search key
00887  * to lookup sessions (using the mansession_id cookie, or nonce key from
00888  * Digest Authentication http header).
00889  */
00890 #define MAX_BLACKLIST_CMD_LEN 2
00891 static const struct {
00892    const char *words[AST_MAX_CMD_LEN];
00893 } command_blacklist[] = {
00894    {{ "module", "load", NULL }},
00895    {{ "module", "unload", NULL }},
00896    {{ "restart", "gracefully", NULL }},
00897 };
00898 
00899 /* In order to understand what the heck is going on with the
00900  * mansession_session and mansession structs, we need to have a bit of a history
00901  * lesson.
00902  *
00903  * In the beginning, there was the mansession. The mansession contained data that was
00904  * intrinsic to a manager session, such as the time that it started, the name of the logged-in
00905  * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
00906  * sessions, these were used to represent the TCP socket over which the AMI session was taking
00907  * place. It makes perfect sense for these fields to be a part of the session-specific data since
00908  * the session actually defines this information.
00909  *
00910  * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
00911  * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
00912  * but rather to the action that is being executed. Because a single session may execute many commands
00913  * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
00914  * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
00915  * has had a chance to properly close its handles.
00916  *
00917  * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
00918  * from being run at the same time in a single session. Some manager actions may block for a long time, thus
00919  * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
00920  * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
00921  * part of the action instead.
00922  *
00923  * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
00924  * contain the action-specific information, such as which file to write to. In order to maintain expectations
00925  * of action handlers and not have to change the public API of the manager code, we would need to name this
00926  * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
00927  * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
00928  * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
00929  * data.
00930  */
00931 struct mansession_session {
00932    pthread_t ms_t;      /*!< Execution thread, basically useless */
00933             /* XXX need to document which fields it is protecting */
00934    struct sockaddr_in sin; /*!< address we are connecting from */
00935    FILE *f;    /*!< fdopen() on the underlying fd */
00936    int fd;        /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
00937    int inuse;     /*!< number of HTTP sessions using this entry */
00938    int needdestroy;  /*!< Whether an HTTP session should be destroyed */
00939    pthread_t waiting_thread;  /*!< Sleeping thread using this descriptor */
00940    uint32_t managerid;  /*!< Unique manager identifier, 0 for AMI sessions */
00941    time_t sessionstart;    /*!< Session start time */
00942    struct timeval sessionstart_tv; /*!< Session start time */
00943    time_t sessiontimeout;  /*!< Session timeout if HTTP */
00944    char username[80];   /*!< Logged in username */
00945    char challenge[10];  /*!< Authentication challenge */
00946    int authenticated;   /*!< Authentication status */
00947    int readperm;     /*!< Authorization for reading */
00948    int writeperm;    /*!< Authorization for writing */
00949    char inbuf[1025]; /*!< Buffer */
00950             /* we use the extra byte to add a '\0' and simplify parsing */
00951    int inlen;     /*!< number of buffered bytes */
00952    int send_events;  /*!<  XXX what ? */
00953    struct eventqent *last_ev; /*!< last event processed. */
00954    int writetimeout; /*!< Timeout for ast_carefulwrite() */
00955    int pending_event;         /*!< Pending events indicator in case when waiting_thread is NULL */
00956    time_t noncetime; /*!< Timer for nonce value expiration */
00957    struct ao2_container *whitefilters;
00958    struct ao2_container *blackfilters;
00959    unsigned long oldnonce; /*!< Stale nonce value */
00960    unsigned long nc; /*!< incremental  nonce counter */
00961    AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
00962    AST_LIST_ENTRY(mansession_session) list;
00963 };
00964 
00965 /* In case you didn't read that giant block of text above the mansession_session struct, the
00966  * 'mansession' struct is named this solely to keep the API the same in Asterisk. This structure really
00967  * represents data that is different from Manager action to Manager action. The mansession_session pointer
00968  * contained within points to session-specific data.
00969  */
00970 struct mansession {
00971    struct mansession_session *session;
00972    struct ast_tcptls_session_instance *tcptls_session;
00973    FILE *f;
00974    int fd;
00975    struct manager_custom_hook *hook;
00976    ast_mutex_t lock;
00977 };
00978 
00979 static struct ao2_container *sessions = NULL;
00980 
00981 struct manager_channel_variable {
00982    AST_LIST_ENTRY(manager_channel_variable) entry;
00983    unsigned int isfunc:1;
00984    char name[0]; /* allocate off the end the real size. */
00985 };
00986 
00987 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
00988 
00989 /*! \brief user descriptor, as read from the config file.
00990  *
00991  * \note It is still missing some fields -- e.g. we can have multiple permit and deny
00992  * lines which are not supported here, and readperm/writeperm/writetimeout
00993  * are not stored.
00994  */
00995 struct ast_manager_user {
00996    char username[80];
00997    char *secret;
00998    struct ast_ha *ha;      /*!< ACL setting */
00999    int readperm;        /*! Authorization for reading */
01000    int writeperm;       /*! Authorization for writing */
01001    int writetimeout;    /*! Per user Timeout for ast_carefulwrite() */
01002    int displayconnects;    /*!< XXX unused */
01003    int keep;         /*!< mark entries created on a reload */
01004    struct ao2_container *whitefilters;
01005    struct ao2_container *blackfilters;
01006    char *a1_hash;       /*!< precalculated A1 for Digest auth */
01007    AST_RWLIST_ENTRY(ast_manager_user) list;
01008 };
01009 
01010 /*! \brief list of users found in the config file */
01011 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
01012 
01013 /*! \brief list of actions registered */
01014 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
01015 
01016 /*! \brief list of hooks registered */
01017 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
01018 
01019 static void free_channelvars(void);
01020 
01021 /*! \brief Add a custom hook to be called when an event is fired */
01022 void ast_manager_register_hook(struct manager_custom_hook *hook)
01023 {
01024    AST_RWLIST_WRLOCK(&manager_hooks);
01025    AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
01026    AST_RWLIST_UNLOCK(&manager_hooks);
01027 }
01028 
01029 /*! \brief Delete a custom hook to be called when an event is fired */
01030 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
01031 {
01032    AST_RWLIST_WRLOCK(&manager_hooks);
01033    AST_RWLIST_REMOVE(&manager_hooks, hook, list);
01034    AST_RWLIST_UNLOCK(&manager_hooks);
01035 }
01036 
01037 int check_manager_enabled()
01038 {
01039    return manager_enabled;
01040 }
01041 
01042 int check_webmanager_enabled()
01043 {
01044    return (webmanager_enabled && manager_enabled);
01045 }
01046 
01047 /*!
01048  * Grab a reference to the last event, update usecount as needed.
01049  * Can handle a NULL pointer.
01050  */
01051 static struct eventqent *grab_last(void)
01052 {
01053    struct eventqent *ret;
01054 
01055    AST_RWLIST_WRLOCK(&all_events);
01056    ret = AST_RWLIST_LAST(&all_events);
01057    /* the list is never empty now, but may become so when
01058     * we optimize it in the future, so be prepared.
01059     */
01060    if (ret) {
01061       ast_atomic_fetchadd_int(&ret->usecount, 1);
01062    }
01063    AST_RWLIST_UNLOCK(&all_events);
01064    return ret;
01065 }
01066 
01067 /*!
01068  * Purge unused events. Remove elements from the head
01069  * as long as their usecount is 0 and there is a next element.
01070  */
01071 static void purge_events(void)
01072 {
01073    struct eventqent *ev;
01074    struct timeval now = ast_tvnow();
01075 
01076    AST_RWLIST_WRLOCK(&all_events);
01077    while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
01078        ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
01079       AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
01080       ast_free(ev);
01081    }
01082 
01083    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
01084       /* Never release the last event */
01085       if (!AST_RWLIST_NEXT(ev, eq_next)) {
01086          break;
01087       }
01088 
01089       /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
01090       if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
01091          AST_RWLIST_REMOVE_CURRENT(eq_next);
01092          ast_free(ev);
01093       }
01094    }
01095    AST_RWLIST_TRAVERSE_SAFE_END;
01096    AST_RWLIST_UNLOCK(&all_events);
01097 }
01098 
01099 /*!
01100  * helper functions to convert back and forth between
01101  * string and numeric representation of set of flags
01102  */
01103 static const struct permalias {
01104    int num;
01105    const char *label;
01106 } perms[] = {
01107    { EVENT_FLAG_SYSTEM, "system" },
01108    { EVENT_FLAG_CALL, "call" },
01109    { EVENT_FLAG_LOG, "log" },
01110    { EVENT_FLAG_VERBOSE, "verbose" },
01111    { EVENT_FLAG_COMMAND, "command" },
01112    { EVENT_FLAG_AGENT, "agent" },
01113    { EVENT_FLAG_USER, "user" },
01114    { EVENT_FLAG_CONFIG, "config" },
01115    { EVENT_FLAG_DTMF, "dtmf" },
01116    { EVENT_FLAG_REPORTING, "reporting" },
01117    { EVENT_FLAG_CDR, "cdr" },
01118    { EVENT_FLAG_DIALPLAN, "dialplan" },
01119    { EVENT_FLAG_ORIGINATE, "originate" },
01120    { EVENT_FLAG_AGI, "agi" },
01121    { EVENT_FLAG_CC, "cc" },
01122    { EVENT_FLAG_AOC, "aoc" },
01123    { INT_MAX, "all" },
01124    { 0, "none" },
01125 };
01126 
01127 /*! \brief Convert authority code to a list of options */
01128 static const char *authority_to_str(int authority, struct ast_str **res)
01129 {
01130    int i;
01131    char *sep = "";
01132 
01133    ast_str_reset(*res);
01134    for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
01135       if (authority & perms[i].num) {
01136          ast_str_append(res, 0, "%s%s", sep, perms[i].label);
01137          sep = ",";
01138       }
01139    }
01140 
01141    if (ast_str_strlen(*res) == 0)   /* replace empty string with something sensible */
01142       ast_str_append(res, 0, "<none>");
01143 
01144    return ast_str_buffer(*res);
01145 }
01146 
01147 /*! Tells you if smallstr exists inside bigstr
01148    which is delim by delim and uses no buf or stringsep
01149    ast_instring("this|that|more","this",'|') == 1;
01150 
01151    feel free to move this to app.c -anthm */
01152 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
01153 {
01154    const char *val = bigstr, *next;
01155 
01156    do {
01157       if ((next = strchr(val, delim))) {
01158          if (!strncmp(val, smallstr, (next - val))) {
01159             return 1;
01160          } else {
01161             continue;
01162          }
01163       } else {
01164          return !strcmp(smallstr, val);
01165       }
01166    } while (*(val = (next + 1)));
01167 
01168    return 0;
01169 }
01170 
01171 static int get_perm(const char *instr)
01172 {
01173    int x = 0, ret = 0;
01174 
01175    if (!instr) {
01176       return 0;
01177    }
01178 
01179    for (x = 0; x < ARRAY_LEN(perms); x++) {
01180       if (ast_instring(instr, perms[x].label, ',')) {
01181          ret |= perms[x].num;
01182       }
01183    }
01184 
01185    return ret;
01186 }
01187 
01188 /*!
01189  * A number returns itself, false returns 0, true returns all flags,
01190  * other strings return the flags that are set.
01191  */
01192 static int strings_to_mask(const char *string)
01193 {
01194    const char *p;
01195 
01196    if (ast_strlen_zero(string)) {
01197       return -1;
01198    }
01199 
01200    for (p = string; *p; p++) {
01201       if (*p < '0' || *p > '9') {
01202          break;
01203       }
01204    }
01205    if (!*p) { /* all digits */
01206       return atoi(string);
01207    }
01208    if (ast_false(string)) {
01209       return 0;
01210    }
01211    if (ast_true(string)) { /* all permissions */
01212       int x, ret = 0;
01213       for (x = 0; x < ARRAY_LEN(perms); x++) {
01214          ret |= perms[x].num;
01215       }
01216       return ret;
01217    }
01218    return get_perm(string);
01219 }
01220 
01221 /*! \brief Unreference manager session object.
01222      If no more references, then go ahead and delete it */
01223 static struct mansession_session *unref_mansession(struct mansession_session *s)
01224 {
01225    int refcount = ao2_ref(s, -1);
01226         if (manager_debug) {
01227       ast_log(LOG_DEBUG, "Mansession: %p refcount now %d\n", s, refcount - 1);
01228    }
01229    return s;
01230 }
01231 
01232 static void event_filter_destructor(void *obj)
01233 {
01234    regex_t *regex_filter = obj;
01235    regfree(regex_filter);
01236 }
01237 
01238 static void session_destructor(void *obj)
01239 {
01240    struct mansession_session *session = obj;
01241    struct eventqent *eqe = session->last_ev;
01242    struct ast_datastore *datastore;
01243 
01244    /* Get rid of each of the data stores on the session */
01245    while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
01246       /* Free the data store */
01247       ast_datastore_free(datastore);
01248    }
01249 
01250    if (session->f != NULL) {
01251       fclose(session->f);
01252    }
01253    if (eqe) {
01254       ast_atomic_fetchadd_int(&eqe->usecount, -1);
01255    }
01256 
01257    if (session->whitefilters) {
01258       ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
01259       ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
01260    }
01261 
01262    if (session->blackfilters) {
01263       ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
01264       ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
01265    }
01266 }
01267 
01268 /*! \brief Allocate manager session structure and add it to the list of sessions */
01269 static struct mansession_session *build_mansession(struct sockaddr_in sin)
01270 {
01271    struct mansession_session *newsession;
01272 
01273    if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
01274       return NULL;
01275    }
01276 
01277    if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
01278       ao2_ref(newsession, -1);
01279       return NULL;
01280    }
01281 
01282    if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
01283       ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
01284       return NULL;
01285    }
01286 
01287    newsession->fd = -1;
01288    newsession->waiting_thread = AST_PTHREADT_NULL;
01289    newsession->writetimeout = 100;
01290    newsession->send_events = -1;
01291    newsession->sin = sin;
01292 
01293    ao2_link(sessions, newsession);
01294 
01295    return newsession;
01296 }
01297 
01298 static int mansession_cmp_fn(void *obj, void *arg, int flags)
01299 {
01300    struct mansession_session *s = obj;
01301    char *str = arg;
01302    return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
01303 }
01304 
01305 static void session_destroy(struct mansession_session *s)
01306 {
01307    unref_mansession(s);
01308    ao2_unlink(sessions, s);
01309 }
01310 
01311 
01312 static int check_manager_session_inuse(const char *name)
01313 {
01314    struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
01315    int inuse = 0;
01316 
01317    if (session) {
01318       inuse = 1;
01319       unref_mansession(session);
01320    }
01321    return inuse;
01322 }
01323 
01324 
01325 /*!
01326  * lookup an entry in the list of registered users.
01327  * must be called with the list lock held.
01328  */
01329 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
01330 {
01331    struct ast_manager_user *user = NULL;
01332 
01333    AST_RWLIST_TRAVERSE(&users, user, list) {
01334       if (!strcasecmp(user->username, name)) {
01335          break;
01336       }
01337    }
01338 
01339    return user;
01340 }
01341 
01342 /*! \brief Get displayconnects config option.
01343  *  \param session manager session to get parameter from.
01344  *  \return displayconnects config option value.
01345  */
01346 static int manager_displayconnects (struct mansession_session *session)
01347 {
01348    struct ast_manager_user *user = NULL;
01349    int ret = 0;
01350 
01351    AST_RWLIST_RDLOCK(&users);
01352    if ((user = get_manager_by_name_locked (session->username))) {
01353       ret = user->displayconnects;
01354    }
01355    AST_RWLIST_UNLOCK(&users);
01356 
01357    return ret;
01358 }
01359 
01360 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01361 {
01362    struct manager_action *cur;
01363    struct ast_str *authority;
01364    int num, l, which;
01365    char *ret = NULL;
01366 #ifdef AST_XML_DOCS
01367    char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
01368 #endif
01369 
01370    switch (cmd) {
01371    case CLI_INIT:
01372       e->command = "manager show command";
01373       e->usage =
01374          "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
01375          "  Shows the detailed description for a specific Asterisk manager interface command.\n";
01376       return NULL;
01377    case CLI_GENERATE:
01378       l = strlen(a->word);
01379       which = 0;
01380       AST_RWLIST_RDLOCK(&actions);
01381       AST_RWLIST_TRAVERSE(&actions, cur, list) {
01382          if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
01383             ret = ast_strdup(cur->action);
01384             break;   /* make sure we exit even if ast_strdup() returns NULL */
01385          }
01386       }
01387       AST_RWLIST_UNLOCK(&actions);
01388       return ret;
01389    }
01390    authority = ast_str_alloca(80);
01391    if (a->argc < 4) {
01392       return CLI_SHOWUSAGE;
01393    }
01394 
01395 #ifdef AST_XML_DOCS
01396    /* setup the titles */
01397    term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
01398    term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
01399    term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
01400    term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
01401    term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
01402 #endif
01403 
01404    AST_RWLIST_RDLOCK(&actions);
01405    AST_RWLIST_TRAVERSE(&actions, cur, list) {
01406       for (num = 3; num < a->argc; num++) {
01407          if (!strcasecmp(cur->action, a->argv[num])) {
01408 #ifdef AST_XML_DOCS
01409             if (cur->docsrc == AST_XML_DOC) {
01410                ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
01411                   syntax_title,
01412                   ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
01413                   synopsis_title,
01414                   ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
01415                   description_title,
01416                   ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
01417                   arguments_title,
01418                   ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
01419                   seealso_title,
01420                   ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1));
01421             } else {
01422 #endif
01423                ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
01424                      cur->action, cur->synopsis,
01425                      authority_to_str(cur->authority, &authority),
01426                      S_OR(cur->description, ""));
01427 #ifdef AST_XML_DOCS
01428             }
01429 #endif
01430          }
01431       }
01432    }
01433    AST_RWLIST_UNLOCK(&actions);
01434 
01435    return CLI_SUCCESS;
01436 }
01437 
01438 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01439 {
01440    switch (cmd) {
01441    case CLI_INIT:
01442       e->command = "manager set debug [on|off]";
01443       e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
01444       return NULL;
01445    case CLI_GENERATE:
01446       return NULL;
01447    }
01448 
01449    if (a->argc == 3) {
01450       ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
01451    } else if (a->argc == 4) {
01452       if (!strcasecmp(a->argv[3], "on")) {
01453          manager_debug = 1;
01454       } else if (!strcasecmp(a->argv[3], "off")) {
01455          manager_debug = 0;
01456       } else {
01457          return CLI_SHOWUSAGE;
01458       }
01459    }
01460    return CLI_SUCCESS;
01461 }
01462 
01463 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01464 {
01465    struct ast_manager_user *user = NULL;
01466    int l, which;
01467    char *ret = NULL;
01468    struct ast_str *rauthority = ast_str_alloca(128);
01469    struct ast_str *wauthority = ast_str_alloca(128);
01470 
01471    switch (cmd) {
01472    case CLI_INIT:
01473       e->command = "manager show user";
01474       e->usage =
01475          " Usage: manager show user <user>\n"
01476          "        Display all information related to the manager user specified.\n";
01477       return NULL;
01478    case CLI_GENERATE:
01479       l = strlen(a->word);
01480       which = 0;
01481       if (a->pos != 3) {
01482          return NULL;
01483       }
01484       AST_RWLIST_RDLOCK(&users);
01485       AST_RWLIST_TRAVERSE(&users, user, list) {
01486          if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
01487             ret = ast_strdup(user->username);
01488             break;
01489          }
01490       }
01491       AST_RWLIST_UNLOCK(&users);
01492       return ret;
01493    }
01494 
01495    if (a->argc != 4) {
01496       return CLI_SHOWUSAGE;
01497    }
01498 
01499    AST_RWLIST_RDLOCK(&users);
01500 
01501    if (!(user = get_manager_by_name_locked(a->argv[3]))) {
01502       ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
01503       AST_RWLIST_UNLOCK(&users);
01504       return CLI_SUCCESS;
01505    }
01506 
01507    ast_cli(a->fd, "\n");
01508    ast_cli(a->fd,
01509       "       username: %s\n"
01510       "         secret: %s\n"
01511       "            acl: %s\n"
01512       "      read perm: %s\n"
01513       "     write perm: %s\n"
01514       "displayconnects: %s\n",
01515       (user->username ? user->username : "(N/A)"),
01516       (user->secret ? "<Set>" : "(N/A)"),
01517       (user->ha ? "yes" : "no"),
01518       authority_to_str(user->readperm, &rauthority),
01519       authority_to_str(user->writeperm, &wauthority),
01520       (user->displayconnects ? "yes" : "no"));
01521 
01522    AST_RWLIST_UNLOCK(&users);
01523 
01524    return CLI_SUCCESS;
01525 }
01526 
01527 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01528 {
01529    struct ast_manager_user *user = NULL;
01530    int count_amu = 0;
01531    switch (cmd) {
01532    case CLI_INIT:
01533       e->command = "manager show users";
01534       e->usage =
01535          "Usage: manager show users\n"
01536          "       Prints a listing of all managers that are currently configured on that\n"
01537          " system.\n";
01538       return NULL;
01539    case CLI_GENERATE:
01540       return NULL;
01541    }
01542    if (a->argc != 3) {
01543       return CLI_SHOWUSAGE;
01544    }
01545 
01546    AST_RWLIST_RDLOCK(&users);
01547 
01548    /* If there are no users, print out something along those lines */
01549    if (AST_RWLIST_EMPTY(&users)) {
01550       ast_cli(a->fd, "There are no manager users.\n");
01551       AST_RWLIST_UNLOCK(&users);
01552       return CLI_SUCCESS;
01553    }
01554 
01555    ast_cli(a->fd, "\nusername\n--------\n");
01556 
01557    AST_RWLIST_TRAVERSE(&users, user, list) {
01558       ast_cli(a->fd, "%s\n", user->username);
01559       count_amu++;
01560    }
01561 
01562    AST_RWLIST_UNLOCK(&users);
01563 
01564    ast_cli(a->fd,"-------------------\n"
01565             "%d manager users configured.\n", count_amu);
01566    return CLI_SUCCESS;
01567 }
01568 
01569 /*! \brief  CLI command  manager list commands */
01570 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01571 {
01572    struct manager_action *cur;
01573    struct ast_str *authority;
01574 #define HSMC_FORMAT "  %-15.15s  %-15.15s  %-55.55s\n"
01575    switch (cmd) {
01576    case CLI_INIT:
01577       e->command = "manager show commands";
01578       e->usage =
01579          "Usage: manager show commands\n"
01580          "  Prints a listing of all the available Asterisk manager interface commands.\n";
01581       return NULL;
01582    case CLI_GENERATE:
01583       return NULL;
01584    }
01585    authority = ast_str_alloca(80);
01586    ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
01587    ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
01588 
01589    AST_RWLIST_RDLOCK(&actions);
01590    AST_RWLIST_TRAVERSE(&actions, cur, list)
01591       ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
01592    AST_RWLIST_UNLOCK(&actions);
01593 
01594    return CLI_SUCCESS;
01595 }
01596 
01597 /*! \brief CLI command manager list connected */
01598 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01599 {
01600    struct mansession_session *session;
01601    time_t now = time(NULL);
01602 #define HSMCONN_FORMAT1 "  %-15.15s  %-15.15s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
01603 #define HSMCONN_FORMAT2 "  %-15.15s  %-15.15s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
01604    int count = 0;
01605    struct ao2_iterator i;
01606 
01607    switch (cmd) {
01608    case CLI_INIT:
01609       e->command = "manager show connected";
01610       e->usage =
01611          "Usage: manager show connected\n"
01612          "  Prints a listing of the users that are currently connected to the\n"
01613          "Asterisk manager interface.\n";
01614       return NULL;
01615    case CLI_GENERATE:
01616       return NULL;
01617    }
01618 
01619    ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
01620 
01621    i = ao2_iterator_init(sessions, 0);
01622    while ((session = ao2_iterator_next(&i))) {
01623       ao2_lock(session);
01624       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);
01625       count++;
01626       ao2_unlock(session);
01627       unref_mansession(session);
01628    }
01629    ao2_iterator_destroy(&i);
01630    ast_cli(a->fd, "%d users connected.\n", count);
01631 
01632    return CLI_SUCCESS;
01633 }
01634 
01635 /*! \brief CLI command manager list eventq */
01636 /* Should change to "manager show connected" */
01637 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01638 {
01639    struct eventqent *s;
01640    switch (cmd) {
01641    case CLI_INIT:
01642       e->command = "manager show eventq";
01643       e->usage =
01644          "Usage: manager show eventq\n"
01645          "  Prints a listing of all events pending in the Asterisk manger\n"
01646          "event queue.\n";
01647       return NULL;
01648    case CLI_GENERATE:
01649       return NULL;
01650    }
01651    AST_RWLIST_RDLOCK(&all_events);
01652    AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
01653       ast_cli(a->fd, "Usecount: %d\n", s->usecount);
01654       ast_cli(a->fd, "Category: %d\n", s->category);
01655       ast_cli(a->fd, "Event:\n%s", s->eventdata);
01656    }
01657    AST_RWLIST_UNLOCK(&all_events);
01658 
01659    return CLI_SUCCESS;
01660 }
01661 
01662 /*! \brief CLI command manager reload */
01663 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01664 {
01665    switch (cmd) {
01666    case CLI_INIT:
01667       e->command = "manager reload";
01668       e->usage =
01669          "Usage: manager reload\n"
01670          "       Reloads the manager configuration.\n";
01671       return NULL;
01672    case CLI_GENERATE:
01673       return NULL;
01674    }
01675    if (a->argc > 2) {
01676       return CLI_SHOWUSAGE;
01677    }
01678    reload_manager();
01679    return CLI_SUCCESS;
01680 }
01681 
01682 static struct eventqent *advance_event(struct eventqent *e)
01683 {
01684    struct eventqent *next;
01685 
01686    AST_RWLIST_RDLOCK(&all_events);
01687    if ((next = AST_RWLIST_NEXT(e, eq_next))) {
01688       ast_atomic_fetchadd_int(&next->usecount, 1);
01689       ast_atomic_fetchadd_int(&e->usecount, -1);
01690    }
01691    AST_RWLIST_UNLOCK(&all_events);
01692    return next;
01693 }
01694 
01695 /*
01696  * Generic function to return either the first or the last matching header
01697  * from a list of variables, possibly skipping empty strings.
01698  * At the moment there is only one use of this function in this file,
01699  * so we make it static.
01700  */
01701 #define  GET_HEADER_FIRST_MATCH  0
01702 #define  GET_HEADER_LAST_MATCH   1
01703 #define  GET_HEADER_SKIP_EMPTY   2
01704 static const char *__astman_get_header(const struct message *m, char *var, int mode)
01705 {
01706    int x, l = strlen(var);
01707    const char *result = "";
01708 
01709    for (x = 0; x < m->hdrcount; x++) {
01710       const char *h = m->headers[x];
01711       if (!strncasecmp(var, h, l) && h[l] == ':') {
01712          const char *value = h + l + 1;
01713          value = ast_skip_blanks(value); /* ignore leading spaces in the value */
01714          /* found a potential candidate */
01715          if (mode & GET_HEADER_SKIP_EMPTY && ast_strlen_zero(value))
01716             continue;   /* not interesting */
01717          if (mode & GET_HEADER_LAST_MATCH)
01718             result = value;   /* record the last match so far */
01719          else
01720             return value;
01721       }
01722    }
01723 
01724    return "";
01725 }
01726 
01727 /*
01728  * Return the first matching variable from an array.
01729  * This is the legacy function and is implemented in therms of
01730  * __astman_get_header().
01731  */
01732 const char *astman_get_header(const struct message *m, char *var)
01733 {
01734    return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
01735 }
01736 
01737 
01738 struct ast_variable *astman_get_variables(const struct message *m)
01739 {
01740    int varlen, x, y;
01741    struct ast_variable *head = NULL, *cur;
01742 
01743    AST_DECLARE_APP_ARGS(args,
01744       AST_APP_ARG(vars)[32];
01745    );
01746 
01747    varlen = strlen("Variable: ");
01748 
01749    for (x = 0; x < m->hdrcount; x++) {
01750       char *parse, *var, *val;
01751 
01752       if (strncasecmp("Variable: ", m->headers[x], varlen)) {
01753          continue;
01754       }
01755       parse = ast_strdupa(m->headers[x] + varlen);
01756 
01757       AST_STANDARD_APP_ARGS(args, parse);
01758       if (!args.argc) {
01759          continue;
01760       }
01761       for (y = 0; y < args.argc; y++) {
01762          if (!args.vars[y]) {
01763             continue;
01764          }
01765          var = val = ast_strdupa(args.vars[y]);
01766          strsep(&val, "=");
01767          if (!val || ast_strlen_zero(var)) {
01768             continue;
01769          }
01770          cur = ast_variable_new(var, val, "");
01771          cur->next = head;
01772          head = cur;
01773       }
01774    }
01775 
01776    return head;
01777 }
01778 
01779 /* access for hooks to send action messages to ami */
01780 
01781 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
01782 {
01783    const char *action;
01784    int ret = 0;
01785    struct manager_action *tmp;
01786    struct mansession s = {.session = NULL, };
01787    struct message m = { 0 };
01788    char header_buf[1025] = { '\0' };
01789    const char *src = msg;
01790    int x = 0;
01791    int curlen;
01792 
01793    if (hook == NULL) {
01794       return -1;
01795    }
01796 
01797    /* convert msg string to message struct */
01798    curlen = strlen(msg);
01799    for (x = 0; x < curlen; x++) {
01800       int cr;  /* set if we have \r */
01801       if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
01802          cr = 2;  /* Found. Update length to include \r\n */
01803       else if (src[x] == '\n')
01804          cr = 1;  /* also accept \n only */
01805       else
01806          continue;
01807       /* don't copy empty lines */
01808       if (x) {
01809          memmove(header_buf, src, x);  /*... but trim \r\n */
01810          header_buf[x] = '\0';      /* terminate the string */
01811          m.headers[m.hdrcount++] = ast_strdupa(header_buf);
01812       }
01813       x += cr;
01814       curlen -= x;      /* remaining size */
01815       src += x;      /* update pointer */
01816       x = -1;        /* reset loop */
01817    }
01818 
01819    action = astman_get_header(&m,"Action");
01820    if (action && strcasecmp(action,"login")) {
01821 
01822       AST_RWLIST_RDLOCK(&actions);
01823       AST_RWLIST_TRAVERSE(&actions, tmp, list) {
01824          if (strcasecmp(action, tmp->action))
01825             continue;
01826          /*
01827          * we have to simulate a session for this action request
01828          * to be able to pass it down for processing
01829          * This is necessary to meet the previous design of manager.c
01830          */
01831          s.hook = hook;
01832          s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
01833          ret = tmp->func(&s, &m);
01834          break;
01835       }
01836       AST_RWLIST_UNLOCK(&actions);
01837    }
01838    return ret;
01839 }
01840 
01841 
01842 /*!
01843  * helper function to send a string to the socket.
01844  * Return -1 on error (e.g. buffer full).
01845  */
01846 static int send_string(struct mansession *s, char *string)
01847 {
01848    /* It's a result from one of the hook's action invocation */
01849    if (s->hook) {
01850       /*
01851        * to send responses, we're using the same function
01852        * as for receiving events. We call the event "HookResponse"
01853        */
01854       s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
01855       return 0;
01856    } else if (s->f) {
01857       return ast_careful_fwrite(s->f, s->fd, string, strlen(string), s->session->writetimeout);
01858    } else {
01859       return ast_careful_fwrite(s->session->f, s->session->fd, string, strlen(string), s->session->writetimeout);
01860    }
01861 }
01862 
01863 /*!
01864  * \brief thread local buffer for astman_append
01865  *
01866  * \note This can not be defined within the astman_append() function
01867  *       because it declares a couple of functions that get used to
01868  *       initialize the thread local storage key.
01869  */
01870 AST_THREADSTORAGE(astman_append_buf);
01871 AST_THREADSTORAGE(userevent_buf);
01872 
01873 /*! \brief initial allocated size for the astman_append_buf */
01874 #define ASTMAN_APPEND_BUF_INITSIZE   256
01875 
01876 /*!
01877  * utility functions for creating AMI replies
01878  */
01879 void astman_append(struct mansession *s, const char *fmt, ...)
01880 {
01881    va_list ap;
01882    struct ast_str *buf;
01883 
01884    if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
01885       return;
01886    }
01887 
01888    va_start(ap, fmt);
01889    ast_str_set_va(&buf, 0, fmt, ap);
01890    va_end(ap);
01891 
01892    if (s->f != NULL || s->session->f != NULL) {
01893       send_string(s, ast_str_buffer(buf));
01894    } else {
01895       ast_verbose("fd == -1 in astman_append, should not happen\n");
01896    }
01897 }
01898 
01899 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
01900    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
01901    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
01902    be non-zero). In either of these cases, there is no need to lock-protect the session's
01903    fd, since no other output will be sent (events will be queued), and no input will
01904    be read until either the current action finishes or get_input() obtains the session
01905    lock.
01906  */
01907 
01908 /*! \brief send a response with an optional message,
01909  * and terminate it with an empty line.
01910  * m is used only to grab the 'ActionID' field.
01911  *
01912  * Use the explicit constant MSG_MOREDATA to remove the empty line.
01913  * XXX MSG_MOREDATA should go to a header file.
01914  */
01915 #define MSG_MOREDATA ((char *)astman_send_response)
01916 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
01917 {
01918    const char *id = astman_get_header(m, "ActionID");
01919 
01920    astman_append(s, "Response: %s\r\n", resp);
01921    if (!ast_strlen_zero(id)) {
01922       astman_append(s, "ActionID: %s\r\n", id);
01923    }
01924    if (listflag) {
01925       astman_append(s, "EventList: %s\r\n", listflag);   /* Start, complete, cancelled */
01926    }
01927    if (msg == MSG_MOREDATA) {
01928       return;
01929    } else if (msg) {
01930       astman_append(s, "Message: %s\r\n\r\n", msg);
01931    } else {
01932       astman_append(s, "\r\n");
01933    }
01934 }
01935 
01936 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
01937 {
01938    astman_send_response_full(s, m, resp, msg, NULL);
01939 }
01940 
01941 void astman_send_error(struct mansession *s, const struct message *m, char *error)
01942 {
01943    astman_send_response_full(s, m, "Error", error, NULL);
01944 }
01945 
01946 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
01947 {
01948    astman_send_response_full(s, m, "Success", msg, NULL);
01949 }
01950 
01951 static void astman_start_ack(struct mansession *s, const struct message *m)
01952 {
01953    astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
01954 }
01955 
01956 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
01957 {
01958    astman_send_response_full(s, m, "Success", msg, listflag);
01959 }
01960 
01961 /*! \brief Lock the 'mansession' structure. */
01962 static void mansession_lock(struct mansession *s)
01963 {
01964    ast_mutex_lock(&s->lock);
01965 }
01966 
01967 /*! \brief Unlock the 'mansession' structure. */
01968 static void mansession_unlock(struct mansession *s)
01969 {
01970    ast_mutex_unlock(&s->lock);
01971 }
01972 
01973 /*! \brief
01974    Rather than braindead on,off this now can also accept a specific int mask value
01975    or a ',' delim list of mask strings (the same as manager.conf) -anthm
01976 */
01977 static int set_eventmask(struct mansession *s, const char *eventmask)
01978 {
01979    int maskint = strings_to_mask(eventmask);
01980 
01981    ao2_lock(s->session);
01982    if (maskint >= 0) {
01983       s->session->send_events = maskint;
01984    }
01985    ao2_unlock(s->session);
01986 
01987    return maskint;
01988 }
01989 
01990 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
01991 {
01992    return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
01993          AST_SECURITY_EVENT_TRANSPORT_TCP;
01994 }
01995 
01996 static struct sockaddr_in *mansession_encode_sin_local(const struct mansession *s,
01997       struct sockaddr_in *sin_local)
01998 {
01999    ast_sockaddr_to_sin(&s->tcptls_session->parent->local_address,
02000              sin_local);
02001 
02002    return sin_local;
02003 }
02004 
02005 static void report_invalid_user(const struct mansession *s, const char *username)
02006 {
02007    struct sockaddr_in sin_local;
02008    char session_id[32];
02009    struct ast_security_event_inval_acct_id inval_acct_id = {
02010       .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
02011       .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
02012       .common.service    = "AMI",
02013       .common.account_id = username,
02014       .common.session_tv = &s->session->sessionstart_tv,
02015       .common.local_addr = {
02016          .sin       = mansession_encode_sin_local(s, &sin_local),
02017          .transport = mansession_get_transport(s),
02018       },
02019       .common.remote_addr = {
02020          .sin       = &s->session->sin,
02021          .transport = mansession_get_transport(s),
02022       },
02023       .common.session_id = session_id,
02024    };
02025 
02026    snprintf(session_id, sizeof(session_id), "%p", s);
02027 
02028    ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
02029 }
02030 
02031 static void report_failed_acl(const struct mansession *s, const char *username)
02032 {
02033    struct sockaddr_in sin_local;
02034    char session_id[32];
02035    struct ast_security_event_failed_acl failed_acl_event = {
02036       .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
02037       .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
02038       .common.service    = "AMI",
02039       .common.account_id = username,
02040       .common.session_tv = &s->session->sessionstart_tv,
02041       .common.local_addr = {
02042          .sin       = mansession_encode_sin_local(s, &sin_local),
02043          .transport = mansession_get_transport(s),
02044       },
02045       .common.remote_addr = {
02046          .sin       = &s->session->sin,
02047          .transport = mansession_get_transport(s),
02048       },
02049       .common.session_id = session_id,
02050    };
02051 
02052    snprintf(session_id, sizeof(session_id), "%p", s->session);
02053 
02054    ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
02055 }
02056 
02057 static void report_inval_password(const struct mansession *s, const char *username)
02058 {
02059    struct sockaddr_in sin_local;
02060    char session_id[32];
02061    struct ast_security_event_inval_password inval_password = {
02062       .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
02063       .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
02064       .common.service    = "AMI",
02065       .common.account_id = username,
02066       .common.session_tv = &s->session->sessionstart_tv,
02067       .common.local_addr = {
02068          .sin       = mansession_encode_sin_local(s, &sin_local),
02069          .transport = mansession_get_transport(s),
02070       },
02071       .common.remote_addr = {
02072          .sin       = &s->session->sin,
02073          .transport = mansession_get_transport(s),
02074       },
02075       .common.session_id = session_id,
02076    };
02077 
02078    snprintf(session_id, sizeof(session_id), "%p", s->session);
02079 
02080    ast_security_event_report(AST_SEC_EVT(&inval_password));
02081 }
02082 
02083 static void report_auth_success(const struct mansession *s)
02084 {
02085    struct sockaddr_in sin_local;
02086    char session_id[32];
02087    struct ast_security_event_successful_auth successful_auth = {
02088       .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
02089       .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
02090       .common.service    = "AMI",
02091       .common.account_id = s->session->username,
02092       .common.session_tv = &s->session->sessionstart_tv,
02093       .common.local_addr = {
02094          .sin       = mansession_encode_sin_local(s, &sin_local),
02095          .transport = mansession_get_transport(s),
02096       },
02097       .common.remote_addr = {
02098          .sin       = &s->session->sin,
02099          .transport = mansession_get_transport(s),
02100       },
02101       .common.session_id = session_id,
02102    };
02103 
02104    snprintf(session_id, sizeof(session_id), "%p", s->session);
02105 
02106    ast_security_event_report(AST_SEC_EVT(&successful_auth));
02107 }
02108 
02109 static void report_req_not_allowed(const struct mansession *s, const char *action)
02110 {
02111    struct sockaddr_in sin_local;
02112    char session_id[32];
02113    char request_type[64];
02114    struct ast_security_event_req_not_allowed req_not_allowed = {
02115       .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
02116       .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
02117       .common.service    = "AMI",
02118       .common.account_id = s->session->username,
02119       .common.session_tv = &s->session->sessionstart_tv,
02120       .common.local_addr = {
02121          .sin       = mansession_encode_sin_local(s, &sin_local),
02122          .transport = mansession_get_transport(s),
02123       },
02124       .common.remote_addr = {
02125          .sin       = &s->session->sin,
02126          .transport = mansession_get_transport(s),
02127       },
02128       .common.session_id = session_id,
02129 
02130       .request_type      = request_type,
02131    };
02132 
02133    snprintf(session_id, sizeof(session_id), "%p", s->session);
02134    snprintf(request_type, sizeof(request_type), "Action: %s", action);
02135 
02136    ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
02137 }
02138 
02139 static void report_req_bad_format(const struct mansession *s, const char *action)
02140 {
02141    struct sockaddr_in sin_local;
02142    char session_id[32];
02143    char request_type[64];
02144    struct ast_security_event_req_bad_format req_bad_format = {
02145       .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
02146       .common.version    = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
02147       .common.service    = "AMI",
02148       .common.account_id = s->session->username,
02149       .common.session_tv = &s->session->sessionstart_tv,
02150       .common.local_addr = {
02151          .sin       = mansession_encode_sin_local(s, &sin_local),
02152          .transport = mansession_get_transport(s),
02153       },
02154       .common.remote_addr = {
02155          .sin       = &s->session->sin,
02156          .transport = mansession_get_transport(s),
02157       },
02158       .common.session_id = session_id,
02159 
02160       .request_type      = request_type,
02161    };
02162 
02163    snprintf(session_id, sizeof(session_id), "%p", s->session);
02164    snprintf(request_type, sizeof(request_type), "Action: %s", action);
02165 
02166    ast_security_event_report(AST_SEC_EVT(&req_bad_format));
02167 }
02168 
02169 static void report_failed_challenge_response(const struct mansession *s,
02170       const char *response, const char *expected_response)
02171 {
02172    struct sockaddr_in sin_local;
02173    char session_id[32];
02174    struct ast_security_event_chal_resp_failed chal_resp_failed = {
02175       .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
02176       .common.version    = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
02177       .common.service    = "AMI",
02178       .common.account_id = s->session->username,
02179       .common.session_tv = &s->session->sessionstart_tv,
02180       .common.local_addr = {
02181          .sin       = mansession_encode_sin_local(s, &sin_local),
02182          .transport = mansession_get_transport(s),
02183       },
02184       .common.remote_addr = {
02185          .sin       = &s->session->sin,
02186          .transport = mansession_get_transport(s),
02187       },
02188       .common.session_id = session_id,
02189 
02190       .challenge         = s->session->challenge,
02191       .response          = response,
02192       .expected_response = expected_response,
02193    };
02194 
02195    snprintf(session_id, sizeof(session_id), "%p", s->session);
02196 
02197    ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
02198 }
02199 
02200 static void report_session_limit(const struct mansession *s)
02201 {
02202    struct sockaddr_in sin_local;
02203    char session_id[32];
02204    struct ast_security_event_session_limit session_limit = {
02205       .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
02206       .common.version    = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
02207       .common.service    = "AMI",
02208       .common.account_id = s->session->username,
02209       .common.session_tv = &s->session->sessionstart_tv,
02210       .common.local_addr = {
02211          .sin       = mansession_encode_sin_local(s, &sin_local),
02212          .transport = mansession_get_transport(s),
02213       },
02214       .common.remote_addr = {
02215          .sin       = &s->session->sin,
02216          .transport = mansession_get_transport(s),
02217       },
02218       .common.session_id = session_id,
02219    };
02220 
02221    snprintf(session_id, sizeof(session_id), "%p", s->session);
02222 
02223    ast_security_event_report(AST_SEC_EVT(&session_limit));
02224 }
02225 
02226 /*
02227  * Here we start with action_ handlers for AMI actions,
02228  * and the internal functions used by them.
02229  * Generally, the handlers are called action_foo()
02230  */
02231 
02232 /* helper function for action_login() */
02233 static int authenticate(struct mansession *s, const struct message *m)
02234 {
02235    const char *username = astman_get_header(m, "Username");
02236    const char *password = astman_get_header(m, "Secret");
02237    int error = -1;
02238    struct ast_manager_user *user = NULL;
02239    regex_t *regex_filter;
02240    struct ao2_iterator filter_iter;
02241    struct ast_sockaddr addr;
02242 
02243    if (ast_strlen_zero(username)) { /* missing username */
02244       return -1;
02245    }
02246 
02247    /* locate user in locked state */
02248    AST_RWLIST_WRLOCK(&users);
02249 
02250    ast_sockaddr_from_sin(&addr, &s->session->sin);
02251 
02252    if (!(user = get_manager_by_name_locked(username))) {
02253       report_invalid_user(s, username);
02254       ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
02255    } else if (user->ha && !ast_apply_ha(user->ha, &addr)) {
02256       report_failed_acl(s, username);
02257       ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
02258    } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
02259       const char *key = astman_get_header(m, "Key");
02260       if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
02261          int x;
02262          int len = 0;
02263          char md5key[256] = "";
02264          struct MD5Context md5;
02265          unsigned char digest[16];
02266 
02267          MD5Init(&md5);
02268          MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
02269          MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
02270          MD5Final(digest, &md5);
02271          for (x = 0; x < 16; x++)
02272             len += sprintf(md5key + len, "%2.2x", digest[x]);
02273          if (!strcmp(md5key, key)) {
02274             error = 0;
02275          } else {
02276             report_failed_challenge_response(s, key, md5key);
02277          }
02278       } else {
02279          ast_debug(1, "MD5 authentication is not possible.  challenge: '%s'\n",
02280             S_OR(s->session->challenge, ""));
02281       }
02282    } else if (user->secret) {
02283       if (!strcmp(password, user->secret)) {
02284          error = 0;
02285       } else {
02286          report_inval_password(s, username);
02287       }
02288    }
02289 
02290    if (error) {
02291       ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
02292       AST_RWLIST_UNLOCK(&users);
02293       return -1;
02294    }
02295 
02296    /* auth complete */
02297 
02298    /* All of the user parameters are copied to the session so that in the event
02299      * of a reload and a configuration change, the session parameters are not
02300      * changed. */
02301    ast_copy_string(s->session->username, username, sizeof(s->session->username));
02302    s->session->readperm = user->readperm;
02303    s->session->writeperm = user->writeperm;
02304    s->session->writetimeout = user->writetimeout;
02305 
02306    filter_iter = ao2_iterator_init(user->whitefilters, 0);
02307    while ((regex_filter = ao2_iterator_next(&filter_iter))) {
02308       ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
02309       ao2_t_ref(regex_filter, -1, "remove iterator ref");
02310    }
02311    ao2_iterator_destroy(&filter_iter);
02312 
02313    filter_iter = ao2_iterator_init(user->blackfilters, 0);
02314    while ((regex_filter = ao2_iterator_next(&filter_iter))) {
02315       ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
02316       ao2_t_ref(regex_filter, -1, "remove iterator ref");
02317    }
02318    ao2_iterator_destroy(&filter_iter);
02319 
02320    s->session->sessionstart = time(NULL);
02321    s->session->sessionstart_tv = ast_tvnow();
02322    set_eventmask(s, astman_get_header(m, "Events"));
02323 
02324    report_auth_success(s);
02325 
02326    AST_RWLIST_UNLOCK(&users);
02327    return 0;
02328 }
02329 
02330 static int action_ping(struct mansession *s, const struct message *m)
02331 {
02332    const char *actionid = astman_get_header(m, "ActionID");
02333    struct timeval now = ast_tvnow();
02334 
02335    astman_append(s, "Response: Success\r\n");
02336    if (!ast_strlen_zero(actionid)){
02337       astman_append(s, "ActionID: %s\r\n", actionid);
02338    }
02339    astman_append(
02340       s,
02341       "Ping: Pong\r\n"
02342       "Timestamp: %ld.%06lu\r\n"
02343       "\r\n",
02344       (long) now.tv_sec, (unsigned long) now.tv_usec);
02345    return 0;
02346 }
02347 
02348 static int action_getconfig(struct mansession *s, const struct message *m)
02349 {
02350    struct ast_config *cfg;
02351    const char *fn = astman_get_header(m, "Filename");
02352    const char *category = astman_get_header(m, "Category");
02353    int catcount = 0;
02354    int lineno = 0;
02355    char *cur_category = NULL;
02356    struct ast_variable *v;
02357    struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02358 
02359    if (ast_strlen_zero(fn)) {
02360       astman_send_error(s, m, "Filename not specified");
02361       return 0;
02362    }
02363    cfg = ast_config_load2(fn, "manager", config_flags);
02364    if (cfg == CONFIG_STATUS_FILEMISSING) {
02365       astman_send_error(s, m, "Config file not found");
02366       return 0;
02367    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02368       astman_send_error(s, m, "Config file has invalid format");
02369       return 0;
02370    }
02371 
02372    astman_start_ack(s, m);
02373    while ((cur_category = ast_category_browse(cfg, cur_category))) {
02374       if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
02375          lineno = 0;
02376          astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
02377          for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
02378             astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
02379          }
02380          catcount++;
02381       }
02382    }
02383    if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
02384       astman_append(s, "No categories found\r\n");
02385    }
02386    ast_config_destroy(cfg);
02387    astman_append(s, "\r\n");
02388 
02389    return 0;
02390 }
02391 
02392 static int action_listcategories(struct mansession *s, const struct message *m)
02393 {
02394    struct ast_config *cfg;
02395    const char *fn = astman_get_header(m, "Filename");
02396    char *category = NULL;
02397    struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02398    int catcount = 0;
02399 
02400    if (ast_strlen_zero(fn)) {
02401       astman_send_error(s, m, "Filename not specified");
02402       return 0;
02403    }
02404    if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
02405       astman_send_error(s, m, "Config file not found");
02406       return 0;
02407    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02408       astman_send_error(s, m, "Config file has invalid format");
02409       return 0;
02410    }
02411    astman_start_ack(s, m);
02412    while ((category = ast_category_browse(cfg, category))) {
02413       astman_append(s, "Category-%06d: %s\r\n", catcount, category);
02414       catcount++;
02415    }
02416    if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
02417       astman_append(s, "Error: no categories found\r\n");
02418    }
02419    ast_config_destroy(cfg);
02420    astman_append(s, "\r\n");
02421 
02422    return 0;
02423 }
02424 
02425 
02426 
02427 
02428 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
02429 static void json_escape(char *out, const char *in)
02430 {
02431    for (; *in; in++) {
02432       if (*in == '\\' || *in == '\"') {
02433          *out++ = '\\';
02434       }
02435       *out++ = *in;
02436    }
02437    *out = '\0';
02438 }
02439 
02440 static int action_getconfigjson(struct mansession *s, const struct message *m)
02441 {
02442    struct ast_config *cfg;
02443    const char *fn = astman_get_header(m, "Filename");
02444    char *category = NULL;
02445    struct ast_variable *v;
02446    int comma1 = 0;
02447    char *buf = NULL;
02448    unsigned int buf_len = 0;
02449    struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02450 
02451    if (ast_strlen_zero(fn)) {
02452       astman_send_error(s, m, "Filename not specified");
02453       return 0;
02454    }
02455 
02456    if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
02457       astman_send_error(s, m, "Config file not found");
02458       return 0;
02459    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02460       astman_send_error(s, m, "Config file has invalid format");
02461       return 0;
02462    }
02463 
02464    buf_len = 512;
02465    buf = alloca(buf_len);
02466 
02467    astman_start_ack(s, m);
02468    astman_append(s, "JSON: {");
02469    while ((category = ast_category_browse(cfg, category))) {
02470       int comma2 = 0;
02471       if (buf_len < 2 * strlen(category) + 1) {
02472          buf_len *= 2;
02473          buf = alloca(buf_len);
02474       }
02475       json_escape(buf, category);
02476       astman_append(s, "%s\"%s\":[", comma1 ? "," : "", buf);
02477       if (!comma1) {
02478          comma1 = 1;
02479       }
02480       for (v = ast_variable_browse(cfg, category); v; v = v->next) {
02481          if (comma2) {
02482             astman_append(s, ",");
02483          }
02484          if (buf_len < 2 * strlen(v->name) + 1) {
02485             buf_len *= 2;
02486             buf = alloca(buf_len);
02487          }
02488          json_escape(buf, v->name);
02489          astman_append(s, "\"%s", buf);
02490          if (buf_len < 2 * strlen(v->value) + 1) {
02491             buf_len *= 2;
02492             buf = alloca(buf_len);
02493          }
02494          json_escape(buf, v->value);
02495          astman_append(s, "%s\"", buf);
02496          if (!comma2) {
02497             comma2 = 1;
02498          }
02499       }
02500       astman_append(s, "]");
02501    }
02502    astman_append(s, "}\r\n\r\n");
02503 
02504    ast_config_destroy(cfg);
02505 
02506    return 0;
02507 }
02508 
02509 /* helper function for action_updateconfig */
02510 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
02511 {
02512    int x;
02513    char hdr[40];
02514    const char *action, *cat, *var, *value, *match, *line;
02515    struct ast_category *category;
02516    struct ast_variable *v;
02517    struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
02518    enum error_type result = 0;
02519 
02520    for (x = 0; x < 100000; x++) {   /* 100000 = the max number of allowed updates + 1 */
02521       unsigned int object = 0;
02522 
02523       snprintf(hdr, sizeof(hdr), "Action-%06d", x);
02524       action = astman_get_header(m, hdr);
02525       if (ast_strlen_zero(action))     /* breaks the for loop if no action header */
02526          break;                        /* this could cause problems if actions come in misnumbered */
02527 
02528       snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
02529       cat = astman_get_header(m, hdr);
02530       if (ast_strlen_zero(cat)) {      /* every action needs a category */
02531          result =  UNSPECIFIED_CATEGORY;
02532          break;
02533       }
02534 
02535       snprintf(hdr, sizeof(hdr), "Var-%06d", x);
02536       var = astman_get_header(m, hdr);
02537 
02538       snprintf(hdr, sizeof(hdr), "Value-%06d", x);
02539       value = astman_get_header(m, hdr);
02540 
02541       if (!ast_strlen_zero(value) && *value == '>') {
02542          object = 1;
02543          value++;
02544       }
02545 
02546       snprintf(hdr, sizeof(hdr), "Match-%06d", x);
02547       match = astman_get_header(m, hdr);
02548 
02549       snprintf(hdr, sizeof(hdr), "Line-%06d", x);
02550       line = astman_get_header(m, hdr);
02551 
02552       if (!strcasecmp(action, "newcat")) {
02553          if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
02554             result = FAILURE_NEWCAT;   /* already exist */
02555             break;
02556          }
02557          if (!(category = ast_category_new(cat, dfn, -1))) {
02558             result = FAILURE_ALLOCATION;
02559             break;
02560          }
02561          if (ast_strlen_zero(match)) {
02562             ast_category_append(cfg, category);
02563          } else {
02564             ast_category_insert(cfg, category, match);
02565          }
02566       } else if (!strcasecmp(action, "renamecat")) {
02567          if (ast_strlen_zero(value)) {
02568             result = UNSPECIFIED_ARGUMENT;
02569             break;
02570          }
02571          if (!(category = ast_category_get(cfg, cat))) {
02572             result = UNKNOWN_CATEGORY;
02573             break;
02574          }
02575          ast_category_rename(category, value);
02576       } else if (!strcasecmp(action, "delcat")) {
02577          if (ast_category_delete(cfg, cat)) {
02578             result = FAILURE_DELCAT;
02579             break;
02580          }
02581       } else if (!strcasecmp(action, "emptycat")) {
02582          if (ast_category_empty(cfg, cat)) {
02583             result = FAILURE_EMPTYCAT;
02584             break;
02585          }
02586       } else if (!strcasecmp(action, "update")) {
02587          if (ast_strlen_zero(var)) {
02588             result = UNSPECIFIED_ARGUMENT;
02589             break;
02590          }
02591          if (!(category = ast_category_get(cfg,cat))) {
02592             result = UNKNOWN_CATEGORY;
02593             break;
02594          }
02595          if (ast_variable_update(category, var, value, match, object)) {
02596             result = FAILURE_UPDATE;
02597             break;
02598          }
02599       } else if (!strcasecmp(action, "delete")) {
02600          if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
02601             result = UNSPECIFIED_ARGUMENT;
02602             break;
02603          }
02604          if (!(category = ast_category_get(cfg, cat))) {
02605             result = UNKNOWN_CATEGORY;
02606             break;
02607          }
02608          if (ast_variable_delete(category, var, match, line)) {
02609             result = FAILURE_DELETE;
02610             break;
02611          }
02612       } else if (!strcasecmp(action, "append")) {
02613          if (ast_strlen_zero(var)) {
02614             result = UNSPECIFIED_ARGUMENT;
02615             break;
02616          }
02617          if (!(category = ast_category_get(cfg, cat))) {
02618             result = UNKNOWN_CATEGORY;
02619             break;
02620          }
02621          if (!(v = ast_variable_new(var, value, dfn))) {
02622             result = FAILURE_ALLOCATION;
02623             break;
02624          }
02625          if (object || (match && !strcasecmp(match, "object"))) {
02626             v->object = 1;
02627          }
02628          ast_variable_append(category, v);
02629       } else if (!strcasecmp(action, "insert")) {
02630          if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
02631             result = UNSPECIFIED_ARGUMENT;
02632             break;
02633          }
02634          if (!(category = ast_category_get(cfg, cat))) {
02635             result = UNKNOWN_CATEGORY;
02636             break;
02637          }
02638          if (!(v = ast_variable_new(var, value, dfn))) {
02639             result = FAILURE_ALLOCATION;
02640             break;
02641          }
02642          ast_variable_insert(category, v, line);
02643       }
02644       else {
02645          ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
02646          result = UNKNOWN_ACTION;
02647          break;
02648       }
02649    }
02650    ast_free(str1);
02651    ast_free(str2);
02652    return result;
02653 }
02654 
02655 static int action_updateconfig(struct mansession *s, const struct message *m)
02656 {
02657    struct ast_config *cfg;
02658    const char *sfn = astman_get_header(m, "SrcFilename");
02659    const char *dfn = astman_get_header(m, "DstFilename");
02660    int res;
02661    const char *rld = astman_get_header(m, "Reload");
02662    struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02663    enum error_type result;
02664 
02665    if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
02666       astman_send_error(s, m, "Filename not specified");
02667       return 0;
02668    }
02669    if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
02670       astman_send_error(s, m, "Config file not found");
02671       return 0;
02672    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02673       astman_send_error(s, m, "Config file has invalid format");
02674       return 0;
02675    }
02676    result = handle_updates(s, m, cfg, dfn);
02677    if (!result) {
02678       ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
02679       res = ast_config_text_file_save(dfn, cfg, "Manager");
02680       ast_config_destroy(cfg);
02681       if (res) {
02682          astman_send_error(s, m, "Save of config failed");
02683          return 0;
02684       }
02685       astman_send_ack(s, m, NULL);
02686       if (!ast_strlen_zero(rld)) {
02687          if (ast_true(rld)) {
02688             rld = NULL;
02689          }
02690          ast_module_reload(rld);
02691       }
02692    } else {
02693       ast_config_destroy(cfg);
02694       switch(result) {
02695       case UNKNOWN_ACTION:
02696          astman_send_error(s, m, "Unknown action command");
02697          break;
02698       case UNKNOWN_CATEGORY:
02699          astman_send_error(s, m, "Given category does not exist");
02700          break;
02701       case UNSPECIFIED_CATEGORY:
02702          astman_send_error(s, m, "Category not specified");
02703          break;
02704       case UNSPECIFIED_ARGUMENT:
02705          astman_send_error(s, m, "Problem with category, value, or line (if required)");
02706          break;
02707       case FAILURE_ALLOCATION:
02708          astman_send_error(s, m, "Memory allocation failure, this should not happen");
02709          break;
02710       case FAILURE_NEWCAT:
02711          astman_send_error(s, m, "Create category did not complete successfully");
02712          break;
02713       case FAILURE_DELCAT:
02714          astman_send_error(s, m, "Delete category did not complete successfully");
02715          break;
02716       case FAILURE_EMPTYCAT:
02717          astman_send_error(s, m, "Empty category did not complete successfully");
02718          break;
02719       case FAILURE_UPDATE:
02720          astman_send_error(s, m, "Update did not complete successfully");
02721          break;
02722       case FAILURE_DELETE:
02723          astman_send_error(s, m, "Delete did not complete successfully");
02724          break;
02725       case FAILURE_APPEND:
02726          astman_send_error(s, m, "Append did not complete successfully");
02727          break;
02728       }
02729    }
02730    return 0;
02731 }
02732 
02733 static int action_createconfig(struct mansession *s, const struct message *m)
02734 {
02735    int fd;
02736    const char *fn = astman_get_header(m, "Filename");
02737    struct ast_str *filepath = ast_str_alloca(PATH_MAX);
02738    ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
02739    ast_str_append(&filepath, 0, "%s", fn);
02740 
02741    if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
02742       close(fd);
02743       astman_send_ack(s, m, "New configuration file created successfully");
02744    } else {
02745       astman_send_error(s, m, strerror(errno));
02746    }
02747 
02748    return 0;
02749 }
02750 
02751 static int action_waitevent(struct mansession *s, const struct message *m)
02752 {
02753    const char *timeouts = astman_get_header(m, "Timeout");
02754    int timeout = -1;
02755    int x;
02756    int needexit = 0;
02757    const char *id = astman_get_header(m, "ActionID");
02758    char idText[256];
02759 
02760    if (!ast_strlen_zero(id)) {
02761       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
02762    } else {
02763       idText[0] = '\0';
02764    }
02765 
02766    if (!ast_strlen_zero(timeouts)) {
02767       sscanf(timeouts, "%30i", &timeout);
02768       if (timeout < -1) {
02769          timeout = -1;
02770       }
02771       /* XXX maybe put an upper bound, or prevent the use of 0 ? */
02772    }
02773 
02774    ao2_lock(s->session);
02775    if (s->session->waiting_thread != AST_PTHREADT_NULL) {
02776       pthread_kill(s->session->waiting_thread, SIGURG);
02777    }
02778 
02779    if (s->session->managerid) { /* AMI-over-HTTP session */
02780       /*
02781        * Make sure the timeout is within the expire time of the session,
02782        * as the client will likely abort the request if it does not see
02783        * data coming after some amount of time.
02784        */
02785       time_t now = time(NULL);
02786       int max = s->session->sessiontimeout - now - 10;
02787 
02788       if (max < 0) { /* We are already late. Strange but possible. */
02789          max = 0;
02790       }
02791       if (timeout < 0 || timeout > max) {
02792          timeout = max;
02793       }
02794       if (!s->session->send_events) {  /* make sure we record events */
02795          s->session->send_events = -1;
02796       }
02797    }
02798    ao2_unlock(s->session);
02799 
02800    /* XXX should this go inside the lock ? */
02801    s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
02802    ast_debug(1, "Starting waiting for an event!\n");
02803 
02804    for (x = 0; x < timeout || timeout < 0; x++) {
02805       ao2_lock(s->session);
02806       if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
02807          needexit = 1;
02808       }
02809       /* We can have multiple HTTP session point to the same mansession entry.
02810        * The way we deal with it is not very nice: newcomers kick out the previous
02811        * HTTP session. XXX this needs to be improved.
02812        */
02813       if (s->session->waiting_thread != pthread_self()) {
02814          needexit = 1;
02815       }
02816       if (s->session->needdestroy) {
02817          needexit = 1;
02818       }
02819       ao2_unlock(s->session);
02820       if (needexit) {
02821          break;
02822       }
02823       if (s->session->managerid == 0) {   /* AMI session */
02824          if (ast_wait_for_input(s->session->fd, 1000)) {
02825             break;
02826          }
02827       } else { /* HTTP session */
02828          sleep(1);
02829       }
02830    }
02831    ast_debug(1, "Finished waiting for an event!\n");
02832 
02833    ao2_lock(s->session);
02834    if (s->session->waiting_thread == pthread_self()) {
02835       struct eventqent *eqe = s->session->last_ev;
02836       astman_send_response(s, m, "Success", "Waiting for Event completed.");
02837       AST_RWLIST_RDLOCK(&all_events);
02838       while ((eqe = advance_event(eqe))) {
02839          if (((s->session->readperm & eqe->category) == eqe->category) &&
02840              ((s->session->send_events & eqe->category) == eqe->category)) {
02841             astman_append(s, "%s", eqe->eventdata);
02842          }
02843          s->session->last_ev = eqe;
02844       }
02845       AST_RWLIST_UNLOCK(&all_events);
02846       astman_append(s,
02847          "Event: WaitEventComplete\r\n"
02848          "%s"
02849          "\r\n", idText);
02850       s->session->waiting_thread = AST_PTHREADT_NULL;
02851    } else {
02852       ast_debug(1, "Abandoning event request!\n");
02853    }
02854    ao2_unlock(s->session);
02855 
02856    return 0;
02857 }
02858 
02859 /*! \note The actionlock is read-locked by the caller of this function */
02860 static int action_listcommands(struct mansession *s, const struct message *m)
02861 {
02862    struct manager_action *cur;
02863    struct ast_str *temp = ast_str_alloca(BUFSIZ); /* XXX very large ? */
02864 
02865    astman_start_ack(s, m);
02866    AST_RWLIST_TRAVERSE(&actions, cur, list) {
02867       if (s->session->writeperm & cur->authority || cur->authority == 0) {
02868          astman_append(s, "%s: %s (Priv: %s)\r\n",
02869             cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
02870       }
02871    }
02872    astman_append(s, "\r\n");
02873 
02874    return 0;
02875 }
02876 
02877 static int action_events(struct mansession *s, const struct message *m)
02878 {
02879    const char *mask = astman_get_header(m, "EventMask");
02880    int res, x;
02881 
02882    res = set_eventmask(s, mask);
02883    if (broken_events_action) {
02884       /* if this option is set we should not return a response on
02885        * error, or when all events are set */
02886 
02887       if (res > 0) {
02888          for (x = 0; x < ARRAY_LEN(perms); x++) {
02889             if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
02890                return 0;
02891             }
02892          }
02893          astman_append(s, "Response: Success\r\n"
02894                 "Events: On\r\n\r\n");
02895       } else if (res == 0)
02896          astman_append(s, "Response: Success\r\n"
02897                 "Events: Off\r\n\r\n");
02898       return 0;
02899    }
02900 
02901    if (res > 0)
02902       astman_append(s, "Response: Success\r\n"
02903              "Events: On\r\n\r\n");
02904    else if (res == 0)
02905       astman_append(s, "Response: Success\r\n"
02906              "Events: Off\r\n\r\n");
02907    else
02908       astman_send_error(s, m, "Invalid event mask");
02909 
02910    return 0;
02911 }
02912 
02913 static int action_logoff(struct mansession *s, const struct message *m)
02914 {
02915    astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
02916    return -1;
02917 }
02918 
02919 static int action_login(struct mansession *s, const struct message *m)
02920 {
02921 
02922    /* still authenticated - don't process again */
02923    if (s->session->authenticated) {
02924       astman_send_ack(s, m, "Already authenticated");
02925       return 0;
02926    }
02927 
02928    if (authenticate(s, m)) {
02929       sleep(1);
02930       astman_send_error(s, m, "Authentication failed");
02931       return -1;
02932    }
02933    s->session->authenticated = 1;
02934    if (manager_displayconnects(s->session)) {
02935       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));
02936    }
02937    astman_send_ack(s, m, "Authentication accepted");
02938    if (ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
02939       manager_event(EVENT_FLAG_SYSTEM, "FullyBooted", "Status: Fully Booted\r\n");
02940    }
02941    return 0;
02942 }
02943 
02944 static int action_challenge(struct mansession *s, const struct message *m)
02945 {
02946    const char *authtype = astman_get_header(m, "AuthType");
02947 
02948    if (!strcasecmp(authtype, "MD5")) {
02949       if (ast_strlen_zero(s->session->challenge)) {
02950          snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
02951       }
02952       mansession_lock(s);
02953       astman_start_ack(s, m);
02954       astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
02955       mansession_unlock(s);
02956    } else {
02957       astman_send_error(s, m, "Must specify AuthType");
02958    }
02959    return 0;
02960 }
02961 
02962 static int action_hangup(struct mansession *s, const struct message *m)
02963 {
02964    struct ast_channel *c = NULL;
02965    int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
02966    const char *name = astman_get_header(m, "Channel");
02967    const char *cause = astman_get_header(m, "Cause");
02968 
02969    if (ast_strlen_zero(name)) {
02970       astman_send_error(s, m, "No channel specified");
02971       return 0;
02972    }
02973 
02974    if (!ast_strlen_zero(cause)) {
02975       char *endptr;
02976       causecode = strtol(cause, &endptr, 10);
02977       if (causecode < 0 || causecode > 127 || *endptr != '\0') {
02978          ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
02979          /* keep going, better to hangup without cause than to not hang up at all */
02980          causecode = 0; /* do not set channel's hangupcause */
02981       }
02982    }
02983 
02984    if (!(c = ast_channel_get_by_name(name))) {
02985       astman_send_error(s, m, "No such channel");
02986       return 0;
02987    }
02988 
02989    ast_channel_lock(c);
02990    if (causecode > 0) {
02991       ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
02992             c->name, causecode, c->hangupcause);
02993       c->hangupcause = causecode;
02994    }
02995    ast_softhangup_nolock(c, AST_SOFTHANGUP_EXPLICIT);
02996    ast_channel_unlock(c);
02997 
02998    c = ast_channel_unref(c);
02999 
03000    astman_send_ack(s, m, "Channel Hungup");
03001 
03002    return 0;
03003 }
03004 
03005 static int action_setvar(struct mansession *s, const struct message *m)
03006 {
03007    struct ast_channel *c = NULL;
03008    const char *name = astman_get_header(m, "Channel");
03009    const char *varname = astman_get_header(m, "Variable");
03010    const char *varval = astman_get_header(m, "Value");
03011    int res = 0;
03012    
03013    if (ast_strlen_zero(varname)) {
03014       astman_send_error(s, m, "No variable specified");
03015       return 0;
03016    }
03017 
03018    if (!ast_strlen_zero(name)) {
03019       if (!(c = ast_channel_get_by_name(name))) {
03020          astman_send_error(s, m, "No such channel");
03021          return 0;
03022       }
03023    }
03024 
03025    res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
03026 
03027    if (c) {
03028       c = ast_channel_unref(c);
03029    }
03030    if (res == 0) {
03031       astman_send_ack(s, m, "Variable Set"); 
03032    } else {
03033       astman_send_error(s, m, "Variable not set");
03034    }
03035    return 0;
03036 }
03037 
03038 static int action_getvar(struct mansession *s, const struct message *m)
03039 {
03040    struct ast_channel *c = NULL;
03041    const char *name = astman_get_header(m, "Channel");
03042    const char *varname = astman_get_header(m, "Variable");
03043    char *varval;
03044    char workspace[1024] = "";
03045 
03046    if (ast_strlen_zero(varname)) {
03047       astman_send_error(s, m, "No variable specified");
03048       return 0;
03049    }
03050 
03051    if (!ast_strlen_zero(name)) {
03052       if (!(c = ast_channel_get_by_name(name))) {
03053          astman_send_error(s, m, "No such channel");
03054          return 0;
03055       }
03056    }
03057 
03058    if (varname[strlen(varname) - 1] == ')') {
03059       if (!c) {
03060          c = ast_dummy_channel_alloc();
03061          if (c) {
03062             ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
03063             c = ast_channel_release(c);
03064          } else
03065             ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution.  Function results may be blank.\n");
03066       } else {
03067          ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
03068       }
03069       varval = workspace;
03070    } else {
03071       pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
03072    }
03073 
03074    if (c) {
03075       c = ast_channel_unref(c);
03076    }
03077 
03078    astman_start_ack(s, m);
03079    astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
03080 
03081    return 0;
03082 }
03083 
03084 /*! \brief Manager "status" command to show channels */
03085 /* Needs documentation... */
03086 static int action_status(struct mansession *s, const struct message *m)
03087 {
03088    const char *name = astman_get_header(m, "Channel");
03089    const char *cvariables = astman_get_header(m, "Variables");
03090    char *variables = ast_strdupa(S_OR(cvariables, ""));
03091    struct ast_channel *c;
03092    char bridge[256];
03093    struct timeval now = ast_tvnow();
03094    long elapsed_seconds = 0;
03095    int channels = 0;
03096    int all = ast_strlen_zero(name); /* set if we want all channels */
03097    const char *id = astman_get_header(m, "ActionID");
03098    char idText[256];
03099    AST_DECLARE_APP_ARGS(vars,
03100       AST_APP_ARG(name)[100];
03101    );
03102    struct ast_str *str = ast_str_create(1000);
03103    struct ast_channel_iterator *iter = NULL;
03104 
03105    if (!ast_strlen_zero(id)) {
03106       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
03107    } else {
03108       idText[0] = '\0';
03109    }
03110 
03111    if (all) {
03112       if (!(iter = ast_channel_iterator_all_new())) {
03113          ast_free(str);
03114          astman_send_error(s, m, "Memory Allocation Failure");
03115          return 1;
03116       }
03117       c = ast_channel_iterator_next(iter);
03118    } else {
03119       if (!(c = ast_channel_get_by_name(name))) {
03120          astman_send_error(s, m, "No such channel");
03121          ast_free(str);
03122          return 0;
03123       }
03124    }
03125 
03126    astman_send_ack(s, m, "Channel status will follow");
03127 
03128    if (!ast_strlen_zero(cvariables)) {
03129       AST_STANDARD_APP_ARGS(vars, variables);
03130    }
03131 
03132    /* if we look by name, we break after the first iteration */
03133    for (; c; c = ast_channel_iterator_next(iter)) {
03134       ast_channel_lock(c);
03135 
03136       if (!ast_strlen_zero(cvariables)) {
03137          int i;
03138          ast_str_reset(str);
03139          for (i = 0; i < vars.argc; i++) {
03140             char valbuf[512], *ret = NULL;
03141 
03142             if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
03143                if (ast_func_read(c, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
03144                   valbuf[0] = '\0';
03145                }
03146                ret = valbuf;
03147             } else {
03148                pbx_retrieve_variable(c, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);
03149             }
03150 
03151             ast_str_append(&str, 0, "Variable: %s=%s\r\n", vars.name[i], ret);
03152          }
03153       }
03154 
03155       channels++;
03156       if (c->_bridge) {
03157          snprintf(bridge, sizeof(bridge), "BridgedChannel: %s\r\nBridgedUniqueid: %s\r\n", c->_bridge->name, c->_bridge->uniqueid);
03158       } else {
03159          bridge[0] = '\0';
03160       }
03161       if (c->pbx) {
03162          if (c->cdr) {
03163             elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
03164          }
03165          astman_append(s,
03166          "Event: Status\r\n"
03167          "Privilege: Call\r\n"
03168          "Channel: %s\r\n"
03169          "CallerIDNum: %s\r\n"
03170          "CallerIDName: %s\r\n"
03171          "Accountcode: %s\r\n"
03172          "ChannelState: %d\r\n"
03173          "ChannelStateDesc: %s\r\n"
03174          "Context: %s\r\n"
03175          "Extension: %s\r\n"
03176          "Priority: %d\r\n"
03177          "Seconds: %ld\r\n"
03178          "%s"
03179          "Uniqueid: %s\r\n"
03180          "%s"
03181          "%s"
03182          "\r\n",
03183          c->name,
03184          S_COR(c->caller.id.number.valid, c->caller.id.number.str, ""),
03185          S_COR(c->caller.id.name.valid, c->caller.id.name.str, ""),
03186          c->accountcode,
03187          c->_state,
03188          ast_state2str(c->_state), c->context,
03189          c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, ast_str_buffer(str), idText);
03190       } else {
03191          astman_append(s,
03192             "Event: Status\r\n"
03193             "Privilege: Call\r\n"
03194             "Channel: %s\r\n"
03195             "CallerIDNum: %s\r\n"
03196             "CallerIDName: %s\r\n"
03197             "Account: %s\r\n"
03198             "State: %s\r\n"
03199             "%s"
03200             "Uniqueid: %s\r\n"
03201             "%s"
03202             "%s"
03203             "\r\n",
03204             c->name,
03205             S_COR(c->caller.id.number.valid, c->caller.id.number.str, "<unknown>"),
03206             S_COR(c->caller.id.name.valid, c->caller.id.name.str, "<unknown>"),
03207             c->accountcode,
03208             ast_state2str(c->_state), bridge, c->uniqueid,
03209             ast_str_buffer(str), idText);
03210       }
03211 
03212       ast_channel_unlock(c);
03213       c = ast_channel_unref(c);
03214 
03215       if (!all) {
03216          break;
03217       }
03218    }
03219 
03220    if (iter) {
03221       ast_channel_iterator_destroy(iter);
03222    }
03223 
03224    astman_append(s,
03225       "Event: StatusComplete\r\n"
03226       "%s"
03227       "Items: %d\r\n"
03228       "\r\n", idText, channels);
03229 
03230    ast_free(str);
03231 
03232    return 0;
03233 }
03234 
03235 static int action_sendtext(struct mansession *s, const struct message *m)
03236 {
03237    struct ast_channel *c = NULL;
03238    const char *name = astman_get_header(m, "Channel");
03239    const char *textmsg = astman_get_header(m, "Message");
03240    int res = 0;
03241 
03242    if (ast_strlen_zero(name)) {
03243       astman_send_error(s, m, "No channel specified");
03244       return 0;
03245    }
03246 
03247    if (ast_strlen_zero(textmsg)) {
03248       astman_send_error(s, m, "No Message specified");
03249       return 0;
03250    }
03251 
03252    if (!(c = ast_channel_get_by_name(name))) {
03253       astman_send_error(s, m, "No such channel");
03254       return 0;
03255    }
03256 
03257    ast_channel_lock(c);
03258    res = ast_sendtext(c, textmsg);
03259    ast_channel_unlock(c);
03260    c = ast_channel_unref(c);
03261 
03262    if (res > 0) {
03263       astman_send_ack(s, m, "Success");
03264    } else {
03265       astman_send_error(s, m, "Failure");
03266    }
03267 
03268    return res;
03269 }
03270 
03271 /*! \brief  action_redirect: The redirect manager command */
03272 static int action_redirect(struct mansession *s, const struct message *m)
03273 {
03274    const char *name = astman_get_header(m, "Channel");
03275    const char *name2 = astman_get_header(m, "ExtraChannel");
03276    const char *exten = astman_get_header(m, "Exten");
03277    const char *exten2 = astman_get_header(m, "ExtraExten");
03278    const char *context = astman_get_header(m, "Context");
03279    const char *context2 = astman_get_header(m, "ExtraContext");
03280    const char *priority = astman_get_header(m, "Priority");
03281    const char *priority2 = astman_get_header(m, "ExtraPriority");
03282    struct ast_channel *chan, *chan2 = NULL;
03283    int pi, pi2 = 0;
03284    int res;
03285 
03286    if (ast_strlen_zero(name)) {
03287       astman_send_error(s, m, "Channel not specified");
03288       return 0;
03289    }
03290 
03291    if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
03292       if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
03293          astman_send_error(s, m, "Invalid priority");
03294          return 0;
03295       }
03296    }
03297 
03298    if (!ast_strlen_zero(priority2) && (sscanf(priority2, "%30d", &pi2) != 1)) {
03299       if ((pi2 = ast_findlabel_extension(NULL, context2, exten2, priority2, NULL)) < 1) {
03300          astman_send_error(s, m, "Invalid ExtraPriority");
03301          return 0;
03302       }
03303    }
03304 
03305    if (!(chan = ast_channel_get_by_name(name))) {
03306       char buf[256];
03307       snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
03308       astman_send_error(s, m, buf);
03309       return 0;
03310    }
03311 
03312    if (ast_check_hangup_locked(chan)) {
03313       astman_send_error(s, m, "Redirect failed, channel not up.");
03314       chan = ast_channel_unref(chan);
03315       return 0;
03316    }
03317 
03318    if (!ast_strlen_zero(name2)) {
03319       chan2 = ast_channel_get_by_name(name2);
03320    }
03321 
03322    if (chan2 && ast_check_hangup_locked(chan2)) {
03323       astman_send_error(s, m, "Redirect failed, extra channel not up.");
03324       chan = ast_channel_unref(chan);
03325       chan2 = ast_channel_unref(chan2);
03326       return 0;
03327    }
03328 
03329    if (chan->pbx) {
03330       ast_channel_lock(chan);
03331       ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
03332       ast_channel_unlock(chan);
03333    }
03334 
03335    res = ast_async_goto(chan, context, exten, pi);
03336    if (!res) {
03337       if (!ast_strlen_zero(name2)) {
03338          if (chan2) {
03339             if (chan2->pbx) {
03340                ast_channel_lock(chan2);
03341                ast_set_flag(chan2, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
03342                ast_channel_unlock(chan2);
03343             }
03344             if (context2) {
03345                res = ast_async_goto(chan2, context2, exten2, pi2);
03346             } else {
03347                res = ast_async_goto(chan2, context, exten, pi);
03348             }
03349          } else {
03350             res = -1;
03351          }
03352          if (!res) {
03353             astman_send_ack(s, m, "Dual Redirect successful");
03354          } else {
03355             astman_send_error(s, m, "Secondary redirect failed");
03356          }
03357       } else {
03358          astman_send_ack(s, m, "Redirect successful");
03359       }
03360    } else {
03361       astman_send_error(s, m, "Redirect failed");
03362    }
03363 
03364    if (chan) {
03365       chan = ast_channel_unref(chan);
03366    }
03367 
03368    if (chan2) {
03369       chan2 = ast_channel_unref(chan2);
03370    }
03371 
03372    return 0;
03373 }
03374 
03375 static int action_atxfer(struct mansession *s, const struct message *m)
03376 {
03377    const char *name = astman_get_header(m, "Channel");
03378    const char *exten = astman_get_header(m, "Exten");
03379    const char *context = astman_get_header(m, "Context");
03380    struct ast_channel *chan = NULL;
03381    struct ast_call_feature *atxfer_feature = NULL;
03382    char *feature_code = NULL;
03383 
03384    if (ast_strlen_zero(name)) {
03385       astman_send_error(s, m, "No channel specified");
03386       return 0;
03387    }
03388    if (ast_strlen_zero(exten)) {
03389       astman_send_error(s, m, "No extension specified");
03390       return 0;
03391    }
03392 
03393    if (!(atxfer_feature = ast_find_call_feature("atxfer"))) {
03394       astman_send_error(s, m, "No attended transfer feature found");
03395       return 0;
03396    }
03397 
03398    if (!(chan = ast_channel_get_by_name(name))) {
03399       astman_send_error(s, m, "Channel specified does not exist");
03400       return 0;
03401    }
03402 
03403    if (!ast_strlen_zero(context)) {
03404       pbx_builtin_setvar_helper(chan, "TRANSFER_CONTEXT", context);
03405    }
03406 
03407    for (feature_code = atxfer_feature->exten; feature_code && *feature_code; ++feature_code) {
03408       struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *feature_code };
03409       ast_queue_frame(chan, &f);
03410    }
03411 
03412    for (feature_code = (char *)exten; feature_code && *feature_code; ++feature_code) {
03413       struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *feature_code };
03414       ast_queue_frame(chan, &f);
03415    }
03416 
03417    chan = ast_channel_unref(chan);
03418 
03419    astman_send_ack(s, m, "Atxfer successfully queued");
03420 
03421    return 0;
03422 }
03423 
03424 static int check_blacklist(const char *cmd)
03425 {
03426    char *cmd_copy, *cur_cmd;
03427    char *cmd_words[MAX_BLACKLIST_CMD_LEN] = { NULL, };
03428    int i;
03429 
03430    cmd_copy = ast_strdupa(cmd);
03431    for (i = 0; i < MAX_BLACKLIST_CMD_LEN && (cur_cmd = strsep(&cmd_copy, " ")); i++) {
03432       cur_cmd = ast_strip(cur_cmd);
03433       if (ast_strlen_zero(cur_cmd)) {
03434          i--;
03435          continue;
03436       }
03437 
03438       cmd_words[i] = cur_cmd;
03439    }
03440 
03441    for (i = 0; i < ARRAY_LEN(command_blacklist); i++) {
03442       int j, match = 1;
03443 
03444       for (j = 0; command_blacklist[i].words[j]; j++) {
03445          if (ast_strlen_zero(cmd_words[j]) || strcasecmp(cmd_words[j], command_blacklist[i].words[j])) {
03446             match = 0;
03447             break;
03448          }
03449       }
03450 
03451       if (match) {
03452          return 1;
03453       }
03454    }
03455 
03456    return 0;
03457 }
03458 
03459 /*! \brief  Manager command "command" - execute CLI command */
03460 static int action_command(struct mansession *s, const struct message *m)
03461 {
03462    const char *cmd = astman_get_header(m, "Command");
03463    const char *id = astman_get_header(m, "ActionID");
03464    char *buf, *final_buf;
03465    char template[] = "/tmp/ast-ami-XXXXXX";  /* template for temporary file */
03466    int fd;
03467    off_t l;
03468 
03469    if (ast_strlen_zero(cmd)) {
03470       astman_send_error(s, m, "No command provided");
03471       return 0;
03472    }
03473 
03474    if (check_blacklist(cmd)) {
03475       astman_send_error(s, m, "Command blacklisted");
03476       return 0;
03477    }
03478 
03479    fd = mkstemp(template);
03480 
03481    astman_append(s, "Response: Follows\r\nPrivilege: Command\r\n");
03482    if (!ast_strlen_zero(id)) {
03483       astman_append(s, "ActionID: %s\r\n", id);
03484    }
03485    /* FIXME: Wedge a ActionID response in here, waiting for later changes */
03486    ast_cli_command(fd, cmd);  /* XXX need to change this to use a FILE * */
03487    l = lseek(fd, 0, SEEK_END);   /* how many chars available */
03488 
03489    /* This has a potential to overflow the stack.  Hence, use the heap. */
03490    buf = ast_calloc(1, l + 1);
03491    final_buf = ast_calloc(1, l + 1);
03492    if (buf) {
03493       lseek(fd, 0, SEEK_SET);
03494       if (read(fd, buf, l) < 0) {
03495          ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
03496       }
03497       buf[l] = '\0';
03498       if (final_buf) {
03499          term_strip(final_buf, buf, l);
03500          final_buf[l] = '\0';
03501       }
03502       astman_append(s, "%s", S_OR(final_buf, buf));
03503       ast_free(buf);
03504    }
03505    close(fd);
03506    unlink(template);
03507    astman_append(s, "--END COMMAND--\r\n\r\n");
03508    if (final_buf) {
03509       ast_free(final_buf);
03510    }
03511    return 0;
03512 }
03513 
03514 /*! \brief helper function for originate */
03515 struct fast_originate_helper {
03516    char tech[AST_MAX_EXTENSION];
03517    /*! data can contain a channel name, extension number, username, password, etc. */
03518    char data[512];
03519    int timeout;
03520    format_t format;           /*!< Codecs used for a call */
03521    char app[AST_MAX_APP];
03522    char appdata[AST_MAX_EXTENSION];
03523    char cid_name[AST_MAX_EXTENSION];
03524    char cid_num[AST_MAX_EXTENSION];
03525    char context[AST_MAX_CONTEXT];
03526    char exten[AST_MAX_EXTENSION];
03527    char idtext[AST_MAX_EXTENSION];
03528    char account[AST_MAX_ACCOUNT_CODE];
03529    int priority;
03530    struct ast_variable *vars;
03531 };
03532 
03533 static void *fast_originate(void *data)
03534 {
03535    struct fast_originate_helper *in = data;
03536    int res;
03537    int reason = 0;
03538    struct ast_channel *chan = NULL, *chans[1];
03539    char requested_channel[AST_CHANNEL_NAME];
03540 
03541    if (!ast_strlen_zero(in->app)) {
03542       res = ast_pbx_outgoing_app(in->tech, in->format, in->data, in->timeout, in->app, in->appdata, &reason, 1,
03543          S_OR(in->cid_num, NULL),
03544          S_OR(in->cid_name, NULL),
03545          in->vars, in->account, &chan);
03546    } else {
03547       res = ast_pbx_outgoing_exten(in->tech, in->format, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1,
03548          S_OR(in->cid_num, NULL),
03549          S_OR(in->cid_name, NULL),
03550          in->vars, in->account, &chan);
03551    }
03552 
03553    if (!chan) {
03554       snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
03555    }
03556    /* Tell the manager what happened with the channel */
03557    chans[0] = chan;
03558    ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
03559       "%s%s"
03560       "Response: %s\r\n"
03561       "Channel: %s\r\n"
03562       "Context: %s\r\n"
03563       "Exten: %s\r\n"
03564       "Reason: %d\r\n"
03565       "Uniqueid: %s\r\n"
03566       "CallerIDNum: %s\r\n"
03567       "CallerIDName: %s\r\n",
03568       in->idtext, ast_strlen_zero(in->idtext) ? "" : "\r\n", res ? "Failure" : "Success",
03569       chan ? chan->name : requested_channel, in->context, in->exten, reason,
03570       chan ? chan->uniqueid : "<null>",
03571       S_OR(in->cid_num, "<unknown>"),
03572       S_OR(in->cid_name, "<unknown>")
03573       );
03574 
03575    /* Locked by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
03576    if (chan) {
03577       ast_channel_unlock(chan);
03578    }
03579    ast_free(in);
03580    return NULL;
03581 }
03582 
03583 static int aocmessage_get_unit_entry(const struct message *m, struct ast_aoc_unit_entry *entry, unsigned int entry_num)
03584 {
03585    const char *unitamount;
03586    const char *unittype;
03587    struct ast_str *str = ast_str_alloca(32);
03588 
03589    memset(entry, 0, sizeof(*entry));
03590 
03591    ast_str_set(&str, 0, "UnitAmount(%u)", entry_num);
03592    unitamount = astman_get_header(m, ast_str_buffer(str));
03593 
03594    ast_str_set(&str, 0, "UnitType(%u)", entry_num);
03595    unittype = astman_get_header(m, ast_str_buffer(str));
03596 
03597    if (!ast_strlen_zero(unitamount) && (sscanf(unitamount, "%30u", &entry->amount) == 1)) {
03598       entry->valid_amount = 1;
03599    }
03600 
03601    if (!ast_strlen_zero(unittype) && sscanf(unittype, "%30u", &entry->type) == 1) {
03602       entry->valid_type = 1;
03603    }
03604 
03605    return 0;
03606 }
03607 
03608 static int action_aocmessage(struct mansession *s, const struct message *m)
03609 {
03610    const char *channel = astman_get_header(m, "Channel");
03611    const char *pchannel = astman_get_header(m, "ChannelPrefix");
03612    const char *msgtype = astman_get_header(m, "MsgType");
03613    const char *chargetype = astman_get_header(m, "ChargeType");
03614    const char *currencyname = astman_get_header(m, "CurrencyName");
03615    const char *currencyamount = astman_get_header(m, "CurrencyAmount");
03616    const char *mult = astman_get_header(m, "CurrencyMultiplier");
03617    const char *totaltype = astman_get_header(m, "TotalType");
03618    const char *aocbillingid = astman_get_header(m, "AOCBillingId");
03619    const char *association_id= astman_get_header(m, "ChargingAssociationId");
03620    const char *association_num = astman_get_header(m, "ChargingAssociationNumber");
03621    const char *association_plan = astman_get_header(m, "ChargingAssociationPlan");
03622 
03623    enum ast_aoc_type _msgtype;
03624    enum ast_aoc_charge_type _chargetype;
03625    enum ast_aoc_currency_multiplier _mult = AST_AOC_MULT_ONE;
03626    enum ast_aoc_total_type _totaltype = AST_AOC_TOTAL;
03627    enum ast_aoc_billing_id _billingid = AST_AOC_BILLING_NA;
03628    unsigned int _currencyamount = 0;
03629    int _association_id = 0;
03630    unsigned int _association_plan = 0;
03631    struct ast_channel *chan = NULL;
03632 
03633    struct ast_aoc_decoded *decoded = NULL;
03634    struct ast_aoc_encoded *encoded = NULL;
03635    size_t encoded_size = 0;
03636 
03637    if (ast_strlen_zero(channel) && ast_strlen_zero(pchannel)) {
03638       astman_send_error(s, m, "Channel and PartialChannel are not specified. Specify at least one of these.");
03639       goto aocmessage_cleanup;
03640    }
03641 
03642    if (!(chan = ast_channel_get_by_name(channel)) && !ast_strlen_zero(pchannel)) {
03643       chan = ast_channel_get_by_name_prefix(pchannel, strlen(pchannel));
03644    }
03645 
03646    if (!chan) {
03647       astman_send_error(s, m, "No such channel");
03648       goto aocmessage_cleanup;
03649    }
03650 
03651    if (ast_strlen_zero(msgtype) || (strcasecmp(msgtype, "d") && strcasecmp(msgtype, "e"))) {
03652       astman_send_error(s, m, "Invalid MsgType");
03653       goto aocmessage_cleanup;
03654    }
03655 
03656    if (ast_strlen_zero(chargetype)) {
03657       astman_send_error(s, m, "ChargeType not specified");
03658       goto aocmessage_cleanup;
03659    }
03660 
03661    _msgtype = strcasecmp(msgtype, "d") ? AST_AOC_E : AST_AOC_D;
03662 
03663    if (!strcasecmp(chargetype, "NA")) {
03664       _chargetype = AST_AOC_CHARGE_NA;
03665    } else if (!strcasecmp(chargetype, "Free")) {
03666       _chargetype = AST_AOC_CHARGE_FREE;
03667    } else if (!strcasecmp(chargetype, "Currency")) {
03668       _chargetype = AST_AOC_CHARGE_CURRENCY;
03669    } else if (!strcasecmp(chargetype, "Unit")) {
03670       _chargetype = AST_AOC_CHARGE_UNIT;
03671    } else {
03672       astman_send_error(s, m, "Invalid ChargeType");
03673       goto aocmessage_cleanup;
03674    }
03675 
03676    if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
03677 
03678       if (ast_strlen_zero(currencyamount) || (sscanf(currencyamount, "%30u", &_currencyamount) != 1)) {
03679          astman_send_error(s, m, "Invalid CurrencyAmount, CurrencyAmount is a required when ChargeType is Currency");
03680          goto aocmessage_cleanup;
03681       }
03682 
03683       if (ast_strlen_zero(mult)) {
03684          astman_send_error(s, m, "ChargeMultiplier unspecified, ChargeMultiplier is required when ChargeType is Currency.");
03685          goto aocmessage_cleanup;
03686       } else if (!strcasecmp(mult, "onethousandth")) {
03687          _mult = AST_AOC_MULT_ONETHOUSANDTH;
03688       } else if (!strcasecmp(mult, "onehundredth")) {
03689          _mult = AST_AOC_MULT_ONEHUNDREDTH;
03690       } else if (!strcasecmp(mult, "onetenth")) {
03691          _mult = AST_AOC_MULT_ONETENTH;
03692       } else if (!strcasecmp(mult, "one")) {
03693          _mult = AST_AOC_MULT_ONE;
03694       } else if (!strcasecmp(mult, "ten")) {
03695          _mult = AST_AOC_MULT_TEN;
03696       } else if (!strcasecmp(mult, "hundred")) {
03697          _mult = AST_AOC_MULT_HUNDRED;
03698       } else if (!strcasecmp(mult, "thousand")) {
03699          _mult = AST_AOC_MULT_THOUSAND;
03700       } else {
03701          astman_send_error(s, m, "Invalid ChargeMultiplier");
03702          goto aocmessage_cleanup;
03703       }
03704    }
03705 
03706    /* create decoded object and start setting values */
03707    if (!(decoded = ast_aoc_create(_msgtype, _chargetype, 0))) {
03708          astman_send_error(s, m, "Message Creation Failed");
03709          goto aocmessage_cleanup;
03710    }
03711 
03712    if (_msgtype == AST_AOC_D) {
03713       if (!ast_strlen_zero(totaltype) && !strcasecmp(totaltype, "subtotal")) {
03714          _totaltype = AST_AOC_SUBTOTAL;
03715       }
03716 
03717       if (ast_strlen_zero(aocbillingid)) {
03718          /* ignore this is optional */
03719       } else if (!strcasecmp(aocbillingid, "Normal")) {
03720          _billingid = AST_AOC_BILLING_NORMAL;
03721       } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
03722          _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
03723       } else if (!strcasecmp(aocbillingid, "CreditCard")) {
03724          _billingid = AST_AOC_BILLING_CREDIT_CARD;
03725       } else {
03726          astman_send_error(s, m, "Invalid AOC-D AOCBillingId");
03727          goto aocmessage_cleanup;
03728       }
03729    } else {
03730       if (ast_strlen_zero(aocbillingid)) {
03731          /* ignore this is optional */
03732       } else if (!strcasecmp(aocbillingid, "Normal")) {
03733          _billingid = AST_AOC_BILLING_NORMAL;
03734       } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
03735          _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
03736       } else if (!strcasecmp(aocbillingid, "CreditCard")) {
03737          _billingid = AST_AOC_BILLING_CREDIT_CARD;
03738       } else if (!strcasecmp(aocbillingid, "CallFwdUnconditional")) {
03739          _billingid = AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL;
03740       } else if (!strcasecmp(aocbillingid, "CallFwdBusy")) {
03741          _billingid = AST_AOC_BILLING_CALL_FWD_BUSY;
03742       } else if (!strcasecmp(aocbillingid, "CallFwdNoReply")) {
03743          _billingid = AST_AOC_BILLING_CALL_FWD_NO_REPLY;
03744       } else if (!strcasecmp(aocbillingid, "CallDeflection")) {
03745          _billingid = AST_AOC_BILLING_CALL_DEFLECTION;
03746       } else if (!strcasecmp(aocbillingid, "CallTransfer")) {
03747          _billingid = AST_AOC_BILLING_CALL_TRANSFER;
03748       } else {
03749          astman_send_error(s, m, "Invalid AOC-E AOCBillingId");
03750          goto aocmessage_cleanup;
03751       }
03752 
03753       if (!ast_strlen_zero(association_id) && (sscanf(association_id, "%30d", &_association_id) != 1)) {
03754          astman_send_error(s, m, "Invalid ChargingAssociationId");
03755          goto aocmessage_cleanup;
03756       }
03757       if (!ast_strlen_zero(association_plan) && (sscanf(association_plan, "%30u", &_association_plan) != 1)) {
03758          astman_send_error(s, m, "Invalid ChargingAssociationPlan");
03759          goto aocmessage_cleanup;
03760       }
03761 
03762       if (_association_id) {
03763          ast_aoc_set_association_id(decoded, _association_id);
03764       } else if (!ast_strlen_zero(association_num)) {
03765          ast_aoc_set_association_number(decoded, association_num, _association_plan);
03766       }
03767    }
03768 
03769    if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
03770       ast_aoc_set_currency_info(decoded, _currencyamount, _mult, ast_strlen_zero(currencyname) ? NULL : currencyname);
03771    } else if (_chargetype == AST_AOC_CHARGE_UNIT) {
03772       struct ast_aoc_unit_entry entry;
03773       int i;
03774 
03775       /* multiple unit entries are possible, lets get them all */
03776       for (i = 0; i < 32; i++) {
03777          if (aocmessage_get_unit_entry(m, &entry, i)) {
03778             break; /* that's the end then */
03779          }
03780 
03781          ast_aoc_add_unit_entry(decoded, entry.valid_amount, entry.amount, entry.valid_type, entry.type);
03782       }
03783 
03784       /* at least one unit entry is required */
03785       if (!i) {
03786          astman_send_error(s, m, "Invalid UnitAmount(0), At least one valid unit entry is required when ChargeType is set to Unit");
03787          goto aocmessage_cleanup;
03788       }
03789 
03790    }
03791 
03792    ast_aoc_set_billing_id(decoded, _billingid);
03793    ast_aoc_set_total_type(decoded, _totaltype);
03794 
03795 
03796    if ((encoded = ast_aoc_encode(decoded, &encoded_size, NULL)) && !ast_indicate_data(chan, AST_CONTROL_AOC, encoded, encoded_size)) {
03797       astman_send_ack(s, m, "AOC Message successfully queued on channel");
03798    } else {
03799       astman_send_error(s, m, "Error encoding AOC message, could not queue onto channel");
03800    }
03801 
03802 aocmessage_cleanup:
03803 
03804    ast_aoc_destroy_decoded(decoded);
03805    ast_aoc_destroy_encoded(encoded);
03806 
03807    if (chan) {
03808       chan = ast_channel_unref(chan);
03809    }
03810    return 0;
03811 }
03812 
03813 static int action_originate(struct mansession *s, const struct message *m)
03814 {
03815    const char *name = astman_get_header(m, "Channel");
03816    const char *exten = astman_get_header(m, "Exten");
03817    const char *context = astman_get_header(m, "Context");
03818    const char *priority = astman_get_header(m, "Priority");
03819    const char *timeout = astman_get_header(m, "Timeout");
03820    const char *callerid = astman_get_header(m, "CallerID");
03821    const char *account = astman_get_header(m, "Account");
03822    const char *app = astman_get_header(m, "Application");
03823    const char *appdata = astman_get_header(m, "Data");
03824    const char *async = astman_get_header(m, "Async");
03825    const char *id = astman_get_header(m, "ActionID");
03826    const char *codecs = astman_get_header(m, "Codecs");
03827    struct ast_variable *vars;
03828    char *tech, *data;
03829    char *l = NULL, *n = NULL;
03830    int pi = 0;
03831    int res;
03832    int to = 30000;
03833    int reason = 0;
03834    char tmp[256];
03835    char tmp2[256];
03836    format_t format = AST_FORMAT_SLINEAR;
03837 
03838    pthread_t th;
03839    if (ast_strlen_zero(name)) {
03840       astman_send_error(s, m, "Channel not specified");
03841       return 0;
03842    }
03843    if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
03844       if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
03845          astman_send_error(s, m, "Invalid priority");
03846          return 0;
03847       }
03848    }
03849    if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%30d", &to) != 1)) {
03850       astman_send_error(s, m, "Invalid timeout");
03851       return 0;
03852    }
03853    ast_copy_string(tmp, name, sizeof(tmp));
03854    tech = tmp;
03855    data = strchr(tmp, '/');
03856    if (!data) {
03857       astman_send_error(s, m, "Invalid channel");
03858       return 0;
03859    }
03860    *data++ = '\0';
03861    ast_copy_string(tmp2, callerid, sizeof(tmp2));
03862    ast_callerid_parse(tmp2, &n, &l);
03863    if (n) {
03864       if (ast_strlen_zero(n)) {
03865          n = NULL;
03866       }
03867    }
03868    if (l) {
03869       ast_shrink_phone_number(l);
03870       if (ast_strlen_zero(l)) {
03871          l = NULL;
03872       }
03873    }
03874    if (!ast_strlen_zero(codecs)) {
03875       format = 0;
03876       ast_parse_allow_disallow(NULL, &format, codecs, 1);
03877    }
03878    /* Allocate requested channel variables */
03879    vars = astman_get_variables(m);
03880 
03881    if (ast_true(async)) {
03882       struct fast_originate_helper *fast = ast_calloc(1, sizeof(*fast));
03883       if (!fast) {
03884          res = -1;
03885       } else {
03886          if (!ast_strlen_zero(id))
03887             snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s", id);
03888          ast_copy_string(fast->tech, tech, sizeof(fast->tech));
03889          ast_copy_string(fast->data, data, sizeof(fast->data));
03890          ast_copy_string(fast->app, app, sizeof(fast->app));
03891          ast_copy_string(fast->appdata, appdata, sizeof(fast->appdata));
03892          if (l) {
03893             ast_copy_string(fast->cid_num, l, sizeof(fast->cid_num));
03894          }
03895          if (n) {
03896             ast_copy_string(fast->cid_name, n, sizeof(fast->cid_name));
03897          }
03898          fast->vars = vars;
03899          ast_copy_string(fast->context, context, sizeof(fast->context));
03900          ast_copy_string(fast->exten, exten, sizeof(fast->exten));
03901          ast_copy_string(fast->account, account, sizeof(fast->account));
03902          fast->format = format;
03903          fast->timeout = to;
03904          fast->priority = pi;
03905          if (ast_pthread_create_detached(&th, NULL, fast_originate, fast)) {
03906             ast_free(fast);
03907             res = -1;
03908          } else {
03909             res = 0;
03910          }
03911       }
03912    } else if (!ast_strlen_zero(app)) {
03913       /* To run the System application (or anything else that goes to shell), you must have the additional System privilege */
03914       if (!(s->session->writeperm & EVENT_FLAG_SYSTEM)
03915          && (
03916             strcasestr(app, "system") ||      /* System(rm -rf /)
03917                                                  TrySystem(rm -rf /)       */
03918             strcasestr(app, "exec") ||        /* Exec(System(rm -rf /))
03919                                                  TryExec(System(rm -rf /)) */
03920             strcasestr(app, "agi") ||         /* AGI(/bin/rm,-rf /)
03921                                                  EAGI(/bin/rm,-rf /)       */
03922             strstr(appdata, "SHELL") ||       /* NoOp(${SHELL(rm -rf /)})  */
03923             strstr(appdata, "EVAL")           /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
03924             )) {
03925          astman_send_error(s, m, "Originate with certain 'Application' arguments requires the additional System privilege, which you do not have.");
03926          return 0;
03927       }
03928       res = ast_pbx_outgoing_app(tech, format, data, to, app, appdata, &reason, 1, l, n, vars, account, NULL);
03929    } else {
03930       if (exten && context && pi) {
03931          res = ast_pbx_outgoing_exten(tech, format, data, to, context, exten, pi, &reason, 1, l, n, vars, account, NULL);
03932       } else {
03933          astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
03934          if (vars) {
03935             ast_variables_destroy(vars);
03936          }
03937          return 0;
03938       }
03939    }
03940    if (!res) {
03941       astman_send_ack(s, m, "Originate successfully queued");
03942    } else {
03943       astman_send_error(s, m, "Originate failed");
03944    }
03945    return 0;
03946 }
03947 
03948 static int action_mailboxstatus(struct mansession *s, const struct message *m)
03949 {
03950    const char *mailbox = astman_get_header(m, "Mailbox");
03951    int ret;
03952 
03953    if (ast_strlen_zero(mailbox)) {
03954       astman_send_error(s, m, "Mailbox not specified");
03955       return 0;
03956    }
03957    ret = ast_app_has_voicemail(mailbox, NULL);
03958    astman_start_ack(s, m);
03959    astman_append(s, "Message: Mailbox Status\r\n"
03960           "Mailbox: %s\r\n"
03961           "Waiting: %d\r\n\r\n", mailbox, ret);
03962    return 0;
03963 }
03964 
03965 static int action_mailboxcount(struct mansession *s, const struct message *m)
03966 {
03967    const char *mailbox = astman_get_header(m, "Mailbox");
03968    int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;;
03969 
03970    if (ast_strlen_zero(mailbox)) {
03971       astman_send_error(s, m, "Mailbox not specified");
03972       return 0;
03973    }
03974    ast_app_inboxcount2(mailbox, &urgentmsgs, &newmsgs, &oldmsgs);
03975    astman_start_ack(s, m);
03976    astman_append(s,   "Message: Mailbox Message Count\r\n"
03977             "Mailbox: %s\r\n"
03978             "UrgMessages: %d\r\n"
03979             "NewMessages: %d\r\n"
03980             "OldMessages: %d\r\n"
03981             "\r\n",
03982             mailbox, urgentmsgs, newmsgs, oldmsgs);
03983    return 0;
03984 }
03985 
03986 static int action_extensionstate(struct mansession *s, const struct message *m)
03987 {
03988    const char *exten = astman_get_header(m, "Exten");
03989    const char *context = astman_get_header(m, "Context");
03990    char hint[256] = "";
03991    int status;
03992    if (ast_strlen_zero(exten)) {
03993       astman_send_error(s, m, "Extension not specified");
03994       return 0;
03995    }
03996    if (ast_strlen_zero(context)) {
03997       context = "default";
03998    }
03999    status = ast_extension_state(NULL, context, exten);
04000    ast_get_hint(hint, sizeof(hint) - 1, NULL, 0, NULL, context, exten);
04001    astman_start_ack(s, m);
04002    astman_append(s,   "Message: Extension Status\r\n"
04003             "Exten: %s\r\n"
04004             "Context: %s\r\n"
04005             "Hint: %s\r\n"
04006             "Status: %d\r\n\r\n",
04007             exten, context, hint, status);
04008    return 0;
04009 }
04010 
04011 static int action_timeout(struct mansession *s, const struct message *m)
04012 {
04013    struct ast_channel *c;
04014    const char *name = astman_get_header(m, "Channel");
04015    double timeout = atof(astman_get_header(m, "Timeout"));
04016    struct timeval when = { timeout, 0 };
04017 
04018    if (ast_strlen_zero(name)) {
04019       astman_send_error(s, m, "No channel specified");
04020       return 0;
04021    }
04022 
04023    if (!timeout || timeout < 0) {
04024       astman_send_error(s, m, "No timeout specified");
04025       return 0;
04026    }
04027 
04028    if (!(c = ast_channel_get_by_name(name))) {
04029       astman_send_error(s, m, "No such channel");
04030       return 0;
04031    }
04032 
04033    when.tv_usec = (timeout - when.tv_sec) * 1000000.0;
04034 
04035    ast_channel_lock(c);
04036    ast_channel_setwhentohangup_tv(c, when);
04037    ast_channel_unlock(c);
04038    c = ast_channel_unref(c);
04039 
04040    astman_send_ack(s, m, "Timeout Set");
04041 
04042    return 0;
04043 }
04044 
04045 static int whitefilter_cmp_fn(void *obj, void *arg, void *data, int flags)
04046 {
04047    regex_t *regex_filter = obj;
04048    const char *eventdata = arg;
04049    int *result = data;
04050 
04051    if (!regexec(regex_filter, eventdata, 0, NULL, 0)) {
04052       *result = 1;
04053       return (CMP_MATCH | CMP_STOP);
04054    }
04055 
04056    return 0;
04057 }
04058 
04059 static int blackfilter_cmp_fn(void *obj, void *arg, void *data, int flags)
04060 {
04061    regex_t *regex_filter = obj;
04062    const char *eventdata = arg;
04063    int *result = data;
04064 
04065    if (regexec(regex_filter, eventdata, 0, NULL, 0)) {
04066       *result = 1;
04067       return (CMP_MATCH | CMP_STOP);
04068    }
04069 
04070    return 0;
04071 }
04072 
04073 static int match_filter(struct mansession *s, char *eventdata)
04074 {
04075    int result = 0;
04076 
04077    ast_debug(3, "Examining event:\n%s\n", eventdata);
04078    if (!ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
04079       return 1; /* no filtering means match all */
04080    } else if (ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
04081       /* white filters only: implied black all filter processed first, then white filters */
04082       ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container"); 
04083    } else if (!ao2_container_count(s->session->whitefilters) && ao2_container_count(s->session->blackfilters)) {
04084       /* black filters only: implied white all filter processed first, then black filters */
04085       ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container"); 
04086    } else {
04087       /* white and black filters: implied black all filter processed first, then white filters, and lastly black filters */
04088       ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container"); 
04089       if (result) {
04090          result = 0;
04091          ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container"); 
04092       }
04093    }
04094 
04095    return result;
04096 }
04097 
04098 /*!
04099  * Send any applicable events to the client listening on this socket.
04100  * Wait only for a finite time on each event, and drop all events whether
04101  * they are successfully sent or not.
04102  */
04103 static int process_events(struct mansession *s)
04104 {
04105    int ret = 0;
04106 
04107    ao2_lock(s->session);
04108    if (s->session->f != NULL) {
04109       struct eventqent *eqe = s->session->last_ev;
04110       AST_RWLIST_RDLOCK(&all_events);
04111       while ((eqe = advance_event(eqe))) {
04112          if (!ret && s->session->authenticated &&
04113              (s->session->readperm & eqe->category) == eqe->category &&
04114              (s->session->send_events & eqe->category) == eqe->category) {
04115                if (match_filter(s, eqe->eventdata)) {
04116                   if (send_string(s, eqe->eventdata) < 0)
04117                      ret = -1;   /* don't send more */
04118                }
04119          }
04120          s->session->last_ev = eqe;
04121       }
04122       AST_RWLIST_UNLOCK(&all_events);
04123    }
04124    ao2_unlock(s->session);
04125    return ret;
04126 }
04127 
04128 static int action_userevent(struct mansession *s, const struct message *m)
04129 {
04130    const char *event = astman_get_header(m, "UserEvent");
04131    struct ast_str *body = ast_str_thread_get(&userevent_buf, 16);
04132    int x;
04133 
04134    ast_str_reset(body);
04135 
04136    for (x = 0; x < m->hdrcount; x++) {
04137       if (strncasecmp("UserEvent:", m->headers[x], strlen("UserEvent:"))) {
04138          ast_str_append(&body, 0, "%s\r\n", m->headers[x]);
04139       }
04140    }
04141 
04142    astman_send_ack(s, m, "Event Sent");   
04143    manager_event(EVENT_FLAG_USER, "UserEvent", "UserEvent: %s\r\n%s", event, ast_str_buffer(body));
04144    return 0;
04145 }
04146 
04147 /*! \brief Show PBX core settings information */
04148 static int action_coresettings(struct mansession *s, const struct message *m)
04149 {
04150    const char *actionid = astman_get_header(m, "ActionID");
04151    char idText[150];
04152 
04153    if (!ast_strlen_zero(actionid)) {
04154       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
04155    } else {
04156       idText[0] = '\0';
04157    }
04158 
04159    astman_append(s, "Response: Success\r\n"
04160          "%s"
04161          "AMIversion: %s\r\n"
04162          "AsteriskVersion: %s\r\n"
04163          "SystemName: %s\r\n"
04164          "CoreMaxCalls: %d\r\n"
04165          "CoreMaxLoadAvg: %f\r\n"
04166          "CoreRunUser: %s\r\n"
04167          "CoreRunGroup: %s\r\n"
04168          "CoreMaxFilehandles: %d\r\n"
04169          "CoreRealTimeEnabled: %s\r\n"
04170          "CoreCDRenabled: %s\r\n"
04171          "CoreHTTPenabled: %s\r\n"
04172          "\r\n",
04173          idText,
04174          AMI_VERSION,
04175          ast_get_version(),
04176          ast_config_AST_SYSTEM_NAME,
04177          option_maxcalls,
04178          option_maxload,
04179          ast_config_AST_RUN_USER,
04180          ast_config_AST_RUN_GROUP,
04181          option_maxfiles,
04182          AST_CLI_YESNO(ast_realtime_enabled()),
04183          AST_CLI_YESNO(check_cdr_enabled()),
04184          AST_CLI_YESNO(check_webmanager_enabled())
04185          );
04186    return 0;
04187 }
04188 
04189 /*! \brief Show PBX core status information */
04190 static int action_corestatus(struct mansession *s, const struct message *m)
04191 {
04192    const char *actionid = astman_get_header(m, "ActionID");
04193    char idText[150];
04194    char startuptime[150], startupdate[150];
04195    char reloadtime[150], reloaddate[150];
04196    struct ast_tm tm;
04197 
04198    if (!ast_strlen_zero(actionid)) {
04199       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
04200    } else {
04201       idText[0] = '\0';
04202    }
04203 
04204    ast_localtime(&ast_startuptime, &tm, NULL);
04205    ast_strftime(startuptime, sizeof(startuptime), "%H:%M:%S", &tm);
04206    ast_strftime(startupdate, sizeof(startupdate), "%Y-%m-%d", &tm);
04207    ast_localtime(&ast_lastreloadtime, &tm, NULL);
04208    ast_strftime(reloadtime, sizeof(reloadtime), "%H:%M:%S", &tm);
04209    ast_strftime(reloaddate, sizeof(reloaddate), "%Y-%m-%d", &tm);
04210 
04211    astman_append(s, "Response: Success\r\n"
04212          "%s"
04213          "CoreStartupDate: %s\r\n"
04214          "CoreStartupTime: %s\r\n"
04215          "CoreReloadDate: %s\r\n"
04216          "CoreReloadTime: %s\r\n"
04217          "CoreCurrentCalls: %d\r\n"
04218          "\r\n",
04219          idText,
04220          startupdate,
04221          startuptime,
04222          reloaddate,
04223          reloadtime,
04224          ast_active_channels()
04225          );
04226    return 0;
04227 }
04228 
04229 /*! \brief Send a reload event */
04230 static int action_reload(struct mansession *s, const struct message *m)
04231 {
04232    const char *module = astman_get_header(m, "Module");
04233    int res = ast_module_reload(S_OR(module, NULL));
04234 
04235    if (res == 2) {
04236       astman_send_ack(s, m, "Module Reloaded");
04237    } else {
04238       astman_send_error(s, m, s == 0 ? "No such module" : "Module does not support reload");
04239    }
04240    return 0;
04241 }
04242 
04243 /*! \brief  Manager command "CoreShowChannels" - List currently defined channels
04244  *          and some information about them. */
04245 static int action_coreshowchannels(struct mansession *s, const struct message *m)
04246 {
04247    const char *actionid = astman_get_header(m, "ActionID");
04248    char idText[256];
04249    struct ast_channel *c = NULL;
04250    int numchans = 0;
04251    int duration, durh, durm, durs;
04252    struct ast_channel_iterator *iter;
04253 
04254    if (!ast_strlen_zero(actionid)) {
04255       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
04256    } else {
04257       idText[0] = '\0';
04258    }
04259 
04260    if (!(iter = ast_channel_iterator_all_new())) {
04261       astman_send_error(s, m, "Memory Allocation Failure");
04262       return 1;
04263    }
04264 
04265    astman_send_listack(s, m, "Channels will follow", "start");
04266 
04267    for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
04268       struct ast_channel *bc;
04269       char durbuf[10] = "";
04270 
04271       ast_channel_lock(c);
04272 
04273       bc = ast_bridged_channel(c);
04274       if (c->cdr && !ast_tvzero(c->cdr->start)) {
04275          duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
04276          durh = duration / 3600;
04277          durm = (duration % 3600) / 60;
04278          durs = duration % 60;
04279          snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
04280       }
04281 
04282       astman_append(s,
04283          "Event: CoreShowChannel\r\n"
04284          "%s"
04285          "Channel: %s\r\n"
04286          "UniqueID: %s\r\n"
04287          "Context: %s\r\n"
04288          "Extension: %s\r\n"
04289          "Priority: %d\r\n"
04290          "ChannelState: %d\r\n"
04291          "ChannelStateDesc: %s\r\n"
04292          "Application: %s\r\n"
04293          "ApplicationData: %s\r\n"
04294          "CallerIDnum: %s\r\n"
04295          "Duration: %s\r\n"
04296          "AccountCode: %s\r\n"
04297          "BridgedChannel: %s\r\n"
04298          "BridgedUniqueID: %s\r\n"
04299          "\r\n", idText, c->name, c->uniqueid, c->context, c->exten, c->priority, c->_state,
04300          ast_state2str(c->_state), c->appl ? c->appl : "", c->data ? S_OR(c->data, "") : "",
04301          S_COR(c->caller.id.number.valid, c->caller.id.number.str, ""),
04302          durbuf, S_OR(c->accountcode, ""), bc ? bc->name : "", bc ? bc->uniqueid : "");
04303 
04304       ast_channel_unlock(c);
04305 
04306       numchans++;
04307    }
04308 
04309    astman_append(s,
04310       "Event: CoreShowChannelsComplete\r\n"
04311       "EventList: Complete\r\n"
04312       "ListItems: %d\r\n"
04313       "%s"
04314       "\r\n", numchans, idText);
04315 
04316    ast_channel_iterator_destroy(iter);
04317 
04318    return 0;
04319 }
04320 
04321 /* Manager function to check if module is loaded */
04322 static int manager_modulecheck(struct mansession *s, const struct message *m)
04323 {
04324    int res;
04325    const char *module = astman_get_header(m, "Module");
04326    const char *id = astman_get_header(m, "ActionID");
04327    char idText[256];
04328 #if !defined(LOW_MEMORY)
04329    const char *version;
04330 #endif
04331    char filename[PATH_MAX];
04332    char *cut;
04333 
04334    ast_copy_string(filename, module, sizeof(filename));
04335    if ((cut = strchr(filename, '.'))) {
04336       *cut = '\0';
04337    } else {
04338       cut = filename + strlen(filename);
04339    }
04340    snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".so");
04341    ast_log(LOG_DEBUG, "**** ModuleCheck .so file %s\n", filename);
04342    res = ast_module_check(filename);
04343    if (!res) {
04344       astman_send_error(s, m, "Module not loaded");
04345       return 0;
04346    }
04347    snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".c");
04348    ast_log(LOG_DEBUG, "**** ModuleCheck .c file %s\n", filename);
04349 #if !defined(LOW_MEMORY)
04350    version = ast_file_version_find(filename);
04351 #endif
04352 
04353    if (!ast_strlen_zero(id)) {
04354       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
04355    } else {
04356       idText[0] = '\0';
04357    }
04358    astman_append(s, "Response: Success\r\n%s", idText);
04359 #if !defined(LOW_MEMORY)
04360    astman_append(s, "Version: %s\r\n\r\n", version ? version : "");
04361 #endif
04362    return 0;
04363 }
04364 
04365 static int manager_moduleload(struct mansession *s, const struct message *m)
04366 {
04367    int res;
04368    const char *module = astman_get_header(m, "Module");
04369    const char *loadtype = astman_get_header(m, "LoadType");
04370 
04371    if (!loadtype || strlen(loadtype) == 0) {
04372       astman_send_error(s, m, "Incomplete ModuleLoad action.");
04373    }
04374    if ((!module || strlen(module) == 0) && strcasecmp(loadtype, "reload") != 0) {
04375       astman_send_error(s, m, "Need module name");
04376    }
04377 
04378    if (!strcasecmp(loadtype, "load")) {
04379       res = ast_load_resource(module);
04380       if (res) {
04381          astman_send_error(s, m, "Could not load module.");
04382       } else {
04383          astman_send_ack(s, m, "Module loaded.");
04384       }
04385    } else if (!strcasecmp(loadtype, "unload")) {
04386       res = ast_unload_resource(module, AST_FORCE_SOFT);
04387       if (res) {
04388          astman_send_error(s, m, "Could not unload module.");
04389       } else {
04390          astman_send_ack(s, m, "Module unloaded.");
04391       }
04392    } else if (!strcasecmp(loadtype, "reload")) {
04393       if (module != NULL) {
04394          res = ast_module_reload(module);
04395          if (res == 0) {
04396             astman_send_error(s, m, "No such module.");
04397          } else if (res == 1) {
04398             astman_send_error(s, m, "Module does not support reload action.");
04399          } else {
04400             astman_send_ack(s, m, "Module reloaded.");
04401          }
04402       } else {
04403          ast_module_reload(NULL);   /* Reload all modules */
04404          astman_send_ack(s, m, "All modules reloaded");
04405       }
04406    } else
04407       astman_send_error(s, m, "Incomplete ModuleLoad action.");
04408    return 0;
04409 }
04410 
04411 /*
04412  * Done with the action handlers here, we start with the code in charge
04413  * of accepting connections and serving them.
04414  * accept_thread() forks a new thread for each connection, session_do(),
04415  * which in turn calls get_input() repeatedly until a full message has
04416  * been accumulated, and then invokes process_message() to pass it to
04417  * the appropriate handler.
04418  */
04419 
04420 /*
04421  * Process an AMI message, performing desired action.
04422  * Return 0 on success, -1 on error that require the session to be destroyed.
04423  */
04424 static int process_message(struct mansession *s, const struct message *m)
04425 {
04426    char action[80] = "";
04427    int ret = 0;
04428    struct manager_action *tmp;
04429    const char *user = astman_get_header(m, "Username");
04430    int (*call_func)(struct mansession *s, const struct message *m) = NULL;
04431 
04432    ast_copy_string(action, __astman_get_header(m, "Action", GET_HEADER_SKIP_EMPTY), sizeof(action));
04433 
04434    if (ast_strlen_zero(action)) {
04435       report_req_bad_format(s, "NONE");
04436       mansession_lock(s);
04437       astman_send_error(s, m, "Missing action in request");
04438       mansession_unlock(s);
04439       return 0;
04440    }
04441 
04442    if (!s->session->authenticated && strcasecmp(action, "Login") && strcasecmp(action, "Logoff") && strcasecmp(action, "Challenge")) {
04443       if (!s->session->authenticated) {
04444          report_req_not_allowed(s, action);
04445       }
04446       mansession_lock(s);
04447       astman_send_error(s, m, "Permission denied");
04448       mansession_unlock(s);
04449       return 0;
04450    }
04451 
04452    if (!allowmultiplelogin && !s->session->authenticated && user &&
04453       (!strcasecmp(action, "Login") || !strcasecmp(action, "Challenge"))) {
04454       if (check_manager_session_inuse(user)) {
04455          report_session_limit(s);
04456          sleep(1);
04457          mansession_lock(s);
04458          astman_send_error(s, m, "Login Already In Use");
04459          mansession_unlock(s);
04460          return -1;
04461       }
04462    }
04463 
04464    AST_RWLIST_RDLOCK(&actions);
04465    AST_RWLIST_TRAVERSE(&actions, tmp, list) {
04466       if (strcasecmp(action, tmp->action)) {
04467          continue;
04468       }
04469       if (s->session->writeperm & tmp->authority || tmp->authority == 0) {
04470          call_func = tmp->func;
04471       } else {
04472          astman_send_error(s, m, "Permission denied");
04473          report_req_not_allowed(s, action);
04474       }
04475       break;
04476    }
04477    AST_RWLIST_UNLOCK(&actions);
04478 
04479    if (tmp && call_func) {
04480       /* call AMI function after actions list are unlocked */
04481       ast_debug(1, "Running action '%s'\n", tmp->action);
04482       ret = call_func(s, m);
04483    } else {
04484       char buf[512];
04485       if (!tmp) {
04486          report_req_bad_format(s, action);
04487       }
04488       snprintf(buf, sizeof(buf), "Invalid/unknown command: %s. Use Action: ListCommands to show available commands.", action);
04489       mansession_lock(s);
04490       astman_send_error(s, m, buf);
04491       mansession_unlock(s);
04492    }
04493    if (ret) {
04494       return ret;
04495    }
04496    /* Once done with our message, deliver any pending events unless the
04497       requester doesn't want them as part of this response.
04498    */
04499    if (ast_strlen_zero(astman_get_header(m, "SuppressEvents"))) {
04500       return process_events(s);
04501    } else {
04502       return ret;
04503    }
04504 }
04505 
04506 /*!
04507  * Read one full line (including crlf) from the manager socket.
04508  * \note \verbatim
04509  * \r\n is the only valid terminator for the line.
04510  * (Note that, later, '\0' will be considered as the end-of-line marker,
04511  * so everything between the '\0' and the '\r\n' will not be used).
04512  * Also note that we assume output to have at least "maxlen" space.
04513  * \endverbatim
04514  */
04515 static int get_input(struct mansession *s, char *output)
04516 {
04517    int res, x;
04518    int maxlen = sizeof(s->session->inbuf) - 1;
04519    char *src = s->session->inbuf;
04520 
04521    /*
04522     * Look for \r\n within the buffer. If found, copy to the output
04523     * buffer and return, trimming the \r\n (not used afterwards).
04524     */
04525    for (x = 0; x < s->session->inlen; x++) {
04526       int cr;  /* set if we have \r */
04527       if (src[x] == '\r' && x+1 < s->session->inlen && src[x + 1] == '\n') {
04528          cr = 2;  /* Found. Update length to include \r\n */
04529       } else if (src[x] == '\n') {
04530          cr = 1;  /* also accept \n only */
04531       } else {
04532          continue;
04533       }
04534       memmove(output, src, x);   /*... but trim \r\n */
04535       output[x] = '\0';    /* terminate the string */
04536       x += cr;       /* number of bytes used */
04537       s->session->inlen -= x;       /* remaining size */
04538       memmove(src, src + x, s->session->inlen); /* remove used bytes */
04539       return 1;
04540    }
04541    if (s->session->inlen >= maxlen) {
04542       /* no crlf found, and buffer full - sorry, too long for us */
04543       ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(s->session->sin.sin_addr), src);
04544       s->session->inlen = 0;
04545    }
04546    res = 0;
04547    while (res == 0) {
04548       ao2_lock(s->session);
04549       if (s->session->pending_event) {
04550          s->session->pending_event = 0;
04551          ao2_unlock(s->session);
04552          return 0;
04553       }
04554       s->session->waiting_thread = pthread_self();
04555       ao2_unlock(s->session);
04556 
04557       res = ast_wait_for_input(s->session->fd, -1);   /* return 0 on timeout ? */
04558 
04559       ao2_lock(s->session);
04560       s->session->waiting_thread = AST_PTHREADT_NULL;
04561       ao2_unlock(s->session);
04562    }
04563    if (res < 0) {
04564       /* If we get a signal from some other thread (typically because
04565        * there are new events queued), return 0 to notify the caller.
04566        */
04567       if (errno == EINTR || errno == EAGAIN) {
04568          return 0;
04569       }
04570       ast_log(LOG_WARNING, "poll() returned error: %s\n", strerror(errno));
04571       return -1;
04572    }
04573 
04574    ao2_lock(s->session);
04575    res = fread(src + s->session->inlen, 1, maxlen - s->session->inlen, s->session->f);
04576    if (res < 1) {
04577       res = -1;   /* error return */
04578    } else {
04579       s->session->inlen += res;
04580       src[s->session->inlen] = '\0';
04581       res = 0;
04582    }
04583    ao2_unlock(s->session);
04584    return res;
04585 }
04586 
04587 static int do_message(struct mansession *s)
04588 {
04589    struct message m = { 0 };
04590    char header_buf[sizeof(s->session->inbuf)] = { '\0' };
04591    int res;
04592 
04593    for (;;) {
04594       /* Check if any events are pending and do them if needed */
04595       if (process_events(s)) {
04596          return -1;
04597       }
04598       res = get_input(s, header_buf);
04599       if (res == 0) {
04600          continue;
04601       } else if (res > 0) {
04602          if (ast_strlen_zero(header_buf)) {
04603             return process_message(s, &m) ? -1 : 0;
04604          } else if (m.hdrcount < (AST_MAX_MANHEADERS - 1)) {
04605             m.headers[m.hdrcount++] = ast_strdupa(header_buf);
04606          }
04607       } else {
04608          return res;
04609       }
04610    }
04611 }
04612 
04613 /*! \brief The body of the individual manager session.
04614  * Call get_input() to read one line at a time
04615  * (or be woken up on new events), collect the lines in a
04616  * message until found an empty line, and execute the request.
04617  * In any case, deliver events asynchronously through process_events()
04618  * (called from here if no line is available, or at the end of
04619  * process_message(). )
04620  */
04621 static void *session_do(void *data)
04622 {
04623    struct ast_tcptls_session_instance *ser = data;
04624    struct mansession_session *session;
04625    struct mansession s = {
04626       .tcptls_session = data,
04627    };
04628    int flags;
04629    int res;
04630    struct sockaddr_in ser_remote_address_tmp;
04631    struct protoent *p;
04632 
04633    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
04634    session = build_mansession(ser_remote_address_tmp);
04635 
04636    if (session == NULL) {
04637       goto done;
04638    }
04639 
04640    /* here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
04641     * This is necessary to prevent delays (caused by buffering) as we
04642     * write to the socket in bits and peices. */
04643    p = getprotobyname("tcp");
04644    if (p) {
04645       int arg = 1;
04646       if( setsockopt(ser->fd, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
04647          ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\nSome manager actions may be slow to respond.\n", strerror(errno));
04648       }
04649    } else {
04650       ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY, getprotobyname(\"tcp\") failed\nSome manager actions may be slow to respond.\n");
04651    }
04652 
04653    flags = fcntl(ser->fd, F_GETFL);
04654    if (!block_sockets) { /* make sure socket is non-blocking */
04655       flags |= O_NONBLOCK;
04656    } else {
04657       flags &= ~O_NONBLOCK;
04658    }
04659    fcntl(ser->fd, F_SETFL, flags);
04660 
04661    ao2_lock(session);
04662    /* Hook to the tail of the event queue */
04663    session->last_ev = grab_last();
04664 
04665    ast_mutex_init(&s.lock);
04666 
04667    /* these fields duplicate those in the 'ser' structure */
04668    session->fd = s.fd = ser->fd;
04669    session->f = s.f = ser->f;
04670    session->sin = ser_remote_address_tmp;
04671    s.session = session;
04672 
04673    AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
04674 
04675    ao2_unlock(session);
04676    astman_append(&s, "Asterisk Call Manager/%s\r\n", AMI_VERSION);   /* welcome prompt */
04677    for (;;) {
04678       if ((res = do_message(&s)) < 0) {
04679          break;
04680       }
04681    }
04682    /* session is over, explain why and terminate */
04683    if (session->authenticated) {
04684       if (manager_displayconnects(session)) {
04685          ast_verb(2, "Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
04686       }
04687    } else {
04688       if (displayconnects) {
04689          ast_verb(2, "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
04690       }
04691    }
04692 
04693    /* It is possible under certain circumstances for this session thread
04694       to complete its work and exit *before* the thread that created it
04695       has finished executing the ast_pthread_create_background() function.
04696       If this occurs, some versions of glibc appear to act in a buggy
04697       fashion and attempt to write data into memory that it thinks belongs
04698       to the thread but is in fact not owned by the thread (or may have
04699       been freed completely).
04700 
04701       Causing this thread to yield to other threads at least one time
04702       appears to work around this bug.
04703    */
04704    usleep(1);
04705 
04706    session_destroy(session);
04707 
04708    ast_mutex_destroy(&s.lock);
04709 done:
04710    ao2_ref(ser, -1);
04711    ser = NULL;
04712    return NULL;
04713 }
04714 
04715 /*! \brief remove at most n_max stale session from the list. */
04716 static void purge_sessions(int n_max)
04717 {
04718    struct mansession_session *session;
04719    time_t now = time(NULL);
04720    struct ao2_iterator i;
04721 
04722    i = ao2_iterator_init(sessions, 0);
04723    while ((session = ao2_iterator_next(&i)) && n_max > 0) {
04724       ao2_lock(session);
04725       if (session->sessiontimeout && (now > session->sessiontimeout) && !session->inuse) {
04726          if (session->authenticated && (VERBOSITY_ATLEAST(2)) && manager_displayconnects(session)) {
04727             ast_verb(2, "HTTP Manager '%s' timed out from %s\n",
04728                session->username, ast_inet_ntoa(session->sin.sin_addr));
04729          }
04730          ao2_unlock(session);
04731          session_destroy(session);
04732          n_max--;
04733       } else {
04734          ao2_unlock(session);
04735          unref_mansession(session);
04736       }
04737    }
04738    ao2_iterator_destroy(&i);
04739 }
04740 
04741 /*
04742  * events are appended to a queue from where they
04743  * can be dispatched to clients.
04744  */
04745 static int append_event(const char *str, int category)
04746 {
04747    struct eventqent *tmp = ast_malloc(sizeof(*tmp) + strlen(str));
04748    static int seq;   /* sequence number */
04749 
04750    if (!tmp) {
04751       return -1;
04752    }
04753 
04754    /* need to init all fields, because ast_malloc() does not */
04755    tmp->usecount = 0;
04756    tmp->category = category;
04757    tmp->seq = ast_atomic_fetchadd_int(&seq, 1);
04758    tmp->tv = ast_tvnow();
04759    AST_RWLIST_NEXT(tmp, eq_next) = NULL;
04760    strcpy(tmp->eventdata, str);
04761 
04762    AST_RWLIST_WRLOCK(&all_events);
04763    AST_RWLIST_INSERT_TAIL(&all_events, tmp, eq_next);
04764    AST_RWLIST_UNLOCK(&all_events);
04765 
04766    return 0;
04767 }
04768 
04769 AST_THREADSTORAGE(manager_event_funcbuf);
04770 
04771 static void append_channel_vars(struct ast_str **pbuf, struct ast_channel *chan)
04772 {
04773    struct manager_channel_variable *var;
04774    AST_RWLIST_RDLOCK(&channelvars);
04775    AST_LIST_TRAVERSE(&channelvars, var, entry) {
04776       const char *val = "";
04777       if (var->isfunc) {
04778          struct ast_str *res = ast_str_thread_get(&manager_event_funcbuf, 16);
04779          int ret;
04780          if (res && (ret = ast_func_read2(chan, var->name, &res, 0)) == 0) {
04781             val = ast_str_buffer(res);
04782          }
04783       } else {
04784          val = pbx_builtin_getvar_helper(chan, var->name);
04785       }
04786       ast_str_append(pbuf, 0, "ChanVariable(%s): %s=%s\r\n", chan->name, var->name, val ? val : "");
04787    }
04788    AST_RWLIST_UNLOCK(&channelvars);
04789 }
04790 
04791 /* XXX see if can be moved inside the function */
04792 AST_THREADSTORAGE(manager_event_buf);
04793 #define MANAGER_EVENT_BUF_INITSIZE   256
04794 
04795 int __ast_manager_event_multichan(int category, const char *event, int chancount, struct
04796    ast_channel **chans, const char *file, int line, const char *func, const char *fmt, ...)
04797 {
04798    struct mansession_session *session;
04799    struct manager_custom_hook *hook;
04800    struct ast_str *auth = ast_str_alloca(80);
04801    const char *cat_str;
04802    va_list ap;
04803    struct timeval now;
04804    struct ast_str *buf;
04805    int i;
04806 
04807    if (!sessions && AST_RWLIST_EMPTY(&manager_hooks)) {
04808       return 0;
04809    }
04810    
04811    if (!(buf = ast_str_thread_get(&manager_event_buf, MANAGER_EVENT_BUF_INITSIZE))) {
04812       return -1;
04813    }
04814 
04815    cat_str = authority_to_str(category, &auth);
04816    ast_str_set(&buf, 0,
04817          "Event: %s\r\nPrivilege: %s\r\n",
04818           event, cat_str);
04819 
04820    if (timestampevents) {
04821       now = ast_tvnow();
04822       ast_str_append(&buf, 0,
04823             "Timestamp: %ld.%06lu\r\n",
04824              (long)now.tv_sec, (unsigned long) now.tv_usec);
04825    }
04826    if (manager_debug) {
04827       static int seq;
04828       ast_str_append(&buf, 0,
04829             "SequenceNumber: %d\r\n",
04830              ast_atomic_fetchadd_int(&seq, 1));
04831       ast_str_append(&buf, 0,
04832             "File: %s\r\nLine: %d\r\nFunc: %s\r\n", file, line, func);
04833    }
04834 
04835    va_start(ap, fmt);
04836    ast_str_append_va(&buf, 0, fmt, ap);
04837    va_end(ap);
04838    for (i = 0; i < chancount; i++) {
04839       append_channel_vars(&buf, chans[i]);
04840    }
04841 
04842    ast_str_append(&buf, 0, "\r\n");
04843 
04844    append_event(ast_str_buffer(buf), category);
04845 
04846    /* Wake up any sleeping sessions */
04847    if (sessions) {
04848       struct ao2_iterator i;
04849       i = ao2_iterator_init(sessions, 0);
04850       while ((session = ao2_iterator_next(&i))) {
04851          ao2_lock(session);
04852          if (session->waiting_thread != AST_PTHREADT_NULL) {
04853             pthread_kill(session->waiting_thread, SIGURG);
04854          } else {
04855             /* We have an event to process, but the mansession is
04856              * not waiting for it. We still need to indicate that there
04857              * is an event waiting so that get_input processes the pending
04858              * event instead of polling.
04859              */
04860             session->pending_event = 1;
04861          }
04862          ao2_unlock(session);
04863          unref_mansession(session);
04864       }
04865       ao2_iterator_destroy(&i);
04866    }
04867 
04868    if (!AST_RWLIST_EMPTY(&manager_hooks)) {
04869       AST_RWLIST_RDLOCK(&manager_hooks);
04870       AST_RWLIST_TRAVERSE(&manager_hooks, hook, list) {
04871          hook->helper(category, event, ast_str_buffer(buf));
04872       }
04873       AST_RWLIST_UNLOCK(&manager_hooks);
04874    }
04875 
04876    return 0;
04877 }
04878 
04879 /*
04880  * support functions to register/unregister AMI action handlers,
04881  */
04882 int ast_manager_unregister(char *action)
04883 {
04884    struct manager_action *cur;
04885    struct timespec tv = { 5, };
04886 
04887    if (AST_RWLIST_TIMEDWRLOCK(&actions, &tv)) {
04888       ast_log(LOG_ERROR, "Could not obtain lock on manager list\n");
04889       return -1;
04890    }
04891    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&actions, cur, list) {
04892       if (!strcasecmp(action, cur->action)) {
04893          AST_RWLIST_REMOVE_CURRENT(list);
04894          ast_string_field_free_memory(cur);
04895          ast_free(cur);
04896          ast_verb(2, "Manager unregistered action %s\n", action);
04897          break;
04898       }
04899    }
04900    AST_RWLIST_TRAVERSE_SAFE_END;
04901    AST_RWLIST_UNLOCK(&actions);
04902 
04903    return 0;
04904 }
04905 
04906 static int manager_state_cb(char *context, char *exten, int state, void *data)
04907 {
04908    /* Notify managers of change */
04909    char hint[512];
04910    ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
04911 
04912    manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nHint: %s\r\nStatus: %d\r\n", exten, context, hint, state);
04913    return 0;
04914 }
04915 
04916 static int ast_manager_register_struct(struct manager_action *act)
04917 {
04918    struct manager_action *cur, *prev = NULL;
04919    struct timespec tv = { 5, };
04920 
04921    if (AST_RWLIST_TIMEDWRLOCK(&actions, &tv)) {
04922       ast_log(LOG_ERROR, "Could not obtain lock on manager list\n");
04923       return -1;
04924    }
04925    AST_RWLIST_TRAVERSE(&actions, cur, list) {
04926       int ret = strcasecmp(cur->action, act->action);
04927       if (ret == 0) {
04928          ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
04929          AST_RWLIST_UNLOCK(&actions);
04930          return -1;
04931       }
04932       if (ret > 0) { /* Insert these alphabetically */
04933          prev = cur;
04934          break;
04935       }
04936    }
04937 
04938    if (prev) {
04939       AST_RWLIST_INSERT_AFTER(&actions, prev, act, list);
04940    } else {
04941       AST_RWLIST_INSERT_HEAD(&actions, act, list);
04942    }
04943 
04944    ast_verb(2, "Manager registered action %s\n", act->action);
04945 
04946    AST_RWLIST_UNLOCK(&actions);
04947 
04948    return 0;
04949 }
04950 
04951 /*! \brief register a new command with manager, including online help. This is
04952    the preferred way to register a manager command */
04953 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), const char *synopsis, const char *description)
04954 {
04955    struct manager_action *cur = NULL;
04956 #ifdef AST_XML_DOCS
04957    char *tmpxml;
04958 #endif
04959 
04960    if (!(cur = ast_calloc_with_stringfields(1, struct manager_action, 128))) {
04961       return -1;
04962    }
04963 
04964    cur->action = action;
04965    cur->authority = auth;
04966    cur->func = func;
04967 #ifdef AST_XML_DOCS
04968    if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
04969       tmpxml = ast_xmldoc_build_synopsis("manager", action);
04970       ast_string_field_set(cur, synopsis, tmpxml);
04971       ast_free(tmpxml);
04972 
04973       tmpxml = ast_xmldoc_build_syntax("manager", action);
04974       ast_string_field_set(cur, syntax, tmpxml);
04975       ast_free(tmpxml);
04976 
04977       tmpxml = ast_xmldoc_build_description("manager", action);
04978       ast_string_field_set(cur, description, tmpxml);
04979       ast_free(tmpxml);
04980 
04981       tmpxml = ast_xmldoc_build_seealso("manager", action);
04982       ast_string_field_set(cur, seealso, tmpxml);
04983       ast_free(tmpxml);
04984 
04985       tmpxml = ast_xmldoc_build_arguments("manager", action);
04986       ast_string_field_set(cur, arguments, tmpxml);
04987       ast_free(tmpxml);
04988 
04989       cur->docsrc = AST_XML_DOC;
04990    } else {
04991 #endif
04992       ast_string_field_set(cur, synopsis, synopsis);
04993       ast_string_field_set(cur, description, description);
04994 #ifdef AST_XML_DOCS
04995       cur->docsrc = AST_STATIC_DOC;
04996    }
04997 #endif
04998    if (ast_manager_register_struct(cur)) {
04999       ast_free(cur);
05000       return -1;
05001    }
05002 
05003    return 0;
05004 }
05005 /*! @}
05006  END Doxygen group */
05007 
05008 /*
05009  * The following are support functions for AMI-over-http.
05010  * The common entry point is generic_http_callback(),
05011  * which extracts HTTP header and URI fields and reformats
05012  * them into AMI messages, locates a proper session
05013  * (using the mansession_id Cookie or GET variable),
05014  * and calls process_message() as for regular AMI clients.
05015  * When done, the output (which goes to a temporary file)
05016  * is read back into a buffer and reformatted as desired,
05017  * then fed back to the client over the original socket.
05018  */
05019 
05020 enum output_format {
05021    FORMAT_RAW,
05022    FORMAT_HTML,
05023    FORMAT_XML,
05024 };
05025 
05026 static const char * const contenttype[] = {
05027    [FORMAT_RAW] = "plain",
05028    [FORMAT_HTML] = "html",
05029    [FORMAT_XML] =  "xml",
05030 };
05031 
05032 /*!
05033  * locate an http session in the list. The search key (ident) is
05034  * the value of the mansession_id cookie (0 is not valid and means
05035  * a session on the AMI socket).
05036  */
05037 static struct mansession_session *find_session(uint32_t ident, int incinuse)
05038 {
05039    struct mansession_session *session;
05040    struct ao2_iterator i;
05041 
05042    if (ident == 0) {
05043       return NULL;
05044    }
05045 
05046    i = ao2_iterator_init(sessions, 0);
05047    while ((session = ao2_iterator_next(&i))) {
05048       ao2_lock(session);
05049       if (session->managerid == ident && !session->needdestroy) {
05050          ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
05051          break;
05052       }
05053       ao2_unlock(session);
05054       unref_mansession(session);
05055    }
05056    ao2_iterator_destroy(&i);
05057 
05058    return session;
05059 }
05060 
05061 /*!
05062  * locate an http session in the list.
05063  * The search keys (nonce) and (username) is value from received
05064  * "Authorization" http header.
05065  * As well as in find_session() function, the value of the nonce can't be zero.
05066  * (0 meansi, that the session used for AMI socket connection).
05067  * Flag (stale) is set, if client used valid, but old, nonce value.
05068  *
05069  */
05070 static struct mansession_session *find_session_by_nonce(const char *username, unsigned long nonce, int *stale)
05071 {
05072    struct mansession_session *session;
05073    struct ao2_iterator i;
05074 
05075    if (nonce == 0 || username == NULL || stale == NULL) {
05076       return NULL;
05077    }
05078 
05079    i = ao2_iterator_init(sessions, 0);
05080    while ((session = ao2_iterator_next(&i))) {
05081       ao2_lock(session);
05082       if (!strcasecmp(session->username, username) && session->managerid == nonce) {
05083          *stale = 0;
05084          break;
05085       } else if (!strcasecmp(session->username, username) && session->oldnonce == nonce) {
05086          *stale = 1;
05087          break;
05088       }
05089       ao2_unlock(session);
05090       unref_mansession(session);
05091    }
05092    ao2_iterator_destroy(&i);
05093    return session;
05094 }
05095 
05096 int astman_is_authed(uint32_t ident)
05097 {
05098    int authed;
05099    struct mansession_session *session;
05100 
05101    if (!(session = find_session(ident, 0)))
05102       return 0;
05103 
05104    authed = (session->authenticated != 0);
05105 
05106    ao2_unlock(session);
05107    unref_mansession(session);
05108 
05109    return authed;
05110 }
05111 
05112 int astman_verify_session_readpermissions(uint32_t ident, int perm)
05113 {
05114    int result = 0;
05115    struct mansession_session *session;
05116    struct ao2_iterator i;
05117 
05118    if (ident == 0) {
05119       return 0;
05120    }
05121 
05122    i = ao2_iterator_init(sessions, 0);
05123    while ((session = ao2_iterator_next(&i))) {
05124       ao2_lock(session);
05125       if ((session->managerid == ident) && (session->readperm & perm)) {
05126          result = 1;
05127          ao2_unlock(session);
05128          unref_mansession(session);
05129          break;
05130       }
05131       ao2_unlock(session);
05132       unref_mansession(session);
05133    }
05134    ao2_iterator_destroy(&i);
05135    return result;
05136 }
05137 
05138 int astman_verify_session_writepermissions(uint32_t ident, int perm)
05139 {
05140    int result = 0;
05141    struct mansession_session *session;
05142    struct ao2_iterator i;
05143 
05144    if (ident == 0) {
05145       return 0;
05146    }
05147 
05148    i = ao2_iterator_init(sessions, 0);
05149    while ((session = ao2_iterator_next(&i))) {
05150       ao2_lock(session);
05151       if ((session->managerid == ident) && (session->writeperm & perm)) {
05152          result = 1;
05153          ao2_unlock(session);
05154          unref_mansession(session);
05155          break;
05156       }
05157       ao2_unlock(session);
05158       unref_mansession(session);
05159    }
05160    ao2_iterator_destroy(&i);
05161    return result;
05162 }
05163 
05164 /*
05165  * convert to xml with various conversion:
05166  * mode & 1 -> lowercase;
05167  * mode & 2 -> replace non-alphanumeric chars with underscore
05168  */
05169 static void xml_copy_escape(struct ast_str **out, const char *src, int mode)
05170 {
05171    /* store in a local buffer to avoid calling ast_str_append too often */
05172    char buf[256];
05173    char *dst = buf;
05174    int space = sizeof(buf);
05175    /* repeat until done and nothing to flush */
05176    for ( ; *src || dst != buf ; src++) {
05177       if (*src == '\0' || space < 10) {   /* flush */
05178          *dst++ = '\0';
05179          ast_str_append(out, 0, "%s", buf);
05180          dst = buf;
05181          space = sizeof(buf);
05182          if (*src == '\0') {
05183             break;
05184          }
05185       }
05186 
05187       if ( (mode & 2) && !isalnum(*src)) {
05188          *dst++ = '_';
05189          space--;
05190          continue;
05191       }
05192       switch (*src) {
05193       case '<':
05194          strcpy(dst, "&lt;");
05195          dst += 4;
05196          space -= 4;
05197          break;
05198       case '>':
05199          strcpy(dst, "&gt;");
05200          dst += 4;
05201          space -= 4;
05202          break;
05203       case '\"':
05204          strcpy(dst, "&quot;");
05205          dst += 6;
05206          space -= 6;
05207          break;
05208       case '\'':
05209          strcpy(dst, "&apos;");
05210          dst += 6;
05211          space -= 6;
05212          break;
05213       case '&':
05214          strcpy(dst, "&amp;");
05215          dst += 5;
05216          space -= 5;
05217          break;
05218 
05219       default:
05220          *dst++ = mode ? tolower(*src) : *src;
05221          space--;
05222       }
05223    }
05224 }
05225 
05226 struct variable_count {
05227    char *varname;
05228    int count;
05229 };
05230 
05231 static int variable_count_hash_fn(const void *vvc, const int flags)
05232 {
05233    const struct variable_count *vc = vvc;
05234 
05235    return ast_str_hash(vc->varname);
05236 }
05237 
05238 static int variable_count_cmp_fn(void *obj, void *vstr, int flags)
05239 {
05240    /* Due to the simplicity of struct variable_count, it makes no difference
05241     * if you pass in objects or strings, the same operation applies. This is
05242     * due to the fact that the hash occurs on the first element, which means
05243     * the address of both the struct and the string are exactly the same. */
05244    struct variable_count *vc = obj;
05245    char *str = vstr;
05246    return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
05247 }
05248 
05249 /*! \brief Convert the input into XML or HTML.
05250  * The input is supposed to be a sequence of lines of the form
05251  * Name: value
05252  * optionally followed by a blob of unformatted text.
05253  * A blank line is a section separator. Basically, this is a
05254  * mixture of the format of Manager Interface and CLI commands.
05255  * The unformatted text is considered as a single value of a field
05256  * named 'Opaque-data'.
05257  *
05258  * At the moment the output format is the following (but it may
05259  * change depending on future requirements so don't count too
05260  * much on it when writing applications):
05261  *
05262  * General: the unformatted text is used as a value of
05263  * XML output:  to be completed
05264  *
05265  * \verbatim
05266  *   Each section is within <response type="object" id="xxx">
05267  *   where xxx is taken from ajaxdest variable or defaults to unknown
05268  *   Each row is reported as an attribute Name="value" of an XML
05269  *   entity named from the variable ajaxobjtype, default to "generic"
05270  * \endverbatim
05271  *
05272  * HTML output:
05273  *   each Name-value pair is output as a single row of a two-column table.
05274  *   Sections (blank lines in the input) are separated by a <HR>
05275  *
05276  */
05277 static void xml_translate(struct ast_str **out, char *in, struct ast_variable *get_vars, enum output_format format)
05278 {
05279    struct ast_variable *v;
05280    const char *dest = NULL;
05281    char *var, *val;
05282    const char *objtype = NULL;
05283    int in_data = 0;  /* parsing data */
05284    int inobj = 0;
05285    int xml = (format == FORMAT_XML);
05286    struct variable_count *vc = NULL;
05287    struct ao2_container *vco = NULL;
05288 
05289    if (xml) {
05290       /* dest and objtype need only for XML format */
05291       for (v = get_vars; v; v = v->next) {
05292          if (!strcasecmp(v->name, "ajaxdest")) {
05293             dest = v->value;
05294          } else if (!strcasecmp(v->name, "ajaxobjtype")) {
05295             objtype = v->value;
05296          }
05297       }
05298       if (ast_strlen_zero(dest)) {
05299          dest = "unknown";
05300       }
05301       if (ast_strlen_zero(objtype)) {
05302          objtype = "generic";
05303       }
05304    }
05305 
05306    /* we want to stop when we find an empty line */
05307    while (in && *in) {
05308       val = strsep(&in, "\r\n"); /* mark start and end of line */
05309       if (in && *in == '\n') {   /* remove trailing \n if any */
05310          in++;
05311       }
05312       ast_trim_blanks(val);
05313       ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
05314       if (ast_strlen_zero(val)) {
05315          /* empty line */
05316          if (in_data) {
05317             /* close data in Opaque mode */
05318             ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05319             in_data = 0;
05320          }
05321 
05322          if (inobj) {
05323             /* close block */
05324             ast_str_append(out, 0, xml ? " /></response>\n" :
05325                "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05326             inobj = 0;
05327             ao2_ref(vco, -1);
05328             vco = NULL;
05329          }
05330          continue;
05331       }
05332 
05333       if (!inobj) {
05334          /* start new block */
05335          if (xml) {
05336             ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
05337          }
05338          vco = ao2_container_alloc(37, variable_count_hash_fn, variable_count_cmp_fn);
05339          inobj = 1;
05340       }
05341 
05342       if (in_data) {
05343          /* Process data field in Opaque mode */
05344          xml_copy_escape(out, val, 0);   /* data field */
05345          ast_str_append(out, 0, xml ? "\n" : "<br>\n");
05346          continue;
05347       }
05348 
05349       /* We expect "Name: value" line here */
05350       var = strsep(&val, ":");
05351       if (val) {
05352          /* found the field name */
05353          val = ast_skip_blanks(val);
05354          ast_trim_blanks(var);
05355       } else {
05356          /* field name not found, switch to opaque mode */
05357          val = var;
05358          var = "Opaque-data";
05359          in_data = 1;
05360       }
05361 
05362 
05363       ast_str_append(out, 0, xml ? " " : "<tr><td>");
05364       if ((vc = ao2_find(vco, var, 0))) {
05365          vc->count++;
05366       } else {
05367          /* Create a new entry for this one */
05368          vc = ao2_alloc(sizeof(*vc), NULL);
05369          vc->varname = var;
05370          vc->count = 1;
05371          ao2_link(vco, vc);
05372       }
05373 
05374       xml_copy_escape(out, var, xml ? 1 | 2 : 0); /* data name */
05375       if (vc->count > 1) {
05376          ast_str_append(out, 0, "-%d", vc->count);
05377       }
05378       ao2_ref(vc, -1);
05379       ast_str_append(out, 0, xml ? "='" : "</td><td>");
05380       xml_copy_escape(out, val, 0); /* data field */
05381       ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05382    }
05383 
05384    if (inobj) {
05385       ast_str_append(out, 0, xml ? " /></response>\n" :
05386          "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05387       ao2_ref(vco, -1);
05388    }
05389 }
05390 
05391 static int generic_http_callback(struct ast_tcptls_session_instance *ser,
05392                     enum ast_http_method method,
05393                     enum output_format format,
05394                     struct sockaddr_in *remote_address, const char *uri,
05395                     struct ast_variable *get_params,
05396                     struct ast_variable *headers)
05397 {
05398    struct mansession s = { .session = NULL, .tcptls_session = ser };
05399    struct mansession_session *session = NULL;
05400    uint32_t ident = 0;
05401    int blastaway = 0;
05402    struct ast_variable *v, *cookies, *params = get_params;
05403    char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
05404    struct ast_str *http_header = NULL, *out = NULL;
05405    struct message m = { 0 };
05406    unsigned int x;
05407    size_t hdrlen;
05408 
05409    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
05410       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
05411       return -1;
05412    }
05413 
05414    cookies = ast_http_get_cookies(headers);
05415    for (v = cookies; v; v = v->next) {
05416       if (!strcasecmp(v->name, "mansession_id")) {
05417          sscanf(v->value, "%30x", &ident);
05418          break;
05419       }
05420    }
05421    if (cookies) {
05422       ast_variables_destroy(cookies);
05423    }
05424 
05425    if (!(session = find_session(ident, 1))) {
05426 
05427       /**/
05428       /* Create new session.
05429        * While it is not in the list we don't need any locking
05430        */
05431       if (!(session = build_mansession(*remote_address))) {
05432          ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05433          return -1;
05434       }
05435       ao2_lock(session);
05436       session->sin = *remote_address;
05437       session->fd = -1;
05438       session->waiting_thread = AST_PTHREADT_NULL;
05439       session->send_events = 0;
05440       session->inuse = 1;
05441       /*!\note There is approximately a 1 in 1.8E19 chance that the following
05442        * calculation will produce 0, which is an invalid ID, but due to the
05443        * properties of the rand() function (and the constantcy of s), that
05444        * won't happen twice in a row.
05445        */
05446       while ((session->managerid = ast_random() ^ (unsigned long) session) == 0);
05447       session->last_ev = grab_last();
05448       AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
05449    }
05450    ao2_unlock(session);
05451 
05452    http_header = ast_str_create(128);
05453    out = ast_str_create(2048);
05454 
05455    ast_mutex_init(&s.lock);
05456 
05457    if (http_header == NULL || out == NULL) {
05458       ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
05459       goto generic_callback_out;
05460    }
05461 
05462    s.session = session;
05463    s.fd = mkstemp(template);  /* create a temporary file for command output */
05464    unlink(template);
05465    if (s.fd <= -1) {
05466       ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
05467       goto generic_callback_out;
05468    }
05469    s.f = fdopen(s.fd, "w+");
05470    if (!s.f) {
05471       ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
05472       ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
05473       close(s.fd);
05474       goto generic_callback_out;
05475    }
05476 
05477    if (method == AST_HTTP_POST) {
05478       params = ast_http_get_post_vars(ser, headers);
05479    }
05480 
05481    for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
05482       hdrlen = strlen(v->name) + strlen(v->value) + 3;
05483       m.headers[m.hdrcount] = alloca(hdrlen);
05484       snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
05485       ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
05486       m.hdrcount = x + 1;
05487    }
05488 
05489    if (process_message(&s, &m)) {
05490       if (session->authenticated) {
05491          if (manager_displayconnects(session)) {
05492             ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05493          }
05494       } else {
05495          if (displayconnects) {
05496             ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
05497          }
05498       }
05499       session->needdestroy = 1;
05500    }
05501 
05502    ast_str_append(&http_header, 0,
05503       "Content-type: text/%s\r\n"
05504       "Cache-Control: no-cache;\r\n"
05505       "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
05506       "Pragma: SuppressEvents\r\n",
05507       contenttype[format],
05508       session->managerid, httptimeout);
05509 
05510    if (format == FORMAT_XML) {
05511       ast_str_append(&out, 0, "<ajax-response>\n");
05512    } else if (format == FORMAT_HTML) {
05513       /*
05514        * When handling AMI-over-HTTP in HTML format, we provide a simple form for
05515        * debugging purposes. This HTML code should not be here, we
05516        * should read from some config file...
05517        */
05518 
05519 #define ROW_FMT   "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
05520 #define TEST_STRING \
05521    "<form action=\"manager\" method=\"post\">\n\
05522    Action: <select name=\"action\">\n\
05523       <option value=\"\">-----&gt;</option>\n\
05524       <option value=\"login\">login</option>\n\
05525       <option value=\"command\">Command</option>\n\
05526       <option value=\"waitevent\">waitevent</option>\n\
05527       <option value=\"listcommands\">listcommands</option>\n\
05528    </select>\n\
05529    or <input name=\"action\"><br/>\n\
05530    CLI Command <input name=\"command\"><br>\n\
05531    user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
05532    <input type=\"submit\">\n</form>\n"
05533 
05534       ast_str_append(&out, 0, "<title>Asterisk&trade; Manager Interface</title>");
05535       ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
05536       ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
05537       ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
05538    }
05539 
05540    if (s.f != NULL) {   /* have temporary output */
05541       char *buf;
05542       size_t l;
05543 
05544       if ((l = ftell(s.f))) {
05545          if (MAP_FAILED == (buf = mmap(NULL, l + 1, PROT_READ | PROT_WRITE, MAP_PRIVATE, s.fd, 0))) {
05546             ast_log(LOG_WARNING, "mmap failed.  Manager output was not processed\n");
05547          } else {
05548             buf[l] = '\0';
05549             if (format == FORMAT_XML || format == FORMAT_HTML) {
05550                xml_translate(&out, buf, params, format);
05551             } else {
05552                ast_str_append(&out, 0, "%s", buf);
05553             }
05554             munmap(buf, l + 1);
05555          }
05556       } else if (format == FORMAT_XML || format == FORMAT_HTML) {
05557          xml_translate(&out, "", params, format);
05558       }
05559       fclose(s.f);
05560       s.f = NULL;
05561       s.fd = -1;
05562    }
05563 
05564    if (format == FORMAT_XML) {
05565       ast_str_append(&out, 0, "</ajax-response>\n");
05566    } else if (format == FORMAT_HTML) {
05567       ast_str_append(&out, 0, "</table></body>\r\n");
05568    }
05569 
05570    ao2_lock(session);
05571    /* Reset HTTP timeout.  If we're not authenticated, keep it extremely short */
05572    session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
05573 
05574    if (session->needdestroy) {
05575       if (session->inuse == 1) {
05576          ast_debug(1, "Need destroy, doing it now!\n");
05577          blastaway = 1;
05578       } else {
05579          ast_debug(1, "Need destroy, but can't do it yet!\n");
05580          if (session->waiting_thread != AST_PTHREADT_NULL) {
05581             pthread_kill(session->waiting_thread, SIGURG);
05582          }
05583          session->inuse--;
05584       }
05585    } else {
05586       session->inuse--;
05587    }
05588    ao2_unlock(session);
05589 
05590    ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
05591    http_header = out = NULL;
05592 
05593 generic_callback_out:
05594    ast_mutex_destroy(&s.lock);
05595 
05596    /* Clear resource */
05597 
05598    if (method == AST_HTTP_POST && params) {
05599       ast_variables_destroy(params);
05600    }
05601    if (http_header) {
05602       ast_free(http_header);
05603    }
05604    if (out) {
05605       ast_free(out);
05606    }
05607 
05608    if (session && blastaway) {
05609       session_destroy(session);
05610    } else if (session && session->f) {
05611       fclose(session->f);
05612       session->f = NULL;
05613    }
05614 
05615    return 0;
05616 }
05617 
05618 static int auth_http_callback(struct ast_tcptls_session_instance *ser,
05619                     enum ast_http_method method,
05620                     enum output_format format,
05621                     struct sockaddr_in *remote_address, const char *uri,
05622                     struct ast_variable *get_params,
05623                     struct ast_variable *headers)
05624 {
05625    struct mansession_session *session = NULL;
05626    struct mansession s = { NULL, };
05627    struct ast_variable *v, *params = get_params;
05628    char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
05629    struct ast_str *http_header = NULL, *out = NULL;
05630    size_t result_size = 512;
05631    struct message m = { 0 };
05632    unsigned int x;
05633    size_t hdrlen;
05634 
05635    time_t time_now = time(NULL);
05636    unsigned long nonce = 0, nc;
05637    struct ast_http_digest d = { NULL, };
05638    struct ast_manager_user *user = NULL;
05639    int stale = 0;
05640    char resp_hash[256]="";
05641    /* Cache for user data */
05642    char u_username[80];
05643    int u_readperm;
05644    int u_writeperm;
05645    int u_writetimeout;
05646    int u_displayconnects;
05647    struct ast_sockaddr addr;
05648 
05649    if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
05650       ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
05651       return -1;
05652    }
05653 
05654    /* Find "Authorization: " header */
05655    for (v = headers; v; v = v->next) {
05656       if (!strcasecmp(v->name, "Authorization")) {
05657          break;
05658       }
05659    }
05660 
05661    if (!v || ast_strlen_zero(v->value)) {
05662       goto out_401; /* Authorization Header not present - send auth request */
05663    }
05664 
05665    /* Digest found - parse */
05666    if (ast_string_field_init(&d, 128)) {
05667       ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05668       return -1;
05669    }
05670 
05671    if (ast_parse_digest(v->value, &d, 0, 1)) {
05672       /* Error in Digest - send new one */
05673       nonce = 0;
05674       goto out_401;
05675    }
05676    if (sscanf(d.nonce, "%30lx", &nonce) != 1) {
05677       ast_log(LOG_WARNING, "Received incorrect nonce in Digest <%s>\n", d.nonce);
05678       nonce = 0;
05679       goto out_401;
05680    }
05681 
05682    AST_RWLIST_WRLOCK(&users);
05683    user = get_manager_by_name_locked(d.username);
05684    if(!user) {
05685       AST_RWLIST_UNLOCK(&users);
05686       ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
05687       nonce = 0;
05688       goto out_401;
05689    }
05690 
05691    ast_sockaddr_from_sin(&addr, remote_address);
05692    /* --- We have User for this auth, now check ACL */
05693    if (user->ha && !ast_apply_ha(user->ha, &addr)) {
05694       AST_RWLIST_UNLOCK(&users);
05695       ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
05696       ast_http_error(ser, 403, "Permission denied", "Permission denied\n");
05697       return -1;
05698    }
05699 
05700    /* --- We have auth, so check it */
05701 
05702    /* compute the expected response to compare with what we received */
05703    {
05704       char a2[256];
05705       char a2_hash[256];
05706       char resp[256];
05707 
05708       /* XXX Now request method are hardcoded in A2 */
05709       snprintf(a2, sizeof(a2), "%s:%s", ast_get_http_method(method), d.uri);
05710       ast_md5_hash(a2_hash, a2);
05711 
05712       if (d.qop) {
05713          /* RFC 2617 */
05714          snprintf(resp, sizeof(resp), "%s:%08lx:%s:%s:auth:%s", user->a1_hash, nonce, d.nc, d.cnonce, a2_hash);
05715       }  else {
05716          /* RFC 2069 */
05717          snprintf(resp, sizeof(resp), "%s:%08lx:%s", user->a1_hash, nonce, a2_hash);
05718       }
05719       ast_md5_hash(resp_hash, resp);
05720    }
05721 
05722    if (!d.nonce  || strncasecmp(d.response, resp_hash, strlen(resp_hash))) {
05723       /* Something was wrong, so give the client to try with a new challenge */
05724       AST_RWLIST_UNLOCK(&users);
05725       nonce = 0;
05726       goto out_401;
05727    }
05728 
05729    /*
05730     * User are pass Digest authentication.
05731     * Now, cache the user data and unlock user list.
05732     */
05733    ast_copy_string(u_username, user->username, sizeof(u_username));
05734    u_readperm = user->readperm;
05735    u_writeperm = user->writeperm;
05736    u_displayconnects = user->displayconnects;
05737    u_writetimeout = user->writetimeout;
05738    AST_RWLIST_UNLOCK(&users);
05739 
05740    if (!(session = find_session_by_nonce(d.username, nonce, &stale))) {
05741       /*
05742        * Create new session.
05743        * While it is not in the list we don't need any locking
05744        */
05745       if (!(session = build_mansession(*remote_address))) {
05746          ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05747          return -1;
05748       }
05749       ao2_lock(session);
05750 
05751       ast_copy_string(session->username, u_username, sizeof(session->username));
05752       session->managerid = nonce;
05753       session->last_ev = grab_last();
05754       AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
05755 
05756       session->readperm = u_readperm;
05757       session->writeperm = u_writeperm;
05758       session->writetimeout = u_writetimeout;
05759 
05760       if (u_displayconnects) {
05761          ast_verb(2, "HTTP Manager '%s' logged in from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05762       }
05763       session->noncetime = session->sessionstart = time_now;
05764       session->authenticated = 1;
05765    } else if (stale) {
05766       /*
05767        * Session found, but nonce is stale.
05768        *
05769        * This could be because an old request (w/old nonce) arrived.
05770        *
05771        * This may be as the result of http proxy usage (separate delay or
05772        * multipath) or in a situation where a page was refreshed too quickly
05773        * (seen in Firefox).
05774        *
05775        * In this situation, we repeat the 401 auth with the current nonce
05776        * value.
05777        */
05778       nonce = session->managerid;
05779       ao2_unlock(session);
05780       stale = 1;
05781       goto out_401;
05782    } else {
05783       sscanf(d.nc, "%30lx", &nc);
05784       if (session->nc >= nc || ((time_now - session->noncetime) > 62) ) {
05785          /*
05786           * Nonce time expired (> 2 minutes) or something wrong with nonce
05787           * counter.
05788           *
05789           * Create new nonce key and resend Digest auth request. Old nonce
05790           * is saved for stale checking...
05791           */
05792          session->nc = 0; /* Reset nonce counter */
05793          session->oldnonce = session->managerid;
05794          nonce = session->managerid = ast_random();
05795          session->noncetime = time_now;
05796          ao2_unlock(session);
05797          stale = 1;
05798          goto out_401;
05799       } else {
05800          session->nc = nc; /* All OK, save nonce counter */
05801       }
05802    }
05803 
05804 
05805    /* Reset session timeout. */
05806    session->sessiontimeout = time(NULL) + (httptimeout > 5 ? httptimeout : 5);
05807    ao2_unlock(session);
05808 
05809    ast_mutex_init(&s.lock);
05810    s.session = session;
05811    s.fd = mkstemp(template);  /* create a temporary file for command output */
05812    unlink(template);
05813    if (s.fd <= -1) {
05814       ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
05815       goto auth_callback_out;
05816    }
05817    s.f = fdopen(s.fd, "w+");
05818    if (!s.f) {
05819       ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
05820       ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
05821       close(s.fd);
05822       goto auth_callback_out;
05823    }
05824 
05825    if (method == AST_HTTP_POST) {
05826       params = ast_http_get_post_vars(ser, headers);
05827    }
05828 
05829    for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
05830       hdrlen = strlen(v->name) + strlen(v->value) + 3;
05831       m.headers[m.hdrcount] = alloca(hdrlen);
05832       snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
05833       ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
05834       m.hdrcount = x + 1;
05835    }
05836 
05837    if (process_message(&s, &m)) {
05838       if (u_displayconnects) {
05839          ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05840       }
05841 
05842       session->needdestroy = 1;
05843    }
05844 
05845    if (s.f) {
05846       result_size = ftell(s.f); /* Calculate approx. size of result */
05847    }
05848 
05849    http_header = ast_str_create(80);
05850    out = ast_str_create(result_size * 2 + 512);
05851 
05852    if (http_header == NULL || out == NULL) {
05853       ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
05854       goto auth_callback_out;
05855    }
05856 
05857    ast_str_append(&http_header, 0, "Content-type: text/%s", contenttype[format]);
05858 
05859    if (format == FORMAT_XML) {
05860       ast_str_append(&out, 0, "<ajax-response>\n");
05861    } else if (format == FORMAT_HTML) {
05862       ast_str_append(&out, 0,
05863       "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
05864       "<html><head>\r\n"
05865       "<title>Asterisk&trade; Manager Interface</title>\r\n"
05866       "</head><body style=\"background-color: #ffffff;\">\r\n"
05867       "<form method=\"POST\">\r\n"
05868       "<table align=\"center\" style=\"background-color: #f1f1f1;\" width=\"500\">\r\n"
05869       "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\"><h1>Manager Tester</h1></th></tr>\r\n"
05870       "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\">Action: <input name=\"action\" /> Cmd: <input name=\"command\" /><br>"
05871       "<input type=\"submit\" value=\"Send request\" /></th></tr>\r\n");
05872    }
05873 
05874    if (s.f != NULL) {   /* have temporary output */
05875       char *buf;
05876       size_t l = ftell(s.f);
05877 
05878       if (l) {
05879          if ((buf = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_SHARED, s.fd, 0))) {
05880             if (format == FORMAT_XML || format == FORMAT_HTML) {
05881                xml_translate(&out, buf, params, format);
05882             } else {
05883                ast_str_append(&out, 0, "%s", buf);
05884             }
05885             munmap(buf, l);
05886          }
05887       } else if (format == FORMAT_XML || format == FORMAT_HTML) {
05888          xml_translate(&out, "", params, format);
05889       }
05890       fclose(s.f);
05891       s.f = NULL;
05892       s.fd = -1;
05893    }
05894 
05895    if (format == FORMAT_XML) {
05896       ast_str_append(&out, 0, "</ajax-response>\n");
05897    } else if (format == FORMAT_HTML) {
05898       ast_str_append(&out, 0, "</table></form></body></html>\r\n");
05899    }
05900 
05901    ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
05902    http_header = out = NULL;
05903 
05904 auth_callback_out:
05905    ast_mutex_destroy(&s.lock);
05906 
05907    /* Clear resources and unlock manager session */
05908    if (method == AST_HTTP_POST && params) {
05909       ast_variables_destroy(params);
05910    }
05911 
05912    ast_free(http_header);
05913    ast_free(out);
05914 
05915    ao2_lock(session);
05916    if (session->f) {
05917       fclose(session->f);
05918    }
05919    session->f = NULL;
05920    session->fd = -1;
05921    ao2_unlock(session);
05922 
05923    if (session->needdestroy) {
05924       ast_debug(1, "Need destroy, doing it now!\n");
05925       session_destroy(session);
05926    }
05927    ast_string_field_free_memory(&d);
05928    return 0;
05929 
05930 out_401:
05931    if (!nonce) {
05932       nonce = ast_random();
05933    }
05934 
05935    ast_http_auth(ser, global_realm, nonce, nonce, stale, NULL);
05936    ast_string_field_free_memory(&d);
05937    return 0;
05938 }
05939 
05940 static int manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params,  struct ast_variable *headers)
05941 {
05942    int retval;
05943    struct sockaddr_in ser_remote_address_tmp;
05944 
05945    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05946    retval = generic_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
05947    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05948    return retval;
05949 }
05950 
05951 static int mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
05952 {
05953    int retval;
05954    struct sockaddr_in ser_remote_address_tmp;
05955 
05956    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05957    retval = generic_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
05958    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05959    return retval;
05960 }
05961 
05962 static int rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
05963 {
05964    int retval;
05965    struct sockaddr_in ser_remote_address_tmp;
05966 
05967    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05968    retval = generic_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
05969    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05970    return retval;
05971 }
05972 
05973 static struct ast_http_uri rawmanuri = {
05974    .description = "Raw HTTP Manager Event Interface",
05975    .uri = "rawman",
05976    .callback = rawman_http_callback,
05977    .data = NULL,
05978    .key = __FILE__,
05979 };
05980 
05981 static struct ast_http_uri manageruri = {
05982    .description = "HTML Manager Event Interface",
05983    .uri = "manager",
05984    .callback = manager_http_callback,
05985    .data = NULL,
05986    .key = __FILE__,
05987 };
05988 
05989 static struct ast_http_uri managerxmluri = {
05990    .description = "XML Manager Event Interface",
05991    .uri = "mxml",
05992    .callback = mxml_http_callback,
05993    .data = NULL,
05994    .key = __FILE__,
05995 };
05996 
05997 
05998 /* Callback with Digest authentication */
05999 static int auth_manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params,  struct ast_variable *headers)
06000 {
06001    int retval;
06002    struct sockaddr_in ser_remote_address_tmp;
06003 
06004    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06005    retval = auth_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
06006    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06007    return retval;
06008 }
06009 
06010 static int auth_mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
06011 {
06012    int retval;
06013    struct sockaddr_in ser_remote_address_tmp;
06014 
06015    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06016    retval = auth_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
06017    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06018    return retval;
06019 }
06020 
06021 static int auth_rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
06022 {
06023    int retval;
06024    struct sockaddr_in ser_remote_address_tmp;
06025 
06026    ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06027    retval = auth_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
06028    ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06029    return retval;
06030 }
06031 
06032 static struct ast_http_uri arawmanuri = {
06033    .description = "Raw HTTP Manager Event Interface w/Digest authentication",
06034    .uri = "arawman",
06035    .has_subtree = 0,
06036    .callback = auth_rawman_http_callback,
06037    .data = NULL,
06038    .key = __FILE__,
06039 };
06040 
06041 static struct ast_http_uri amanageruri = {
06042    .description = "HTML Manager Event Interface w/Digest authentication",
06043    .uri = "amanager",
06044    .has_subtree = 0,
06045    .callback = auth_manager_http_callback,
06046    .data = NULL,
06047    .key = __FILE__,
06048 };
06049 
06050 static struct ast_http_uri amanagerxmluri = {
06051    .description = "XML Manager Event Interface w/Digest authentication",
06052    .uri = "amxml",
06053    .has_subtree = 0,
06054    .callback = auth_mxml_http_callback,
06055    .data = NULL,
06056    .key = __FILE__,
06057 };
06058 
06059 static int registered = 0;
06060 static int webregged = 0;
06061 
06062 /*! \brief cleanup code called at each iteration of server_root,
06063  * guaranteed to happen every 5 seconds at most
06064  */
06065 static void purge_old_stuff(void *data)
06066 {
06067    purge_sessions(1);
06068    purge_events();
06069 }
06070 
06071 static struct ast_tls_config ami_tls_cfg;
06072 static struct ast_tcptls_session_args ami_desc = {
06073    .accept_fd = -1,
06074    .master = AST_PTHREADT_NULL,
06075    .tls_cfg = NULL,
06076    .poll_timeout = 5000,   /* wake up every 5 seconds */
06077    .periodic_fn = purge_old_stuff,
06078    .name = "AMI server",
06079    .accept_fn = ast_tcptls_server_root,   /* thread doing the accept() */
06080    .worker_fn = session_do,   /* thread handling the session */
06081 };
06082 
06083 static struct ast_tcptls_session_args amis_desc = {
06084    .accept_fd = -1,
06085    .master = AST_PTHREADT_NULL,
06086    .tls_cfg = &ami_tls_cfg,
06087    .poll_timeout = -1,  /* the other does the periodic cleanup */
06088    .name = "AMI TLS server",
06089    .accept_fn = ast_tcptls_server_root,   /* thread doing the accept() */
06090    .worker_fn = session_do,   /* thread handling the session */
06091 };
06092 
06093 /*! \brief CLI command manager show settings */
06094 static char *handle_manager_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06095 {
06096    switch (cmd) {
06097    case CLI_INIT:
06098       e->command = "manager show settings";
06099       e->usage =
06100          "Usage: manager show settings\n"
06101          "       Provides detailed list of the configuration of the Manager.\n";
06102       return NULL;
06103    case CLI_GENERATE:
06104       return NULL;
06105    }
06106 #define FORMAT "  %-25.25s  %-15.15s\n"
06107 #define FORMAT2 "  %-25.25s  %-15d\n"
06108    if (a->argc != 3) {
06109       return CLI_SHOWUSAGE;
06110    }
06111    ast_cli(a->fd, "\nGlobal Settings:\n");
06112    ast_cli(a->fd, "----------------\n");
06113    ast_cli(a->fd, FORMAT, "Manager (AMI):", AST_CLI_YESNO(manager_enabled));
06114    ast_cli(a->fd, FORMAT, "Web Manager (AMI/HTTP):", AST_CLI_YESNO(webmanager_enabled));
06115    ast_cli(a->fd, FORMAT, "TCP Bindaddress:", ast_sockaddr_stringify(&ami_desc.local_address));
06116    ast_cli(a->fd, FORMAT2, "HTTP Timeout (minutes):", httptimeout);
06117    ast_cli(a->fd, FORMAT, "TLS Enable:", AST_CLI_YESNO(ami_tls_cfg.enabled));
06118    ast_cli(a->fd, FORMAT, "TLS Bindaddress:", ast_sockaddr_stringify(&amis_desc.local_address));
06119    ast_cli(a->fd, FORMAT, "TLS Certfile:", ami_tls_cfg.certfile);
06120    ast_cli(a->fd, FORMAT, "TLS Privatekey:", ami_tls_cfg.pvtfile);
06121    ast_cli(a->fd, FORMAT, "TLS Cipher:", ami_tls_cfg.cipher);
06122    ast_cli(a->fd, FORMAT, "Allow multiple login:", AST_CLI_YESNO(allowmultiplelogin));
06123    ast_cli(a->fd, FORMAT, "Display connects:", AST_CLI_YESNO(displayconnects));
06124    ast_cli(a->fd, FORMAT, "Timestamp events:", AST_CLI_YESNO(timestampevents));
06125    ast_cli(a->fd, FORMAT, "Channel vars:", S_OR(manager_channelvars, ""));
06126    ast_cli(a->fd, FORMAT, "Debug:", AST_CLI_YESNO(manager_debug));
06127    ast_cli(a->fd, FORMAT, "Block sockets:", AST_CLI_YESNO(block_sockets));
06128 #undef FORMAT
06129 #undef FORMAT2
06130 
06131    return CLI_SUCCESS;
06132 }
06133 
06134 static struct ast_cli_entry cli_manager[] = {
06135    AST_CLI_DEFINE(handle_showmancmd, "Show a manager interface command"),
06136    AST_CLI_DEFINE(handle_showmancmds, "List manager interface commands"),
06137    AST_CLI_DEFINE(handle_showmanconn, "List connected manager interface users"),
06138    AST_CLI_DEFINE(handle_showmaneventq, "List manager interface queued events"),
06139    AST_CLI_DEFINE(handle_showmanagers, "List configured manager users"),
06140    AST_CLI_DEFINE(handle_showmanager, "Display information on a specific manager user"),
06141    AST_CLI_DEFINE(handle_mandebug, "Show, enable, disable debugging of the manager code"),
06142    AST_CLI_DEFINE(handle_manager_reload, "Reload manager configurations"),
06143    AST_CLI_DEFINE(handle_manager_show_settings, "Show manager global settings"),
06144 };
06145 
06146 static int __init_manager(int reload)
06147 {
06148    struct ast_config *ucfg = NULL, *cfg = NULL;
06149    const char *val;
06150    char *cat = NULL;
06151    int newhttptimeout = DEFAULT_HTTPTIMEOUT;
06152    struct ast_manager_user *user = NULL;
06153    struct ast_variable *var;
06154    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
06155    char a1[256];
06156    char a1_hash[256];
06157    struct sockaddr_in ami_desc_local_address_tmp = { 0, };
06158    struct sockaddr_in amis_desc_local_address_tmp = { 0, };
06159 
06160    if (!registered) {
06161       /* Register default actions */
06162       ast_manager_register_xml("Ping", 0, action_ping);
06163       ast_manager_register_xml("Events", 0, action_events);
06164       ast_manager_register_xml("Logoff", 0, action_logoff);
06165       ast_manager_register_xml("Login", 0, action_login);
06166       ast_manager_register_xml("Challenge", 0, action_challenge);
06167       ast_manager_register_xml("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup);
06168       ast_manager_register_xml("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status);
06169       ast_manager_register_xml("Setvar", EVENT_FLAG_CALL, action_setvar);
06170       ast_manager_register_xml("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar);
06171       ast_manager_register_xml("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig);
06172       ast_manager_register_xml("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson);
06173       ast_manager_register_xml("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig);
06174       ast_manager_register_xml("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig);
06175       ast_manager_register_xml("ListCategories", EVENT_FLAG_CONFIG, action_listcategories);
06176       ast_manager_register_xml("Redirect", EVENT_FLAG_CALL, action_redirect);
06177       ast_manager_register_xml("Atxfer", EVENT_FLAG_CALL, action_atxfer);
06178       ast_manager_register_xml("Originate", EVENT_FLAG_ORIGINATE, action_originate);
06179       ast_manager_register_xml("Command", EVENT_FLAG_COMMAND, action_command);
06180       ast_manager_register_xml("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate);
06181       ast_manager_register_xml("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout);
06182       ast_manager_register_xml("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus);
06183       ast_manager_register_xml("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount);
06184       ast_manager_register_xml("ListCommands", 0, action_listcommands);
06185       ast_manager_register_xml("SendText", EVENT_FLAG_CALL, action_sendtext);
06186       ast_manager_register_xml("UserEvent", EVENT_FLAG_USER, action_userevent);
06187       ast_manager_register_xml("WaitEvent", 0, action_waitevent);
06188       ast_manager_register_xml("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings);
06189       ast_manager_register_xml("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus);
06190       ast_manager_register_xml("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload);
06191       ast_manager_register_xml("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels);
06192       ast_manager_register_xml("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload);
06193       ast_manager_register_xml("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck);
06194       ast_manager_register_xml("AOCMessage", EVENT_FLAG_AOC, action_aocmessage);
06195 
06196       ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
06197       ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
06198       registered = 1;
06199       /* Append placeholder event so master_eventq never runs dry */
06200       append_event("Event: Placeholder\r\n\r\n", 0);
06201    }
06202    if ((cfg = ast_config_load2("manager.conf", "manager", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
06203       return 0;
06204    }
06205 
06206    manager_enabled = DEFAULT_ENABLED;
06207    webmanager_enabled = DEFAULT_WEBENABLED;
06208    displayconnects = DEFAULT_DISPLAYCONNECTS;
06209    broken_events_action = DEFAULT_BROKENEVENTSACTION;
06210    block_sockets = DEFAULT_BLOCKSOCKETS;
06211    timestampevents = DEFAULT_TIMESTAMPEVENTS;
06212    httptimeout = DEFAULT_HTTPTIMEOUT;
06213 
06214    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
06215       ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid. Asterisk management interface (AMI) disabled.\n");
06216       return 0;
06217    }
06218 
06219    /* default values */
06220    ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
06221    memset(&ami_desc.local_address, 0, sizeof(struct sockaddr_in));
06222    memset(&amis_desc.local_address, 0, sizeof(amis_desc.local_address));
06223    amis_desc_local_address_tmp.sin_port = htons(5039);
06224    ami_desc_local_address_tmp.sin_port = htons(DEFAULT_MANAGER_PORT);
06225 
06226    ami_tls_cfg.enabled = 0;
06227    if (ami_tls_cfg.certfile) {
06228       ast_free(ami_tls_cfg.certfile);
06229    }
06230    ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
06231    if (ami_tls_cfg.pvtfile) {
06232       ast_free(ami_tls_cfg.pvtfile);
06233    }
06234    ami_tls_cfg.pvtfile = ast_strdup("");
06235    if (ami_tls_cfg.cipher) {
06236       ast_free(ami_tls_cfg.cipher);
06237    }
06238    ami_tls_cfg.cipher = ast_strdup("");
06239 
06240    free_channelvars();
06241 
06242    for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
06243       val = var->value;
06244 
06245       if (!ast_tls_read_conf(&ami_tls_cfg, &amis_desc, var->name, val)) {
06246          continue;
06247       }
06248 
06249       if (!strcasecmp(var->name, "enabled")) {
06250          manager_enabled = ast_true(val);
06251       } else if (!strcasecmp(var->name, "block-sockets")) {
06252          block_sockets = ast_true(val);
06253       } else if (!strcasecmp(var->name, "webenabled")) {
06254          webmanager_enabled = ast_true(val);
06255       } else if (!strcasecmp(var->name, "port")) {
06256          ami_desc_local_address_tmp.sin_port = htons(atoi(val));
06257       } else if (!strcasecmp(var->name, "bindaddr")) {
06258          if (!inet_aton(val, &ami_desc_local_address_tmp.sin_addr)) {
06259             ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
06260             memset(&ami_desc_local_address_tmp.sin_addr, 0,
06261                    sizeof(ami_desc_local_address_tmp.sin_addr));
06262          }
06263       } else if (!strcasecmp(var->name, "brokeneventsaction")) {
06264          broken_events_action = ast_true(val);
06265       } else if (!strcasecmp(var->name, "allowmultiplelogin")) {
06266          allowmultiplelogin = ast_true(val);
06267       } else if (!strcasecmp(var->name, "displayconnects")) {
06268          displayconnects = ast_true(val);
06269       } else if (!strcasecmp(var->name, "timestampevents")) {
06270          timestampevents = ast_true(val);
06271       } else if (!strcasecmp(var->name, "debug")) {
06272          manager_debug = ast_true(val);
06273       } else if (!strcasecmp(var->name, "httptimeout")) {
06274          newhttptimeout = atoi(val);
06275       } else if (!strcasecmp(var->name, "channelvars")) {
06276          struct manager_channel_variable *mcv;
06277          char *remaining = ast_strdupa(val), *next;
06278          ast_free(manager_channelvars);
06279          manager_channelvars = ast_strdup(val);
06280          AST_RWLIST_WRLOCK(&channelvars);
06281          while ((next = strsep(&remaining, ",|"))) {
06282             if (!(mcv = ast_calloc(1, sizeof(*mcv) + strlen(next) + 1))) {
06283                break;
06284             }
06285             strcpy(mcv->name, next); /* SAFE */
06286             if (strchr(next, '(')) {
06287                mcv->isfunc = 1;
06288             }
06289             AST_RWLIST_INSERT_TAIL(&channelvars, mcv, entry);
06290          }
06291          AST_RWLIST_UNLOCK(&channelvars);
06292       } else {
06293          ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
06294             var->name, val);
06295       }
06296    }
06297 
06298    ami_desc_local_address_tmp.sin_family = AF_INET;
06299    amis_desc_local_address_tmp.sin_family = AF_INET;
06300 
06301    /* if the amis address has not been set, default is the same as non secure ami */
06302    if (!amis_desc_local_address_tmp.sin_addr.s_addr) {
06303       amis_desc_local_address_tmp.sin_addr =
06304           ami_desc_local_address_tmp.sin_addr;
06305    }
06306 
06307    if (manager_enabled) {
06308       ast_sockaddr_from_sin(&ami_desc.local_address, &ami_desc_local_address_tmp);
06309       ast_sockaddr_from_sin(&amis_desc.local_address, &amis_desc_local_address_tmp);
06310    }
06311 
06312    AST_RWLIST_WRLOCK(&users);
06313 
06314    /* First, get users from users.conf */
06315    ucfg = ast_config_load2("users.conf", "manager", config_flags);
06316    if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
06317       const char *hasmanager;
06318       int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
06319 
06320       while ((cat = ast_category_browse(ucfg, cat))) {
06321          if (!strcasecmp(cat, "general")) {
06322             continue;
06323          }
06324 
06325          hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
06326          if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
06327             const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
06328             const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
06329             const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
06330             const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
06331             const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
06332 
06333             /* Look for an existing entry,
06334              * if none found - create one and add it to the list
06335              */
06336             if (!(user = get_manager_by_name_locked(cat))) {
06337                if (!(user = ast_calloc(1, sizeof(*user)))) {
06338                   break;
06339                }
06340 
06341                /* Copy name over */
06342                ast_copy_string(user->username, cat, sizeof(user->username));
06343                /* Insert into list */
06344                AST_LIST_INSERT_TAIL(&users, user, list);
06345                user->ha = NULL;
06346                user->keep = 1;
06347                user->readperm = -1;
06348                user->writeperm = -1;
06349                /* Default displayconnect from [general] */
06350                user->displayconnects = displayconnects;
06351                user->writetimeout = 100;
06352             }
06353 
06354             if (!user_secret) {
06355                user_secret = ast_variable_retrieve(ucfg, "general", "secret");
06356             }
06357             if (!user_read) {
06358                user_read = ast_variable_retrieve(ucfg, "general", "read");
06359             }
06360             if (!user_write) {
06361                user_write = ast_variable_retrieve(ucfg, "general", "write");
06362             }
06363             if (!user_displayconnects) {
06364                user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
06365             }
06366             if (!user_writetimeout) {
06367                user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
06368             }
06369 
06370             if (!ast_strlen_zero(user_secret)) {
06371                if (user->secret) {
06372                   ast_free(user->secret);
06373                }
06374                user->secret = ast_strdup(user_secret);
06375             }
06376 
06377             if (user_read) {
06378                user->readperm = get_perm(user_read);
06379             }
06380             if (user_write) {
06381                user->writeperm = get_perm(user_write);
06382             }
06383             if (user_displayconnects) {
06384                user->displayconnects = ast_true(user_displayconnects);
06385             }
06386             if (user_writetimeout) {
06387                int value = atoi(user_writetimeout);
06388                if (value < 100) {
06389                   ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at users.conf line %d\n", var->value, var->lineno);
06390                } else {
06391                   user->writetimeout = value;
06392                }
06393             }
06394          }
06395       }
06396       ast_config_destroy(ucfg);
06397    }
06398 
06399    /* cat is NULL here in any case */
06400 
06401    while ((cat = ast_category_browse(cfg, cat))) {
06402       struct ast_ha *oldha;
06403 
06404       if (!strcasecmp(cat, "general")) {
06405          continue;
06406       }
06407 
06408       /* Look for an existing entry, if none found - create one and add it to the list */
06409       if (!(user = get_manager_by_name_locked(cat))) {
06410          if (!(user = ast_calloc(1, sizeof(*user)))) {
06411             break;
06412          }
06413          /* Copy name over */
06414          ast_copy_string(user->username, cat, sizeof(user->username));
06415 
06416          user->ha = NULL;
06417          user->readperm = 0;
06418          user->writeperm = 0;
06419          /* Default displayconnect from [general] */
06420          user->displayconnects = displayconnects;
06421          user->writetimeout = 100;
06422          user->whitefilters = ao2_container_alloc(1, NULL, NULL);
06423          user->blackfilters = ao2_container_alloc(1, NULL, NULL);
06424 
06425          /* Insert into list */
06426          AST_RWLIST_INSERT_TAIL(&users, user, list);
06427       } else {
06428          ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
06429          ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
06430       }
06431 
06432       /* Make sure we keep this user and don't destroy it during cleanup */
06433       user->keep = 1;
06434       oldha = user->ha;
06435       user->ha = NULL;
06436 
06437       var = ast_variable_browse(cfg, cat);
06438       for (; var; var = var->next) {
06439          if (!strcasecmp(var->name, "secret")) {
06440             if (user->secret) {
06441                ast_free(user->secret);
06442             }
06443             user->secret = ast_strdup(var->value);
06444          } else if (!strcasecmp(var->name, "deny") ||
06445                    !strcasecmp(var->name, "permit")) {
06446             user->ha = ast_append_ha(var->name, var->value, user->ha, NULL);
06447          }  else if (!strcasecmp(var->name, "read") ) {
06448             user->readperm = get_perm(var->value);
06449          }  else if (!strcasecmp(var->name, "write") ) {
06450             user->writeperm = get_perm(var->value);
06451          }  else if (!strcasecmp(var->name, "displayconnects") ) {
06452             user->displayconnects = ast_true(var->value);
06453          } else if (!strcasecmp(var->name, "writetimeout")) {
06454             int value = atoi(var->value);
06455             if (value < 100) {
06456                ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
06457             } else {
06458                user->writetimeout = value;
06459             }
06460          } else if (!strcasecmp(var->name, "eventfilter")) {
06461             const char *value = var->value;
06462             regex_t *new_filter = ao2_t_alloc(sizeof(*new_filter), event_filter_destructor, "event_filter allocation");
06463             if (new_filter) {
06464                int is_blackfilter;
06465                if (value[0] == '!') {
06466                   is_blackfilter = 1;
06467                   value++;
06468                } else {
06469                   is_blackfilter = 0;
06470                }
06471                if (regcomp(new_filter, value, 0)) {
06472                   ao2_t_ref(new_filter, -1, "failed to make regx");
06473                } else {
06474                   if (is_blackfilter) {
06475                      ao2_t_link(user->blackfilters, new_filter, "link new filter into black user container");
06476                   } else {
06477                      ao2_t_link(user->whitefilters, new_filter, "link new filter into white user container");
06478                   }
06479                }
06480             }
06481          } else {
06482             ast_debug(1, "%s is an unknown option.\n", var->name);
06483          }
06484       }
06485       ast_free_ha(oldha);
06486    }
06487    ast_config_destroy(cfg);
06488 
06489    /* Perform cleanup - essentially prune out old users that no longer exist */
06490    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
06491       if (user->keep) { /* valid record. clear flag for the next round */
06492          user->keep = 0;
06493 
06494          /* Calculate A1 for Digest auth */
06495          snprintf(a1, sizeof(a1), "%s:%s:%s", user->username, global_realm, user->secret);
06496          ast_md5_hash(a1_hash,a1);
06497          if (user->a1_hash) {
06498             ast_free(user->a1_hash);
06499          }
06500          user->a1_hash = ast_strdup(a1_hash);
06501          continue;
06502       }
06503       /* We do not need to keep this user so take them out of the list */
06504       AST_RWLIST_REMOVE_CURRENT(list);
06505       ast_debug(4, "Pruning user '%s'\n", user->username);
06506       /* Free their memory now */
06507       if (user->a1_hash) {
06508          ast_free(user->a1_hash);
06509       }
06510       if (user->secret) {
06511          ast_free(user->secret);
06512       }
06513       ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
06514       ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
06515       ao2_t_ref(user->whitefilters, -1, "decrement ref for white container, should be last one");
06516       ao2_t_ref(user->blackfilters, -1, "decrement ref for black container, should be last one");
06517       ast_free_ha(user->ha);
06518       ast_free(user);
06519    }
06520    AST_RWLIST_TRAVERSE_SAFE_END;
06521 
06522    AST_RWLIST_UNLOCK(&users);
06523 
06524    if (!reload) {
06525       /* If you have a NULL hash fn, you only need a single bucket */
06526       sessions = ao2_container_alloc(1, NULL, mansession_cmp_fn);
06527    }
06528 
06529    if (webmanager_enabled && manager_enabled) {
06530       if (!webregged) {
06531 
06532          ast_http_uri_link(&rawmanuri);
06533          ast_http_uri_link(&manageruri);
06534          ast_http_uri_link(&managerxmluri);
06535 
06536          ast_http_uri_link(&arawmanuri);
06537          ast_http_uri_link(&amanageruri);
06538          ast_http_uri_link(&amanagerxmluri);
06539          webregged = 1;
06540       }
06541    } else {
06542       if (webregged) {
06543          ast_http_uri_unlink(&rawmanuri);
06544          ast_http_uri_unlink(&manageruri);
06545          ast_http_uri_unlink(&managerxmluri);
06546 
06547          ast_http_uri_unlink(&arawmanuri);
06548          ast_http_uri_unlink(&amanageruri);
06549          ast_http_uri_unlink(&amanagerxmluri);
06550          webregged = 0;
06551       }
06552    }
06553 
06554    if (newhttptimeout > 0) {
06555       httptimeout = newhttptimeout;
06556    }
06557 
06558    manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: Manager\r\nStatus: %s\r\nMessage: Manager reload Requested\r\n", manager_enabled ? "Enabled" : "Disabled");
06559 
06560    ast_tcptls_server_start(&ami_desc);
06561    if (ast_ssl_setup(amis_desc.tls_cfg)) {
06562       ast_tcptls_server_start(&amis_desc);
06563    }
06564    return 0;
06565 }
06566 
06567 /* clear out every entry in the channelvar list */
06568 static void free_channelvars(void)
06569 {
06570    struct manager_channel_variable *var;
06571    AST_RWLIST_WRLOCK(&channelvars);
06572    while ((var = AST_RWLIST_REMOVE_HEAD(&channelvars, entry))) {
06573       ast_free(var);
06574    }
06575    AST_RWLIST_UNLOCK(&channelvars);
06576 }
06577 
06578 int init_manager(void)
06579 {
06580    return __init_manager(0);
06581 }
06582 
06583 int reload_manager(void)
06584 {
06585    return __init_manager(1);
06586 }
06587 
06588 int astman_datastore_add(struct mansession *s, struct ast_datastore *datastore)
06589 {
06590    AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
06591 
06592    return 0;
06593 }
06594 
06595 int astman_datastore_remove(struct mansession *s, struct ast_datastore *datastore)
06596 {
06597    return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
06598 }
06599 
06600 struct ast_datastore *astman_datastore_find(struct mansession *s, const struct ast_datastore_info *info, const char *uid)
06601 {
06602    struct ast_datastore *datastore = NULL;
06603 
06604    if (info == NULL)
06605       return NULL;
06606 
06607    AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
06608       if (datastore->info != info) {
06609          continue;
06610       }
06611 
06612       if (uid == NULL) {
06613          /* matched by type only */
06614          break;
06615       }
06616 
06617       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
06618          /* Matched by type AND uid */
06619          break;
06620       }
06621    }
06622    AST_LIST_TRAVERSE_SAFE_END;
06623 
06624    return datastore;
06625 }

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