Sat Mar 26 11:07:52 2011

Asterisk developer's documentation


pbx.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, 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 Core PBX routines.
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 #include "asterisk.h"
00026 
00027 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 290713 $")
00028 
00029 #include "asterisk/_private.h"
00030 #include "asterisk/paths.h"   /* use ast_config_AST_SYSTEM_NAME */
00031 #include <ctype.h>
00032 #include <time.h>
00033 #include <sys/time.h>
00034 #if defined(HAVE_SYSINFO)
00035 #include <sys/sysinfo.h>
00036 #endif
00037 #if defined(SOLARIS)
00038 #include <sys/loadavg.h>
00039 #endif
00040 
00041 #include "asterisk/lock.h"
00042 #include "asterisk/cli.h"
00043 #include "asterisk/pbx.h"
00044 #include "asterisk/channel.h"
00045 #include "asterisk/file.h"
00046 #include "asterisk/callerid.h"
00047 #include "asterisk/cdr.h"
00048 #include "asterisk/cel.h"
00049 #include "asterisk/config.h"
00050 #include "asterisk/term.h"
00051 #include "asterisk/time.h"
00052 #include "asterisk/manager.h"
00053 #include "asterisk/ast_expr.h"
00054 #include "asterisk/linkedlists.h"
00055 #define  SAY_STUBS   /* generate declarations and stubs for say methods */
00056 #include "asterisk/say.h"
00057 #include "asterisk/utils.h"
00058 #include "asterisk/causes.h"
00059 #include "asterisk/musiconhold.h"
00060 #include "asterisk/app.h"
00061 #include "asterisk/devicestate.h"
00062 #include "asterisk/event.h"
00063 #include "asterisk/hashtab.h"
00064 #include "asterisk/module.h"
00065 #include "asterisk/indications.h"
00066 #include "asterisk/taskprocessor.h"
00067 #include "asterisk/xmldoc.h"
00068 
00069 /*!
00070  * \note I M P O R T A N T :
00071  *
00072  *    The speed of extension handling will likely be among the most important
00073  * aspects of this PBX.  The switching scheme as it exists right now isn't
00074  * terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
00075  * of priorities, but a constant search time here would be great ;-)
00076  *
00077  * A new algorithm to do searching based on a 'compiled' pattern tree is introduced
00078  * here, and shows a fairly flat (constant) search time, even for over
00079  * 10000 patterns.
00080  *
00081  * Also, using a hash table for context/priority name lookup can help prevent
00082  * the find_extension routines from absorbing exponential cpu cycles as the number
00083  * of contexts/priorities grow. I've previously tested find_extension with red-black trees,
00084  * which have O(log2(n)) speed. Right now, I'm using hash tables, which do
00085  * searches (ideally) in O(1) time. While these techniques do not yield much
00086  * speed in small dialplans, they are worth the trouble in large dialplans.
00087  *
00088  */
00089 
00090 /*** DOCUMENTATION
00091    <application name="Answer" language="en_US">
00092       <synopsis>
00093          Answer a channel if ringing.
00094       </synopsis>
00095       <syntax>
00096          <parameter name="delay">
00097             <para>Asterisk will wait this number of milliseconds before returning to
00098             the dialplan after answering the call.</para>
00099          </parameter>
00100          <parameter name="nocdr">
00101             <para>Asterisk will send an answer signal to the calling phone, but will not
00102             set the disposition or answer time in the CDR for this call.</para>
00103          </parameter>
00104       </syntax>
00105       <description>
00106          <para>If the call has not been answered, this application will
00107          answer it. Otherwise, it has no effect on the call.</para>
00108       </description>
00109       <see-also>
00110          <ref type="application">Hangup</ref>
00111       </see-also>
00112    </application>
00113    <application name="BackGround" language="en_US">
00114       <synopsis>
00115          Play an audio file while waiting for digits of an extension to go to.
00116       </synopsis>
00117       <syntax>
00118          <parameter name="filenames" required="true" argsep="&amp;">
00119             <argument name="filename1" required="true" />
00120             <argument name="filename2" multiple="true" />
00121          </parameter>
00122          <parameter name="options">
00123             <optionlist>
00124                <option name="s">
00125                   <para>Causes the playback of the message to be skipped
00126                   if the channel is not in the <literal>up</literal> state (i.e. it
00127                   hasn't been answered yet). If this happens, the
00128                   application will return immediately.</para>
00129                </option>
00130                <option name="n">
00131                   <para>Don't answer the channel before playing the files.</para>
00132                </option>
00133                <option name="m">
00134                   <para>Only break if a digit hit matches a one digit
00135                   extension in the destination context.</para>
00136                </option>
00137             </optionlist>
00138          </parameter>
00139          <parameter name="langoverride">
00140             <para>Explicitly specifies which language to attempt to use for the requested sound files.</para>
00141          </parameter>
00142          <parameter name="context">
00143             <para>This is the dialplan context that this application will use when exiting
00144             to a dialed extension.</para>
00145          </parameter>
00146       </syntax>
00147       <description>
00148          <para>This application will play the given list of files <emphasis>(do not put extension)</emphasis>
00149          while waiting for an extension to be dialed by the calling channel. To continue waiting
00150          for digits after this application has finished playing files, the <literal>WaitExten</literal>
00151          application should be used.</para>
00152          <para>If one of the requested sound files does not exist, call processing will be terminated.</para>
00153          <para>This application sets the following channel variable upon completion:</para>
00154          <variablelist>
00155             <variable name="BACKGROUNDSTATUS">
00156                <para>The status of the background attempt as a text string.</para>
00157                <value name="SUCCESS" />
00158                <value name="FAILED" />
00159             </variable>
00160          </variablelist>
00161       </description>
00162       <see-also>
00163          <ref type="application">ControlPlayback</ref>
00164          <ref type="application">WaitExten</ref>
00165          <ref type="application">BackgroundDetect</ref>
00166          <ref type="function">TIMEOUT</ref>
00167       </see-also>
00168    </application>
00169    <application name="Busy" language="en_US">
00170       <synopsis>
00171          Indicate the Busy condition.
00172       </synopsis>
00173       <syntax>
00174          <parameter name="timeout">
00175             <para>If specified, the calling channel will be hung up after the specified number of seconds.
00176             Otherwise, this application will wait until the calling channel hangs up.</para>
00177          </parameter>
00178       </syntax>
00179       <description>
00180          <para>This application will indicate the busy condition to the calling channel.</para>
00181       </description>
00182       <see-also>
00183          <ref type="application">Congestion</ref>
00184          <ref type="application">Progess</ref>
00185          <ref type="application">Playtones</ref>
00186          <ref type="application">Hangup</ref>
00187       </see-also>
00188    </application>
00189    <application name="Congestion" language="en_US">
00190       <synopsis>
00191          Indicate the Congestion condition.
00192       </synopsis>
00193       <syntax>
00194          <parameter name="timeout">
00195             <para>If specified, the calling channel will be hung up after the specified number of seconds.
00196             Otherwise, this application will wait until the calling channel hangs up.</para>
00197          </parameter>
00198       </syntax>
00199       <description>
00200          <para>This application will indicate the congestion condition to the calling channel.</para>
00201       </description>
00202       <see-also>
00203          <ref type="application">Busy</ref>
00204          <ref type="application">Progess</ref>
00205          <ref type="application">Playtones</ref>
00206          <ref type="application">Hangup</ref>
00207       </see-also>
00208    </application>
00209    <application name="ExecIfTime" language="en_US">
00210       <synopsis>
00211          Conditional application execution based on the current time.
00212       </synopsis>
00213       <syntax argsep="?">
00214          <parameter name="day_condition" required="true">
00215             <argument name="times" required="true" />
00216             <argument name="weekdays" required="true" />
00217             <argument name="mdays" required="true" />
00218             <argument name="months" required="true" />
00219             <argument name="timezone" required="false" />
00220          </parameter>
00221          <parameter name="appname" required="true" hasparams="optional">
00222             <argument name="appargs" required="true" />
00223          </parameter>
00224       </syntax>
00225       <description>
00226          <para>This application will execute the specified dialplan application, with optional
00227          arguments, if the current time matches the given time specification.</para>
00228       </description>
00229       <see-also>
00230          <ref type="application">Exec</ref>
00231          <ref type="application">TryExec</ref>
00232       </see-also>
00233    </application>
00234    <application name="Goto" language="en_US">
00235       <synopsis>
00236          Jump to a particular priority, extension, or context.
00237       </synopsis>
00238       <syntax>
00239          <parameter name="context" />
00240          <parameter name="extensions" />
00241          <parameter name="priority" required="true" />
00242       </syntax>
00243       <description>
00244          <para>This application will set the current context, extension, and priority in the channel structure.
00245          After it completes, the pbx engine will continue dialplan execution at the specified location.
00246          If no specific <replaceable>extension</replaceable>, or <replaceable>extension</replaceable> and
00247          <replaceable>context</replaceable>, are specified, then this application will
00248          just set the specified <replaceable>priority</replaceable> of the current extension.</para>
00249          <para>At least a <replaceable>priority</replaceable> is required as an argument, or the goto will
00250          return a <literal>-1</literal>,  and the channel and call will be terminated.</para>
00251          <para>If the location that is put into the channel information is bogus, and asterisk cannot
00252          find that location in the dialplan, then the execution engine will try to find and execute the code in
00253          the <literal>i</literal> (invalid) extension in the current context. If that does not exist, it will try to execute the
00254          <literal>h</literal> extension. If either or neither the <literal>h</literal> or <literal>i</literal> extensions
00255          have been defined, the channel is hung up, and the execution of instructions on the channel is terminated.
00256          What this means is that, for example, you specify a context that does not exist, then
00257          it will not be possible to find the <literal>h</literal> or <literal>i</literal> extensions,
00258          and the call will terminate!</para>
00259       </description>
00260       <see-also>
00261          <ref type="application">GotoIf</ref>
00262          <ref type="application">GotoIfTime</ref>
00263          <ref type="application">Gosub</ref>
00264          <ref type="application">Macro</ref>
00265       </see-also>
00266    </application>
00267    <application name="GotoIf" language="en_US">
00268       <synopsis>
00269          Conditional goto.
00270       </synopsis>
00271       <syntax argsep="?">
00272          <parameter name="condition" required="true" />
00273          <parameter name="destination" required="true" argsep=":">
00274             <argument name="labeliftrue">
00275                <para>Continue at <replaceable>labeliftrue</replaceable> if the condition is true.</para>
00276             </argument>
00277             <argument name="labeliffalse">
00278                <para>Continue at <replaceable>labeliffalse</replaceable> if the condition is false.</para>
00279             </argument>
00280          </parameter>
00281       </syntax>
00282       <description>
00283          <para>This application will set the current context, extension, and priority in the channel structure
00284          based on the evaluation of the given condition. After this application completes, the
00285          pbx engine will continue dialplan execution at the specified location in the dialplan.
00286          The labels are specified with the same syntax as used within the Goto application.
00287          If the label chosen by the condition is omitted, no jump is performed, and the execution passes to the
00288          next instruction. If the target location is bogus, and does not exist, the execution engine will try
00289          to find and execute the code in the <literal>i</literal> (invalid) extension in the current context.
00290          If that does not exist, it will try to execute the <literal>h</literal> extension.
00291          If either or neither the <literal>h</literal> or <literal>i</literal> extensions have been defined,
00292          the channel is hung up, and the execution of instructions on the channel is terminated.
00293          Remember that this command can set the current context, and if the context specified
00294          does not exist, then it will not be able to find any 'h' or 'i' extensions there, and
00295          the channel and call will both be terminated!.</para>
00296       </description>
00297       <see-also>
00298          <ref type="application">Goto</ref>
00299          <ref type="application">GotoIfTime</ref>
00300          <ref type="application">GosubIf</ref>
00301          <ref type="application">MacroIf</ref>
00302       </see-also>
00303    </application>
00304    <application name="GotoIfTime" language="en_US">
00305       <synopsis>
00306          Conditional Goto based on the current time.
00307       </synopsis>
00308       <syntax argsep="?">
00309          <parameter name="condition" required="true">
00310             <argument name="times" required="true" />
00311             <argument name="weekdays" required="true" />
00312             <argument name="mdays" required="true" />
00313             <argument name="months" required="true" />
00314             <argument name="timezone" required="false" />
00315          </parameter>
00316          <parameter name="destination" required="true" argsep=":">
00317             <argument name="labeliftrue" />
00318             <argument name="labeliffalse" />
00319          </parameter>
00320       </syntax>
00321       <description>
00322          <para>This application will set the context, extension, and priority in the channel structure
00323          based on the evaluation of the given time specification. After this application completes,
00324          the pbx engine will continue dialplan execution at the specified location in the dialplan.
00325          If the current time is within the given time specification, the channel will continue at
00326          <replaceable>labeliftrue</replaceable>. Otherwise the channel will continue at <replaceable>labeliffalse</replaceable>.
00327          If the label chosen by the condition is omitted, no jump is performed, and execution passes to the next
00328          instruction. If the target jump location is bogus, the same actions would be taken as for <literal>Goto</literal>.
00329          Further information on the time specification can be found in examples
00330          illustrating how to do time-based context includes in the dialplan.</para>
00331       </description>
00332       <see-also>
00333          <ref type="application">GotoIf</ref>
00334          <ref type="function">IFTIME</ref>
00335          <ref type="function">TESTTIME</ref>
00336       </see-also>
00337    </application>
00338    <application name="ImportVar" language="en_US">
00339       <synopsis>
00340          Import a variable from a channel into a new variable.
00341       </synopsis>
00342       <syntax argsep="=">
00343          <parameter name="newvar" required="true" />
00344          <parameter name="vardata" required="true">
00345             <argument name="channelname" required="true" />
00346             <argument name="variable" required="true" />
00347          </parameter>
00348       </syntax>
00349       <description>
00350          <para>This application imports a <replaceable>variable</replaceable> from the specified
00351          <replaceable>channel</replaceable> (as opposed to the current one) and stores it as a variable
00352          (<replaceable>newvar</replaceable>) in the current channel (the channel that is calling this
00353          application). Variables created by this application have the same inheritance properties as those
00354          created with the <literal>Set</literal> application.</para>
00355       </description>
00356       <see-also>
00357          <ref type="application">Set</ref>
00358       </see-also>
00359    </application>
00360    <application name="Hangup" language="en_US">
00361       <synopsis>
00362          Hang up the calling channel.
00363       </synopsis>
00364       <syntax>
00365          <parameter name="causecode">
00366             <para>If a <replaceable>causecode</replaceable> is given the channel's
00367             hangup cause will be set to the given value.</para>
00368          </parameter>
00369       </syntax>
00370       <description>
00371          <para>This application will hang up the calling channel.</para>
00372       </description>
00373       <see-also>
00374          <ref type="application">Answer</ref>
00375          <ref type="application">Busy</ref>
00376          <ref type="application">Congestion</ref>
00377       </see-also>
00378    </application>
00379    <application name="Incomplete" language="en_US">
00380       <synopsis>
00381          Returns AST_PBX_INCOMPLETE value.
00382       </synopsis>
00383       <syntax>
00384          <parameter name="n">
00385             <para>If specified, then Incomplete will not attempt to answer the channel first.</para>
00386             <note><para>Most channel types need to be in Answer state in order to receive DTMF.</para></note>
00387          </parameter>
00388       </syntax>
00389       <description>
00390          <para>Signals the PBX routines that the previous matched extension is incomplete
00391          and that further input should be allowed before matching can be considered
00392          to be complete.  Can be used within a pattern match when certain criteria warrants
00393          a longer match.</para>
00394       </description>
00395    </application>
00396    <application name="NoOp" language="en_US">
00397       <synopsis>
00398          Do Nothing (No Operation).
00399       </synopsis>
00400       <syntax>
00401          <parameter name="text">
00402             <para>Any text provided can be viewed at the Asterisk CLI.</para>
00403          </parameter>
00404       </syntax>
00405       <description>
00406          <para>This application does nothing. However, it is useful for debugging purposes.</para>
00407          <para>This method can be used to see the evaluations of variables or functions without having any effect.</para>
00408       </description>
00409       <see-also>
00410          <ref type="application">Verbose</ref>
00411          <ref type="application">Log</ref>
00412       </see-also>
00413    </application>
00414    <application name="Proceeding" language="en_US">
00415       <synopsis>
00416          Indicate proceeding.
00417       </synopsis>
00418       <syntax />
00419       <description>
00420          <para>This application will request that a proceeding message be provided to the calling channel.</para>
00421       </description>
00422    </application>
00423    <application name="Progress" language="en_US">
00424       <synopsis>
00425          Indicate progress.
00426       </synopsis>
00427       <syntax />
00428       <description>
00429          <para>This application will request that in-band progress information be provided to the calling channel.</para>
00430       </description>
00431       <see-also>
00432          <ref type="application">Busy</ref>
00433          <ref type="application">Congestion</ref>
00434          <ref type="application">Ringing</ref>
00435          <ref type="application">Playtones</ref>
00436       </see-also>
00437    </application>
00438    <application name="RaiseException" language="en_US">
00439       <synopsis>
00440          Handle an exceptional condition.
00441       </synopsis>
00442       <syntax>
00443          <parameter name="reason" required="true" />
00444       </syntax>
00445       <description>
00446          <para>This application will jump to the <literal>e</literal> extension in the current context, setting the
00447          dialplan function EXCEPTION(). If the <literal>e</literal> extension does not exist, the call will hangup.</para>
00448       </description>
00449       <see-also>
00450          <ref type="function">Exception</ref>
00451       </see-also>
00452    </application>
00453    <application name="ResetCDR" language="en_US">
00454       <synopsis>
00455          Resets the Call Data Record.
00456       </synopsis>
00457       <syntax>
00458          <parameter name="options">
00459             <optionlist>
00460                <option name="w">
00461                   <para>Store the current CDR record before resetting it.</para>
00462                </option>
00463                <option name="a">
00464                   <para>Store any stacked records.</para>
00465                </option>
00466                <option name="v">
00467                   <para>Save CDR variables.</para>
00468                </option>
00469                <option name="e">
00470                   <para>Enable CDR only (negate effects of NoCDR).</para>
00471                </option>
00472             </optionlist>
00473          </parameter>
00474       </syntax>
00475       <description>
00476          <para>This application causes the Call Data Record to be reset.</para>
00477       </description>
00478       <see-also>
00479          <ref type="application">ForkCDR</ref>
00480          <ref type="application">NoCDR</ref>
00481       </see-also>
00482    </application>
00483    <application name="Ringing" language="en_US">
00484       <synopsis>
00485          Indicate ringing tone.
00486       </synopsis>
00487       <syntax />
00488       <description>
00489          <para>This application will request that the channel indicate a ringing tone to the user.</para>
00490       </description>
00491       <see-also>
00492          <ref type="application">Busy</ref>
00493          <ref type="application">Congestion</ref>
00494          <ref type="application">Progress</ref>
00495          <ref type="application">Playtones</ref>
00496       </see-also>
00497    </application>
00498    <application name="SayAlpha" language="en_US">
00499       <synopsis>
00500          Say Alpha.
00501       </synopsis>
00502       <syntax>
00503          <parameter name="string" required="true" />
00504       </syntax>
00505       <description>
00506          <para>This application will play the sounds that correspond to the letters of the
00507          given <replaceable>string</replaceable>.</para>
00508       </description>
00509       <see-also>
00510          <ref type="application">SayDigits</ref>
00511          <ref type="application">SayNumber</ref>
00512          <ref type="application">SayPhonetic</ref>
00513          <ref type="function">CHANNEL</ref>
00514       </see-also>
00515    </application>
00516    <application name="SayDigits" language="en_US">
00517       <synopsis>
00518          Say Digits.
00519       </synopsis>
00520       <syntax>
00521          <parameter name="digits" required="true" />
00522       </syntax>
00523       <description>
00524          <para>This application will play the sounds that correspond to the digits of
00525          the given number. This will use the language that is currently set for the channel.</para>
00526       </description>
00527       <see-also>
00528          <ref type="application">SayAlpha</ref>
00529          <ref type="application">SayNumber</ref>
00530          <ref type="application">SayPhonetic</ref>
00531          <ref type="function">CHANNEL</ref>
00532       </see-also>
00533    </application>
00534    <application name="SayNumber" language="en_US">
00535       <synopsis>
00536          Say Number.
00537       </synopsis>
00538       <syntax>
00539          <parameter name="digits" required="true" />
00540          <parameter name="gender" />
00541       </syntax>
00542       <description>
00543          <para>This application will play the sounds that correspond to the given <replaceable>digits</replaceable>.
00544          Optionally, a <replaceable>gender</replaceable> may be specified. This will use the language that is currently
00545          set for the channel. See the LANGUAGE() function for more information on setting the language for the channel.</para>
00546       </description>
00547       <see-also>
00548          <ref type="application">SayAlpha</ref>
00549          <ref type="application">SayDigits</ref>
00550          <ref type="application">SayPhonetic</ref>
00551          <ref type="function">CHANNEL</ref>
00552       </see-also>
00553    </application>
00554    <application name="SayPhonetic" language="en_US">
00555       <synopsis>
00556          Say Phonetic.
00557       </synopsis>
00558       <syntax>
00559          <parameter name="string" required="true" />
00560       </syntax>
00561       <description>
00562          <para>This application will play the sounds from the phonetic alphabet that correspond to the
00563          letters in the given <replaceable>string</replaceable>.</para>
00564       </description>
00565       <see-also>
00566          <ref type="application">SayAlpha</ref>
00567          <ref type="application">SayDigits</ref>
00568          <ref type="application">SayNumber</ref>
00569       </see-also>
00570    </application>
00571    <application name="Set" language="en_US">
00572       <synopsis>
00573          Set channel variable or function value.
00574       </synopsis>
00575       <syntax argsep="=">
00576          <parameter name="name" required="true" />
00577          <parameter name="value" required="true" />
00578       </syntax>
00579       <description>
00580          <para>This function can be used to set the value of channel variables or dialplan functions.
00581          When setting variables, if the variable name is prefixed with <literal>_</literal>,
00582          the variable will be inherited into channels created from the current channel.
00583          If the variable name is prefixed with <literal>__</literal>, the variable will be
00584          inherited into channels created from the current channel and all children channels.</para>
00585          <note><para>If (and only if), in <filename>/etc/asterisk/asterisk.conf</filename>, you have
00586          a <literal>[compat]</literal> category, and you have <literal>app_set = 1.6</literal> under that,then
00587          the behavior of this app changes, and does not strip surrounding quotes from the right hand side as
00588          it did previously in 1.4. The <literal>app_set = 1.6</literal> is only inserted if <literal>make samples</literal>
00589          is executed, or if users insert this by hand into the <filename>asterisk.conf</filename> file.
00590          The advantages of not stripping out quoting, and not caring about the separator characters (comma and vertical bar)
00591          were sufficient to make these changes in 1.6. Confusion about how many backslashes would be needed to properly
00592          protect separators and quotes in various database access strings has been greatly
00593          reduced by these changes.</para></note>
00594       </description>
00595       <see-also>
00596          <ref type="application">MSet</ref>
00597          <ref type="function">GLOBAL</ref>
00598          <ref type="function">SET</ref>
00599          <ref type="function">ENV</ref>
00600       </see-also>
00601    </application>
00602    <application name="MSet" language="en_US">
00603       <synopsis>
00604          Set channel variable(s) or function value(s).
00605       </synopsis>
00606       <syntax>
00607          <parameter name="set1" required="true" argsep="=">
00608             <argument name="name1" required="true" />
00609             <argument name="value1" required="true" />
00610          </parameter>
00611          <parameter name="set2" multiple="true" argsep="=">
00612             <argument name="name2" required="true" />
00613             <argument name="value2" required="true" />
00614          </parameter>
00615       </syntax>
00616       <description>
00617          <para>This function can be used to set the value of channel variables or dialplan functions.
00618          When setting variables, if the variable name is prefixed with <literal>_</literal>,
00619          the variable will be inherited into channels created from the current channel
00620          If the variable name is prefixed with <literal>__</literal>, the variable will be
00621          inherited into channels created from the current channel and all children channels.
00622          MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus
00623          prone to doing things that you may not expect. For example, it strips surrounding
00624          double-quotes from the right-hand side (value). If you need to put a separator
00625          character (comma or vert-bar), you will need to escape them by inserting a backslash
00626          before them. Avoid its use if possible.</para>
00627       </description>
00628       <see-also>
00629          <ref type="application">Set</ref>
00630       </see-also>
00631    </application>
00632    <application name="SetAMAFlags" language="en_US">
00633       <synopsis>
00634          Set the AMA Flags.
00635       </synopsis>
00636       <syntax>
00637          <parameter name="flag" />
00638       </syntax>
00639       <description>
00640          <para>This application will set the channel's AMA Flags for billing purposes.</para>
00641       </description>
00642       <see-also>
00643          <ref type="function">CDR</ref>
00644       </see-also>
00645    </application>
00646    <application name="Wait" language="en_US">
00647       <synopsis>
00648          Waits for some time.
00649       </synopsis>
00650       <syntax>
00651          <parameter name="seconds" required="true">
00652             <para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
00653             application to wait for 1.5 seconds.</para>
00654          </parameter>
00655       </syntax>
00656       <description>
00657          <para>This application waits for a specified number of <replaceable>seconds</replaceable>.</para>
00658       </description>
00659    </application>
00660    <application name="WaitExten" language="en_US">
00661       <synopsis>
00662          Waits for an extension to be entered.
00663       </synopsis>
00664       <syntax>
00665          <parameter name="seconds">
00666             <para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
00667             application to wait for 1.5 seconds.</para>
00668          </parameter>
00669          <parameter name="options">
00670             <optionlist>
00671                <option name="m">
00672                   <para>Provide music on hold to the caller while waiting for an extension.</para>
00673                   <argument name="x">
00674                      <para>Specify the class for music on hold.</para>
00675                   </argument>
00676                </option>
00677             </optionlist>
00678          </parameter>
00679       </syntax>
00680       <description>
00681          <para>This application waits for the user to enter a new extension for a specified number
00682          of <replaceable>seconds</replaceable>.</para>
00683          <xi:include xpointer="xpointer(/docs/application[@name='Macro']/description/warning[2])" />
00684       </description>
00685       <see-also>
00686          <ref type="application">Background</ref>
00687          <ref type="function">TIMEOUT</ref>
00688       </see-also>
00689    </application>
00690    <function name="EXCEPTION" language="en_US">
00691       <synopsis>
00692          Retrieve the details of the current dialplan exception.
00693       </synopsis>
00694       <syntax>
00695          <parameter name="field" required="true">
00696             <para>The following fields are available for retrieval:</para>
00697             <enumlist>
00698                <enum name="reason">
00699                   <para>INVALID, ERROR, RESPONSETIMEOUT, ABSOLUTETIMEOUT, or custom
00700                   value set by the RaiseException() application</para>
00701                </enum>
00702                <enum name="context">
00703                   <para>The context executing when the exception occurred.</para>
00704                </enum>
00705                <enum name="exten">
00706                   <para>The extension executing when the exception occurred.</para>
00707                </enum>
00708                <enum name="priority">
00709                   <para>The numeric priority executing when the exception occurred.</para>
00710                </enum>
00711             </enumlist>
00712          </parameter>
00713       </syntax>
00714       <description>
00715          <para>Retrieve the details (specified <replaceable>field</replaceable>) of the current dialplan exception.</para>
00716       </description>
00717       <see-also>
00718          <ref type="application">RaiseException</ref>
00719       </see-also>
00720    </function>
00721    <function name="TESTTIME" language="en_US">
00722       <synopsis>
00723          Sets a time to be used with the channel to test logical conditions.
00724       </synopsis>
00725       <syntax>
00726          <parameter name="date" required="true" argsep=" ">
00727             <para>Date in ISO 8601 format</para>
00728          </parameter>
00729          <parameter name="time" required="true" argsep=" ">
00730             <para>Time in HH:MM:SS format (24-hour time)</para>
00731          </parameter>
00732          <parameter name="zone" required="false">
00733             <para>Timezone name</para>
00734          </parameter>
00735       </syntax>
00736       <description>
00737          <para>To test dialplan timing conditions at times other than the current time, use
00738          this function to set an alternate date and time.  For example, you may wish to evaluate
00739          whether a location will correctly identify to callers that the area is closed on Christmas
00740          Day, when Christmas would otherwise fall on a day when the office is normally open.</para>
00741       </description>
00742       <see-also>
00743          <ref type="application">GotoIfTime</ref>
00744       </see-also>
00745    </function>
00746    <manager name="ShowDialPlan" language="en_US">
00747       <synopsis>
00748          Show dialplan contexts and extensions
00749       </synopsis>
00750       <syntax>
00751          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00752          <parameter name="Extension">
00753             <para>Show a specific extension.</para>
00754          </parameter>
00755          <parameter name="Context">
00756             <para>Show a specific context.</para>
00757          </parameter>
00758       </syntax>
00759       <description>
00760          <para>Show dialplan contexts and extensions. Be aware that showing the full dialplan
00761          may take a lot of capacity.</para>
00762       </description>
00763    </manager>
00764  ***/
00765 
00766 #ifdef LOW_MEMORY
00767 #define EXT_DATA_SIZE 256
00768 #else
00769 #define EXT_DATA_SIZE 8192
00770 #endif
00771 
00772 #define SWITCH_DATA_LENGTH 256
00773 
00774 #define VAR_BUF_SIZE 4096
00775 
00776 #define  VAR_NORMAL     1
00777 #define  VAR_SOFTTRAN   2
00778 #define  VAR_HARDTRAN   3
00779 
00780 #define BACKGROUND_SKIP    (1 << 0)
00781 #define BACKGROUND_NOANSWER   (1 << 1)
00782 #define BACKGROUND_MATCHEXTEN (1 << 2)
00783 #define BACKGROUND_PLAYBACK   (1 << 3)
00784 
00785 AST_APP_OPTIONS(background_opts, {
00786    AST_APP_OPTION('s', BACKGROUND_SKIP),
00787    AST_APP_OPTION('n', BACKGROUND_NOANSWER),
00788    AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
00789    AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
00790 });
00791 
00792 #define WAITEXTEN_MOH      (1 << 0)
00793 #define WAITEXTEN_DIALTONE (1 << 1)
00794 
00795 AST_APP_OPTIONS(waitexten_opts, {
00796    AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
00797    AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0),
00798 });
00799 
00800 struct ast_context;
00801 struct ast_app;
00802 
00803 static struct ast_taskprocessor *device_state_tps;
00804 
00805 AST_THREADSTORAGE(switch_data);
00806 AST_THREADSTORAGE(extensionstate_buf);
00807 
00808 /*!
00809    \brief ast_exten: An extension
00810    The dialplan is saved as a linked list with each context
00811    having it's own linked list of extensions - one item per
00812    priority.
00813 */
00814 struct ast_exten {
00815    char *exten;         /*!< Extension name */
00816    int matchcid;        /*!< Match caller id ? */
00817    const char *cidmatch;      /*!< Caller id to match for this extension */
00818    int priority;        /*!< Priority */
00819    const char *label;      /*!< Label */
00820    struct ast_context *parent;   /*!< The context this extension belongs to  */
00821    const char *app;     /*!< Application to execute */
00822    struct ast_app *cached_app;     /*!< Cached location of application */
00823    void *data;       /*!< Data to use (arguments) */
00824    void (*datad)(void *);     /*!< Data destructor */
00825    struct ast_exten *peer;    /*!< Next higher priority with our extension */
00826    struct ast_hashtab *peer_table;    /*!< Priorities list in hashtab form -- only on the head of the peer list */
00827    struct ast_hashtab *peer_label_table; /*!< labeled priorities in the peers -- only on the head of the peer list */
00828    const char *registrar;     /*!< Registrar */
00829    struct ast_exten *next;    /*!< Extension with a greater ID */
00830    char stuff[0];
00831 };
00832 
00833 /*! \brief ast_include: include= support in extensions.conf */
00834 struct ast_include {
00835    const char *name;
00836    const char *rname;         /*!< Context to include */
00837    const char *registrar;        /*!< Registrar */
00838    int hastime;            /*!< If time construct exists */
00839    struct ast_timing timing;               /*!< time construct */
00840    struct ast_include *next;     /*!< Link them together */
00841    char stuff[0];
00842 };
00843 
00844 /*! \brief ast_sw: Switch statement in extensions.conf */
00845 struct ast_sw {
00846    char *name;
00847    const char *registrar;        /*!< Registrar */
00848    char *data;          /*!< Data load */
00849    int eval;
00850    AST_LIST_ENTRY(ast_sw) list;
00851    char stuff[0];
00852 };
00853 
00854 /*! \brief ast_ignorepat: Ignore patterns in dial plan */
00855 struct ast_ignorepat {
00856    const char *registrar;
00857    struct ast_ignorepat *next;
00858    const char pattern[0];
00859 };
00860 
00861 /*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
00862 struct match_char
00863 {
00864    int is_pattern; /* the pattern started with '_' */
00865    int deleted;    /* if this is set, then... don't return it */
00866    int specificity; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */
00867    struct match_char *alt_char;
00868    struct match_char *next_char;
00869    struct ast_exten *exten; /* attached to last char of a pattern for exten */
00870    char x[1];       /* the pattern itself-- matches a single char */
00871 };
00872 
00873 struct scoreboard  /* make sure all fields are 0 before calling new_find_extension */
00874 {
00875    int total_specificity;
00876    int total_length;
00877    char last_char;   /* set to ! or . if they are the end of the pattern */
00878    int canmatch;     /* if the string to match was just too short */
00879    struct match_char *node;
00880    struct ast_exten *canmatch_exten;
00881    struct ast_exten *exten;
00882 };
00883 
00884 /*! \brief ast_context: An extension context */
00885 struct ast_context {
00886    ast_rwlock_t lock;         /*!< A lock to prevent multiple threads from clobbering the context */
00887    struct ast_exten *root;       /*!< The root of the list of extensions */
00888    struct ast_hashtab *root_table;            /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree  */
00889    struct match_char *pattern_tree;        /*!< A tree to speed up extension pattern matching */
00890    struct ast_context *next;     /*!< Link them together */
00891    struct ast_include *includes;    /*!< Include other contexts */
00892    struct ast_ignorepat *ignorepats;   /*!< Patterns for which to continue playing dialtone */
00893    char *registrar;        /*!< Registrar -- make sure you malloc this, as the registrar may have to survive module unloads */
00894    int refcount;                   /*!< each module that would have created this context should inc/dec this as appropriate */
00895    AST_LIST_HEAD_NOLOCK(, ast_sw) alts;   /*!< Alternative switches */
00896    ast_mutex_t macrolock;        /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
00897    char name[0];           /*!< Name of the context */
00898 };
00899 
00900 /*! \brief ast_app: A registered application */
00901 struct ast_app {
00902    int (*execute)(struct ast_channel *chan, const char *data);
00903    AST_DECLARE_STRING_FIELDS(
00904       AST_STRING_FIELD(synopsis);     /*!< Synopsis text for 'show applications' */
00905       AST_STRING_FIELD(description);  /*!< Description (help text) for 'show application &lt;name&gt;' */
00906       AST_STRING_FIELD(syntax);       /*!< Syntax text for 'core show applications' */
00907       AST_STRING_FIELD(arguments);    /*!< Arguments description */
00908       AST_STRING_FIELD(seealso);      /*!< See also */
00909    );
00910 #ifdef AST_XML_DOCS
00911    enum ast_doc_src docsrc;      /*!< Where the documentation come from. */
00912 #endif
00913    AST_RWLIST_ENTRY(ast_app) list;     /*!< Next app in list */
00914    struct ast_module *module;    /*!< Module this app belongs to */
00915    char name[0];           /*!< Name of the application */
00916 };
00917 
00918 /*! \brief ast_state_cb: An extension state notify register item */
00919 struct ast_state_cb {
00920    int id;
00921    void *data;
00922    ast_state_cb_type callback;
00923    AST_LIST_ENTRY(ast_state_cb) entry;
00924 };
00925 
00926 /*! \brief Structure for dial plan hints
00927 
00928   \note Hints are pointers from an extension in the dialplan to one or
00929   more devices (tech/name)
00930    - See \ref AstExtState
00931 */
00932 struct ast_hint {
00933    struct ast_exten *exten;   /*!< Extension */
00934    int laststate;       /*!< Last known state */
00935    AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks; /*!< Callback list for this extension */
00936    AST_RWLIST_ENTRY(ast_hint) list;/*!< Pointer to next hint in list */
00937 };
00938 
00939 static const struct cfextension_states {
00940    int extension_state;
00941    const char * const text;
00942 } extension_states[] = {
00943    { AST_EXTENSION_NOT_INUSE,                     "Idle" },
00944    { AST_EXTENSION_INUSE,                         "InUse" },
00945    { AST_EXTENSION_BUSY,                          "Busy" },
00946    { AST_EXTENSION_UNAVAILABLE,                   "Unavailable" },
00947    { AST_EXTENSION_RINGING,                       "Ringing" },
00948    { AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
00949    { AST_EXTENSION_ONHOLD,                        "Hold" },
00950    { AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD,  "InUse&Hold" }
00951 };
00952 
00953 struct statechange {
00954    AST_LIST_ENTRY(statechange) entry;
00955    char dev[0];
00956 };
00957 
00958 struct pbx_exception {
00959    AST_DECLARE_STRING_FIELDS(
00960       AST_STRING_FIELD(context); /*!< Context associated with this exception */
00961       AST_STRING_FIELD(exten);   /*!< Exten associated with this exception */
00962       AST_STRING_FIELD(reason);     /*!< The exception reason */
00963    );
00964 
00965    int priority;           /*!< Priority associated with this exception */
00966 };
00967 
00968 static int pbx_builtin_answer(struct ast_channel *, const char *);
00969 static int pbx_builtin_goto(struct ast_channel *, const char *);
00970 static int pbx_builtin_hangup(struct ast_channel *, const char *);
00971 static int pbx_builtin_background(struct ast_channel *, const char *);
00972 static int pbx_builtin_wait(struct ast_channel *, const char *);
00973 static int pbx_builtin_waitexten(struct ast_channel *, const char *);
00974 static int pbx_builtin_incomplete(struct ast_channel *, const char *);
00975 static int pbx_builtin_resetcdr(struct ast_channel *, const char *);
00976 static int pbx_builtin_setamaflags(struct ast_channel *, const char *);
00977 static int pbx_builtin_ringing(struct ast_channel *, const char *);
00978 static int pbx_builtin_proceeding(struct ast_channel *, const char *);
00979 static int pbx_builtin_progress(struct ast_channel *, const char *);
00980 static int pbx_builtin_congestion(struct ast_channel *, const char *);
00981 static int pbx_builtin_busy(struct ast_channel *, const char *);
00982 static int pbx_builtin_noop(struct ast_channel *, const char *);
00983 static int pbx_builtin_gotoif(struct ast_channel *, const char *);
00984 static int pbx_builtin_gotoiftime(struct ast_channel *, const char *);
00985 static int pbx_builtin_execiftime(struct ast_channel *, const char *);
00986 static int pbx_builtin_saynumber(struct ast_channel *, const char *);
00987 static int pbx_builtin_saydigits(struct ast_channel *, const char *);
00988 static int pbx_builtin_saycharacters(struct ast_channel *, const char *);
00989 static int pbx_builtin_sayphonetic(struct ast_channel *, const char *);
00990 static int matchcid(const char *cidpattern, const char *callerid);
00991 #ifdef NEED_DEBUG
00992 static void log_match_char_tree(struct match_char *node, char *prefix); /* for use anywhere */
00993 #endif
00994 static int pbx_builtin_importvar(struct ast_channel *, const char *);
00995 static void set_ext_pri(struct ast_channel *c, const char *exten, int pri);
00996 static void new_find_extension(const char *str, struct scoreboard *score,
00997       struct match_char *tree, int length, int spec, const char *callerid,
00998       const char *label, enum ext_match_t action);
00999 static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern);
01000 static struct match_char *add_exten_to_pattern_tree(struct ast_context *con,
01001       struct ast_exten *e1, int findonly);
01002 static struct match_char *add_pattern_node(struct ast_context *con,
01003       struct match_char *current, char *pattern, int is_pattern,
01004       int already, int specificity, struct match_char **parent);
01005 static void create_match_char_tree(struct ast_context *con);
01006 static struct ast_exten *get_canmatch_exten(struct match_char *node);
01007 static void destroy_pattern_tree(struct match_char *pattern_tree);
01008 static int hashtab_compare_extens(const void *ha_a, const void *ah_b);
01009 static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b);
01010 static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b);
01011 static unsigned int hashtab_hash_extens(const void *obj);
01012 static unsigned int hashtab_hash_priority(const void *obj);
01013 static unsigned int hashtab_hash_labels(const void *obj);
01014 static void __ast_internal_context_destroy( struct ast_context *con);
01015 static int ast_add_extension_nolock(const char *context, int replace, const char *extension,
01016    int priority, const char *label, const char *callerid,
01017    const char *application, void *data, void (*datad)(void *), const char *registrar);
01018 static int add_pri_lockopt(struct ast_context *con, struct ast_exten *tmp,
01019    struct ast_exten *el, struct ast_exten *e, int replace, int lockhints);
01020 static int ast_add_extension2_lockopt(struct ast_context *con,
01021    int replace, const char *extension, int priority, const char *label, const char *callerid,
01022    const char *application, void *data, void (*datad)(void *),
01023    const char *registrar, int lockconts, int lockhints);
01024 
01025 /* a func for qsort to use to sort a char array */
01026 static int compare_char(const void *a, const void *b)
01027 {
01028    const char *ac = a;
01029    const char *bc = b;
01030    if ((*ac) < (*bc))
01031       return -1;
01032    else if ((*ac) == (*bc))
01033       return 0;
01034    else
01035       return 1;
01036 }
01037 
01038 /* labels, contexts are case sensitive  priority numbers are ints */
01039 int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b)
01040 {
01041    const struct ast_context *ac = ah_a;
01042    const struct ast_context *bc = ah_b;
01043    if (!ac || !bc) /* safety valve, but it might prevent a crash you'd rather have happen */
01044       return 1;
01045    /* assume context names are registered in a string table! */
01046    return strcmp(ac->name, bc->name);
01047 }
01048 
01049 static int hashtab_compare_extens(const void *ah_a, const void *ah_b)
01050 {
01051    const struct ast_exten *ac = ah_a;
01052    const struct ast_exten *bc = ah_b;
01053    int x = strcmp(ac->exten, bc->exten);
01054    if (x) { /* if exten names are diff, then return */
01055       return x;
01056    }
01057 
01058    /* but if they are the same, do the cidmatch values match? */
01059    if (ac->matchcid && bc->matchcid) {
01060       return strcmp(ac->cidmatch,bc->cidmatch);
01061    } else if (!ac->matchcid && !bc->matchcid) {
01062       return 0; /* if there's no matchcid on either side, then this is a match */
01063    } else {
01064       return 1; /* if there's matchcid on one but not the other, they are different */
01065    }
01066 }
01067 
01068 static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b)
01069 {
01070    const struct ast_exten *ac = ah_a;
01071    const struct ast_exten *bc = ah_b;
01072    return ac->priority != bc->priority;
01073 }
01074 
01075 static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b)
01076 {
01077    const struct ast_exten *ac = ah_a;
01078    const struct ast_exten *bc = ah_b;
01079    return strcmp(S_OR(ac->label, ""), S_OR(bc->label, ""));
01080 }
01081 
01082 unsigned int ast_hashtab_hash_contexts(const void *obj)
01083 {
01084    const struct ast_context *ac = obj;
01085    return ast_hashtab_hash_string(ac->name);
01086 }
01087 
01088 static unsigned int hashtab_hash_extens(const void *obj)
01089 {
01090    const struct ast_exten *ac = obj;
01091    unsigned int x = ast_hashtab_hash_string(ac->exten);
01092    unsigned int y = 0;
01093    if (ac->matchcid)
01094       y = ast_hashtab_hash_string(ac->cidmatch);
01095    return x+y;
01096 }
01097 
01098 static unsigned int hashtab_hash_priority(const void *obj)
01099 {
01100    const struct ast_exten *ac = obj;
01101    return ast_hashtab_hash_int(ac->priority);
01102 }
01103 
01104 static unsigned int hashtab_hash_labels(const void *obj)
01105 {
01106    const struct ast_exten *ac = obj;
01107    return ast_hashtab_hash_string(S_OR(ac->label, ""));
01108 }
01109 
01110 
01111 AST_RWLOCK_DEFINE_STATIC(globalslock);
01112 static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
01113 
01114 static int autofallthrough = 1;
01115 static int extenpatternmatchnew = 0;
01116 static char *overrideswitch = NULL;
01117 
01118 /*! \brief Subscription for device state change events */
01119 static struct ast_event_sub *device_state_sub;
01120 
01121 AST_MUTEX_DEFINE_STATIC(maxcalllock);
01122 static int countcalls;
01123 static int totalcalls;
01124 
01125 static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
01126 
01127 /*! \brief Declaration of builtin applications */
01128 static struct pbx_builtin {
01129    char name[AST_MAX_APP];
01130    int (*execute)(struct ast_channel *chan, const char *data);
01131 } builtins[] =
01132 {
01133    /* These applications are built into the PBX core and do not
01134       need separate modules */
01135 
01136    { "Answer",         pbx_builtin_answer },
01137    { "BackGround",     pbx_builtin_background },
01138    { "Busy",           pbx_builtin_busy },
01139    { "Congestion",     pbx_builtin_congestion },
01140    { "ExecIfTime",     pbx_builtin_execiftime },
01141    { "Goto",           pbx_builtin_goto },
01142    { "GotoIf",         pbx_builtin_gotoif },
01143    { "GotoIfTime",     pbx_builtin_gotoiftime },
01144    { "ImportVar",      pbx_builtin_importvar },
01145    { "Hangup",         pbx_builtin_hangup },
01146    { "Incomplete",     pbx_builtin_incomplete },
01147    { "NoOp",           pbx_builtin_noop },
01148    { "Proceeding",     pbx_builtin_proceeding },
01149    { "Progress",       pbx_builtin_progress },
01150    { "RaiseException", pbx_builtin_raise_exception },
01151    { "ResetCDR",       pbx_builtin_resetcdr },
01152    { "Ringing",        pbx_builtin_ringing },
01153    { "SayAlpha",       pbx_builtin_saycharacters },
01154    { "SayDigits",      pbx_builtin_saydigits },
01155    { "SayNumber",      pbx_builtin_saynumber },
01156    { "SayPhonetic",    pbx_builtin_sayphonetic },
01157    { "Set",            pbx_builtin_setvar },
01158    { "MSet",           pbx_builtin_setvar_multiple },
01159    { "SetAMAFlags",    pbx_builtin_setamaflags },
01160    { "Wait",           pbx_builtin_wait },
01161    { "WaitExten",      pbx_builtin_waitexten }
01162 };
01163 
01164 static struct ast_context *contexts;
01165 static struct ast_hashtab *contexts_table = NULL;
01166 
01167 /*!\brief Lock for the ast_context list
01168  * This lock MUST be recursive, or a deadlock on reload may result.  See
01169  * https://issues.asterisk.org/view.php?id=17643
01170  */
01171 AST_MUTEX_DEFINE_STATIC(conlock);
01172 
01173 static AST_RWLIST_HEAD_STATIC(apps, ast_app);
01174 
01175 static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
01176 
01177 static int stateid = 1;
01178 /* WARNING:
01179    When holding this list's lock, do _not_ do anything that will cause conlock
01180    to be taken, unless you _already_ hold it. The ast_merge_contexts_and_delete
01181    function will take the locks in conlock/hints order, so any other
01182    paths that require both locks must also take them in that order.
01183 */
01184 static AST_RWLIST_HEAD_STATIC(hints, ast_hint);
01185 
01186 static AST_LIST_HEAD_NOLOCK_STATIC(statecbs, ast_state_cb);
01187 
01188 #ifdef CONTEXT_DEBUG
01189 
01190 /* these routines are provided for doing run-time checks
01191    on the extension structures, in case you are having
01192    problems, this routine might help you localize where
01193    the problem is occurring. It's kinda like a debug memory
01194    allocator's arena checker... It'll eat up your cpu cycles!
01195    but you'll see, if you call it in the right places,
01196    right where your problems began...
01197 */
01198 
01199 /* you can break on the check_contexts_trouble()
01200 routine in your debugger to stop at the moment
01201 there's a problem */
01202 void check_contexts_trouble(void);
01203 
01204 void check_contexts_trouble(void)
01205 {
01206    int x = 1;
01207    x = 2;
01208 }
01209 
01210 static struct ast_context *find_context_locked(const char *context);
01211 static struct ast_context *find_context(const char *context);
01212 int check_contexts(char *, int);
01213 
01214 int check_contexts(char *file, int line )
01215 {
01216    struct ast_hashtab_iter *t1;
01217    struct ast_context *c1, *c2;
01218    int found = 0;
01219    struct ast_exten *e1, *e2, *e3;
01220    struct ast_exten ex;
01221 
01222    /* try to find inconsistencies */
01223    /* is every context in the context table in the context list and vice-versa ? */
01224 
01225    if (!contexts_table) {
01226       ast_log(LOG_NOTICE,"Called from: %s:%d: No contexts_table!\n", file, line);
01227       usleep(500000);
01228    }
01229 
01230    t1 = ast_hashtab_start_traversal(contexts_table);
01231    while( (c1 = ast_hashtab_next(t1))) {
01232       for(c2=contexts;c2;c2=c2->next) {
01233          if (!strcmp(c1->name, c2->name)) {
01234             found = 1;
01235             break;
01236          }
01237       }
01238       if (!found) {
01239          ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the linked list\n", file, line, c1->name);
01240          check_contexts_trouble();
01241       }
01242    }
01243    ast_hashtab_end_traversal(t1);
01244    for(c2=contexts;c2;c2=c2->next) {
01245       c1 = find_context_locked(c2->name);
01246       if (!c1) {
01247          ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the hashtab\n", file, line, c2->name);
01248          check_contexts_trouble();
01249       } else
01250          ast_unlock_contexts();
01251    }
01252 
01253    /* loop thru all contexts, and verify the exten structure compares to the 
01254       hashtab structure */
01255    for(c2=contexts;c2;c2=c2->next) {
01256       c1 = find_context_locked(c2->name);
01257       if (c1)
01258       {
01259 
01260          ast_unlock_contexts();
01261 
01262          /* is every entry in the root list also in the root_table? */
01263          for(e1 = c1->root; e1; e1=e1->next)
01264          {
01265             char dummy_name[1024];
01266             ex.exten = dummy_name;
01267             ex.matchcid = e1->matchcid;
01268             ex.cidmatch = e1->cidmatch;
01269             ast_copy_string(dummy_name, e1->exten, sizeof(dummy_name));
01270             e2 = ast_hashtab_lookup(c1->root_table, &ex);
01271             if (!e2) {
01272                if (e1->matchcid) {
01273                   ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s (CID match: %s) but it is not in its root_table\n", file, line, c2->name, dummy_name, e1->cidmatch );
01274                } else {
01275                   ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, dummy_name );
01276                }
01277                check_contexts_trouble();
01278             }
01279          }
01280 
01281          /* is every entry in the root_table also in the root list? */ 
01282          if (!c2->root_table) {
01283             if (c2->root) {
01284                ast_log(LOG_NOTICE,"Called from: %s:%d: No c2->root_table for context %s!\n", file, line, c2->name);
01285                usleep(500000);
01286             }
01287          } else {
01288             t1 = ast_hashtab_start_traversal(c2->root_table);
01289             while( (e2 = ast_hashtab_next(t1)) ) {
01290                for(e1=c2->root;e1;e1=e1->next) {
01291                   if (!strcmp(e1->exten, e2->exten)) {
01292                      found = 1;
01293                      break;
01294                   }
01295                }
01296                if (!found) {
01297                   ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, e2->exten);
01298                   check_contexts_trouble();
01299                }
01300 
01301             }
01302             ast_hashtab_end_traversal(t1);
01303          }
01304       }
01305       /* is every priority reflected in the peer_table at the head of the list? */
01306 
01307       /* is every entry in the root list also in the root_table? */
01308       /* are the per-extension peer_tables in the right place? */
01309 
01310       for(e1 = c2->root; e1; e1 = e1->next) {
01311 
01312          for(e2=e1;e2;e2=e2->peer) {
01313             ex.priority = e2->priority;
01314             if (e2 != e1 && e2->peer_table) {
01315                ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
01316                check_contexts_trouble();
01317             }
01318 
01319             if (e2 != e1 && e2->peer_label_table) {
01320                ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_label_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
01321                check_contexts_trouble();
01322             }
01323 
01324             if (e2 == e1 && !e2->peer_table){
01325                ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_table!\n", file, line, c2->name, e1->exten, e2->priority );
01326                check_contexts_trouble();
01327             }
01328 
01329             if (e2 == e1 && !e2->peer_label_table) {
01330                ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_label_table!\n", file, line, c2->name, e1->exten, e2->priority );
01331                check_contexts_trouble();
01332             }
01333 
01334 
01335             e3 = ast_hashtab_lookup(e1->peer_table, &ex);
01336             if (!e3) {
01337                ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer_table\n", file, line, c2->name, e1->exten, e2->priority );
01338                check_contexts_trouble();
01339             }
01340          }
01341 
01342          if (!e1->peer_table){
01343             ast_log(LOG_NOTICE,"Called from: %s:%d: No e1->peer_table!\n", file, line);
01344             usleep(500000);
01345          }
01346 
01347          /* is every entry in the peer_table also in the peer list? */
01348          t1 = ast_hashtab_start_traversal(e1->peer_table);
01349          while( (e2 = ast_hashtab_next(t1)) ) {
01350             for(e3=e1;e3;e3=e3->peer) {
01351                if (e3->priority == e2->priority) {
01352                   found = 1;
01353                   break;
01354                }
01355             }
01356             if (!found) {
01357                ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer list\n", file, line, c2->name, e1->exten, e2->priority );
01358                check_contexts_trouble();
01359             }
01360          }
01361          ast_hashtab_end_traversal(t1);
01362       }
01363    }
01364    return 0;
01365 }
01366 #endif
01367 
01368 /*
01369    \note This function is special. It saves the stack so that no matter
01370    how many times it is called, it returns to the same place */
01371 int pbx_exec(struct ast_channel *c, /*!< Channel */
01372         struct ast_app *app,  /*!< Application */
01373         const char *data)     /*!< Data for execution */
01374 {
01375    int res;
01376    struct ast_module_user *u = NULL;
01377    const char *saved_c_appl;
01378    const char *saved_c_data;
01379 
01380    if (c->cdr && !ast_check_hangup(c))
01381       ast_cdr_setapp(c->cdr, app->name, data);
01382 
01383    /* save channel values */
01384    saved_c_appl= c->appl;
01385    saved_c_data= c->data;
01386 
01387    c->appl = app->name;
01388    c->data = data;
01389    ast_cel_report_event(c, AST_CEL_APP_START, NULL, NULL, NULL);
01390 
01391    if (app->module)
01392       u = __ast_module_user_add(app->module, c);
01393    if (strcasecmp(app->name, "system") && !ast_strlen_zero(data) &&
01394          strchr(data, '|') && !strchr(data, ',') && !ast_opt_dont_warn) {
01395       ast_log(LOG_WARNING, "The application delimiter is now the comma, not "
01396          "the pipe.  Did you forget to convert your dialplan?  (%s(%s))\n",
01397          app->name, (char *) data);
01398    }
01399    res = app->execute(c, S_OR(data, ""));
01400    if (app->module && u)
01401       __ast_module_user_remove(app->module, u);
01402    ast_cel_report_event(c, AST_CEL_APP_END, NULL, NULL, NULL);
01403    /* restore channel values */
01404    c->appl = saved_c_appl;
01405    c->data = saved_c_data;
01406    return res;
01407 }
01408 
01409 
01410 /*! Go no deeper than this through includes (not counting loops) */
01411 #define AST_PBX_MAX_STACK  128
01412 
01413 /*! \brief Find application handle in linked list
01414  */
01415 struct ast_app *pbx_findapp(const char *app)
01416 {
01417    struct ast_app *tmp;
01418 
01419    AST_RWLIST_RDLOCK(&apps);
01420    AST_RWLIST_TRAVERSE(&apps, tmp, list) {
01421       if (!strcasecmp(tmp->name, app))
01422          break;
01423    }
01424    AST_RWLIST_UNLOCK(&apps);
01425 
01426    return tmp;
01427 }
01428 
01429 static struct ast_switch *pbx_findswitch(const char *sw)
01430 {
01431    struct ast_switch *asw;
01432 
01433    AST_RWLIST_RDLOCK(&switches);
01434    AST_RWLIST_TRAVERSE(&switches, asw, list) {
01435       if (!strcasecmp(asw->name, sw))
01436          break;
01437    }
01438    AST_RWLIST_UNLOCK(&switches);
01439 
01440    return asw;
01441 }
01442 
01443 static inline int include_valid(struct ast_include *i)
01444 {
01445    if (!i->hastime)
01446       return 1;
01447 
01448    return ast_check_timing(&(i->timing));
01449 }
01450 
01451 static void pbx_destroy(struct ast_pbx *p)
01452 {
01453    ast_free(p);
01454 }
01455 
01456 /* form a tree that fully describes all the patterns in a context's extensions
01457  * in this tree, a "node" represents an individual character or character set
01458  * meant to match the corresponding character in a dial string. The tree
01459  * consists of a series of match_char structs linked in a chain
01460  * via the alt_char pointers. More than one pattern can share the same parts of the
01461  * tree as other extensions with the same pattern to that point.
01462  * My first attempt to duplicate the finding of the 'best' pattern was flawed in that
01463  * I misunderstood the general algorithm. I thought that the 'best' pattern
01464  * was the one with lowest total score. This was not true. Thus, if you have
01465  * patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is
01466  * the "best" match because it has fewer X's, and is therefore more specific,
01467  * but this is not how the old algorithm works. It sorts matching patterns
01468  * in a similar collating sequence as sorting alphabetic strings, from left to
01469  * right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match,
01470  * because "1" is more specific than "X".
01471  * So, to accomodate this philosophy, I sort the tree branches along the alt_char
01472  * line so they are lowest to highest in specificity numbers. This way, as soon
01473  * as we encounter our first complete match, we automatically have the "best"
01474  * match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE.
01475  * If anyone would like to resurrect the "wrong" pattern trie searching algorithm,
01476  * they are welcome to revert pbx to before 1 Apr 2008.
01477  * As an example, consider these 4 extensions:
01478  * (a) NXXNXXXXXX
01479  * (b) 307754XXXX
01480  * (c) fax
01481  * (d) NXXXXXXXXX
01482  *
01483  * In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over
01484  * most numbers. For all numbers beginning with 307754, (b) should always win.
01485  *
01486  * These pattern should form a (sorted) tree that looks like this:
01487  *   { "3" }  --next-->  { "0" }  --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) }
01488  *      |
01489  *      |alt
01490  *      |
01491  *   { "f" }  --next-->  { "a" }  --next--> { "x"  exten_match: (c) }
01492  *   { "N" }  --next-->  { "X" }  --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
01493  *      |                                                        |
01494  *      |                                                        |alt
01495  *      |alt                                                     |
01496  *      |                                                     { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
01497  *      |
01498  *     NULL
01499  *
01500  *   In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take
01501  *   fewer CPU cycles than a call to strchr("23456789",*z), where *z is the char to match...
01502  *
01503  *   traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern,  it calls itself
01504  *   on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length.
01505  *   We pass a pointer to a scoreboard down through, also.
01506  *   The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension.
01507  *   The first complete match ends the traversal, which should make this version of the pattern matcher faster
01508  *   the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both
01509  *   these cases, the reason we can stop immediately, is because the first pattern match found will be the "best"
01510  *   according to the sort criteria.
01511  *   Hope the limit on stack depth won't be a problem... this routine should
01512  *   be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch.
01513  *
01514  *   In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d.  All are
01515  *   of length 10; they have total specificities of  24580, 10246, and 25090, respectively, not that this matters
01516  *   at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have
01517  *   left the specificity totals in the code as an artifact; at some point, I will strip it out.
01518  *
01519  *   Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown,
01520  *   because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup
01521  *   can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or
01522  *   more times faster in extreme cases.
01523  *
01524  *   MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you
01525  *   can have patterns in your CID field as well.
01526  *
01527  * */
01528 
01529 
01530 static void update_scoreboard(struct scoreboard *board, int length, int spec, struct ast_exten *exten, char last, const char *callerid, int deleted, struct match_char *node)
01531 {
01532    /* if this extension is marked as deleted, then skip this -- if it never shows
01533       on the scoreboard, it will never be found, nor will halt the traversal. */
01534    if (deleted)
01535       return;
01536    board->total_specificity = spec;
01537    board->total_length = length;
01538    board->exten = exten;
01539    board->last_char = last;
01540    board->node = node;
01541 #ifdef NEED_DEBUG_HERE
01542    ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec);
01543 #endif
01544 }
01545 
01546 #ifdef NEED_DEBUG
01547 static void log_match_char_tree(struct match_char *node, char *prefix)
01548 {
01549    char extenstr[40];
01550    struct ast_str *my_prefix = ast_str_alloca(1024);
01551 
01552    extenstr[0] = '\0';
01553 
01554    if (node && node->exten)
01555       snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
01556 
01557    if (strlen(node->x) > 1) {
01558       ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
01559          node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
01560          node->exten ? node->exten->exten : "", extenstr);
01561    } else {
01562       ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
01563          node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
01564          node->exten ? node->exten->exten : "", extenstr);
01565    }
01566 
01567    ast_str_set(&my_prefix, 0, "%s+       ", prefix);
01568 
01569    if (node->next_char)
01570       log_match_char_tree(node->next_char, ast_str_buffer(my_prefix));
01571 
01572    if (node->alt_char)
01573       log_match_char_tree(node->alt_char, prefix);
01574 }
01575 #endif
01576 
01577 static void cli_match_char_tree(struct match_char *node, char *prefix, int fd)
01578 {
01579    char extenstr[40];
01580    struct ast_str *my_prefix = ast_str_alloca(1024);
01581 
01582    extenstr[0] = '\0';
01583 
01584    if (node && node->exten)
01585       snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
01586 
01587    if (strlen(node->x) > 1) {
01588       ast_cli(fd, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
01589          node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
01590          node->exten ? node->exten->exten : "", extenstr);
01591    } else {
01592       ast_cli(fd, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
01593          node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
01594          node->exten ? node->exten->exten : "", extenstr);
01595    }
01596 
01597    ast_str_set(&my_prefix, 0, "%s+       ", prefix);
01598 
01599    if (node->next_char)
01600       cli_match_char_tree(node->next_char, ast_str_buffer(my_prefix), fd);
01601 
01602    if (node->alt_char)
01603       cli_match_char_tree(node->alt_char, prefix, fd);
01604 }
01605 
01606 static struct ast_exten *get_canmatch_exten(struct match_char *node)
01607 {
01608    /* find the exten at the end of the rope */
01609    struct match_char *node2 = node;
01610 
01611    for (node2 = node; node2; node2 = node2->next_char) {
01612       if (node2->exten) {
01613 #ifdef NEED_DEBUG_HERE
01614          ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten);
01615 #endif
01616          return node2->exten;
01617       }
01618    }
01619 #ifdef NEED_DEBUG_HERE
01620    ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x);
01621 #endif
01622    return 0;
01623 }
01624 
01625 static struct ast_exten *trie_find_next_match(struct match_char *node)
01626 {
01627    struct match_char *m3;
01628    struct match_char *m4;
01629    struct ast_exten *e3;
01630 
01631    if (node && node->x[0] == '.' && !node->x[1]) { /* dot and ! will ALWAYS be next match in a matchmore */
01632       return node->exten;
01633    }
01634 
01635    if (node && node->x[0] == '!' && !node->x[1]) {
01636       return node->exten;
01637    }
01638 
01639    if (!node || !node->next_char) {
01640       return NULL;
01641    }
01642 
01643    m3 = node->next_char;
01644 
01645    if (m3->exten) {
01646       return m3->exten;
01647    }
01648    for (m4 = m3->alt_char; m4; m4 = m4->alt_char) {
01649       if (m4->exten) {
01650          return m4->exten;
01651       }
01652    }
01653    for (m4 = m3; m4; m4 = m4->alt_char) {
01654       e3 = trie_find_next_match(m3);
01655       if (e3) {
01656          return e3;
01657       }
01658    }
01659 
01660    return NULL;
01661 }
01662 
01663 #ifdef DEBUG_THIS
01664 static char *action2str(enum ext_match_t action)
01665 {
01666    switch (action) {
01667    case E_MATCH:
01668       return "MATCH";
01669    case E_CANMATCH:
01670       return "CANMATCH";
01671    case E_MATCHMORE:
01672       return "MATCHMORE";
01673    case E_FINDLABEL:
01674       return "FINDLABEL";
01675    case E_SPAWN:
01676       return "SPAWN";
01677    default:
01678       return "?ACTION?";
01679    }
01680 }
01681 
01682 #endif
01683 
01684 static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *callerid, const char *label, enum ext_match_t action)
01685 {
01686    struct match_char *p; /* note minimal stack storage requirements */
01687    struct ast_exten pattern = { .label = label };
01688 #ifdef DEBUG_THIS
01689    if (tree)
01690       ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree %s action=%s\n", str, tree->x, action2str(action));
01691    else
01692       ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str, action2str(action));
01693 #endif
01694    for (p = tree; p; p = p->alt_char) {
01695       if (p->is_pattern) {
01696          if (p->x[0] == 'N') {
01697             if (p->x[1] == 0 && *str >= '2' && *str <= '9' ) {
01698 #define  NEW_MATCHER_CHK_MATCH          \
01699                if (p->exten && !(*(str + 1))) { /* if a shorter pattern matches along the way, might as well report it */             \
01700                   if (action == E_MATCH || action == E_SPAWN || action == E_FINDLABEL) { /* if in CANMATCH/MATCHMORE, don't let matches get in the way */   \
01701                      update_scoreboard(score, length + 1, spec + p->specificity, p->exten, 0, callerid, p->deleted, p);                 \
01702                      if (!p->deleted) {                                                                                           \
01703                         if (action == E_FINDLABEL) {                                                                             \
01704                            if (ast_hashtab_lookup(score->exten->peer_label_table, &pattern)) {                                  \
01705                               ast_debug(4, "Found label in preferred extension\n");                                            \
01706                               return;                                                                                          \
01707                            }                                                                                                    \
01708                         } else {                                                                                                 \
01709                            ast_debug(4, "returning an exact match-- first found-- %s\n", p->exten->exten);                       \
01710                            return; /* the first match, by definition, will be the best, because of the sorted tree */           \
01711                         }                                                                                                        \
01712                      }                                                                                                            \
01713                   }                                                                                                                \
01714                }
01715                
01716 #define  NEW_MATCHER_RECURSE             \
01717                if (p->next_char && (*(str + 1) || (p->next_char->x[0] == '/' && p->next_char->x[1] == 0)                 \
01718                                                 || p->next_char->x[0] == '!')) {                                          \
01719                   if (*(str + 1) || p->next_char->x[0] == '!') {                                                         \
01720                      new_find_extension(str + 1, score, p->next_char, length + 1, spec + p->specificity, callerid, label, action); \
01721                      if (score->exten)  {                                                                             \
01722                           ast_debug(4 ,"returning an exact match-- %s\n", score->exten->exten);                         \
01723                         return; /* the first match is all we need */                                                 \
01724                      }                                                                                    \
01725                   } else {                                                                                             \
01726                      new_find_extension("/", score, p->next_char, length + 1, spec + p->specificity, callerid, label, action);    \
01727                      if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {      \
01728                           ast_debug(4,"returning a (can/more) match--- %s\n", score->exten ? score->exten->exten :     \
01729                                         "NULL");                                                                        \
01730                         return; /* the first match is all we need */                                                 \
01731                      }                                                                                    \
01732                   }                                                                                                    \
01733                } else if (p->next_char && !*(str + 1)) {                                                                  \
01734                   score->canmatch = 1;                                                                                 \
01735                   score->canmatch_exten = get_canmatch_exten(p);                                                       \
01736                   if (action == E_CANMATCH || action == E_MATCHMORE) {                                                 \
01737                        ast_debug(4, "returning a canmatch/matchmore--- str=%s\n", str);                                  \
01738                      return;                                                                                          \
01739                   }                                                                                        \
01740                }
01741                
01742                NEW_MATCHER_CHK_MATCH;
01743                NEW_MATCHER_RECURSE;
01744             }
01745          } else if (p->x[0] == 'Z') {
01746             if (p->x[1] == 0 && *str >= '1' && *str <= '9' ) {
01747                NEW_MATCHER_CHK_MATCH;
01748                NEW_MATCHER_RECURSE;
01749             }
01750          } else if (p->x[0] == 'X') { 
01751             if (p->x[1] == 0 && *str >= '0' && *str <= '9' ) {
01752                NEW_MATCHER_CHK_MATCH;
01753                NEW_MATCHER_RECURSE;
01754             }
01755          } else if (p->x[0] == '.' && p->x[1] == 0) {
01756             /* how many chars will the . match against? */
01757             int i = 0;
01758             const char *str2 = str;
01759             while (*str2 && *str2 != '/') {
01760                str2++;
01761                i++;
01762             }
01763             if (p->exten && *str2 != '/') {
01764                update_scoreboard(score, length + i, spec + (i * p->specificity), p->exten, '.', callerid, p->deleted, p);
01765                if (score->exten) {
01766                   ast_debug(4,"return because scoreboard has a match with '/'--- %s\n", score->exten->exten);
01767                   return; /* the first match is all we need */
01768                }
01769             }
01770             if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
01771                new_find_extension("/", score, p->next_char, length + i, spec+(p->specificity*i), callerid, label, action);
01772                if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
01773                   ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set--- %s\n", score->exten ? score->exten->exten : "NULL");
01774                   return; /* the first match is all we need */
01775                }
01776             }
01777          } else if (p->x[0] == '!' && p->x[1] == 0) {
01778             /* how many chars will the . match against? */
01779             int i = 1;
01780             const char *str2 = str;
01781             while (*str2 && *str2 != '/') {
01782                str2++;
01783                i++;
01784             }
01785             if (p->exten && *str2 != '/') {
01786                update_scoreboard(score, length + 1, spec + (p->specificity * i), p->exten, '!', callerid, p->deleted, p);
01787                if (score->exten) {
01788                   ast_debug(4, "return because scoreboard has a '!' match--- %s\n", score->exten->exten);
01789                   return; /* the first match is all we need */
01790                }
01791             }
01792             if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
01793                new_find_extension("/", score, p->next_char, length + i, spec + (p->specificity * i), callerid, label, action);
01794                if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
01795                   ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/' and '!'--- %s\n", score->exten ? score->exten->exten : "NULL");
01796                   return; /* the first match is all we need */
01797                }
01798             }
01799          } else if (p->x[0] == '/' && p->x[1] == 0) {
01800             /* the pattern in the tree includes the cid match! */
01801             if (p->next_char && callerid && *callerid) {
01802                new_find_extension(callerid, score, p->next_char, length + 1, spec, callerid, label, action);
01803                if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
01804                   ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/'--- %s\n", score->exten ? score->exten->exten : "NULL");
01805                   return; /* the first match is all we need */
01806                }
01807             }
01808          } else if (strchr(p->x, *str)) {
01809             ast_debug(4, "Nothing strange about this match\n");
01810             NEW_MATCHER_CHK_MATCH;
01811             NEW_MATCHER_RECURSE;
01812          }
01813       } else if (strchr(p->x, *str)) {
01814          ast_debug(4, "Nothing strange about this match\n");
01815          NEW_MATCHER_CHK_MATCH;
01816          NEW_MATCHER_RECURSE;
01817       }
01818    }
01819    ast_debug(4, "return at end of func\n");
01820 }
01821 
01822 /* the algorithm for forming the extension pattern tree is also a bit simple; you
01823  * traverse all the extensions in a context, and for each char of the extension,
01824  * you see if it exists in the tree; if it doesn't, you add it at the appropriate
01825  * spot. What more can I say? At the end of each exten, you cap it off by adding the
01826  * address of the extension involved. Duplicate patterns will be complained about.
01827  *
01828  * Ideally, this would be done for each context after it is created and fully
01829  * filled. It could be done as a finishing step after extensions.conf or .ael is
01830  * loaded, or it could be done when the first search is encountered. It should only
01831  * have to be done once, until the next unload or reload.
01832  *
01833  * I guess forming this pattern tree would be analogous to compiling a regex. Except
01834  * that a regex only handles 1 pattern, really. This trie holds any number
01835  * of patterns. Well, really, it **could** be considered a single pattern,
01836  * where the "|" (or) operator is allowed, I guess, in a way, sort of...
01837  */
01838 
01839 static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern)
01840 {
01841    struct match_char *t;
01842 
01843    if (!current) {
01844       return 0;
01845    }
01846 
01847    for (t = current; t; t = t->alt_char) {
01848       if (is_pattern == t->is_pattern && !strcmp(pat, t->x)) {/* uh, we may want to sort exploded [] contents to make matching easy */
01849          return t;
01850       }
01851    }
01852 
01853    return 0;
01854 }
01855 
01856 /* The first arg is the location of the tree ptr, or the
01857    address of the next_char ptr in the node, so we can mess
01858    with it, if we need to insert at the beginning of the list */
01859 
01860 static void insert_in_next_chars_alt_char_list(struct match_char **parent_ptr, struct match_char *node)
01861 {
01862    struct match_char *curr, *lcurr;
01863 
01864    /* insert node into the tree at "current", so the alt_char list from current is
01865       sorted in increasing value as you go to the leaves */
01866    if (!(*parent_ptr)) {
01867       *parent_ptr = node;
01868       return;
01869    }
01870 
01871    if ((*parent_ptr)->specificity > node->specificity) {
01872       /* insert at head */
01873       node->alt_char = (*parent_ptr);
01874       *parent_ptr = node;
01875       return;
01876    } 
01877 
01878    lcurr = *parent_ptr;
01879    for (curr = (*parent_ptr)->alt_char; curr; curr = curr->alt_char) {
01880       if (curr->specificity > node->specificity) {
01881          node->alt_char = curr;
01882          lcurr->alt_char = node;
01883          break;
01884       }
01885       lcurr = curr;
01886    }
01887 
01888    if (!curr) {
01889       lcurr->alt_char = node;
01890    }
01891 
01892 }
01893 
01894 static struct match_char *add_pattern_node(struct ast_context *con, struct match_char *current, char *pattern, int is_pattern, int already, int specificity, struct match_char **nextcharptr)
01895 {
01896    struct match_char *m;
01897    
01898    if (!(m = ast_calloc(1, sizeof(*m) + strlen(pattern)))) {
01899       return NULL;
01900    }
01901 
01902    /* strcpy is safe here since we know its size and have allocated
01903     * just enough space for when we allocated m
01904     */
01905    strcpy(m->x, pattern);
01906 
01907    /* the specificity scores are the same as used in the old
01908       pattern matcher. */
01909    m->is_pattern = is_pattern;
01910    if (specificity == 1 && is_pattern && pattern[0] == 'N')
01911       m->specificity = 0x0832;
01912    else if (specificity == 1 && is_pattern && pattern[0] == 'Z')
01913       m->specificity = 0x0931;
01914    else if (specificity == 1 && is_pattern && pattern[0] == 'X')
01915       m->specificity = 0x0a30;
01916    else if (specificity == 1 && is_pattern && pattern[0] == '.')
01917       m->specificity = 0x18000;
01918    else if (specificity == 1 && is_pattern && pattern[0] == '!')
01919       m->specificity = 0x28000;
01920    else
01921       m->specificity = specificity;
01922 
01923    if (!con->pattern_tree) {
01924       insert_in_next_chars_alt_char_list(&con->pattern_tree, m);
01925    } else {
01926       if (already) { /* switch to the new regime (traversing vs appending)*/
01927          insert_in_next_chars_alt_char_list(nextcharptr, m);
01928       } else {
01929          insert_in_next_chars_alt_char_list(&current->next_char, m);
01930       }
01931    }
01932 
01933    return m;
01934 }
01935 
01936 static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly)
01937 {
01938    struct match_char *m1 = NULL, *m2 = NULL, **m0;
01939    int specif;
01940    int already;
01941    int pattern = 0;
01942    char buf[256];
01943    char extenbuf[512];
01944    char *s1 = extenbuf;
01945    int l1 = strlen(e1->exten) + strlen(e1->cidmatch) + 2;
01946 
01947 
01948    ast_copy_string(extenbuf, e1->exten, sizeof(extenbuf));
01949 
01950    if (e1->matchcid &&  l1 <= sizeof(extenbuf)) {
01951       strcat(extenbuf, "/");
01952       strcat(extenbuf, e1->cidmatch);
01953    } else if (l1 > sizeof(extenbuf)) {
01954       ast_log(LOG_ERROR, "The pattern %s/%s is too big to deal with: it will be ignored! Disaster!\n", e1->exten, e1->cidmatch);
01955       return 0;
01956    }
01957 #ifdef NEED_DEBUG
01958    ast_log(LOG_DEBUG, "Adding exten %s%c%s to tree\n", s1, e1->matchcid ? '/' : ' ', e1->matchcid ? e1->cidmatch : "");
01959 #endif
01960    m1 = con->pattern_tree; /* each pattern starts over at the root of the pattern tree */
01961    m0 = &con->pattern_tree;
01962    already = 1;
01963 
01964    if ( *s1 == '_') {
01965       pattern = 1;
01966       s1++;
01967    }
01968    while (*s1) {
01969       if (pattern && *s1 == '[' && *(s1 - 1) != '\\') {
01970          char *s2 = buf;
01971          buf[0] = 0;
01972          s1++; /* get past the '[' */
01973          while (*s1 != ']' && *(s1 - 1) != '\\') {
01974             if (*s1 == '\\') {
01975                if (*(s1 + 1) == ']') {
01976                   *s2++ = ']';
01977                   s1 += 2;
01978                } else if (*(s1 + 1) == '\\') {
01979                   *s2++ = '\\';
01980                   s1 += 2;
01981                } else if (*(s1 + 1) == '-') {
01982                   *s2++ = '-';
01983                   s1 += 2;
01984                } else if (*(s1 + 1) == '[') {
01985                   *s2++ = '[';
01986                   s1 += 2;
01987                }
01988             } else if (*s1 == '-') { /* remember to add some error checking to all this! */
01989                char s3 = *(s1 - 1);
01990                char s4 = *(s1 + 1);
01991                for (s3++; s3 <= s4; s3++) {
01992                   *s2++ = s3;
01993                }
01994                s1 += 2;
01995             } else if (*s1 == '\0') {
01996                ast_log(LOG_WARNING, "A matching ']' was not found for '[' in pattern string '%s'\n", extenbuf);
01997                break;
01998             } else {
01999                *s2++ = *s1++;
02000             }
02001          }
02002          *s2 = 0; /* null terminate the exploded range */
02003          /* sort the characters */
02004 
02005          specif = strlen(buf);
02006          qsort(buf, specif, 1, compare_char);
02007          specif <<= 8;
02008          specif += buf[0];
02009       } else if (*s1 == '-') {
02010          /* Skip dashes in patterns */
02011          s1++;
02012          continue;
02013       } else {
02014          if (*s1 == '\\') {
02015             s1++;
02016             buf[0] = *s1;
02017          } else {
02018             if (pattern) {
02019                if (*s1 == 'n') { /* make sure n,x,z patterns are canonicalized to N,X,Z */
02020                   *s1 = 'N';
02021                } else if (*s1 == 'x') {
02022                   *s1 = 'X';
02023                } else if (*s1 == 'z') {
02024                   *s1 = 'Z';
02025                }
02026             }
02027             buf[0] = *s1;
02028          }
02029          buf[1] = 0;
02030          specif = 1;
02031       }
02032       m2 = 0;
02033       if (already && (m2 = already_in_tree(m1, buf, pattern)) && m2->next_char) {
02034          if (!(*(s1 + 1))) {  /* if this is the end of the pattern, but not the end of the tree, then mark this node with the exten...
02035                         a shorter pattern might win if the longer one doesn't match */
02036             if (m2->exten) {
02037                ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n", m2->exten->exten, e1->exten);
02038             }
02039             m2->exten = e1;
02040             m2->deleted = 0;
02041          }
02042          m1 = m2->next_char; /* m1 points to the node to compare against */
02043          m0 = &m2->next_char; /* m0 points to the ptr that points to m1 */
02044       } else { /* not already OR not m2 OR nor m2->next_char */
02045          if (m2) {
02046             if (findonly) {
02047                return m2;
02048             }
02049             m1 = m2; /* while m0 stays the same */
02050          } else {
02051             if (findonly) {
02052                return m1;
02053             }
02054             if (!(m1 = add_pattern_node(con, m1, buf, pattern, already,specif, m0))) { /* m1 is the node just added */
02055                return NULL;
02056             }
02057             m0 = &m1->next_char;
02058          }
02059          if (!(*(s1 + 1))) {
02060             if (m2 && m2->exten) {
02061                ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n", m2->exten->exten, e1->exten);
02062             }
02063             m1->deleted = 0;
02064             m1->exten = e1;
02065          }
02066 
02067          /* The 'already' variable is a mini-optimization designed to make it so that we
02068           * don't have to call already_in_tree when we know it will return false.
02069           */
02070          already = 0;
02071       }
02072       s1++; /* advance to next char */
02073    }
02074    return m1;
02075 }
02076 
02077 static void create_match_char_tree(struct ast_context *con)
02078 {
02079    struct ast_hashtab_iter *t1;
02080    struct ast_exten *e1;
02081 #ifdef NEED_DEBUG
02082    int biggest_bucket, resizes, numobjs, numbucks;
02083 
02084    ast_log(LOG_DEBUG,"Creating Extension Trie for context %s(%p)\n", con->name, con);
02085    ast_hashtab_get_stats(con->root_table, &biggest_bucket, &resizes, &numobjs, &numbucks);
02086    ast_log(LOG_DEBUG,"This tree has %d objects in %d bucket lists, longest list=%d objects, and has resized %d times\n",
02087          numobjs, numbucks, biggest_bucket, resizes);
02088 #endif
02089    t1 = ast_hashtab_start_traversal(con->root_table);
02090    while ((e1 = ast_hashtab_next(t1))) {
02091       if (e1->exten) {
02092          add_exten_to_pattern_tree(con, e1, 0);
02093       } else {
02094          ast_log(LOG_ERROR, "Attempt to create extension with no extension name.\n");
02095       }
02096    }
02097    ast_hashtab_end_traversal(t1);
02098 }
02099 
02100 static void destroy_pattern_tree(struct match_char *pattern_tree) /* pattern tree is a simple binary tree, sort of, so the proper way to destroy it is... recursively! */
02101 {
02102    /* destroy all the alternates */
02103    if (pattern_tree->alt_char) {
02104       destroy_pattern_tree(pattern_tree->alt_char);
02105       pattern_tree->alt_char = 0;
02106    }
02107    /* destroy all the nexts */
02108    if (pattern_tree->next_char) {
02109       destroy_pattern_tree(pattern_tree->next_char);
02110       pattern_tree->next_char = 0;
02111    }
02112    pattern_tree->exten = 0; /* never hurts to make sure there's no pointers laying around */
02113    ast_free(pattern_tree);
02114 }
02115 
02116 /*
02117  * Special characters used in patterns:
02118  * '_'   underscore is the leading character of a pattern.
02119  *    In other position it is treated as a regular char.
02120  * .  one or more of any character. Only allowed at the end of
02121  *    a pattern.
02122  * !  zero or more of anything. Also impacts the result of CANMATCH
02123  *    and MATCHMORE. Only allowed at the end of a pattern.
02124  *    In the core routine, ! causes a match with a return code of 2.
02125  *    In turn, depending on the search mode: (XXX check if it is implemented)
02126  *    - E_MATCH retuns 1 (does match)
02127  *    - E_MATCHMORE returns 0 (no match)
02128  *    - E_CANMATCH returns 1 (does match)
02129  *
02130  * /  should not appear as it is considered the separator of the CID info.
02131  *    XXX at the moment we may stop on this char.
02132  *
02133  * X Z N match ranges 0-9, 1-9, 2-9 respectively.
02134  * [  denotes the start of a set of character. Everything inside
02135  *    is considered literally. We can have ranges a-d and individual
02136  *    characters. A '[' and '-' can be considered literally if they
02137  *    are just before ']'.
02138  *    XXX currently there is no way to specify ']' in a range, nor \ is
02139  *    considered specially.
02140  *
02141  * When we compare a pattern with a specific extension, all characters in the extension
02142  * itself are considered literally.
02143  * XXX do we want to consider space as a separator as well ?
02144  * XXX do we want to consider the separators in non-patterns as well ?
02145  */
02146 
02147 /*!
02148  * \brief helper functions to sort extensions and patterns in the desired way,
02149  * so that more specific patterns appear first.
02150  *
02151  * ext_cmp1 compares individual characters (or sets of), returning
02152  * an int where bits 0-7 are the ASCII code of the first char in the set,
02153  * while bit 8-15 are the cardinality of the set minus 1.
02154  * This way more specific patterns (smaller cardinality) appear first.
02155  * Wildcards have a special value, so that we can directly compare them to
02156  * sets by subtracting the two values. In particular:
02157  *  0x000xx    one character, xx
02158  *  0x0yyxx    yy character set starting with xx
02159  *  0x10000    '.' (one or more of anything)
02160  *  0x20000    '!' (zero or more of anything)
02161  *  0x30000    NUL (end of string)
02162  *  0x40000    error in set.
02163  * The pointer to the string is advanced according to needs.
02164  * NOTES:
02165  * 1. the empty set is equivalent to NUL.
02166  * 2. given that a full set has always 0 as the first element,
02167  *    we could encode the special cases as 0xffXX where XX
02168  *    is 1, 2, 3, 4 as used above.
02169  */
02170 static int ext_cmp1(const char **p, unsigned char *bitwise)
02171 {
02172    int c, cmin = 0xff, count = 0;
02173    const char *end;
02174 
02175    /* load value and advance pointer */
02176    c = *(*p)++;
02177 
02178    /* always return unless we have a set of chars */
02179    switch (toupper(c)) {
02180    default: /* ordinary character */
02181       bitwise[c / 8] = 1 << (c % 8);
02182       return 0x0100 | (c & 0xff);
02183 
02184    case 'N':   /* 2..9 */
02185       bitwise[6] = 0xfc;
02186       bitwise[7] = 0x03;
02187       return 0x0800 | '2';
02188 
02189    case 'X':   /* 0..9 */
02190       bitwise[6] = 0xff;
02191       bitwise[7] = 0x03;
02192       return 0x0A00 | '0';
02193 
02194    case 'Z':   /* 1..9 */
02195       bitwise[6] = 0xfe;
02196       bitwise[7] = 0x03;
02197       return 0x0900 | '1';
02198 
02199    case '.':   /* wildcard */
02200       return 0x18000;
02201 
02202    case '!':   /* earlymatch */
02203       return 0x28000;   /* less specific than NULL */
02204 
02205    case '\0':  /* empty string */
02206       *p = NULL;
02207       return 0x30000;
02208 
02209    case '[':   /* pattern */
02210       break;
02211    }
02212    /* locate end of set */
02213    end = strchr(*p, ']');
02214 
02215    if (end == NULL) {
02216       ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
02217       return 0x40000;   /* XXX make this entry go last... */
02218    }
02219 
02220    for (; *p < end  ; (*p)++) {
02221       unsigned char c1, c2;   /* first-last char in range */
02222       c1 = (unsigned char)((*p)[0]);
02223       if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */
02224          c2 = (unsigned char)((*p)[2]);
02225          *p += 2;    /* skip a total of 3 chars */
02226       } else {        /* individual character */
02227          c2 = c1;
02228       }
02229       if (c1 < cmin) {
02230          cmin = c1;
02231       }
02232       for (; c1 <= c2; c1++) {
02233          unsigned char mask = 1 << (c1 % 8);
02234          /*!\note If two patterns score the same, the one with the lowest
02235           * ascii values will compare as coming first. */
02236          /* Flag the character as included (used) and count it. */
02237          if (!(bitwise[ c1 / 8 ] & mask)) {
02238             bitwise[ c1 / 8 ] |= mask;
02239             count += 0x100;
02240          }
02241       }
02242    }
02243    (*p)++;
02244    return count == 0 ? 0x30000 : (count | cmin);
02245 }
02246 
02247 /*!
02248  * \brief the full routine to compare extensions in rules.
02249  */
02250 static int ext_cmp(const char *a, const char *b)
02251 {
02252    /* make sure non-patterns come first.
02253     * If a is not a pattern, it either comes first or
02254     * we do a more complex pattern comparison.
02255     */
02256    int ret = 0;
02257 
02258    if (a[0] != '_')
02259       return (b[0] == '_') ? -1 : strcmp(a, b);
02260 
02261    /* Now we know a is a pattern; if b is not, a comes first */
02262    if (b[0] != '_')
02263       return 1;
02264 
02265    /* ok we need full pattern sorting routine.
02266     * skip past the underscores */
02267    ++a; ++b;
02268    do {
02269       unsigned char bitwise[2][32] = { { 0, } };
02270       ret = ext_cmp1(&a, bitwise[0]) - ext_cmp1(&b, bitwise[1]);
02271       if (ret == 0) {
02272          /* Are the classes different, even though they score the same? */
02273          ret = memcmp(bitwise[0], bitwise[1], 32);
02274       }
02275    } while (!ret && a && b);
02276    if (ret == 0) {
02277       return 0;
02278    } else {
02279       return (ret > 0) ? 1 : -1;
02280    }
02281 }
02282 
02283 int ast_extension_cmp(const char *a, const char *b)
02284 {
02285    return ext_cmp(a, b);
02286 }
02287 
02288 /*!
02289  * \internal
02290  * \brief used ast_extension_{match|close}
02291  * mode is as follows:
02292  * E_MATCH     success only on exact match
02293  * E_MATCHMORE success only on partial match (i.e. leftover digits in pattern)
02294  * E_CANMATCH  either of the above.
02295  * \retval 0 on no-match
02296  * \retval 1 on match
02297  * \retval 2 on early match.
02298  */
02299 
02300 static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
02301 {
02302    mode &= E_MATCH_MASK;   /* only consider the relevant bits */
02303 
02304 #ifdef NEED_DEBUG_HERE
02305    ast_log(LOG_NOTICE,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern, data, (int)mode);
02306 #endif
02307 
02308    if ( (mode == E_MATCH) && (pattern[0] == '_') && (!strcasecmp(pattern,data)) ) { /* note: if this test is left out, then _x. will not match _x. !!! */
02309 #ifdef NEED_DEBUG_HERE
02310       ast_log(LOG_NOTICE,"return (1) - pattern matches pattern\n");
02311 #endif
02312       return 1;
02313    }
02314 
02315    if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
02316       int ld = strlen(data), lp = strlen(pattern);
02317 
02318       if (lp < ld) {    /* pattern too short, cannot match */
02319 #ifdef NEED_DEBUG_HERE
02320          ast_log(LOG_NOTICE,"return (0) - pattern too short, cannot match\n");
02321 #endif
02322          return 0;
02323       }
02324       /* depending on the mode, accept full or partial match or both */
02325       if (mode == E_MATCH) {
02326 #ifdef NEED_DEBUG_HERE
02327          ast_log(LOG_NOTICE,"return (!strcmp(%s,%s) when mode== E_MATCH)\n", pattern, data);
02328 #endif
02329          return !strcmp(pattern, data); /* 1 on match, 0 on fail */
02330       }
02331       if (ld == 0 || !strncasecmp(pattern, data, ld)) { /* partial or full match */
02332 #ifdef NEED_DEBUG_HERE
02333          ast_log(LOG_NOTICE,"return (mode(%d) == E_MATCHMORE ? lp(%d) > ld(%d) : 1)\n", mode, lp, ld);
02334 #endif
02335          return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
02336       } else {
02337 #ifdef NEED_DEBUG_HERE
02338          ast_log(LOG_NOTICE,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld, pattern, data);
02339 #endif
02340          return 0;
02341       }
02342    }
02343    pattern++; /* skip leading _ */
02344    /*
02345     * XXX below we stop at '/' which is a separator for the CID info. However we should
02346     * not store '/' in the pattern at all. When we insure it, we can remove the checks.
02347     */
02348    while (*data && *pattern && *pattern != '/') {
02349       const char *end;
02350 
02351       if (*data == '-') { /* skip '-' in data (just a separator) */
02352          data++;
02353          continue;
02354       }
02355       switch (toupper(*pattern)) {
02356       case '[':   /* a range */
02357          end = strchr(pattern+1, ']'); /* XXX should deal with escapes ? */
02358          if (end == NULL) {
02359             ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
02360             return 0;   /* unconditional failure */
02361          }
02362          for (pattern++; pattern != end; pattern++) {
02363             if (pattern+2 < end && pattern[1] == '-') { /* this is a range */
02364                if (*data >= pattern[0] && *data <= pattern[2])
02365                   break;   /* match found */
02366                else {
02367                   pattern += 2; /* skip a total of 3 chars */
02368                   continue;
02369                }
02370             } else if (*data == pattern[0])
02371                break;   /* match found */
02372          }
02373          if (pattern == end) {
02374 #ifdef NEED_DEBUG_HERE
02375             ast_log(LOG_NOTICE,"return (0) when pattern==end\n");
02376 #endif
02377             return 0;
02378          }
02379          pattern = end; /* skip and continue */
02380          break;
02381       case 'N':
02382          if (*data < '2' || *data > '9') {
02383 #ifdef NEED_DEBUG_HERE
02384             ast_log(LOG_NOTICE,"return (0) N is matched\n");
02385 #endif
02386             return 0;
02387          }
02388          break;
02389       case 'X':
02390          if (*data < '0' || *data > '9') {
02391 #ifdef NEED_DEBUG_HERE
02392             ast_log(LOG_NOTICE,"return (0) X is matched\n");
02393 #endif
02394             return 0;
02395          }
02396          break;
02397       case 'Z':
02398          if (*data < '1' || *data > '9') {
02399 #ifdef NEED_DEBUG_HERE
02400             ast_log(LOG_NOTICE,"return (0) Z is matched\n");
02401 #endif
02402             return 0;
02403          }
02404          break;
02405       case '.':   /* Must match, even with more digits */
02406 #ifdef NEED_DEBUG_HERE
02407          ast_log(LOG_NOTICE, "return (1) when '.' is matched\n");
02408 #endif
02409          return 1;
02410       case '!':   /* Early match */
02411 #ifdef NEED_DEBUG_HERE
02412          ast_log(LOG_NOTICE, "return (2) when '!' is matched\n");
02413 #endif
02414          return 2;
02415       case ' ':
02416       case '-':   /* Ignore these in patterns */
02417          data--; /* compensate the final data++ */
02418          break;
02419       default:
02420          if (*data != *pattern) {
02421 #ifdef NEED_DEBUG_HERE
02422             ast_log(LOG_NOTICE, "return (0) when *data(%c) != *pattern(%c)\n", *data, *pattern);
02423 #endif
02424             return 0;
02425          }
02426       }
02427       data++;
02428       pattern++;
02429    }
02430    if (*data)        /* data longer than pattern, no match */ {
02431 #ifdef NEED_DEBUG_HERE
02432       ast_log(LOG_NOTICE, "return (0) when data longer than pattern\n");
02433 #endif
02434       return 0;
02435    }
02436 
02437    /*
02438     * match so far, but ran off the end of the data.
02439     * Depending on what is next, determine match or not.
02440     */
02441    if (*pattern == '\0' || *pattern == '/') {   /* exact match */
02442 #ifdef NEED_DEBUG_HERE
02443       ast_log(LOG_NOTICE, "at end, return (%d) in 'exact match'\n", (mode==E_MATCHMORE) ? 0 : 1);
02444 #endif
02445       return (mode == E_MATCHMORE) ? 0 : 1;  /* this is a failure for E_MATCHMORE */
02446    } else if (*pattern == '!')   {     /* early match */
02447 #ifdef NEED_DEBUG_HERE
02448       ast_log(LOG_NOTICE, "at end, return (2) when '!' is matched\n");
02449 #endif
02450       return 2;
02451    } else {                /* partial match */
02452 #ifdef NEED_DEBUG_HERE
02453       ast_log(LOG_NOTICE, "at end, return (%d) which deps on E_MATCH\n", (mode == E_MATCH) ? 0 : 1);
02454 #endif
02455       return (mode == E_MATCH) ? 0 : 1;   /* this is a failure for E_MATCH */
02456    }
02457 }
02458 
02459 /*
02460  * Wrapper around _extension_match_core() to do performance measurement
02461  * using the profiling code.
02462  */
02463 static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
02464 {
02465    int i;
02466    static int prof_id = -2;   /* marker for 'unallocated' id */
02467    if (prof_id == -2) {
02468       prof_id = ast_add_profile("ext_match", 0);
02469    }
02470    ast_mark(prof_id, 1);
02471    i = _extension_match_core(pattern, data, mode);
02472    ast_mark(prof_id, 0);
02473    return i;
02474 }
02475 
02476 int ast_extension_match(const char *pattern, const char *data)
02477 {
02478    return extension_match_core(pattern, data, E_MATCH);
02479 }
02480 
02481 int ast_extension_close(const char *pattern, const char *data, int needmore)
02482 {
02483    if (needmore != E_MATCHMORE && needmore != E_CANMATCH)
02484       ast_log(LOG_WARNING, "invalid argument %d\n", needmore);
02485    return extension_match_core(pattern, data, needmore);
02486 }
02487 
02488 struct fake_context /* this struct is purely for matching in the hashtab */
02489 {
02490    ast_rwlock_t lock;
02491    struct ast_exten *root;
02492    struct ast_hashtab *root_table;
02493    struct match_char *pattern_tree;
02494    struct ast_context *next;
02495    struct ast_include *includes;
02496    struct ast_ignorepat *ignorepats;
02497    const char *registrar;
02498    int refcount;
02499    AST_LIST_HEAD_NOLOCK(, ast_sw) alts;
02500    ast_mutex_t macrolock;
02501    char name[256];
02502 };
02503 
02504 struct ast_context *ast_context_find(const char *name)
02505 {
02506    struct ast_context *tmp = NULL;
02507    struct fake_context item;
02508 
02509    ast_copy_string(item.name, name, sizeof(item.name));
02510 
02511    ast_rdlock_contexts();
02512    if( contexts_table ) {
02513       tmp = ast_hashtab_lookup(contexts_table,&item);
02514    } else {
02515       while ( (tmp = ast_walk_contexts(tmp)) ) {
02516          if (!name || !strcasecmp(name, tmp->name)) {
02517             break;
02518          }
02519       }
02520    }
02521    ast_unlock_contexts();
02522    return tmp;
02523 }
02524 
02525 #define STATUS_NO_CONTEXT  1
02526 #define STATUS_NO_EXTENSION   2
02527 #define STATUS_NO_PRIORITY 3
02528 #define STATUS_NO_LABEL    4
02529 #define STATUS_SUCCESS     5
02530 
02531 static int matchcid(const char *cidpattern, const char *callerid)
02532 {
02533    /* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
02534       failing to get a number should count as a match, otherwise not */
02535 
02536    if (ast_strlen_zero(callerid)) {
02537       return ast_strlen_zero(cidpattern) ? 1 : 0;
02538    }
02539 
02540    return ast_extension_match(cidpattern, callerid);
02541 }
02542 
02543 struct ast_exten *pbx_find_extension(struct ast_channel *chan,
02544    struct ast_context *bypass, struct pbx_find_info *q,
02545    const char *context, const char *exten, int priority,
02546    const char *label, const char *callerid, enum ext_match_t action)
02547 {
02548    int x, res;
02549    struct ast_context *tmp = NULL;
02550    struct ast_exten *e = NULL, *eroot = NULL;
02551    struct ast_include *i = NULL;
02552    struct ast_sw *sw = NULL;
02553    struct ast_exten pattern = {NULL, };
02554    struct scoreboard score = {0, };
02555    struct ast_str *tmpdata = NULL;
02556 
02557    pattern.label = label;
02558    pattern.priority = priority;
02559 #ifdef NEED_DEBUG_HERE
02560    ast_log(LOG_NOTICE, "Looking for cont/ext/prio/label/action = %s/%s/%d/%s/%d\n", context, exten, priority, label, (int) action);
02561 #endif
02562 
02563    /* Initialize status if appropriate */
02564    if (q->stacklen == 0) {
02565       q->status = STATUS_NO_CONTEXT;
02566       q->swo = NULL;
02567       q->data = NULL;
02568       q->foundcontext = NULL;
02569    } else if (q->stacklen >= AST_PBX_MAX_STACK) {
02570       ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
02571       return NULL;
02572    }
02573 
02574    /* Check first to see if we've already been checked */
02575    for (x = 0; x < q->stacklen; x++) {
02576       if (!strcasecmp(q->incstack[x], context))
02577          return NULL;
02578    }
02579 
02580    if (bypass) { /* bypass means we only look there */
02581       tmp = bypass;
02582    } else {      /* look in contexts */
02583       struct fake_context item;
02584 
02585       ast_copy_string(item.name, context, sizeof(item.name));
02586 
02587       tmp = ast_hashtab_lookup(contexts_table, &item);
02588       if (!tmp) {
02589          return NULL;
02590       }
02591    }
02592 
02593    if (q->status < STATUS_NO_EXTENSION)
02594       q->status = STATUS_NO_EXTENSION;
02595 
02596    /* Do a search for matching extension */
02597 
02598    eroot = NULL;
02599    score.total_specificity = 0;
02600    score.exten = 0;
02601    score.total_length = 0;
02602    if (!tmp->pattern_tree && tmp->root_table) {
02603       create_match_char_tree(tmp);
02604 #ifdef NEED_DEBUG
02605       ast_log(LOG_DEBUG, "Tree Created in context %s:\n", context);
02606       log_match_char_tree(tmp->pattern_tree," ");
02607 #endif
02608    }
02609 #ifdef NEED_DEBUG
02610    ast_log(LOG_NOTICE, "The Trie we are searching in:\n");
02611    log_match_char_tree(tmp->pattern_tree, "::  ");
02612 #endif
02613 
02614    do {
02615       if (!ast_strlen_zero(overrideswitch)) {
02616          char *osw = ast_strdupa(overrideswitch), *name;
02617          struct ast_switch *asw;
02618          ast_switch_f *aswf = NULL;
02619          char *datap;
02620          int eval = 0;
02621 
02622          name = strsep(&osw, "/");
02623          asw = pbx_findswitch(name);
02624 
02625          if (!asw) {
02626             ast_log(LOG_WARNING, "No such switch '%s'\n", name);
02627             break;
02628          }
02629 
02630          if (osw && strchr(osw, '$')) {
02631             eval = 1;
02632          }
02633 
02634          if (eval && !(tmpdata = ast_str_thread_get(&switch_data, 512))) {
02635             ast_log(LOG_WARNING, "Can't evaluate overrideswitch?!");
02636             break;
02637          } else if (eval) {
02638             /* Substitute variables now */
02639             pbx_substitute_variables_helper(chan, osw, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
02640             datap = ast_str_buffer(tmpdata);
02641          } else {
02642             datap = osw;
02643          }
02644 
02645          /* equivalent of extension_match_core() at the switch level */
02646          if (action == E_CANMATCH)
02647             aswf = asw->canmatch;
02648          else if (action == E_MATCHMORE)
02649             aswf = asw->matchmore;
02650          else /* action == E_MATCH */
02651             aswf = asw->exists;
02652          if (!aswf) {
02653             res = 0;
02654          } else {
02655             if (chan) {
02656                ast_autoservice_start(chan);
02657             }
02658             res = aswf(chan, context, exten, priority, callerid, datap);
02659             if (chan) {
02660                ast_autoservice_stop(chan);
02661             }
02662          }
02663          if (res) {  /* Got a match */
02664             q->swo = asw;
02665             q->data = datap;
02666             q->foundcontext = context;
02667             /* XXX keep status = STATUS_NO_CONTEXT ? */
02668             return NULL;
02669          }
02670       }
02671    } while (0);
02672 
02673    if (extenpatternmatchnew) {
02674       new_find_extension(exten, &score, tmp->pattern_tree, 0, 0, callerid, label, action);
02675       eroot = score.exten;
02676 
02677       if (score.last_char == '!' && action == E_MATCHMORE) {
02678          /* We match an extension ending in '!'.
02679           * The decision in this case is final and is NULL (no match).
02680           */
02681 #ifdef NEED_DEBUG_HERE
02682          ast_log(LOG_NOTICE,"Returning MATCHMORE NULL with exclamation point.\n");
02683 #endif
02684          return NULL;
02685       }
02686 
02687       if (!eroot && (action == E_CANMATCH || action == E_MATCHMORE) && score.canmatch_exten) {
02688          q->status = STATUS_SUCCESS;
02689 #ifdef NEED_DEBUG_HERE
02690          ast_log(LOG_NOTICE,"Returning CANMATCH exten %s\n", score.canmatch_exten->exten);
02691 #endif
02692          return score.canmatch_exten;
02693       }
02694 
02695       if ((action == E_MATCHMORE || action == E_CANMATCH)  && eroot) {
02696          if (score.node) {
02697             struct ast_exten *z = trie_find_next_match(score.node);
02698             if (z) {
02699 #ifdef NEED_DEBUG_HERE
02700                ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z->exten);
02701 #endif
02702             } else {
02703                if (score.canmatch_exten) {
02704 #ifdef NEED_DEBUG_HERE
02705                   ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE canmatchmatch exten %s(%p)\n", score.canmatch_exten->exten, score.canmatch_exten);
02706 #endif
02707                   return score.canmatch_exten;
02708                } else {
02709 #ifdef NEED_DEBUG_HERE
02710                   ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten NULL\n");
02711 #endif
02712                }
02713             }
02714             return z;
02715          }
02716 #ifdef NEED_DEBUG_HERE
02717          ast_log(LOG_NOTICE, "Returning CANMATCH/MATCHMORE NULL (no next_match)\n");
02718 #endif
02719          return NULL;  /* according to the code, complete matches are null matches in MATCHMORE mode */
02720       }
02721 
02722       if (eroot) {
02723          /* found entry, now look for the right priority */
02724          if (q->status < STATUS_NO_PRIORITY)
02725             q->status = STATUS_NO_PRIORITY;
02726          e = NULL;
02727          if (action == E_FINDLABEL && label ) {
02728             if (q->status < STATUS_NO_LABEL)
02729                q->status = STATUS_NO_LABEL;
02730             e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
02731          } else {
02732             e = ast_hashtab_lookup(eroot->peer_table, &pattern);
02733          }
02734          if (e) { /* found a valid match */
02735             q->status = STATUS_SUCCESS;
02736             q->foundcontext = context;
02737 #ifdef NEED_DEBUG_HERE
02738             ast_log(LOG_NOTICE,"Returning complete match of exten %s\n", e->exten);
02739 #endif
02740             return e;
02741          }
02742       }
02743    } else {   /* the old/current default exten pattern match algorithm */
02744 
02745       /* scan the list trying to match extension and CID */
02746       eroot = NULL;
02747       while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) {
02748          int match = extension_match_core(eroot->exten, exten, action);
02749          /* 0 on fail, 1 on match, 2 on earlymatch */
02750 
02751          if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid)))
02752             continue;   /* keep trying */
02753          if (match == 2 && action == E_MATCHMORE) {
02754             /* We match an extension ending in '!'.
02755              * The decision in this case is final and is NULL (no match).
02756              */
02757             return NULL;
02758          }
02759          /* found entry, now look for the right priority */
02760          if (q->status < STATUS_NO_PRIORITY)
02761             q->status = STATUS_NO_PRIORITY;
02762          e = NULL;
02763          if (action == E_FINDLABEL && label ) {
02764             if (q->status < STATUS_NO_LABEL)
02765                q->status = STATUS_NO_LABEL;
02766             e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
02767          } else {
02768             e = ast_hashtab_lookup(eroot->peer_table, &pattern);
02769          }
02770          if (e) { /* found a valid match */
02771             q->status = STATUS_SUCCESS;
02772             q->foundcontext = context;
02773             return e;
02774          }
02775       }
02776    }
02777 
02778    /* Check alternative switches */
02779    AST_LIST_TRAVERSE(&tmp->alts, sw, list) {
02780       struct ast_switch *asw = pbx_findswitch(sw->name);
02781       ast_switch_f *aswf = NULL;
02782       char *datap;
02783 
02784       if (!asw) {
02785          ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
02786          continue;
02787       }
02788 
02789       /* Substitute variables now */
02790       if (sw->eval) {
02791          if (!(tmpdata = ast_str_thread_get(&switch_data, 512))) {
02792             ast_log(LOG_WARNING, "Can't evaluate switch?!");
02793             continue;
02794          }
02795          pbx_substitute_variables_helper(chan, sw->data, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
02796       }
02797 
02798       /* equivalent of extension_match_core() at the switch level */
02799       if (action == E_CANMATCH)
02800          aswf = asw->canmatch;
02801       else if (action == E_MATCHMORE)
02802          aswf = asw->matchmore;
02803       else /* action == E_MATCH */
02804          aswf = asw->exists;
02805       datap = sw->eval ? ast_str_buffer(tmpdata) : sw->data;
02806       if (!aswf)
02807          res = 0;
02808       else {
02809          if (chan)
02810             ast_autoservice_start(chan);
02811          res = aswf(chan, context, exten, priority, callerid, datap);
02812          if (chan)
02813             ast_autoservice_stop(chan);
02814       }
02815       if (res) {  /* Got a match */
02816          q->swo = asw;
02817          q->data = datap;
02818          q->foundcontext = context;
02819          /* XXX keep status = STATUS_NO_CONTEXT ? */
02820          return NULL;
02821       }
02822    }
02823    q->incstack[q->stacklen++] = tmp->name;   /* Setup the stack */
02824    /* Now try any includes we have in this context */
02825    for (i = tmp->includes; i; i = i->next) {
02826       if (include_valid(i)) {
02827          if ((e = pbx_find_extension(chan, bypass, q, i->rname, exten, priority, label, callerid, action))) {
02828 #ifdef NEED_DEBUG_HERE
02829             ast_log(LOG_NOTICE,"Returning recursive match of %s\n", e->exten);
02830 #endif
02831             return e;
02832          }
02833          if (q->swo)
02834             return NULL;
02835       }
02836    }
02837    return NULL;
02838 }
02839 
02840 /*!
02841  * \brief extract offset:length from variable name.
02842  * \return 1 if there is a offset:length part, which is
02843  * trimmed off (values go into variables)
02844  */
02845 static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
02846 {
02847    int parens = 0;
02848 
02849    *offset = 0;
02850    *length = INT_MAX;
02851    *isfunc = 0;
02852    for (; *var; var++) {
02853       if (*var == '(') {
02854          (*isfunc)++;
02855          parens++;
02856       } else if (*var == ')') {
02857          parens--;
02858       } else if (*var == ':' && parens == 0) {
02859          *var++ = '\0';
02860          sscanf(var, "%30d:%30d", offset, length);
02861          return 1; /* offset:length valid */
02862       }
02863    }
02864    return 0;
02865 }
02866 
02867 /*!
02868  *\brief takes a substring. It is ok to call with value == workspace.
02869  * \param value
02870  * \param offset < 0 means start from the end of the string and set the beginning
02871  *   to be that many characters back.
02872  * \param length is the length of the substring, a value less than 0 means to leave
02873  * that many off the end.
02874  * \param workspace
02875  * \param workspace_len
02876  * Always return a copy in workspace.
02877  */
02878 static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
02879 {
02880    char *ret = workspace;
02881    int lr;  /* length of the input string after the copy */
02882 
02883    ast_copy_string(workspace, value, workspace_len); /* always make a copy */
02884 
02885    lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
02886 
02887    /* Quick check if no need to do anything */
02888    if (offset == 0 && length >= lr) /* take the whole string */
02889       return ret;
02890 
02891    if (offset < 0)   {  /* translate negative offset into positive ones */
02892       offset = lr + offset;
02893       if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
02894          offset = 0;
02895    }
02896 
02897    /* too large offset result in empty string so we know what to return */
02898    if (offset >= lr)
02899       return ret + lr;  /* the final '\0' */
02900 
02901    ret += offset;    /* move to the start position */
02902    if (length >= 0 && length < lr - offset)  /* truncate if necessary */
02903       ret[length] = '\0';
02904    else if (length < 0) {
02905       if (lr > offset - length) /* After we remove from the front and from the rear, is there anything left? */
02906          ret[lr + length - offset] = '\0';
02907       else
02908          ret[0] = '\0';
02909    }
02910 
02911    return ret;
02912 }
02913 
02914 static const char *ast_str_substring(struct ast_str *value, int offset, int length)
02915 {
02916    int lr;  /* length of the input string after the copy */
02917 
02918    lr = ast_str_strlen(value); /* compute length after copy, so we never go out of the workspace */
02919 
02920    /* Quick check if no need to do anything */
02921    if (offset == 0 && length >= lr) /* take the whole string */
02922       return ast_str_buffer(value);
02923 
02924    if (offset < 0)   {  /* translate negative offset into positive ones */
02925       offset = lr + offset;
02926       if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
02927          offset = 0;
02928    }
02929 
02930    /* too large offset result in empty string so we know what to return */
02931    if (offset >= lr) {
02932       ast_str_reset(value);
02933       return ast_str_buffer(value);
02934    }
02935 
02936    if (offset > 0) {
02937       /* Go ahead and chop off the beginning */
02938       memmove(ast_str_buffer(value), ast_str_buffer(value) + offset, ast_str_strlen(value) - offset + 1);
02939       lr -= offset;
02940    }
02941 
02942    if (length >= 0 && length < lr) {   /* truncate if necessary */
02943       char *tmp = ast_str_buffer(value);
02944       tmp[length] = '\0';
02945       ast_str_update(value);
02946    } else if (length < 0) {
02947       if (lr > -length) { /* After we remove from the front and from the rear, is there anything left? */
02948          char *tmp = ast_str_buffer(value);
02949          tmp[lr + length] = '\0';
02950          ast_str_update(value);
02951       } else {
02952          ast_str_reset(value);
02953       }
02954    } else {
02955       /* Nothing to do, but update the buffer length */
02956       ast_str_update(value);
02957    }
02958 
02959    return ast_str_buffer(value);
02960 }
02961 
02962 /*! \brief  Support for Asterisk built-in variables in the dialplan
02963 
02964 \note See also
02965    - \ref AstVar  Channel variables
02966    - \ref AstCauses The HANGUPCAUSE variable
02967  */
02968 void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
02969 {
02970    struct ast_str *str = ast_str_create(16);
02971    const char *cret;
02972 
02973    cret = ast_str_retrieve_variable(&str, 0, c, headp, var);
02974    ast_copy_string(workspace, ast_str_buffer(str), workspacelen);
02975    *ret = cret ? workspace : NULL;
02976    ast_free(str);
02977 }
02978 
02979 const char *ast_str_retrieve_variable(struct ast_str **str, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *var)
02980 {
02981    const char not_found = '\0';
02982    char *tmpvar;
02983    const char *ret;
02984    const char *s; /* the result */
02985    int offset, length;
02986    int i, need_substring;
02987    struct varshead *places[2] = { headp, &globals };  /* list of places where we may look */
02988 
02989    if (c) {
02990       ast_channel_lock(c);
02991       places[0] = &c->varshead;
02992    }
02993    /*
02994     * Make a copy of var because parse_variable_name() modifies the string.
02995     * Then if called directly, we might need to run substring() on the result;
02996     * remember this for later in 'need_substring', 'offset' and 'length'
02997     */
02998    tmpvar = ast_strdupa(var); /* parse_variable_name modifies the string */
02999    need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);
03000 
03001    /*
03002     * Look first into predefined variables, then into variable lists.
03003     * Variable 's' points to the result, according to the following rules:
03004     * s == &not_found (set at the beginning) means that we did not find a
03005     * matching variable and need to look into more places.
03006     * If s != &not_found, s is a valid result string as follows:
03007     * s = NULL if the variable does not have a value;
03008     * you typically do this when looking for an unset predefined variable.
03009     * s = workspace if the result has been assembled there;
03010     * typically done when the result is built e.g. with an snprintf(),
03011     * so we don't need to do an additional copy.
03012     * s != workspace in case we have a string, that needs to be copied
03013     * (the ast_copy_string is done once for all at the end).
03014     * Typically done when the result is already available in some string.
03015     */
03016    s = &not_found;   /* default value */
03017    if (c) { /* This group requires a valid channel */
03018       /* Names with common parts are looked up a piece at a time using strncmp. */
03019       if (!strncmp(var, "CALL", 4)) {
03020          if (!strncmp(var + 4, "ING", 3)) {
03021             if (!strcmp(var + 7, "PRES")) {        /* CALLINGPRES */
03022                ast_str_set(str, maxlen, "%d",
03023                   ast_party_id_presentation(&c->caller.id));
03024                s = ast_str_buffer(*str);
03025             } else if (!strcmp(var + 7, "ANI2")) {    /* CALLINGANI2 */
03026                ast_str_set(str, maxlen, "%d", c->caller.ani2);
03027                s = ast_str_buffer(*str);
03028             } else if (!strcmp(var + 7, "TON")) {     /* CALLINGTON */
03029                ast_str_set(str, maxlen, "%d", c->caller.id.number.plan);
03030                s = ast_str_buffer(*str);
03031             } else if (!strcmp(var + 7, "TNS")) {     /* CALLINGTNS */
03032                ast_str_set(str, maxlen, "%d", c->dialed.transit_network_select);
03033                s = ast_str_buffer(*str);
03034             }
03035          }
03036       } else if (!strcmp(var, "HINT")) {
03037          s = ast_str_get_hint(str, maxlen, NULL, 0, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL;
03038       } else if (!strcmp(var, "HINTNAME")) {
03039          s = ast_str_get_hint(NULL, 0, str, maxlen, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL;
03040       } else if (!strcmp(var, "EXTEN")) {
03041          s = c->exten;
03042       } else if (!strcmp(var, "CONTEXT")) {
03043          s = c->context;
03044       } else if (!strcmp(var, "PRIORITY")) {
03045          ast_str_set(str, maxlen, "%d", c->priority);
03046          s = ast_str_buffer(*str);
03047       } else if (!strcmp(var, "CHANNEL")) {
03048          s = c->name;
03049       } else if (!strcmp(var, "UNIQUEID")) {
03050          s = c->uniqueid;
03051       } else if (!strcmp(var, "HANGUPCAUSE")) {
03052          ast_str_set(str, maxlen, "%d", c->hangupcause);
03053          s = ast_str_buffer(*str);
03054       }
03055    }
03056    if (s == &not_found) { /* look for more */
03057       if (!strcmp(var, "EPOCH")) {
03058          ast_str_set(str, maxlen, "%u", (int) time(NULL));
03059          s = ast_str_buffer(*str);
03060       } else if (!strcmp(var, "SYSTEMNAME")) {
03061          s = ast_config_AST_SYSTEM_NAME;
03062       } else if (!strcmp(var, "ENTITYID")) {
03063          char workspace[20];
03064          ast_eid_to_str(workspace, sizeof(workspace), &ast_eid_default);
03065          s = workspace;
03066       }
03067    }
03068    /* if not found, look into chanvars or global vars */
03069    for (i = 0; s == &not_found && i < ARRAY_LEN(places); i++) {
03070       struct ast_var_t *variables;
03071       if (!places[i])
03072          continue;
03073       if (places[i] == &globals)
03074          ast_rwlock_rdlock(&globalslock);
03075       AST_LIST_TRAVERSE(places[i], variables, entries) {
03076          if (!strcasecmp(ast_var_name(variables), var)) {
03077             s = ast_var_value(variables);
03078             break;
03079          }
03080       }
03081       if (places[i] == &globals)
03082          ast_rwlock_unlock(&globalslock);
03083    }
03084    if (s == &not_found || s == NULL) {
03085       ast_debug(5, "Result of '%s' is NULL\n", var);
03086       ret = NULL;
03087    } else {
03088       ast_debug(5, "Result of '%s' is '%s'\n", var, s);
03089       if (s != ast_str_buffer(*str)) {
03090          ast_str_set(str, maxlen, "%s", s);
03091       }
03092       ret = ast_str_buffer(*str);
03093       if (need_substring) {
03094          ret = ast_str_substring(*str, offset, length);
03095          ast_debug(2, "Final result of '%s' is '%s'\n", var, ret);
03096       }
03097    }
03098 
03099    if (c) {
03100       ast_channel_unlock(c);
03101    }
03102    return ret;
03103 }
03104 
03105 static void exception_store_free(void *data)
03106 {
03107    struct pbx_exception *exception = data;
03108    ast_string_field_free_memory(exception);
03109    ast_free(exception);
03110 }
03111 
03112 static struct ast_datastore_info exception_store_info = {
03113    .type = "EXCEPTION",
03114    .destroy = exception_store_free,
03115 };
03116 
03117 int pbx_builtin_raise_exception(struct ast_channel *chan, const char *reason)
03118 {
03119    struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
03120    struct pbx_exception *exception = NULL;
03121 
03122    if (!ds) {
03123       ds = ast_datastore_alloc(&exception_store_info, NULL);
03124       if (!ds)
03125          return -1;
03126       if (!(exception = ast_calloc_with_stringfields(1, struct pbx_exception, 128))) {
03127          ast_datastore_free(ds);
03128          return -1;
03129       }
03130       ds->data = exception;
03131       ast_channel_datastore_add(chan, ds);
03132    } else
03133       exception = ds->data;
03134 
03135    ast_string_field_set(exception, reason, reason);
03136    ast_string_field_set(exception, context, chan->context);
03137    ast_string_field_set(exception, exten, chan->exten);
03138    exception->priority = chan->priority;
03139    set_ext_pri(chan, "e", 0);
03140    return 0;
03141 }
03142 
03143 static int acf_exception_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
03144 {
03145    struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
03146    struct pbx_exception *exception = NULL;
03147    if (!ds || !ds->data)
03148       return -1;
03149    exception = ds->data;
03150    if (!strcasecmp(data, "REASON"))
03151       ast_copy_string(buf, exception->reason, buflen);
03152    else if (!strcasecmp(data, "CONTEXT"))
03153       ast_copy_string(buf, exception->context, buflen);
03154    else if (!strncasecmp(data, "EXTEN", 5))
03155       ast_copy_string(buf, exception->exten, buflen);
03156    else if (!strcasecmp(data, "PRIORITY"))
03157       snprintf(buf, buflen, "%d", exception->priority);
03158    else
03159       return -1;
03160    return 0;
03161 }
03162 
03163 static struct ast_custom_function exception_function = {
03164    .name = "EXCEPTION",
03165    .read = acf_exception_read,
03166 };
03167 
03168 static char *handle_show_functions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03169 {
03170    struct ast_custom_function *acf;
03171    int count_acf = 0;
03172    int like = 0;
03173 
03174    switch (cmd) {
03175    case CLI_INIT:
03176       e->command = "core show functions [like]";
03177       e->usage =
03178          "Usage: core show functions [like <text>]\n"
03179          "       List builtin functions, optionally only those matching a given string\n";
03180       return NULL;
03181    case CLI_GENERATE:
03182       return NULL;
03183    }
03184 
03185    if (a->argc == 5 && (!strcmp(a->argv[3], "like")) ) {
03186       like = 1;
03187    } else if (a->argc != 3) {
03188       return CLI_SHOWUSAGE;
03189    }
03190 
03191    ast_cli(a->fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
03192 
03193    AST_RWLIST_RDLOCK(&acf_root);
03194    AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
03195       if (!like || strstr(acf->name, a->argv[4])) {
03196          count_acf++;
03197          ast_cli(a->fd, "%-20.20s  %-35.35s  %s\n",
03198             S_OR(acf->name, ""),
03199             S_OR(acf->syntax, ""),
03200             S_OR(acf->synopsis, ""));
03201       }
03202    }
03203    AST_RWLIST_UNLOCK(&acf_root);
03204 
03205    ast_cli(a->fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
03206 
03207    return CLI_SUCCESS;
03208 }
03209 
03210 static char *handle_show_function(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03211 {
03212    struct ast_custom_function *acf;
03213    /* Maximum number of characters added by terminal coloring is 22 */
03214    char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], argtitle[40], seealsotitle[40];
03215    char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *seealso = NULL;
03216    char stxtitle[40], *syntax = NULL, *arguments = NULL;
03217    int syntax_size, description_size, synopsis_size, arguments_size, seealso_size;
03218    char *ret = NULL;
03219    int which = 0;
03220    int wordlen;
03221 
03222    switch (cmd) {
03223    case CLI_INIT:
03224       e->command = "core show function";
03225       e->usage =
03226          "Usage: core show function <function>\n"
03227          "       Describe a particular dialplan function.\n";
03228       return NULL;
03229    case CLI_GENERATE:
03230       wordlen = strlen(a->word);
03231       /* case-insensitive for convenience in this 'complete' function */
03232       AST_RWLIST_RDLOCK(&acf_root);
03233       AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
03234          if (!strncasecmp(a->word, acf->name, wordlen) && ++which > a->n) {
03235             ret = ast_strdup(acf->name);
03236             break;
03237          }
03238       }
03239       AST_RWLIST_UNLOCK(&acf_root);
03240 
03241       return ret;
03242    }
03243 
03244    if (a->argc < 4) {
03245       return CLI_SHOWUSAGE;
03246    }
03247 
03248    if (!(acf = ast_custom_function_find(a->argv[3]))) {
03249       ast_cli(a->fd, "No function by that name registered.\n");
03250       return CLI_FAILURE;
03251    }
03252 
03253    syntax_size = strlen(S_OR(acf->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
03254    if (!(syntax = ast_malloc(syntax_size))) {
03255       ast_cli(a->fd, "Memory allocation failure!\n");
03256       return CLI_FAILURE;
03257    }
03258 
03259    snprintf(info, sizeof(info), "\n  -= Info about function '%s' =- \n\n", acf->name);
03260    term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle));
03261    term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
03262    term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
03263    term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
03264    term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
03265    term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40);
03266    term_color(syntax, S_OR(acf->syntax, "Not available"), COLOR_CYAN, 0, syntax_size);
03267 #ifdef AST_XML_DOCS
03268    if (acf->docsrc == AST_XML_DOC) {
03269       arguments = ast_xmldoc_printable(S_OR(acf->arguments, "Not available"), 1);
03270       synopsis = ast_xmldoc_printable(S_OR(acf->synopsis, "Not available"), 1);
03271       description = ast_xmldoc_printable(S_OR(acf->desc, "Not available"), 1);
03272       seealso = ast_xmldoc_printable(S_OR(acf->seealso, "Not available"), 1);
03273    } else
03274 #endif
03275    {
03276       synopsis_size = strlen(S_OR(acf->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
03277       synopsis = ast_malloc(synopsis_size);
03278 
03279       description_size = strlen(S_OR(acf->desc, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
03280       description = ast_malloc(description_size);
03281 
03282       arguments_size = strlen(S_OR(acf->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
03283       arguments = ast_malloc(arguments_size);
03284 
03285       seealso_size = strlen(S_OR(acf->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
03286       seealso = ast_malloc(seealso_size);
03287 
03288       /* check allocated memory. */
03289       if (!synopsis || !description || !arguments || !seealso) {
03290          ast_free(synopsis);
03291          ast_free(description);
03292          ast_free(arguments);
03293          ast_free(seealso);
03294          ast_free(syntax);
03295          return CLI_FAILURE;
03296       }
03297 
03298       term_color(arguments, S_OR(acf->arguments, "Not available"), COLOR_CYAN, 0, arguments_size);
03299       term_color(synopsis, S_OR(acf->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size);
03300       term_color(description, S_OR(acf->desc, "Not available"), COLOR_CYAN, 0, description_size);
03301       term_color(seealso, S_OR(acf->seealso, "Not available"), COLOR_CYAN, 0, seealso_size);
03302    }
03303 
03304    ast_cli(a->fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n",
03305          infotitle, syntitle, synopsis, destitle, description,
03306          stxtitle, syntax, argtitle, arguments, seealsotitle, seealso);
03307 
03308    ast_free(arguments);
03309    ast_free(synopsis);
03310    ast_free(description);
03311    ast_free(seealso);
03312    ast_free(syntax);
03313 
03314    return CLI_SUCCESS;
03315 }
03316 
03317 struct ast_custom_function *ast_custom_function_find(const char *name)
03318 {
03319    struct ast_custom_function *acf = NULL;
03320 
03321    AST_RWLIST_RDLOCK(&acf_root);
03322    AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
03323       if (!strcmp(name, acf->name))
03324          break;
03325    }
03326    AST_RWLIST_UNLOCK(&acf_root);
03327 
03328    return acf;
03329 }
03330 
03331 int ast_custom_function_unregister(struct ast_custom_function *acf)
03332 {
03333    struct ast_custom_function *cur;
03334 
03335    if (!acf) {
03336       return -1;
03337    }
03338 
03339    AST_RWLIST_WRLOCK(&acf_root);
03340    if ((cur = AST_RWLIST_REMOVE(&acf_root, acf, acflist))) {
03341 #ifdef AST_XML_DOCS
03342       if (cur->docsrc == AST_XML_DOC) {
03343          ast_string_field_free_memory(acf);
03344       }
03345 #endif
03346       ast_verb(2, "Unregistered custom function %s\n", cur->name);
03347    }
03348    AST_RWLIST_UNLOCK(&acf_root);
03349 
03350    return cur ? 0 : -1;
03351 }
03352 
03353 /*! \internal
03354  *  \brief Retrieve the XML documentation of a specified ast_custom_function,
03355  *         and populate ast_custom_function string fields.
03356  *  \param acf ast_custom_function structure with empty 'desc' and 'synopsis'
03357  *             but with a function 'name'.
03358  *  \retval -1 On error.
03359  *  \retval 0 On succes.
03360  */
03361 static int acf_retrieve_docs(struct ast_custom_function *acf)
03362 {
03363 #ifdef AST_XML_DOCS
03364    char *tmpxml;
03365 
03366    /* Let's try to find it in the Documentation XML */
03367    if (!ast_strlen_zero(acf->desc) || !ast_strlen_zero(acf->synopsis)) {
03368       return 0;
03369    }
03370 
03371    if (ast_string_field_init(acf, 128)) {
03372       return -1;
03373    }
03374 
03375    /* load synopsis */
03376    tmpxml = ast_xmldoc_build_synopsis("function", acf->name);
03377    ast_string_field_set(acf, synopsis, tmpxml);
03378    ast_free(tmpxml);
03379 
03380    /* load description */
03381    tmpxml = ast_xmldoc_build_description("function", acf->name);
03382    ast_string_field_set(acf, desc, tmpxml);
03383    ast_free(tmpxml);
03384 
03385    /* load syntax */
03386    tmpxml = ast_xmldoc_build_syntax("function", acf->name);
03387    ast_string_field_set(acf, syntax, tmpxml);
03388    ast_free(tmpxml);
03389 
03390    /* load arguments */
03391    tmpxml = ast_xmldoc_build_arguments("function", acf->name);
03392    ast_string_field_set(acf, arguments, tmpxml);
03393    ast_free(tmpxml);
03394 
03395    /* load seealso */
03396    tmpxml = ast_xmldoc_build_seealso("function", acf->name);
03397    ast_string_field_set(acf, seealso, tmpxml);
03398    ast_free(tmpxml);
03399 
03400    acf->docsrc = AST_XML_DOC;
03401 #endif
03402 
03403    return 0;
03404 }
03405 
03406 int __ast_custom_function_register(struct ast_custom_function *acf, struct ast_module *mod)
03407 {
03408    struct ast_custom_function *cur;
03409    char tmps[80];
03410 
03411    if (!acf) {
03412       return -1;
03413    }
03414 
03415    acf->mod = mod;
03416 #ifdef AST_XML_DOCS
03417    acf->docsrc = AST_STATIC_DOC;
03418 #endif
03419 
03420    if (acf_retrieve_docs(acf)) {
03421       return -1;
03422    }
03423 
03424    AST_RWLIST_WRLOCK(&acf_root);
03425 
03426    AST_RWLIST_TRAVERSE(&acf_root, cur, acflist) {
03427       if (!strcmp(acf->name, cur->name)) {
03428          ast_log(LOG_ERROR, "Function %s already registered.\n", acf->name);
03429          AST_RWLIST_UNLOCK(&acf_root);
03430          return -1;
03431       }
03432    }
03433 
03434    /* Store in alphabetical order */
03435    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&acf_root, cur, acflist) {
03436       if (strcasecmp(acf->name, cur->name) < 0) {
03437          AST_RWLIST_INSERT_BEFORE_CURRENT(acf, acflist);
03438          break;
03439       }
03440    }
03441    AST_RWLIST_TRAVERSE_SAFE_END;
03442 
03443    if (!cur) {
03444       AST_RWLIST_INSERT_TAIL(&acf_root, acf, acflist);
03445    }
03446 
03447    AST_RWLIST_UNLOCK(&acf_root);
03448 
03449    ast_verb(2, "Registered custom function '%s'\n", term_color(tmps, acf->name, COLOR_BRCYAN, 0, sizeof(tmps)));
03450 
03451    return 0;
03452 }
03453 
03454 /*! \brief return a pointer to the arguments of the function,
03455  * and terminates the function name with '\\0'
03456  */
03457 static char *func_args(char *function)
03458 {
03459    char *args = strchr(function, '(');
03460 
03461    if (!args) {
03462       ast_log(LOG_WARNING, "Function '%s' doesn't contain parentheses.  Assuming null argument.\n", function);
03463    } else {
03464       char *p;
03465       *args++ = '\0';
03466       if ((p = strrchr(args, ')'))) {
03467          *p = '\0';
03468       } else {
03469          ast_log(LOG_WARNING, "Can't find trailing parenthesis for function '%s(%s'?\n", function, args);
03470       }
03471    }
03472    return args;
03473 }
03474 
03475 int ast_func_read(struct ast_channel *chan, const char *function, char *workspace, size_t len)
03476 {
03477    char *copy = ast_strdupa(function);
03478    char *args = func_args(copy);
03479    struct ast_custom_function *acfptr = ast_custom_function_find(copy);
03480    int res;
03481    struct ast_module_user *u = NULL;
03482 
03483    if (acfptr == NULL) {
03484       ast_log(LOG_ERROR, "Function %s not registered\n", copy);
03485    } else if (!acfptr->read && !acfptr->read2) {
03486       ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
03487    } else if (acfptr->read) {
03488       if (acfptr->mod) {
03489          u = __ast_module_user_add(acfptr->mod, chan);
03490       }
03491       res = acfptr->read(chan, copy, args, workspace, len);
03492       if (acfptr->mod && u) {
03493          __ast_module_user_remove(acfptr->mod, u);
03494       }
03495       return res;
03496    } else {
03497       struct ast_str *str = ast_str_create(16);
03498       if (acfptr->mod) {
03499          u = __ast_module_user_add(acfptr->mod, chan);
03500       }
03501       res = acfptr->read2(chan, copy, args, &str, 0);
03502       if (acfptr->mod && u) {
03503          __ast_module_user_remove(acfptr->mod, u);
03504       }
03505       ast_copy_string(workspace, ast_str_buffer(str), len > ast_str_size(str) ? ast_str_size(str) : len);
03506       ast_free(str);
03507       return res;
03508    }
03509    return -1;
03510 }
03511 
03512 int ast_func_read2(struct ast_channel *chan, const char *function, struct ast_str **str, ssize_t maxlen)
03513 {
03514    char *copy = ast_strdupa(function);
03515    char *args = func_args(copy);
03516    struct ast_custom_function *acfptr = ast_custom_function_find(copy);
03517    int res;
03518    struct ast_module_user *u = NULL;
03519 
03520    if (acfptr == NULL) {
03521       ast_log(LOG_ERROR, "Function %s not registered\n", copy);
03522    } else if (!acfptr->read && !acfptr->read2) {
03523       ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
03524    } else {
03525       if (acfptr->mod) {
03526          u = __ast_module_user_add(acfptr->mod, chan);
03527       }
03528       if (acfptr->read2) {
03529          /* ast_str enabled */
03530          ast_str_reset(*str);
03531          res = acfptr->read2(chan, copy, args, str, maxlen);
03532       } else {
03533          /* Legacy function pointer, allocate buffer for result */
03534          int maxsize = ast_str_size(*str);
03535          if (maxlen > -1) {
03536             if (maxlen == 0) {
03537                if (acfptr->read_max) {
03538                   maxsize = acfptr->read_max;
03539                } else {
03540                   maxsize = VAR_BUF_SIZE;
03541                }
03542             } else {
03543                maxsize = maxlen;
03544             }
03545             ast_str_make_space(str, maxsize);
03546          }
03547          res = acfptr->read(chan, copy, args, ast_str_buffer(*str), maxsize);
03548       }
03549       if (acfptr->mod && u) {
03550          __ast_module_user_remove(acfptr->mod, u);
03551       }
03552       return res;
03553    }
03554    return -1;
03555 }
03556 
03557 int ast_func_write(struct ast_channel *chan, const char *function, const char *value)
03558 {
03559    char *copy = ast_strdupa(function);
03560    char *args = func_args(copy);
03561    struct ast_custom_function *acfptr = ast_custom_function_find(copy);
03562 
03563    if (acfptr == NULL)
03564       ast_log(LOG_ERROR, "Function %s not registered\n", copy);
03565    else if (!acfptr->write)
03566       ast_log(LOG_ERROR, "Function %s cannot be written to\n", copy);
03567    else {
03568       int res;
03569       struct ast_module_user *u = NULL;
03570       if (acfptr->mod)
03571          u = __ast_module_user_add(acfptr->mod, chan);
03572       res = acfptr->write(chan, copy, args, value);
03573       if (acfptr->mod && u)
03574          __ast_module_user_remove(acfptr->mod, u);
03575       return res;
03576    }
03577 
03578    return -1;
03579 }
03580 
03581 void ast_str_substitute_variables_full(struct ast_str **buf, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *templ, size_t *used)
03582 {
03583    /* Substitutes variables into buf, based on string templ */
03584    char *cp4 = NULL;
03585    const char *tmp, *whereweare;
03586    int orig_size = 0;
03587    int offset, offset2, isfunction;
03588    const char *nextvar, *nextexp, *nextthing;
03589    const char *vars, *vare;
03590    char *finalvars;
03591    int pos, brackets, needsub, len;
03592    struct ast_str *substr1 = ast_str_create(16), *substr2 = NULL, *substr3 = ast_str_create(16);
03593 
03594    ast_str_reset(*buf);
03595    whereweare = tmp = templ;
03596    while (!ast_strlen_zero(whereweare)) {
03597       /* Assume we're copying the whole remaining string */
03598       pos = strlen(whereweare);
03599       nextvar = NULL;
03600       nextexp = NULL;
03601       nextthing = strchr(whereweare, '$');
03602       if (nextthing) {
03603          switch (nextthing[1]) {
03604          case '{':
03605             nextvar = nextthing;
03606             pos = nextvar - whereweare;
03607             break;
03608          case '[':
03609             nextexp = nextthing;
03610             pos = nextexp - whereweare;
03611             break;
03612          default:
03613             pos = 1;
03614          }
03615       }
03616 
03617       if (pos) {
03618          /* Copy that many bytes */
03619          ast_str_append_substr(buf, maxlen, whereweare, pos);
03620 
03621          templ += pos;
03622          whereweare += pos;
03623       }
03624 
03625       if (nextvar) {
03626          /* We have a variable.  Find the start and end, and determine
03627             if we are going to have to recursively call ourselves on the
03628             contents */
03629          vars = vare = nextvar + 2;
03630          brackets = 1;
03631          needsub = 0;
03632 
03633          /* Find the end of it */
03634          while (brackets && *vare) {
03635             if ((vare[0] == '$') && (vare[1] == '{')) {
03636                needsub++;
03637             } else if (vare[0] == '{') {
03638                brackets++;
03639             } else if (vare[0] == '}') {
03640                brackets--;
03641             } else if ((vare[0] == '$') && (vare[1] == '['))
03642                needsub++;
03643             vare++;
03644          }
03645          if (brackets)
03646             ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
03647          len = vare - vars - 1;
03648 
03649          /* Skip totally over variable string */
03650          whereweare += (len + 3);
03651 
03652          /* Store variable name (and truncate) */
03653          ast_str_set_substr(&substr1, 0, vars, len);
03654          ast_debug(5, "Evaluating '%s' (from '%s' len %d)\n", ast_str_buffer(substr1), vars, len);
03655 
03656          /* Substitute if necessary */
03657          if (needsub) {
03658             size_t used;
03659             if (!substr2) {
03660                substr2 = ast_str_create(16);
03661             }
03662 
03663             ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used);
03664             finalvars = ast_str_buffer(substr2);
03665          } else {
03666             finalvars = ast_str_buffer(substr1);
03667          }
03668 
03669          parse_variable_name(finalvars, &offset, &offset2, &isfunction);
03670          if (isfunction) {
03671             /* Evaluate function */
03672             if (c || !headp) {
03673                cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3);
03674             } else {
03675                struct varshead old;
03676                struct ast_channel *bogus = ast_dummy_channel_alloc();
03677                if (bogus) {
03678                   memcpy(&old, &bogus->varshead, sizeof(old));
03679                   memcpy(&bogus->varshead, headp, sizeof(bogus->varshead));
03680                   cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3);
03681                   /* Don't deallocate the varshead that was passed in */
03682                   memcpy(&bogus->varshead, &old, sizeof(bogus->varshead));
03683                   ast_channel_release(bogus);
03684                } else {
03685                   ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution.  Function results may be blank.\n");
03686                }
03687             }
03688             ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
03689          } else {
03690             /* Retrieve variable value */
03691             ast_str_retrieve_variable(&substr3, 0, c, headp, finalvars);
03692             cp4 = ast_str_buffer(substr3);
03693          }
03694          if (cp4) {
03695             ast_str_substring(substr3, offset, offset2);
03696             ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3));
03697          }
03698       } else if (nextexp) {
03699          /* We have an expression.  Find the start and end, and determine
03700             if we are going to have to recursively call ourselves on the
03701             contents */
03702          vars = vare = nextexp + 2;
03703          brackets = 1;
03704          needsub = 0;
03705 
03706          /* Find the end of it */
03707          while (brackets && *vare) {
03708             if ((vare[0] == '$') && (vare[1] == '[')) {
03709                needsub++;
03710                brackets++;
03711                vare++;
03712             } else if (vare[0] == '[') {
03713                brackets++;
03714             } else if (vare[0] == ']') {
03715                brackets--;
03716             } else if ((vare[0] == '$') && (vare[1] == '{')) {
03717                needsub++;
03718                vare++;
03719             }
03720             vare++;
03721          }
03722          if (brackets)
03723             ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
03724          len = vare - vars - 1;
03725 
03726          /* Skip totally over expression */
03727          whereweare += (len + 3);
03728 
03729          /* Store variable name (and truncate) */
03730          ast_str_set_substr(&substr1, 0, vars, len);
03731 
03732          /* Substitute if necessary */
03733          if (needsub) {
03734             size_t used;
03735             if (!substr2) {
03736                substr2 = ast_str_create(16);
03737             }
03738 
03739             ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used);
03740             finalvars = ast_str_buffer(substr2);
03741          } else {
03742             finalvars = ast_str_buffer(substr1);
03743          }
03744 
03745          if (ast_str_expr(&substr3, 0, c, finalvars)) {
03746             ast_debug(2, "Expression result is '%s'\n", ast_str_buffer(substr3));
03747          }
03748          ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3));
03749       }
03750    }
03751    *used = ast_str_strlen(*buf) - orig_size;
03752    ast_free(substr1);
03753    ast_free(substr2);
03754    ast_free(substr3);
03755 }
03756 
03757 void ast_str_substitute_variables(struct ast_str **buf, ssize_t maxlen, struct ast_channel *chan, const char *templ)
03758 {
03759    size_t used;
03760    ast_str_substitute_variables_full(buf, maxlen, chan, NULL, templ, &used);
03761 }
03762 
03763 void ast_str_substitute_variables_varshead(struct ast_str **buf, ssize_t maxlen, struct varshead *headp, const char *templ)
03764 {
03765    size_t used;
03766    ast_str_substitute_variables_full(buf, maxlen, NULL, headp, templ, &used);
03767 }
03768 
03769 void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count, size_t *used)
03770 {
03771    /* Substitutes variables into cp2, based on string cp1, cp2 NO LONGER NEEDS TO BE ZEROED OUT!!!!  */
03772    char *cp4 = NULL;
03773    const char *tmp, *whereweare, *orig_cp2 = cp2;
03774    int length, offset, offset2, isfunction;
03775    char *workspace = NULL;
03776    char *ltmp = NULL, *var = NULL;
03777    char *nextvar, *nextexp, *nextthing;
03778    char *vars, *vare;
03779    int pos, brackets, needsub, len;
03780 
03781    *cp2 = 0; /* just in case nothing ends up there */
03782    whereweare=tmp=cp1;
03783    while (!ast_strlen_zero(whereweare) && count) {
03784       /* Assume we're copying the whole remaining string */
03785       pos = strlen(whereweare);
03786       nextvar = NULL;
03787       nextexp = NULL;
03788       nextthing = strchr(whereweare, '$');
03789       if (nextthing) {
03790          switch (nextthing[1]) {
03791          case '{':
03792             nextvar = nextthing;
03793             pos = nextvar - whereweare;
03794             break;
03795          case '[':
03796             nextexp = nextthing;
03797             pos = nextexp - whereweare;
03798             break;
03799          default:
03800             pos = 1;
03801          }
03802       }
03803 
03804       if (pos) {
03805          /* Can't copy more than 'count' bytes */
03806          if (pos > count)
03807             pos = count;
03808 
03809          /* Copy that many bytes */
03810          memcpy(cp2, whereweare, pos);
03811 
03812          count -= pos;
03813          cp2 += pos;
03814          whereweare += pos;
03815          *cp2 = 0;
03816       }
03817 
03818       if (nextvar) {
03819          /* We have a variable.  Find the start and end, and determine
03820             if we are going to have to recursively call ourselves on the
03821             contents */
03822          vars = vare = nextvar + 2;
03823          brackets = 1;
03824          needsub = 0;
03825 
03826          /* Find the end of it */
03827          while (brackets && *vare) {
03828             if ((vare[0] == '$') && (vare[1] == '{')) {
03829                needsub++;
03830             } else if (vare[0] == '{') {
03831                brackets++;
03832             } else if (vare[0] == '}') {
03833                brackets--;
03834             } else if ((vare[0] == '$') && (vare[1] == '['))
03835                needsub++;
03836             vare++;
03837          }
03838          if (brackets)
03839             ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
03840          len = vare - vars - 1;
03841 
03842          /* Skip totally over variable string */
03843          whereweare += (len + 3);
03844 
03845          if (!var)
03846             var = alloca(VAR_BUF_SIZE);
03847 
03848          /* Store variable name (and truncate) */
03849          ast_copy_string(var, vars, len + 1);
03850 
03851          /* Substitute if necessary */
03852          if (needsub) {
03853             size_t used;
03854             if (!ltmp)
03855                ltmp = alloca(VAR_BUF_SIZE);
03856 
03857             pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used);
03858             vars = ltmp;
03859          } else {
03860             vars = var;
03861          }
03862 
03863          if (!workspace)
03864             workspace = alloca(VAR_BUF_SIZE);
03865 
03866          workspace[0] = '\0';
03867 
03868          parse_variable_name(vars, &offset, &offset2, &isfunction);
03869          if (isfunction) {
03870             /* Evaluate function */
03871             if (c || !headp)
03872                cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
03873             else {
03874                struct varshead old;
03875                struct ast_channel *c = ast_dummy_channel_alloc();
03876                if (c) {
03877                   memcpy(&old, &c->varshead, sizeof(old));
03878                   memcpy(&c->varshead, headp, sizeof(c->varshead));
03879                   cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
03880                   /* Don't deallocate the varshead that was passed in */
03881                   memcpy(&c->varshead, &old, sizeof(c->varshead));
03882                   c = ast_channel_release(c);
03883                } else {
03884                   ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution.  Function results may be blank.\n");
03885                }
03886             }
03887             ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
03888          } else {
03889             /* Retrieve variable value */
03890             pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp);
03891          }
03892          if (cp4) {
03893             cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE);
03894 
03895             length = strlen(cp4);
03896             if (length > count)
03897                length = count;
03898             memcpy(cp2, cp4, length);
03899             count -= length;
03900             cp2 += length;
03901             *cp2 = 0;
03902          }
03903       } else if (nextexp) {
03904          /* We have an expression.  Find the start and end, and determine
03905             if we are going to have to recursively call ourselves on the
03906             contents */
03907          vars = vare = nextexp + 2;
03908          brackets = 1;
03909          needsub = 0;
03910 
03911          /* Find the end of it */
03912          while (brackets && *vare) {
03913             if ((vare[0] == '$') && (vare[1] == '[')) {
03914                needsub++;
03915                brackets++;
03916                vare++;
03917             } else if (vare[0] == '[') {
03918                brackets++;
03919             } else if (vare[0] == ']') {
03920                brackets--;
03921             } else if ((vare[0] == '$') && (vare[1] == '{')) {
03922                needsub++;
03923                vare++;
03924             }
03925             vare++;
03926          }
03927          if (brackets)
03928             ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
03929          len = vare - vars - 1;
03930 
03931          /* Skip totally over expression */
03932          whereweare += (len + 3);
03933 
03934          if (!var)
03935             var = alloca(VAR_BUF_SIZE);
03936 
03937          /* Store variable name (and truncate) */
03938          ast_copy_string(var, vars, len + 1);
03939 
03940          /* Substitute if necessary */
03941          if (needsub) {
03942             size_t used;
03943             if (!ltmp)
03944                ltmp = alloca(VAR_BUF_SIZE);
03945 
03946             pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used);
03947             vars = ltmp;
03948          } else {
03949             vars = var;
03950          }
03951 
03952          length = ast_expr(vars, cp2, count, c);
03953 
03954          if (length) {
03955             ast_debug(1, "Expression result is '%s'\n", cp2);
03956             count -= length;
03957             cp2 += length;
03958             *cp2 = 0;
03959          }
03960       }
03961    }
03962    *used = cp2 - orig_cp2;
03963 }
03964 
03965 void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
03966 {
03967    size_t used;
03968    pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count, &used);
03969 }
03970 
03971 void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count)
03972 {
03973    size_t used;
03974    pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count, &used);
03975 }
03976 
03977 static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e)
03978 {
03979    const char *tmp;
03980 
03981    /* Nothing more to do */
03982    if (!e->data) {
03983       *passdata = '\0';
03984       return;
03985    }
03986 
03987    /* No variables or expressions in e->data, so why scan it? */
03988    if ((!(tmp = strchr(e->data, '$'))) || (!strstr(tmp, "${") && !strstr(tmp, "$["))) {
03989       ast_copy_string(passdata, e->data, datalen);
03990       return;
03991    }
03992 
03993    pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1);
03994 }
03995 
03996 /*!
03997  * \brief The return value depends on the action:
03998  *
03999  * E_MATCH, E_CANMATCH, E_MATCHMORE require a real match,
04000  * and return 0 on failure, -1 on match;
04001  * E_FINDLABEL maps the label to a priority, and returns
04002  * the priority on success, ... XXX
04003  * E_SPAWN, spawn an application,
04004  *
04005  * \retval 0 on success.
04006  * \retval  -1 on failure.
04007  *
04008  * \note The channel is auto-serviced in this function, because doing an extension
04009  * match may block for a long time.  For example, if the lookup has to use a network
04010  * dialplan switch, such as DUNDi or IAX2, it may take a while.  However, the channel
04011  * auto-service code will queue up any important signalling frames to be processed
04012  * after this is done.
04013  */
04014 static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
04015   const char *context, const char *exten, int priority,
04016   const char *label, const char *callerid, enum ext_match_t action, int *found, int combined_find_spawn)
04017 {
04018    struct ast_exten *e;
04019    struct ast_app *app;
04020    int res;
04021    struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
04022    char passdata[EXT_DATA_SIZE];
04023 
04024    int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE);
04025 
04026    ast_rdlock_contexts();
04027    if (found)
04028       *found = 0;
04029 
04030    e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action);
04031    if (e) {
04032       if (found)
04033          *found = 1;
04034       if (matching_action) {
04035          ast_unlock_contexts();
04036          return -1;  /* success, we found it */
04037       } else if (action == E_FINDLABEL) { /* map the label to a priority */
04038          res = e->priority;
04039          ast_unlock_contexts();
04040          return res; /* the priority we were looking for */
04041       } else { /* spawn */
04042          if (!e->cached_app)
04043             e->cached_app = pbx_findapp(e->app);
04044          app = e->cached_app;
04045          ast_unlock_contexts();
04046          if (!app) {
04047             ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
04048             return -1;
04049          }
04050          if (c->context != context)
04051             ast_copy_string(c->context, context, sizeof(c->context));
04052          if (c->exten != exten)
04053             ast_copy_string(c->exten, exten, sizeof(c->exten));
04054          c->priority = priority;
04055          pbx_substitute_variables(passdata, sizeof(passdata), c, e);
04056 #ifdef CHANNEL_TRACE
04057          ast_channel_trace_update(c);
04058 #endif
04059          ast_debug(1, "Launching '%s'\n", app->name);
04060          if (VERBOSITY_ATLEAST(3)) {
04061             char tmp[80], tmp2[80], tmp3[EXT_DATA_SIZE];
04062             ast_verb(3, "Executing [%s@%s:%d] %s(\"%s\", \"%s\") %s\n",
04063                exten, context, priority,
04064                term_color(tmp, app->name, COLOR_BRCYAN, 0, sizeof(tmp)),
04065                term_color(tmp2, c->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)),
04066                term_color(tmp3, passdata, COLOR_BRMAGENTA, 0, sizeof(tmp3)),
04067                "in new stack");
04068          }
04069          manager_event(EVENT_FLAG_DIALPLAN, "Newexten",
04070                "Channel: %s\r\n"
04071                "Context: %s\r\n"
04072                "Extension: %s\r\n"
04073                "Priority: %d\r\n"
04074                "Application: %s\r\n"
04075                "AppData: %s\r\n"
04076                "Uniqueid: %s\r\n",
04077                c->name, c->context, c->exten, c->priority, app->name, passdata, c->uniqueid);
04078          return pbx_exec(c, app, passdata);  /* 0 on success, -1 on failure */
04079       }
04080    } else if (q.swo) {  /* not found here, but in another switch */
04081       if (found)
04082          *found = 1;
04083       ast_unlock_contexts();
04084       if (matching_action) {
04085          return -1;
04086       } else {
04087          if (!q.swo->exec) {
04088             ast_log(LOG_WARNING, "No execution engine for switch %s\n", q.swo->name);
04089             res = -1;
04090          }
04091          return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data);
04092       }
04093    } else { /* not found anywhere, see what happened */
04094       ast_unlock_contexts();
04095       /* Using S_OR here because Solaris doesn't like NULL being passed to ast_log */
04096       switch (q.status) {
04097       case STATUS_NO_CONTEXT:
04098          if (!matching_action && !combined_find_spawn)
04099             ast_log(LOG_NOTICE, "Cannot find extension context '%s'\n", S_OR(context, ""));
04100          break;
04101       case STATUS_NO_EXTENSION:
04102          if (!matching_action && !combined_find_spawn)
04103             ast_log(LOG_NOTICE, "Cannot find extension '%s' in context '%s'\n", exten, S_OR(context, ""));
04104          break;
04105       case STATUS_NO_PRIORITY:
04106          if (!matching_action && !combined_find_spawn)
04107             ast_log(LOG_NOTICE, "No such priority %d in extension '%s' in context '%s'\n", priority, exten, S_OR(context, ""));
04108          break;
04109       case STATUS_NO_LABEL:
04110          if (context && !combined_find_spawn)
04111             ast_log(LOG_NOTICE, "No such label '%s' in extension '%s' in context '%s'\n", label, exten, S_OR(context, ""));
04112          break;
04113       default:
04114          ast_debug(1, "Shouldn't happen!\n");
04115       }
04116 
04117       return (matching_action) ? 0 : -1;
04118    }
04119 }
04120 
04121 /*! \brief Find hint for given extension in context */
04122 static struct ast_exten *ast_hint_extension_nolock(struct ast_channel *c, const char *context, const char *exten)
04123 {
04124    struct pbx_find_info q = { .stacklen = 0 }; /* the rest is set in pbx_find_context */
04125    return pbx_find_extension(c, NULL, &q, context, exten, PRIORITY_HINT, NULL, "", E_MATCH);
04126 }
04127 
04128 static struct ast_exten *ast_hint_extension(struct ast_channel *c, const char *context, const char *exten)
04129 {
04130    struct ast_exten *e;
04131    ast_rdlock_contexts();
04132    e = ast_hint_extension_nolock(c, context, exten);
04133    ast_unlock_contexts();
04134    return e;
04135 }
04136 
04137 enum ast_extension_states ast_devstate_to_extenstate(enum ast_device_state devstate)
04138 {
04139    switch (devstate) {
04140    case AST_DEVICE_ONHOLD:
04141       return AST_EXTENSION_ONHOLD;
04142    case AST_DEVICE_BUSY:
04143       return AST_EXTENSION_BUSY;
04144    case AST_DEVICE_UNKNOWN:
04145       return AST_EXTENSION_NOT_INUSE;
04146    case AST_DEVICE_UNAVAILABLE:
04147    case AST_DEVICE_INVALID:
04148       return AST_EXTENSION_UNAVAILABLE;
04149    case AST_DEVICE_RINGINUSE:
04150       return (AST_EXTENSION_INUSE | AST_EXTENSION_RINGING);
04151    case AST_DEVICE_RINGING:
04152       return AST_EXTENSION_RINGING;
04153    case AST_DEVICE_INUSE:
04154       return AST_EXTENSION_INUSE;
04155    case AST_DEVICE_NOT_INUSE:
04156       return AST_EXTENSION_NOT_INUSE;
04157    case AST_DEVICE_TOTAL: /* not a device state, included for completeness */
04158       break;
04159    }
04160 
04161    return AST_EXTENSION_NOT_INUSE;
04162 }
04163 
04164 /*! \brief Check state of extension by using hints */
04165 static int ast_extension_state2(struct ast_exten *e)
04166 {
04167    struct ast_str *hint = ast_str_thread_get(&extensionstate_buf, 16);
04168    char *cur, *rest;
04169    struct ast_devstate_aggregate agg;
04170 
04171    if (!e)
04172       return -1;
04173 
04174    ast_devstate_aggregate_init(&agg);
04175 
04176    ast_str_set(&hint, 0, "%s", ast_get_extension_app(e));
04177 
04178    rest = ast_str_buffer(hint);  /* One or more devices separated with a & character */
04179 
04180    while ( (cur = strsep(&rest, "&")) ) {
04181       ast_devstate_aggregate_add(&agg, ast_device_state(cur));
04182    }
04183 
04184    return ast_devstate_to_extenstate(ast_devstate_aggregate_result(&agg));
04185 }
04186 
04187 /*! \brief Return extension_state as string */
04188 const char *ast_extension_state2str(int extension_state)
04189 {
04190    int i;
04191 
04192    for (i = 0; (i < ARRAY_LEN(extension_states)); i++) {
04193       if (extension_states[i].extension_state == extension_state)
04194          return extension_states[i].text;
04195    }
04196    return "Unknown";
04197 }
04198 
04199 /*! \brief Check extension state for an extension by using hint */
04200 int ast_extension_state(struct ast_channel *c, const char *context, const char *exten)
04201 {
04202    struct ast_exten *e;
04203 
04204    if (!(e = ast_hint_extension(c, context, exten))) {  /* Do we have a hint for this extension ? */
04205       return -1;                   /* No hint, return -1 */
04206    }
04207 
04208    if (e->exten[0] == '_') {
04209       /* Create this hint on-the-fly */
04210       ast_add_extension(e->parent->name, 0, exten, e->priority, e->label,
04211          e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr,
04212          e->registrar);
04213       if (!(e = ast_hint_extension(c, context, exten))) {
04214          /* Improbable, but not impossible */
04215          return -1;
04216       }
04217    }
04218 
04219    return ast_extension_state2(e);  /* Check all devices in the hint */
04220 }
04221 
04222 static int handle_statechange(void *datap)
04223 {
04224    struct ast_hint *hint;
04225    struct ast_str *str;
04226    struct statechange *sc = datap;
04227 
04228    if (!(str = ast_str_create(1024))) {
04229       return -1;
04230    }
04231 
04232    ast_rdlock_contexts();
04233    AST_RWLIST_RDLOCK(&hints);
04234 
04235    AST_RWLIST_TRAVERSE(&hints, hint, list) {
04236       struct ast_state_cb *cblist;
04237       char *cur, *parse;
04238       int state;
04239 
04240       ast_str_set(&str, 0, "%s", ast_get_extension_app(hint->exten));
04241       parse = str->str;
04242 
04243       while ( (cur = strsep(&parse, "&")) ) {
04244          if (!strcasecmp(cur, sc->dev)) {
04245             break;
04246          }
04247       }
04248 
04249       if (!cur) {
04250          continue;
04251       }
04252 
04253       /* Get device state for this hint */
04254       state = ast_extension_state2(hint->exten);
04255 
04256       if ((state == -1) || (state == hint->laststate)) {
04257          continue;
04258       }
04259 
04260       /* Device state changed since last check - notify the watchers */
04261 
04262       /* For general callbacks */
04263       AST_LIST_TRAVERSE(&statecbs, cblist, entry) {
04264          cblist->callback(hint->exten->parent->name, hint->exten->exten, state, cblist->data);
04265       }
04266 
04267       /* For extension callbacks */
04268       AST_LIST_TRAVERSE(&hint->callbacks, cblist, entry) {
04269          cblist->callback(hint->exten->parent->name, hint->exten->exten, state, cblist->data);
04270       }
04271 
04272       hint->laststate = state;   /* record we saw the change */
04273    }
04274    AST_RWLIST_UNLOCK(&hints);
04275    ast_unlock_contexts();
04276    ast_free(str);
04277    ast_free(sc);
04278    return 0;
04279 }
04280 
04281 /*! \brief  Add watcher for extension states */
04282 int ast_extension_state_add(const char *context, const char *exten,
04283              ast_state_cb_type callback, void *data)
04284 {
04285    struct ast_hint *hint;
04286    struct ast_state_cb *cblist;
04287    struct ast_exten *e;
04288 
04289    /* If there's no context and extension:  add callback to statecbs list */
04290    if (!context && !exten) {
04291       AST_RWLIST_WRLOCK(&hints);
04292 
04293       AST_LIST_TRAVERSE(&statecbs, cblist, entry) {
04294          if (cblist->callback == callback) {
04295             cblist->data = data;
04296             AST_RWLIST_UNLOCK(&hints);
04297             return 0;
04298          }
04299       }
04300 
04301       /* Now insert the callback */
04302       if (!(cblist = ast_calloc(1, sizeof(*cblist)))) {
04303          AST_RWLIST_UNLOCK(&hints);
04304          return -1;
04305       }
04306       cblist->id = 0;
04307       cblist->callback = callback;
04308       cblist->data = data;
04309 
04310       AST_LIST_INSERT_HEAD(&statecbs, cblist, entry);
04311 
04312       AST_RWLIST_UNLOCK(&hints);
04313 
04314       return 0;
04315    }
04316 
04317    if (!context || !exten)
04318       return -1;
04319 
04320    /* This callback type is for only one hint, so get the hint */
04321    e = ast_hint_extension(NULL, context, exten);
04322    if (!e) {
04323       return -1;
04324    }
04325 
04326    /* If this is a pattern, dynamically create a new extension for this
04327     * particular match.  Note that this will only happen once for each
04328     * individual extension, because the pattern will no longer match first.
04329     */
04330    if (e->exten[0] == '_') {
04331       ast_add_extension(e->parent->name, 0, exten, e->priority, e->label,
04332          e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr,
04333          e->registrar);
04334       e = ast_hint_extension(NULL, context, exten);
04335       if (!e || e->exten[0] == '_') {
04336          return -1;
04337       }
04338    }
04339 
04340    /* Find the hint in the list of hints */
04341    AST_RWLIST_WRLOCK(&hints);
04342 
04343    AST_RWLIST_TRAVERSE(&hints, hint, list) {
04344       if (hint->exten == e)
04345          break;
04346    }
04347 
04348    if (!hint) {
04349       /* We have no hint, sorry */
04350       AST_RWLIST_UNLOCK(&hints);
04351       return -1;
04352    }
04353 
04354    /* Now insert the callback in the callback list  */
04355    if (!(cblist = ast_calloc(1, sizeof(*cblist)))) {
04356       AST_RWLIST_UNLOCK(&hints);
04357       return -1;
04358    }
04359 
04360    cblist->id = stateid++;    /* Unique ID for this callback */
04361    cblist->callback = callback;  /* Pointer to callback routine */
04362    cblist->data = data;    /* Data for the callback */
04363 
04364    AST_LIST_INSERT_HEAD(&hint->callbacks, cblist, entry);
04365 
04366    AST_RWLIST_UNLOCK(&hints);
04367 
04368    return cblist->id;
04369 }
04370 
04371 /*! \brief Remove a watcher from the callback list */
04372 int ast_extension_state_del(int id, ast_state_cb_type callback)
04373 {
04374    struct ast_state_cb *p_cur = NULL;
04375    int ret = -1;
04376 
04377    if (!id && !callback)
04378       return -1;
04379 
04380    AST_RWLIST_WRLOCK(&hints);
04381 
04382    if (!id) {  /* id == 0 is a callback without extension */
04383       AST_LIST_TRAVERSE_SAFE_BEGIN(&statecbs, p_cur, entry) {
04384          if (p_cur->callback == callback) {
04385             AST_LIST_REMOVE_CURRENT(entry);
04386             break;
04387          }
04388       }
04389       AST_LIST_TRAVERSE_SAFE_END;
04390    } else { /* callback with extension, find the callback based on ID */
04391       struct ast_hint *hint;
04392       AST_RWLIST_TRAVERSE(&hints, hint, list) {
04393          AST_LIST_TRAVERSE_SAFE_BEGIN(&hint->callbacks, p_cur, entry) {
04394             if (p_cur->id == id) {
04395                AST_LIST_REMOVE_CURRENT(entry);
04396                break;
04397             }
04398          }
04399          AST_LIST_TRAVERSE_SAFE_END;
04400 
04401          if (p_cur)
04402             break;
04403       }
04404    }
04405 
04406    if (p_cur) {
04407       ast_free(p_cur);
04408    }
04409 
04410    AST_RWLIST_UNLOCK(&hints);
04411 
04412    return ret;
04413 }
04414 
04415 
04416 /*! \brief Add hint to hint list, check initial extension state; the hints had better be WRLOCKED already! */
04417 static int ast_add_hint_nolock(struct ast_exten *e)
04418 {
04419    struct ast_hint *hint;
04420 
04421    if (!e)
04422       return -1;
04423 
04424    /* Search if hint exists, do nothing */
04425    AST_RWLIST_TRAVERSE(&hints, hint, list) {
04426       if (hint->exten == e) {
04427          ast_debug(2, "HINTS: Not re-adding existing hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e));
04428          return -1;
04429       }
04430    }
04431 
04432    ast_debug(2, "HINTS: Adding hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e));
04433 
04434    if (!(hint = ast_calloc(1, sizeof(*hint)))) {
04435       return -1;
04436    }
04437    /* Initialize and insert new item at the top */
04438    hint->exten = e;
04439    hint->laststate = ast_extension_state2(e);
04440    AST_RWLIST_INSERT_HEAD(&hints, hint, list);
04441 
04442    return 0;
04443 }
04444 
04445 /*! \brief Add hint to hint list, check initial extension state */
04446 static int ast_add_hint(struct ast_exten *e)
04447 {
04448    int ret;
04449 
04450    AST_RWLIST_WRLOCK(&hints);
04451    ret = ast_add_hint_nolock(e);
04452    AST_RWLIST_UNLOCK(&hints);
04453 
04454    return ret;
04455 }
04456 
04457 /*! \brief Change hint for an extension */
04458 static int ast_change_hint(struct ast_exten *oe, struct ast_exten *ne)
04459 {
04460    struct ast_hint *hint;
04461    int res = -1;
04462 
04463    AST_RWLIST_WRLOCK(&hints);
04464    AST_RWLIST_TRAVERSE(&hints, hint, list) {
04465       if (hint->exten == oe) {
04466          hint->exten = ne;
04467          res = 0;
04468          break;
04469       }
04470    }
04471    AST_RWLIST_UNLOCK(&hints);
04472 
04473    return res;
04474 }
04475 
04476 /*! \brief Remove hint from extension */
04477 static int ast_remove_hint(struct ast_exten *e)
04478 {
04479    /* Cleanup the Notifys if hint is removed */
04480    struct ast_hint *hint;
04481    struct ast_state_cb *cblist;
04482    int res = -1;
04483 
04484    if (!e)
04485       return -1;
04486 
04487    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&hints, hint, list) {
04488       if (hint->exten != e)
04489          continue;
04490 
04491       while ((cblist = AST_LIST_REMOVE_HEAD(&hint->callbacks, entry))) {
04492          /* Notify with -1 and remove all callbacks */
04493          cblist->callback(hint->exten->parent->name, hint->exten->exten,
04494             AST_EXTENSION_DEACTIVATED, cblist->data);
04495          ast_free(cblist);
04496       }
04497 
04498       AST_RWLIST_REMOVE_CURRENT(list);
04499       ast_free(hint);
04500 
04501       res = 0;
04502 
04503       break;
04504    }
04505    AST_RWLIST_TRAVERSE_SAFE_END;
04506 
04507    return res;
04508 }
04509 
04510 
04511 /*! \brief Get hint for channel */
04512 int ast_get_hint(char *hint, int hintsize, char *name, int namesize, struct ast_channel *c, const char *context, const char *exten)
04513 {
04514    struct ast_exten *e = ast_hint_extension(c, context, exten);
04515 
04516    if (e) {
04517       if (hint)
04518          ast_copy_string(hint, ast_get_extension_app(e), hintsize);
04519       if (name) {
04520          const char *tmp = ast_get_extension_app_data(e);
04521          if (tmp)
04522             ast_copy_string(name, tmp, namesize);
04523       }
04524       return -1;
04525    }
04526    return 0;
04527 }
04528 
04529 /*! \brief Get hint for channel */
04530 int ast_str_get_hint(struct ast_str **hint, ssize_t hintsize, struct ast_str **name, ssize_t namesize, struct ast_channel *c, const char *context, const char *exten)
04531 {
04532    struct ast_exten *e = ast_hint_extension(c, context, exten);
04533 
04534    if (!e) {
04535       return 0;
04536    }
04537 
04538    if (hint) {
04539       ast_str_set(hint, hintsize, "%s", ast_get_extension_app(e));
04540    }
04541    if (name) {
04542       const char *tmp = ast_get_extension_app_data(e);
04543       if (tmp) {
04544          ast_str_set(name, namesize, "%s", tmp);
04545       }
04546    }
04547    return -1;
04548 }
04549 
04550 int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
04551 {
04552    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCH, 0, 0);
04553 }
04554 
04555 int ast_findlabel_extension(struct ast_channel *c, const char *context, const char *exten, const char *label, const char *callerid)
04556 {
04557    return pbx_extension_helper(c, NULL, context, exten, 0, label, callerid, E_FINDLABEL, 0, 0);
04558 }
04559 
04560 int ast_findlabel_extension2(struct ast_channel *c, struct ast_context *con, const char *exten, const char *label, const char *callerid)
04561 {
04562    return pbx_extension_helper(c, con, NULL, exten, 0, label, callerid, E_FINDLABEL, 0, 0);
04563 }
04564 
04565 int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
04566 {
04567    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_CANMATCH, 0, 0);
04568 }
04569 
04570 int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
04571 {
04572    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCHMORE, 0, 0);
04573 }
04574 
04575 int ast_spawn_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid, int *found, int combined_find_spawn)
04576 {
04577    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_SPAWN, found, combined_find_spawn);
04578 }
04579 
04580 /*! helper function to set extension and priority */
04581 static void set_ext_pri(struct ast_channel *c, const char *exten, int pri)
04582 {
04583    ast_channel_lock(c);
04584    ast_copy_string(c->exten, exten, sizeof(c->exten));
04585    c->priority = pri;
04586    ast_channel_unlock(c);
04587 }
04588 
04589 /*!
04590  * \brief collect digits from the channel into the buffer.
04591  * \param c, buf, buflen, pos
04592  * \param waittime is in milliseconds
04593  * \retval 0 on timeout or done.
04594  * \retval -1 on error.
04595 */
04596 static int collect_digits(struct ast_channel *c, int waittime, char *buf, int buflen, int pos)
04597 {
04598    int digit;
04599 
04600    buf[pos] = '\0';  /* make sure it is properly terminated */
04601    while (ast_matchmore_extension(c, c->context, buf, 1,
04602       S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04603       /* As long as we're willing to wait, and as long as it's not defined,
04604          keep reading digits until we can't possibly get a right answer anymore.  */
04605       digit = ast_waitfordigit(c, waittime);
04606       if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
04607          c->_softhangup = 0;
04608       } else {
04609          if (!digit) /* No entry */
04610             break;
04611          if (digit < 0) /* Error, maybe a  hangup */
04612             return -1;
04613          if (pos < buflen - 1) { /* XXX maybe error otherwise ? */
04614             buf[pos++] = digit;
04615             buf[pos] = '\0';
04616          }
04617          waittime = c->pbx->dtimeoutms;
04618       }
04619    }
04620    return 0;
04621 }
04622 
04623 static enum ast_pbx_result __ast_pbx_run(struct ast_channel *c,
04624       struct ast_pbx_args *args)
04625 {
04626    int found = 0; /* set if we find at least one match */
04627    int res = 0;
04628    int autoloopflag;
04629    int error = 0;    /* set an error conditions */
04630 
04631    /* A little initial setup here */
04632    if (c->pbx) {
04633       ast_log(LOG_WARNING, "%s already has PBX structure??\n", c->name);
04634       /* XXX and now what ? */
04635       ast_free(c->pbx);
04636    }
04637    if (!(c->pbx = ast_calloc(1, sizeof(*c->pbx))))
04638       return -1;
04639    /* Set reasonable defaults */
04640    c->pbx->rtimeoutms = 10000;
04641    c->pbx->dtimeoutms = 5000;
04642 
04643    autoloopflag = ast_test_flag(c, AST_FLAG_IN_AUTOLOOP);   /* save value to restore at the end */
04644    ast_set_flag(c, AST_FLAG_IN_AUTOLOOP);
04645 
04646    /* Start by trying whatever the channel is set to */
04647    if (!ast_exists_extension(c, c->context, c->exten, c->priority,
04648       S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04649       /* If not successful fall back to 's' */
04650       ast_verb(2, "Starting %s at %s,%s,%d failed so falling back to exten 's'\n", c->name, c->context, c->exten, c->priority);
04651       /* XXX the original code used the existing priority in the call to
04652        * ast_exists_extension(), and reset it to 1 afterwards.
04653        * I believe the correct thing is to set it to 1 immediately.
04654        */
04655       set_ext_pri(c, "s", 1);
04656       if (!ast_exists_extension(c, c->context, c->exten, c->priority,
04657          S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04658          /* JK02: And finally back to default if everything else failed */
04659          ast_verb(2, "Starting %s at %s,%s,%d still failed so falling back to context 'default'\n", c->name, c->context, c->exten, c->priority);
04660          ast_copy_string(c->context, "default", sizeof(c->context));
04661       }
04662    }
04663    if (c->cdr) {
04664       /* allow CDR variables that have been collected after channel was created to be visible during call */
04665       ast_cdr_update(c);
04666    }
04667    for (;;) {
04668       char dst_exten[256]; /* buffer to accumulate digits */
04669       int pos = 0;      /* XXX should check bounds */
04670       int digit = 0;
04671       int invalid = 0;
04672       int timeout = 0;
04673 
04674       /* loop on priorities in this context/exten */
04675       while (!(res = ast_spawn_extension(c, c->context, c->exten, c->priority,
04676          S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL),
04677          &found, 1))) {
04678          if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT
04679             && ast_exists_extension(c, c->context, "T", 1,
04680                S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04681             set_ext_pri(c, "T", 0); /* 0 will become 1 with the c->priority++; at the end */
04682             /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
04683             memset(&c->whentohangup, 0, sizeof(c->whentohangup));
04684             c->_softhangup &= ~AST_SOFTHANGUP_TIMEOUT;
04685          } else if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT
04686             && ast_exists_extension(c, c->context, "e", 1,
04687                S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04688             pbx_builtin_raise_exception(c, "ABSOLUTETIMEOUT");
04689             /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
04690             memset(&c->whentohangup, 0, sizeof(c->whentohangup));
04691             c->_softhangup &= ~AST_SOFTHANGUP_TIMEOUT;
04692          } else if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
04693             c->_softhangup = 0;
04694             continue;
04695          } else if (ast_check_hangup(c)) {
04696             ast_debug(1, "Extension %s, priority %d returned normally even though call was hung up\n",
04697                c->exten, c->priority);
04698             error = 1;
04699             break;
04700          }
04701          c->priority++;
04702       } /* end while  - from here on we can use 'break' to go out */
04703       if (found && res) {
04704          /* Something bad happened, or a hangup has been requested. */
04705          if (strchr("0123456789ABCDEF*#", res)) {
04706             ast_debug(1, "Oooh, got something to jump out with ('%c')!\n", res);
04707             pos = 0;
04708             dst_exten[pos++] = digit = res;
04709             dst_exten[pos] = '\0';
04710          } else if (res == AST_PBX_INCOMPLETE) {
04711             ast_debug(1, "Spawn extension (%s,%s,%d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name);
04712             ast_verb(2, "Spawn extension (%s, %s, %d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name);
04713 
04714             /* Don't cycle on incomplete - this will happen if the only extension that matches is our "incomplete" extension */
04715             if (!ast_matchmore_extension(c, c->context, c->exten, 1,
04716                S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04717                invalid = 1;
04718             } else {
04719                ast_copy_string(dst_exten, c->exten, sizeof(dst_exten));
04720                digit = 1;
04721                pos = strlen(dst_exten);
04722             }
04723          } else {
04724             ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
04725             ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
04726 
04727             if ((res == AST_PBX_ERROR)
04728                && ast_exists_extension(c, c->context, "e", 1,
04729                   S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04730                /* if we are already on the 'e' exten, don't jump to it again */
04731                if (!strcmp(c->exten, "e")) {
04732                   ast_verb(2, "Spawn extension (%s, %s, %d) exited ERROR while already on 'e' exten on '%s'\n", c->context, c->exten, c->priority, c->name);
04733                   error = 1;
04734                } else {
04735                   pbx_builtin_raise_exception(c, "ERROR");
04736                   continue;
04737                }
04738             }
04739 
04740             if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
04741                c->_softhangup = 0;
04742                continue;
04743             } else if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT
04744                && ast_exists_extension(c, c->context, "T", 1,
04745                   S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04746                set_ext_pri(c, "T", 1);
04747                /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
04748                memset(&c->whentohangup, 0, sizeof(c->whentohangup));
04749                c->_softhangup &= ~AST_SOFTHANGUP_TIMEOUT;
04750                continue;
04751             } else {
04752                if (c->cdr)
04753                   ast_cdr_update(c);
04754                error = 1;
04755                break;
04756             }
04757          }
04758       }
04759       if (error)
04760          break;
04761 
04762       /*!\note
04763        * We get here on a failure of some kind:  non-existing extension or
04764        * hangup.  We have options, here.  We can either catch the failure
04765        * and continue, or we can drop out entirely. */
04766 
04767       if (invalid
04768          || !ast_exists_extension(c, c->context, c->exten, 1,
04769             S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04770          /*!\note
04771           * If there is no match at priority 1, it is not a valid extension anymore.
04772           * Try to continue at "i" (for invalid) or "e" (for exception) or exit if
04773           * neither exist.
04774           */
04775          if (ast_exists_extension(c, c->context, "i", 1,
04776             S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04777             ast_verb(3, "Sent into invalid extension '%s' in context '%s' on %s\n", c->exten, c->context, c->name);
04778             pbx_builtin_setvar_helper(c, "INVALID_EXTEN", c->exten);
04779             set_ext_pri(c, "i", 1);
04780          } else if (ast_exists_extension(c, c->context, "e", 1,
04781             S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04782             pbx_builtin_raise_exception(c, "INVALID");
04783          } else {
04784             ast_log(LOG_WARNING, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n",
04785                c->name, c->exten, c->context);
04786             error = 1; /* we know what to do with it */
04787             break;
04788          }
04789       } else if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT) {
04790          /* If we get this far with AST_SOFTHANGUP_TIMEOUT, then we know that the "T" extension is next. */
04791          c->_softhangup = 0;
04792       } else { /* keypress received, get more digits for a full extension */
04793          int waittime = 0;
04794          if (digit)
04795             waittime = c->pbx->dtimeoutms;
04796          else if (!autofallthrough)
04797             waittime = c->pbx->rtimeoutms;
04798          if (!waittime) {
04799             const char *status = pbx_builtin_getvar_helper(c, "DIALSTATUS");
04800             if (!status)
04801                status = "UNKNOWN";
04802             ast_verb(3, "Auto fallthrough, channel '%s' status is '%s'\n", c->name, status);
04803             if (!strcasecmp(status, "CONGESTION"))
04804                res = pbx_builtin_congestion(c, "10");
04805             else if (!strcasecmp(status, "CHANUNAVAIL"))
04806                res = pbx_builtin_congestion(c, "10");
04807             else if (!strcasecmp(status, "BUSY"))
04808                res = pbx_builtin_busy(c, "10");
04809             error = 1; /* XXX disable message */
04810             break;   /* exit from the 'for' loop */
04811          }
04812 
04813          if (collect_digits(c, waittime, dst_exten, sizeof(dst_exten), pos))
04814             break;
04815          if (res == AST_PBX_INCOMPLETE && ast_strlen_zero(&dst_exten[pos]))
04816             timeout = 1;
04817          if (!timeout
04818             && ast_exists_extension(c, c->context, dst_exten, 1,
04819                S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* Prepare the next cycle */
04820             set_ext_pri(c, dst_exten, 1);
04821          } else {
04822             /* No such extension */
04823             if (!timeout && !ast_strlen_zero(dst_exten)) {
04824                /* An invalid extension */
04825                if (ast_exists_extension(c, c->context, "i", 1,
04826                   S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04827                   ast_verb(3, "Invalid extension '%s' in context '%s' on %s\n", dst_exten, c->context, c->name);
04828                   pbx_builtin_setvar_helper(c, "INVALID_EXTEN", dst_exten);
04829                   set_ext_pri(c, "i", 1);
04830                } else if (ast_exists_extension(c, c->context, "e", 1,
04831                   S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04832                   pbx_builtin_raise_exception(c, "INVALID");
04833                } else {
04834                   ast_log(LOG_WARNING, "Invalid extension '%s', but no rule 'i' in context '%s'\n", dst_exten, c->context);
04835                   found = 1; /* XXX disable message */
04836                   break;
04837                }
04838             } else {
04839                /* A simple timeout */
04840                if (ast_exists_extension(c, c->context, "t", 1,
04841                   S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04842                   ast_verb(3, "Timeout on %s\n", c->name);
04843                   set_ext_pri(c, "t", 1);
04844                } else if (ast_exists_extension(c, c->context, "e", 1,
04845                   S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04846                   pbx_builtin_raise_exception(c, "RESPONSETIMEOUT");
04847                } else {
04848                   ast_log(LOG_WARNING, "Timeout, but no rule 't' in context '%s'\n", c->context);
04849                   found = 1; /* XXX disable message */
04850                   break;
04851                }
04852             }
04853          }
04854          if (c->cdr) {
04855             ast_verb(2, "CDR updated on %s\n",c->name);
04856             ast_cdr_update(c);
04857          }
04858       }
04859    }
04860 
04861    if (!found && !error) {
04862       ast_log(LOG_WARNING, "Don't know what to do with '%s'\n", c->name);
04863    }
04864 
04865    if (!args || !args->no_hangup_chan) {
04866       ast_softhangup(c, AST_SOFTHANGUP_APPUNLOAD);
04867    }
04868 
04869    if ((!args || !args->no_hangup_chan)
04870       && !ast_test_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN)
04871       && ast_exists_extension(c, c->context, "h", 1,
04872          S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
04873       set_ext_pri(c, "h", 1);
04874       if (c->cdr && ast_opt_end_cdr_before_h_exten) {
04875          ast_cdr_end(c->cdr);
04876       }
04877       while ((res = ast_spawn_extension(c, c->context, c->exten, c->priority,
04878          S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL),
04879          &found, 1)) == 0) {
04880          c->priority++;
04881       }
04882       if (found && res) {
04883          /* Something bad happened, or a hangup has been requested. */
04884          ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
04885          ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
04886       }
04887    }
04888    ast_set2_flag(c, autoloopflag, AST_FLAG_IN_AUTOLOOP);
04889    ast_clear_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN); /* from one round to the next, make sure this gets cleared */
04890    pbx_destroy(c->pbx);
04891    c->pbx = NULL;
04892 
04893    if (!args || !args->no_hangup_chan) {
04894       ast_hangup(c);
04895    }
04896 
04897    return 0;
04898 }
04899 
04900 /*!
04901  * \brief Increase call count for channel
04902  * \retval 0 on success
04903  * \retval non-zero if a configured limit (maxcalls, maxload, minmemfree) was reached 
04904 */
04905 static int increase_call_count(const struct ast_channel *c)
04906 {
04907    int failed = 0;
04908    double curloadavg;
04909 #if defined(HAVE_SYSINFO)
04910    long curfreemem;
04911    struct sysinfo sys_info;
04912 #endif
04913 
04914    ast_mutex_lock(&maxcalllock);
04915    if (option_maxcalls) {
04916       if (countcalls >= option_maxcalls) {
04917          ast_log(LOG_WARNING, "Maximum call limit of %d calls exceeded by '%s'!\n", option_maxcalls, c->name);
04918          failed = -1;
04919       }
04920    }
04921    if (option_maxload) {
04922       getloadavg(&curloadavg, 1);
04923       if (curloadavg >= option_maxload) {
04924          ast_log(LOG_WARNING, "Maximum loadavg limit of %f load exceeded by '%s' (currently %f)!\n", option_maxload, c->name, curloadavg);
04925          failed = -1;
04926       }
04927    }
04928 #if defined(HAVE_SYSINFO)
04929    if (option_minmemfree) {
04930       if (!sysinfo(&sys_info)) {
04931          /* make sure that the free system memory is above the configured low watermark
04932           * convert the amount of freeram from mem_units to MB */
04933          curfreemem = sys_info.freeram / sys_info.mem_unit;
04934          curfreemem /= 1024 * 1024;
04935          if (curfreemem < option_minmemfree) {
04936             ast_log(LOG_WARNING, "Available system memory (~%ldMB) is below the configured low watermark (%ldMB)\n", curfreemem, option_minmemfree);
04937             failed = -1;
04938          }
04939       }
04940    }
04941 #endif
04942 
04943    if (!failed) {
04944       countcalls++;
04945       totalcalls++;
04946    }
04947    ast_mutex_unlock(&maxcalllock);
04948 
04949    return failed;
04950 }
04951 
04952 static void decrease_call_count(void)
04953 {
04954    ast_mutex_lock(&maxcalllock);
04955    if (countcalls > 0)
04956       countcalls--;
04957    ast_mutex_unlock(&maxcalllock);
04958 }
04959 
04960 static void destroy_exten(struct ast_exten *e)
04961 {
04962    if (e->priority == PRIORITY_HINT)
04963       ast_remove_hint(e);
04964 
04965    if (e->peer_table)
04966       ast_hashtab_destroy(e->peer_table,0);
04967    if (e->peer_label_table)
04968       ast_hashtab_destroy(e->peer_label_table, 0);
04969    if (e->datad)
04970       e->datad(e->data);
04971    ast_free(e);
04972 }
04973 
04974 static void *pbx_thread(void *data)
04975 {
04976    /* Oh joyeous kernel, we're a new thread, with nothing to do but
04977       answer this channel and get it going.
04978    */
04979    /* NOTE:
04980       The launcher of this function _MUST_ increment 'countcalls'
04981       before invoking the function; it will be decremented when the
04982       PBX has finished running on the channel
04983     */
04984    struct ast_channel *c = data;
04985 
04986    __ast_pbx_run(c, NULL);
04987    decrease_call_count();
04988 
04989    pthread_exit(NULL);
04990 
04991    return NULL;
04992 }
04993 
04994 enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
04995 {
04996    pthread_t t;
04997 
04998    if (!c) {
04999       ast_log(LOG_WARNING, "Asked to start thread on NULL channel?\n");
05000       return AST_PBX_FAILED;
05001    }
05002 
05003    if (increase_call_count(c))
05004       return AST_PBX_CALL_LIMIT;
05005 
05006    /* Start a new thread, and get something handling this channel. */
05007    if (ast_pthread_create_detached(&t, NULL, pbx_thread, c)) {
05008       ast_log(LOG_WARNING, "Failed to create new channel thread\n");
05009       decrease_call_count();
05010       return AST_PBX_FAILED;
05011    }
05012 
05013    return AST_PBX_SUCCESS;
05014 }
05015 
05016 enum ast_pbx_result ast_pbx_run_args(struct ast_channel *c, struct ast_pbx_args *args)
05017 {
05018    enum ast_pbx_result res = AST_PBX_SUCCESS;
05019 
05020    if (increase_call_count(c)) {
05021       return AST_PBX_CALL_LIMIT;
05022    }
05023 
05024    res = __ast_pbx_run(c, args);
05025 
05026    decrease_call_count();
05027 
05028    return res;
05029 }
05030 
05031 enum ast_pbx_result ast_pbx_run(struct ast_channel *c)
05032 {
05033    return ast_pbx_run_args(c, NULL);
05034 }
05035 
05036 int ast_active_calls(void)
05037 {
05038    return countcalls;
05039 }
05040 
05041 int ast_processed_calls(void)
05042 {
05043    return totalcalls;
05044 }
05045 
05046 int pbx_set_autofallthrough(int newval)
05047 {
05048    int oldval = autofallthrough;
05049    autofallthrough = newval;
05050    return oldval;
05051 }
05052 
05053 int pbx_set_extenpatternmatchnew(int newval)
05054 {
05055    int oldval = extenpatternmatchnew;
05056    extenpatternmatchnew = newval;
05057    return oldval;
05058 }
05059 
05060 void pbx_set_overrideswitch(const char *newval)
05061 {
05062    if (overrideswitch) {
05063       ast_free(overrideswitch);
05064    }
05065    if (!ast_strlen_zero(newval)) {
05066       overrideswitch = ast_strdup(newval);
05067    } else {
05068       overrideswitch = NULL;
05069    }
05070 }
05071 
05072 /*!
05073  * \brief lookup for a context with a given name,
05074  * \retval found context or NULL if not found.
05075 */
05076 static struct ast_context *find_context(const char *context)
05077 {
05078    struct ast_context *c = NULL;
05079    struct fake_context item;
05080 
05081    ast_copy_string(item.name, context, sizeof(item.name));
05082 
05083    c = ast_hashtab_lookup(contexts_table,&item);
05084 
05085    return c;
05086 }
05087 
05088 /*!
05089  * \brief lookup for a context with a given name,
05090  * \retval with conlock held if found.
05091  * \retval NULL if not found.
05092 */
05093 static struct ast_context *find_context_locked(const char *context)
05094 {
05095    struct ast_context *c = NULL;
05096    struct fake_context item;
05097 
05098    ast_copy_string(item.name, context, sizeof(item.name));
05099 
05100    ast_rdlock_contexts();
05101    c = ast_hashtab_lookup(contexts_table,&item);
05102 
05103    if (!c)
05104       ast_unlock_contexts();
05105 
05106    return c;
05107 }
05108 
05109 /*!
05110  * \brief Remove included contexts.
05111  * This function locks contexts list by &conlist, search for the right context
05112  * structure, leave context list locked and call ast_context_remove_include2
05113  * which removes include, unlock contexts list and return ...
05114 */
05115 int ast_context_remove_include(const char *context, const char *include, const char *registrar)
05116 {
05117    int ret = -1;
05118    struct ast_context *c = find_context_locked(context);
05119 
05120    if (c) {
05121       /* found, remove include from this context ... */
05122       ret = ast_context_remove_include2(c, include, registrar);
05123       ast_unlock_contexts();
05124    }
05125    return ret;
05126 }
05127 
05128 /*!
05129  * \brief Locks context, remove included contexts, unlocks context.
05130  * When we call this function, &conlock lock must be locked, because when
05131  * we giving *con argument, some process can remove/change this context
05132  * and after that there can be segfault.
05133  *
05134  * \retval 0 on success.
05135  * \retval -1 on failure.
05136  */
05137 int ast_context_remove_include2(struct ast_context *con, const char *include, const char *registrar)
05138 {
05139    struct ast_include *i, *pi = NULL;
05140    int ret = -1;
05141 
05142    ast_wrlock_context(con);
05143 
05144    /* find our include */
05145    for (i = con->includes; i; pi = i, i = i->next) {
05146       if (!strcmp(i->name, include) &&
05147             (!registrar || !strcmp(i->registrar, registrar))) {
05148          /* remove from list */
05149          ast_verb(3, "Removing inclusion of context '%s' in context '%s; registrar=%s'\n", include, ast_get_context_name(con), registrar);
05150          if (pi)
05151             pi->next = i->next;
05152          else
05153             con->includes = i->next;
05154          /* free include and return */
05155          ast_destroy_timing(&(i->timing));
05156          ast_free(i);
05157          ret = 0;
05158          break;
05159       }
05160    }
05161 
05162    ast_unlock_context(con);
05163 
05164    return ret;
05165 }
05166 
05167 /*!
05168  * \note This function locks contexts list by &conlist, search for the rigt context
05169  * structure, leave context list locked and call ast_context_remove_switch2
05170  * which removes switch, unlock contexts list and return ...
05171  */
05172 int ast_context_remove_switch(const char *context, const char *sw, const char *data, const char *registrar)
05173 {
05174    int ret = -1; /* default error return */
05175    struct ast_context *c = find_context_locked(context);
05176 
05177    if (c) {
05178       /* remove switch from this context ... */
05179       ret = ast_context_remove_switch2(c, sw, data, registrar);
05180       ast_unlock_contexts();
05181    }
05182    return ret;
05183 }
05184 
05185 /*!
05186  * \brief This function locks given context, removes switch, unlock context and
05187  * return.
05188  * \note When we call this function, &conlock lock must be locked, because when
05189  * we giving *con argument, some process can remove/change this context
05190  * and after that there can be segfault.
05191  *
05192  */
05193 int ast_context_remove_switch2(struct ast_context *con, const char *sw, const char *data, const char *registrar)
05194 {
05195    struct ast_sw *i;
05196    int ret = -1;
05197 
05198    ast_wrlock_context(con);
05199 
05200    /* walk switches */
05201    AST_LIST_TRAVERSE_SAFE_BEGIN(&con->alts, i, list) {
05202       if (!strcmp(i->name, sw) && !strcmp(i->data, data) &&
05203          (!registrar || !strcmp(i->registrar, registrar))) {
05204          /* found, remove from list */
05205          ast_verb(3, "Removing switch '%s' from context '%s; registrar=%s'\n", sw, ast_get_context_name(con), registrar);
05206          AST_LIST_REMOVE_CURRENT(list);
05207          ast_free(i); /* free switch and return */
05208          ret = 0;
05209          break;
05210       }
05211    }
05212    AST_LIST_TRAVERSE_SAFE_END;
05213 
05214    ast_unlock_context(con);
05215 
05216    return ret;
05217 }
05218 
05219 /*
05220  * \note This functions lock contexts list, search for the right context,
05221  * call ast_context_remove_extension2, unlock contexts list and return.
05222  * In this function we are using
05223  */
05224 int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
05225 {
05226    return ast_context_remove_extension_callerid(context, extension, priority, NULL, 0, registrar);
05227 }
05228 
05229 int ast_context_remove_extension_callerid(const char *context, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar)
05230 {
05231    int ret = -1; /* default error return */
05232    struct ast_context *c = find_context_locked(context);
05233 
05234    if (c) { /* ... remove extension ... */
05235       ret = ast_context_remove_extension_callerid2(c, extension, priority, callerid, matchcallerid, registrar, 1);
05236       ast_unlock_contexts();
05237    }
05238    return ret;
05239 }
05240 
05241 /*!
05242  * \brief This functionc locks given context, search for the right extension and
05243  * fires out all peer in this extensions with given priority. If priority
05244  * is set to 0, all peers are removed. After that, unlock context and
05245  * return.
05246  * \note When do you want to call this function, make sure that &conlock is locked,
05247  * because some process can handle with your *con context before you lock
05248  * it.
05249  *
05250  */
05251 int ast_context_remove_extension2(struct ast_context *con, const char *extension, int priority, const char *registrar, int already_locked)
05252 {
05253    return ast_context_remove_extension_callerid2(con, extension, priority, NULL, 0, registrar, already_locked);
05254 }
05255 
05256 int ast_context_remove_extension_callerid2(struct ast_context *con, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar, int already_locked)
05257 {
05258    struct ast_exten *exten, *prev_exten = NULL;
05259    struct ast_exten *peer;
05260    struct ast_exten ex, *exten2, *exten3;
05261    char dummy_name[1024];
05262    struct ast_exten *previous_peer = NULL;
05263    struct ast_exten *next_peer = NULL;
05264    int found = 0;
05265 
05266    if (!already_locked)
05267       ast_wrlock_context(con);
05268 
05269    /* Handle this is in the new world */
05270 
05271    /* FIXME For backwards compatibility, if callerid==NULL, then remove ALL
05272     * peers, not just those matching the callerid. */
05273 #ifdef NEED_DEBUG
05274    ast_verb(3,"Removing %s/%s/%d%s%s from trees, registrar=%s\n", con->name, extension, priority, matchcallerid ? "/" : "", matchcallerid ? callerid : "", registrar);
05275 #endif
05276 #ifdef CONTEXT_DEBUG
05277    check_contexts(__FILE__, __LINE__);
05278 #endif
05279    /* find this particular extension */
05280    ex.exten = dummy_name;
05281    ex.matchcid = matchcallerid && !ast_strlen_zero(callerid); /* don't say match if there's no callerid */
05282    ex.cidmatch = callerid;
05283    ast_copy_string(dummy_name, extension, sizeof(dummy_name));
05284    exten = ast_hashtab_lookup(con->root_table, &ex);
05285    if (exten) {
05286       if (priority == 0) {
05287          exten2 = ast_hashtab_remove_this_object(con->root_table, exten);
05288          if (!exten2)
05289             ast_log(LOG_ERROR,"Trying to delete the exten %s from context %s, but could not remove from the root_table\n", extension, con->name);
05290          if (con->pattern_tree) {
05291             struct match_char *x = add_exten_to_pattern_tree(con, exten, 1);
05292 
05293             if (x->exten) { /* this test for safety purposes */
05294                x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
05295                x->exten = 0; /* get rid of what will become a bad pointer */
05296             } else {
05297                ast_log(LOG_WARNING,"Trying to delete an exten from a context, but the pattern tree node returned isn't a full extension\n");
05298             }
05299          }
05300       } else {
05301          ex.priority = priority;
05302          exten2 = ast_hashtab_lookup(exten->peer_table, &ex);
05303          if (exten2) {
05304 
05305             if (exten2->label) { /* if this exten has a label, remove that, too */
05306                exten3 = ast_hashtab_remove_this_object(exten->peer_label_table,exten2);
05307                if (!exten3)
05308                   ast_log(LOG_ERROR,"Did not remove this priority label (%d/%s) from the peer_label_table of context %s, extension %s!\n", priority, exten2->label, con->name, exten2->exten);
05309             }
05310 
05311             exten3 = ast_hashtab_remove_this_object(exten->peer_table, exten2);
05312             if (!exten3)
05313                ast_log(LOG_ERROR,"Did not remove this priority (%d) from the peer_table of context %s, extension %s!\n", priority, con->name, exten2->exten);
05314             if (exten2 == exten && exten2->peer) {
05315                exten2 = ast_hashtab_remove_this_object(con->root_table, exten);
05316                ast_hashtab_insert_immediate(con->root_table, exten2->peer);
05317             }
05318             if (ast_hashtab_size(exten->peer_table) == 0) {
05319                /* well, if the last priority of an exten is to be removed,
05320                   then, the extension is removed, too! */
05321                exten3 = ast_hashtab_remove_this_object(con->root_table, exten);
05322                if (!exten3)
05323                   ast_log(LOG_ERROR,"Did not remove this exten (%s) from the context root_table (%s) (priority %d)\n", exten->exten, con->name, priority);
05324                if (con->pattern_tree) {
05325                   struct match_char *x = add_exten_to_pattern_tree(con, exten, 1);
05326                   if (x->exten) { /* this test for safety purposes */
05327                      x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
05328                      x->exten = 0; /* get rid of what will become a bad pointer */
05329                   }
05330                }
05331             }
05332          } else {
05333             ast_log(LOG_ERROR,"Could not find priority %d of exten %s in context %s!\n",
05334                   priority, exten->exten, con->name);
05335          }
05336       }
05337    } else {
05338       /* hmmm? this exten is not in this pattern tree? */
05339       ast_log(LOG_WARNING,"Cannot find extension %s in root_table in context %s\n",
05340             extension, con->name);
05341    }
05342 #ifdef NEED_DEBUG
05343    if (con->pattern_tree) {
05344       ast_log(LOG_NOTICE,"match char tree after exten removal:\n");
05345       log_match_char_tree(con->pattern_tree, " ");
05346    }
05347 #endif
05348 
05349    /* scan the extension list to find first matching extension-registrar */
05350    for (exten = con->root; exten; prev_exten = exten, exten = exten->next) {
05351       if (!strcmp(exten->exten, extension) &&
05352          (!registrar || !strcmp(exten->registrar, registrar)) &&
05353          (!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(exten->cidmatch) && !strcmp(exten->cidmatch, callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(exten->cidmatch))))
05354          break;
05355    }
05356    if (!exten) {
05357       /* we can't find right extension */
05358       if (!already_locked)
05359          ast_unlock_context(con);
05360       return -1;
05361    }
05362 
05363    /* scan the priority list to remove extension with exten->priority == priority */
05364    for (peer = exten, next_peer = exten->peer ? exten->peer : exten->next;
05365        peer && !strcmp(peer->exten, extension) && (!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(peer->cidmatch) && !strcmp(peer->cidmatch,callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(peer->cidmatch)));
05366          peer = next_peer, next_peer = next_peer ? (next_peer->peer ? next_peer->peer : next_peer->next) : NULL) {
05367       if ((priority == 0 || peer->priority == priority) &&
05368             (!callerid || !matchcallerid || (matchcallerid && !strcmp(peer->cidmatch, callerid))) &&
05369             (!registrar || !strcmp(peer->registrar, registrar) )) {
05370          found = 1;
05371 
05372          /* we are first priority extension? */
05373          if (!previous_peer) {
05374             /*
05375              * We are first in the priority chain, so must update the extension chain.
05376              * The next node is either the next priority or the next extension
05377              */
05378             struct ast_exten *next_node = peer->peer ? peer->peer : peer->next;
05379             if (peer->peer) {
05380                /* move the peer_table and peer_label_table down to the next peer, if
05381                   it is there */
05382                peer->peer->peer_table = peer->peer_table;
05383                peer->peer->peer_label_table = peer->peer_label_table;
05384                peer->peer_table = NULL;
05385                peer->peer_label_table = NULL;
05386             }
05387             if (!prev_exten) {   /* change the root... */
05388                con->root = next_node;
05389             } else {
05390                prev_exten->next = next_node; /* unlink */
05391             }
05392             if (peer->peer)   { /* update the new head of the pri list */
05393                peer->peer->next = peer->next;
05394             }
05395          } else { /* easy, we are not first priority in extension */
05396             previous_peer->peer = peer->peer;
05397          }
05398 
05399          /* now, free whole priority extension */
05400          destroy_exten(peer);
05401       } else {
05402          previous_peer = peer;
05403       }
05404    }
05405    if (!already_locked)
05406       ast_unlock_context(con);
05407    return found ? 0 : -1;
05408 }
05409 
05410 
05411 /*!
05412  * \note This function locks contexts list by &conlist, searches for the right context
05413  * structure, and locks the macrolock mutex in that context.
05414  * macrolock is used to limit a macro to be executed by one call at a time.
05415  */
05416 int ast_context_lockmacro(const char *context)
05417 {
05418    struct ast_context *c = NULL;
05419    int ret = -1;
05420    struct fake_context item;
05421 
05422    ast_rdlock_contexts();
05423 
05424    ast_copy_string(item.name, context, sizeof(item.name));
05425 
05426    c = ast_hashtab_lookup(contexts_table,&item);
05427    if (c)
05428       ret = 0;
05429    ast_unlock_contexts();
05430 
05431    /* if we found context, lock macrolock */
05432    if (ret == 0) {
05433       ret = ast_mutex_lock(&c->macrolock);
05434    }
05435 
05436    return ret;
05437 }
05438 
05439 /*!
05440  * \note This function locks contexts list by &conlist, searches for the right context
05441  * structure, and unlocks the macrolock mutex in that context.
05442  * macrolock is used to limit a macro to be executed by one call at a time.
05443  */
05444 int ast_context_unlockmacro(const char *context)
05445 {
05446    struct ast_context *c = NULL;
05447    int ret = -1;
05448    struct fake_context item;
05449 
05450    ast_rdlock_contexts();
05451 
05452    ast_copy_string(item.name, context, sizeof(item.name));
05453 
05454    c = ast_hashtab_lookup(contexts_table,&item);
05455    if (c)
05456       ret = 0;
05457    ast_unlock_contexts();
05458 
05459    /* if we found context, unlock macrolock */
05460    if (ret == 0) {
05461       ret = ast_mutex_unlock(&c->macrolock);
05462    }
05463 
05464    return ret;
05465 }
05466 
05467 /*! \brief Dynamically register a new dial plan application */
05468 int ast_register_application2(const char *app, int (*execute)(struct ast_channel *, const char *), const char *synopsis, const char *description, void *mod)
05469 {
05470    struct ast_app *tmp, *cur = NULL;
05471    char tmps[80];
05472    int length, res;
05473 #ifdef AST_XML_DOCS
05474    char *tmpxml;
05475 #endif
05476 
05477    AST_RWLIST_WRLOCK(&apps);
05478    AST_RWLIST_TRAVERSE(&apps, tmp, list) {
05479       if (!(res = strcasecmp(app, tmp->name))) {
05480          ast_log(LOG_WARNING, "Already have an application '%s'\n", app);
05481          AST_RWLIST_UNLOCK(&apps);
05482          return -1;
05483       } else if (res < 0)
05484          break;
05485    }
05486 
05487    length = sizeof(*tmp) + strlen(app) + 1;
05488 
05489    if (!(tmp = ast_calloc(1, length))) {
05490       AST_RWLIST_UNLOCK(&apps);
05491       return -1;
05492    }
05493 
05494    if (ast_string_field_init(tmp, 128)) {
05495       AST_RWLIST_UNLOCK(&apps);
05496       ast_free(tmp);
05497       return -1;
05498    }
05499 
05500 #ifdef AST_XML_DOCS
05501    /* Try to lookup the docs in our XML documentation database */
05502    if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
05503       /* load synopsis */
05504       tmpxml = ast_xmldoc_build_synopsis("application", app);
05505       ast_string_field_set(tmp, synopsis, tmpxml);
05506       ast_free(tmpxml);
05507 
05508       /* load description */
05509       tmpxml = ast_xmldoc_build_description("application", app);
05510       ast_string_field_set(tmp, description, tmpxml);
05511       ast_free(tmpxml);
05512 
05513       /* load syntax */
05514       tmpxml = ast_xmldoc_build_syntax("application", app);
05515       ast_string_field_set(tmp, syntax, tmpxml);
05516       ast_free(tmpxml);
05517 
05518       /* load arguments */
05519       tmpxml = ast_xmldoc_build_arguments("application", app);
05520       ast_string_field_set(tmp, arguments, tmpxml);
05521       ast_free(tmpxml);
05522 
05523       /* load seealso */
05524       tmpxml = ast_xmldoc_build_seealso("application", app);
05525       ast_string_field_set(tmp, seealso, tmpxml);
05526       ast_free(tmpxml);
05527       tmp->docsrc = AST_XML_DOC;
05528    } else {
05529 #endif
05530       ast_string_field_set(tmp, synopsis, synopsis);
05531       ast_string_field_set(tmp, description, description);
05532 #ifdef AST_XML_DOCS
05533       tmp->docsrc = AST_STATIC_DOC;
05534    }
05535 #endif
05536 
05537    strcpy(tmp->name, app);
05538    tmp->execute = execute;
05539    tmp->module = mod;
05540 
05541    /* Store in alphabetical order */
05542    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, cur, list) {
05543       if (strcasecmp(tmp->name, cur->name) < 0) {
05544          AST_RWLIST_INSERT_BEFORE_CURRENT(tmp, list);
05545          break;
05546       }
05547    }
05548    AST_RWLIST_TRAVERSE_SAFE_END;
05549    if (!cur)
05550       AST_RWLIST_INSERT_TAIL(&apps, tmp, list);
05551 
05552    ast_verb(2, "Registered application '%s'\n", term_color(tmps, tmp->name, COLOR_BRCYAN, 0, sizeof(tmps)));
05553 
05554    AST_RWLIST_UNLOCK(&apps);
05555 
05556    return 0;
05557 }
05558 
05559 /*
05560  * Append to the list. We don't have a tail pointer because we need
05561  * to scan the list anyways to check for duplicates during insertion.
05562  */
05563 int ast_register_switch(struct ast_switch *sw)
05564 {
05565    struct ast_switch *tmp;
05566 
05567    AST_RWLIST_WRLOCK(&switches);
05568    AST_RWLIST_TRAVERSE(&switches, tmp, list) {
05569       if (!strcasecmp(tmp->name, sw->name)) {
05570          AST_RWLIST_UNLOCK(&switches);
05571          ast_log(LOG_WARNING, "Switch '%s' already found\n", sw->name);
05572          return -1;
05573       }
05574    }
05575    AST_RWLIST_INSERT_TAIL(&switches, sw, list);
05576    AST_RWLIST_UNLOCK(&switches);
05577 
05578    return 0;
05579 }
05580 
05581 void ast_unregister_switch(struct ast_switch *sw)
05582 {
05583    AST_RWLIST_WRLOCK(&switches);
05584    AST_RWLIST_REMOVE(&switches, sw, list);
05585    AST_RWLIST_UNLOCK(&switches);
05586 }
05587 
05588 /*
05589  * Help for CLI commands ...
05590  */
05591 
05592 static void print_app_docs(struct ast_app *aa, int fd)
05593 {
05594    /* Maximum number of characters added by terminal coloring is 22 */
05595    char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], stxtitle[40], argtitle[40];
05596    char seealsotitle[40];
05597    char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *syntax = NULL, *arguments = NULL;
05598    char *seealso = NULL;
05599    int syntax_size, synopsis_size, description_size, arguments_size, seealso_size;
05600 
05601    snprintf(info, sizeof(info), "\n  -= Info about application '%s' =- \n\n", aa->name);
05602    term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle));
05603 
05604    term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
05605    term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
05606    term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
05607    term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
05608    term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40);
05609 
05610 #ifdef AST_XML_DOCS
05611    if (aa->docsrc == AST_XML_DOC) {
05612       description = ast_xmldoc_printable(S_OR(aa->description, "Not available"), 1);
05613       arguments = ast_xmldoc_printable(S_OR(aa->arguments, "Not available"), 1);
05614       synopsis = ast_xmldoc_printable(S_OR(aa->synopsis, "Not available"), 1);
05615       seealso = ast_xmldoc_printable(S_OR(aa->seealso, "Not available"), 1);
05616 
05617       if (!synopsis || !description || !arguments || !seealso) {
05618          goto return_cleanup;
05619       }
05620    } else
05621 #endif
05622    {
05623       synopsis_size = strlen(S_OR(aa->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
05624       synopsis = ast_malloc(synopsis_size);
05625 
05626       description_size = strlen(S_OR(aa->description, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
05627       description = ast_malloc(description_size);
05628 
05629       arguments_size = strlen(S_OR(aa->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
05630       arguments = ast_malloc(arguments_size);
05631 
05632       seealso_size = strlen(S_OR(aa->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
05633       seealso = ast_malloc(seealso_size);
05634 
05635       if (!synopsis || !description || !arguments || !seealso) {
05636          goto return_cleanup;
05637       }
05638 
05639       term_color(synopsis, S_OR(aa->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size);
05640       term_color(description, S_OR(aa->description, "Not available"),   COLOR_CYAN, 0, description_size);
05641       term_color(arguments, S_OR(aa->arguments, "Not available"), COLOR_CYAN, 0, arguments_size);
05642       term_color(seealso, S_OR(aa->seealso, "Not available"), COLOR_CYAN, 0, seealso_size);
05643    }
05644 
05645    /* Handle the syntax the same for both XML and raw docs */
05646    syntax_size = strlen(S_OR(aa->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
05647    if (!(syntax = ast_malloc(syntax_size))) {
05648       goto return_cleanup;
05649    }
05650    term_color(syntax, S_OR(aa->syntax, "Not available"), COLOR_CYAN, 0, syntax_size);
05651 
05652    ast_cli(fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n",
05653          infotitle, syntitle, synopsis, destitle, description,
05654          stxtitle, syntax, argtitle, arguments, seealsotitle, seealso);
05655 
05656 return_cleanup:
05657    ast_free(description);
05658    ast_free(arguments);
05659    ast_free(synopsis);
05660    ast_free(seealso);
05661    ast_free(syntax);
05662 }
05663 
05664 /*
05665  * \brief 'show application' CLI command implementation function...
05666  */
05667 static char *handle_show_application(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05668 {
05669    struct ast_app *aa;
05670    int app, no_registered_app = 1;
05671 
05672    switch (cmd) {
05673    case CLI_INIT:
05674       e->command = "core show application";
05675       e->usage =
05676          "Usage: core show application <application> [<application> [<application> [...]]]\n"
05677          "       Describes a particular application.\n";
05678       return NULL;
05679    case CLI_GENERATE:
05680       /*
05681        * There is a possibility to show informations about more than one
05682        * application at one time. You can type 'show application Dial Echo' and
05683        * you will see informations about these two applications ...
05684        */
05685       return ast_complete_applications(a->line, a->word, a->n);
05686    }
05687 
05688    if (a->argc < 4) {
05689       return CLI_SHOWUSAGE;
05690    }
05691 
05692    AST_RWLIST_RDLOCK(&apps);
05693    AST_RWLIST_TRAVERSE(&apps, aa, list) {
05694       /* Check for each app that was supplied as an argument */
05695       for (app = 3; app < a->argc; app++) {
05696          if (strcasecmp(aa->name, a->argv[app])) {
05697             continue;
05698          }
05699 
05700          /* We found it! */
05701          no_registered_app = 0;
05702 
05703          print_app_docs(aa, a->fd);
05704       }
05705    }
05706    AST_RWLIST_UNLOCK(&apps);
05707 
05708    /* we found at least one app? no? */
05709    if (no_registered_app) {
05710       ast_cli(a->fd, "Your application(s) is (are) not registered\n");
05711       return CLI_FAILURE;
05712    }
05713 
05714    return CLI_SUCCESS;
05715 }
05716 
05717 /*! \brief  handle_show_hints: CLI support for listing registered dial plan hints */
05718 static char *handle_show_hints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05719 {
05720    struct ast_hint *hint;
05721    int num = 0;
05722    int watchers;
05723    struct ast_state_cb *watcher;
05724 
05725    switch (cmd) {
05726    case CLI_INIT:
05727       e->command = "core show hints";
05728       e->usage =
05729          "Usage: core show hints\n"
05730          "       List registered hints\n";
05731       return NULL;
05732    case CLI_GENERATE:
05733       return NULL;
05734    }
05735 
05736    AST_RWLIST_RDLOCK(&hints);
05737    if (AST_RWLIST_EMPTY(&hints)) {
05738       ast_cli(a->fd, "There are no registered dialplan hints\n");
05739       AST_RWLIST_UNLOCK(&hints);
05740       return CLI_SUCCESS;
05741    }
05742    /* ... we have hints ... */
05743    ast_cli(a->fd, "\n    -= Registered Asterisk Dial Plan Hints =-\n");
05744    AST_RWLIST_TRAVERSE(&hints, hint, list) {
05745       watchers = 0;
05746       AST_LIST_TRAVERSE(&hint->callbacks, watcher, entry) {
05747          watchers++;
05748       }
05749       ast_cli(a->fd, "   %20s@%-20.20s: %-20.20s  State:%-15.15s Watchers %2d\n",
05750          ast_get_extension_name(hint->exten),
05751          ast_get_context_name(ast_get_extension_context(hint->exten)),
05752          ast_get_extension_app(hint->exten),
05753          ast_extension_state2str(hint->laststate), watchers);
05754       num++;
05755    }
05756    ast_cli(a->fd, "----------------\n");
05757    ast_cli(a->fd, "- %d hints registered\n", num);
05758    AST_RWLIST_UNLOCK(&hints);
05759    return CLI_SUCCESS;
05760 }
05761 
05762 /*! \brief autocomplete for CLI command 'core show hint' */
05763 static char *complete_core_show_hint(const char *line, const char *word, int pos, int state)
05764 {
05765    struct ast_hint *hint;
05766    char *ret = NULL;
05767    int which = 0;
05768    int wordlen;
05769 
05770    if (pos != 3)
05771       return NULL;
05772 
05773    wordlen = strlen(word);
05774 
05775    AST_RWLIST_RDLOCK(&hints);
05776    /* walk through all hints */
05777    AST_RWLIST_TRAVERSE(&hints, hint, list) {
05778       if (!strncasecmp(word, ast_get_extension_name(hint->exten), wordlen) && ++which > state) {
05779          ret = ast_strdup(ast_get_extension_name(hint->exten));
05780          break;
05781       }
05782    }
05783    AST_RWLIST_UNLOCK(&hints);
05784 
05785    return ret;
05786 }
05787 
05788 /*! \brief  handle_show_hint: CLI support for listing registered dial plan hint */
05789 static char *handle_show_hint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05790 {
05791    struct ast_hint *hint;
05792    int watchers;
05793    int num = 0, extenlen;
05794    struct ast_state_cb *watcher;
05795 
05796    switch (cmd) {
05797    case CLI_INIT:
05798       e->command = "core show hint";
05799       e->usage =
05800          "Usage: core show hint <exten>\n"
05801          "       List registered hint\n";
05802       return NULL;
05803    case CLI_GENERATE:
05804       return complete_core_show_hint(a->line, a->word, a->pos, a->n);
05805    }
05806 
05807    if (a->argc < 4)
05808       return CLI_SHOWUSAGE;
05809 
05810    AST_RWLIST_RDLOCK(&hints);
05811    if (AST_RWLIST_EMPTY(&hints)) {
05812       ast_cli(a->fd, "There are no registered dialplan hints\n");
05813       AST_RWLIST_UNLOCK(&hints);
05814       return CLI_SUCCESS;
05815    }
05816    extenlen = strlen(a->argv[3]);
05817    AST_RWLIST_TRAVERSE(&hints, hint, list) {
05818       if (!strncasecmp(ast_get_extension_name(hint->exten), a->argv[3], extenlen)) {
05819          watchers = 0;
05820          AST_LIST_TRAVERSE(&hint->callbacks, watcher, entry) {
05821             watchers++;
05822          }
05823          ast_cli(a->fd, "   %20s@%-20.20s: %-20.20s  State:%-15.15s Watchers %2d\n",
05824             ast_get_extension_name(hint->exten),
05825             ast_get_context_name(ast_get_extension_context(hint->exten)),
05826             ast_get_extension_app(hint->exten),
05827             ast_extension_state2str(hint->laststate), watchers);
05828          num++;
05829       }
05830    }
05831    AST_RWLIST_UNLOCK(&hints);
05832    if (!num)
05833       ast_cli(a->fd, "No hints matching extension %s\n", a->argv[3]);
05834    else
05835       ast_cli(a->fd, "%d hint%s matching extension %s\n", num, (num!=1 ? "s":""), a->argv[3]);
05836    return CLI_SUCCESS;
05837 }
05838 
05839 
05840 /*! \brief  handle_show_switches: CLI support for listing registered dial plan switches */
05841 static char *handle_show_switches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05842 {
05843    struct ast_switch *sw;
05844 
05845    switch (cmd) {
05846    case CLI_INIT:
05847       e->command = "core show switches";
05848       e->usage =
05849          "Usage: core show switches\n"
05850          "       List registered switches\n";
05851       return NULL;
05852    case CLI_GENERATE:
05853       return NULL;
05854    }
05855 
05856    AST_RWLIST_RDLOCK(&switches);
05857 
05858    if (AST_RWLIST_EMPTY(&switches)) {
05859       AST_RWLIST_UNLOCK(&switches);
05860       ast_cli(a->fd, "There are no registered alternative switches\n");
05861       return CLI_SUCCESS;
05862    }
05863 
05864    ast_cli(a->fd, "\n    -= Registered Asterisk Alternative Switches =-\n");
05865    AST_RWLIST_TRAVERSE(&switches, sw, list)
05866       ast_cli(a->fd, "%s: %s\n", sw->name, sw->description);
05867 
05868    AST_RWLIST_UNLOCK(&switches);
05869 
05870    return CLI_SUCCESS;
05871 }
05872 
05873 static char *handle_show_applications(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05874 {
05875    struct ast_app *aa;
05876    int like = 0, describing = 0;
05877    int total_match = 0;    /* Number of matches in like clause */
05878    int total_apps = 0;     /* Number of apps registered */
05879    static const char * const choices[] = { "like", "describing", NULL };
05880 
05881    switch (cmd) {
05882    case CLI_INIT:
05883       e->command = "core show applications [like|describing]";
05884       e->usage =
05885          "Usage: core show applications [{like|describing} <text>]\n"
05886          "       List applications which are currently available.\n"
05887          "       If 'like', <text> will be a substring of the app name\n"
05888          "       If 'describing', <text> will be a substring of the description\n";
05889       return NULL;
05890    case CLI_GENERATE:
05891       return (a->pos != 3) ? NULL : ast_cli_complete(a->word, choices, a->n);
05892    }
05893 
05894    AST_RWLIST_RDLOCK(&apps);
05895 
05896    if (AST_RWLIST_EMPTY(&apps)) {
05897       ast_cli(a->fd, "There are no registered applications\n");
05898       AST_RWLIST_UNLOCK(&apps);
05899       return CLI_SUCCESS;
05900    }
05901 
05902    /* core list applications like <keyword> */
05903    if ((a->argc == 5) && (!strcmp(a->argv[3], "like"))) {
05904       like = 1;
05905    } else if ((a->argc > 4) && (!strcmp(a->argv[3], "describing"))) {
05906       describing = 1;
05907    }
05908 
05909    /* core list applications describing <keyword1> [<keyword2>] [...] */
05910    if ((!like) && (!describing)) {
05911       ast_cli(a->fd, "    -= Registered Asterisk Applications =-\n");
05912    } else {
05913       ast_cli(a->fd, "    -= Matching Asterisk Applications =-\n");
05914    }
05915 
05916    AST_RWLIST_TRAVERSE(&apps, aa, list) {
05917       int printapp = 0;
05918       total_apps++;
05919       if (like) {
05920          if (strcasestr(aa->name, a->argv[4])) {
05921             printapp = 1;
05922             total_match++;
05923          }
05924       } else if (describing) {
05925          if (aa->description) {
05926             /* Match all words on command line */
05927             int i;
05928             printapp = 1;
05929             for (i = 4; i < a->argc; i++) {
05930                if (!strcasestr(aa->description, a->argv[i])) {
05931                   printapp = 0;
05932                } else {
05933                   total_match++;
05934                }
05935             }
05936          }
05937       } else {
05938          printapp = 1;
05939       }
05940 
05941       if (printapp) {
05942          ast_cli(a->fd,"  %20s: %s\n", aa->name, aa->synopsis ? aa->synopsis : "<Synopsis not available>");
05943       }
05944    }
05945    if ((!like) && (!describing)) {
05946       ast_cli(a->fd, "    -= %d Applications Registered =-\n",total_apps);
05947    } else {
05948       ast_cli(a->fd, "    -= %d Applications Matching =-\n",total_match);
05949    }
05950 
05951    AST_RWLIST_UNLOCK(&apps);
05952 
05953    return CLI_SUCCESS;
05954 }
05955 
05956 /*
05957  * 'show dialplan' CLI command implementation functions ...
05958  */
05959 static char *complete_show_dialplan_context(const char *line, const char *word, int pos,
05960    int state)
05961 {
05962    struct ast_context *c = NULL;
05963    char *ret = NULL;
05964    int which = 0;
05965    int wordlen;
05966 
05967    /* we are do completion of [exten@]context on second position only */
05968    if (pos != 2)
05969       return NULL;
05970 
05971    ast_rdlock_contexts();
05972 
05973    wordlen = strlen(word);
05974 
05975    /* walk through all contexts and return the n-th match */
05976    while ( (c = ast_walk_contexts(c)) ) {
05977       if (!strncasecmp(word, ast_get_context_name(c), wordlen) && ++which > state) {
05978          ret = ast_strdup(ast_get_context_name(c));
05979          break;
05980       }
05981    }
05982 
05983    ast_unlock_contexts();
05984 
05985    return ret;
05986 }
05987 
05988 /*! \brief Counters for the show dialplan manager command */
05989 struct dialplan_counters {
05990    int total_items;
05991    int total_context;
05992    int total_exten;
05993    int total_prio;
05994    int context_existence;
05995    int extension_existence;
05996 };
05997 
05998 /*! \brief helper function to print an extension */
05999 static void print_ext(struct ast_exten *e, char * buf, int buflen)
06000 {
06001    int prio = ast_get_extension_priority(e);
06002    if (prio == PRIORITY_HINT) {
06003       snprintf(buf, buflen, "hint: %s",
06004          ast_get_extension_app(e));
06005    } else {
06006       snprintf(buf, buflen, "%d. %s(%s)",
06007          prio, ast_get_extension_app(e),
06008          (!ast_strlen_zero(ast_get_extension_app_data(e)) ? (char *)ast_get_extension_app_data(e) : ""));
06009    }
06010 }
06011 
06012 /* XXX not verified */
06013 static int show_dialplan_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[])
06014 {
06015    struct ast_context *c = NULL;
06016    int res = 0, old_total_exten = dpc->total_exten;
06017 
06018    ast_rdlock_contexts();
06019 
06020    /* walk all contexts ... */
06021    while ( (c = ast_walk_contexts(c)) ) {
06022       struct ast_exten *e;
06023       struct ast_include *i;
06024       struct ast_ignorepat *ip;
06025       char buf[256], buf2[256];
06026       int context_info_printed = 0;
06027 
06028       if (context && strcmp(ast_get_context_name(c), context))
06029          continue;   /* skip this one, name doesn't match */
06030 
06031       dpc->context_existence = 1;
06032 
06033       ast_rdlock_context(c);
06034 
06035       /* are we looking for exten too? if yes, we print context
06036        * only if we find our extension.
06037        * Otherwise print context even if empty ?
06038        * XXX i am not sure how the rinclude is handled.
06039        * I think it ought to go inside.
06040        */
06041       if (!exten) {
06042          dpc->total_context++;
06043          ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
06044             ast_get_context_name(c), ast_get_context_registrar(c));
06045          context_info_printed = 1;
06046       }
06047 
06048       /* walk extensions ... */
06049       e = NULL;
06050       while ( (e = ast_walk_context_extensions(c, e)) ) {
06051          struct ast_exten *p;
06052 
06053          if (exten && !ast_extension_match(ast_get_extension_name(e), exten))
06054             continue;   /* skip, extension match failed */
06055 
06056          dpc->extension_existence = 1;
06057 
06058          /* may we print context info? */
06059          if (!context_info_printed) {
06060             dpc->total_context++;
06061             if (rinclude) { /* TODO Print more info about rinclude */
06062                ast_cli(fd, "[ Included context '%s' created by '%s' ]\n",
06063                   ast_get_context_name(c), ast_get_context_registrar(c));
06064             } else {
06065                ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
06066                   ast_get_context_name(c), ast_get_context_registrar(c));
06067             }
06068             context_info_printed = 1;
06069          }
06070          dpc->total_prio++;
06071 
06072          /* write extension name and first peer */
06073          if (e->matchcid)
06074             snprintf(buf, sizeof(buf), "'%s' (CID match '%s') => ", ast_get_extension_name(e), e->cidmatch);
06075          else
06076             snprintf(buf, sizeof(buf), "'%s' =>", ast_get_extension_name(e));
06077 
06078          print_ext(e, buf2, sizeof(buf2));
06079 
06080          ast_cli(fd, "  %-17s %-45s [%s]\n", buf, buf2,
06081             ast_get_extension_registrar(e));
06082 
06083          dpc->total_exten++;
06084          /* walk next extension peers */
06085          p = e;   /* skip the first one, we already got it */
06086          while ( (p = ast_walk_extension_priorities(e, p)) ) {
06087             const char *el = ast_get_extension_label(p);
06088             dpc->total_prio++;
06089             if (el)
06090                snprintf(buf, sizeof(buf), "   [%s]", el);
06091             else
06092                buf[0] = '\0';
06093             print_ext(p, buf2, sizeof(buf2));
06094 
06095             ast_cli(fd,"  %-17s %-45s [%s]\n", buf, buf2,
06096                ast_get_extension_registrar(p));
06097          }
06098       }
06099 
06100       /* walk included and write info ... */
06101       i = NULL;
06102       while ( (i = ast_walk_context_includes(c, i)) ) {
06103          snprintf(buf, sizeof(buf), "'%s'", ast_get_include_name(i));
06104          if (exten) {
06105             /* Check all includes for the requested extension */
06106             if (includecount >= AST_PBX_MAX_STACK) {
06107                ast_log(LOG_WARNING, "Maximum include depth exceeded!\n");
06108             } else {
06109                int dupe = 0;
06110                int x;
06111                for (x = 0; x < includecount; x++) {
06112                   if (!strcasecmp(includes[x], ast_get_include_name(i))) {
06113                      dupe++;
06114                      break;
06115                   }
06116                }
06117                if (!dupe) {
06118                   includes[includecount] = ast_get_include_name(i);
06119                   show_dialplan_helper(fd, ast_get_include_name(i), exten, dpc, i, includecount + 1, includes);
06120                } else {
06121                   ast_log(LOG_WARNING, "Avoiding circular include of %s within %s\n", ast_get_include_name(i), context);
06122                }
06123             }
06124          } else {
06125             ast_cli(fd, "  Include =>        %-45s [%s]\n",
06126                buf, ast_get_include_registrar(i));
06127          }
06128       }
06129 
06130       /* walk ignore patterns and write info ... */
06131       ip = NULL;
06132       while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
06133          const char *ipname = ast_get_ignorepat_name(ip);
06134          char ignorepat[AST_MAX_EXTENSION];
06135          snprintf(buf, sizeof(buf), "'%s'", ipname);
06136          snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
06137          if (!exten || ast_extension_match(ignorepat, exten)) {
06138             ast_cli(fd, "  Ignore pattern => %-45s [%s]\n",
06139                buf, ast_get_ignorepat_registrar(ip));
06140          }
06141       }
06142       if (!rinclude) {
06143          struct ast_sw *sw = NULL;
06144          while ( (sw = ast_walk_context_switches(c, sw)) ) {
06145             snprintf(buf, sizeof(buf), "'%s/%s'",
06146                ast_get_switch_name(sw),
06147                ast_get_switch_data(sw));
06148             ast_cli(fd, "  Alt. Switch =>    %-45s [%s]\n",
06149                buf, ast_get_switch_registrar(sw));
06150          }
06151       }
06152 
06153       ast_unlock_context(c);
06154 
06155       /* if we print something in context, make an empty line */
06156       if (context_info_printed)
06157          ast_cli(fd, "\n");
06158    }
06159    ast_unlock_contexts();
06160 
06161    return (dpc->total_exten == old_total_exten) ? -1 : res;
06162 }
06163 
06164 static int show_debug_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[])
06165 {
06166    struct ast_context *c = NULL;
06167    int res = 0, old_total_exten = dpc->total_exten;
06168 
06169    ast_cli(fd,"\n     In-mem exten Trie for Fast Extension Pattern Matching:\n\n");
06170 
06171    ast_cli(fd,"\n           Explanation: Node Contents Format = <char(s) to match>:<pattern?>:<specif>:[matched extension]\n");
06172    ast_cli(fd,    "                        Where <char(s) to match> is a set of chars, any one of which should match the current character\n");
06173    ast_cli(fd,    "                              <pattern?>: Y if this a pattern match (eg. _XZN[5-7]), N otherwise\n");
06174    ast_cli(fd,    "                              <specif>: an assigned 'exactness' number for this matching char. The lower the number, the more exact the match\n");
06175    ast_cli(fd,    "                              [matched exten]: If all chars matched to this point, which extension this matches. In form: EXTEN:<exten string>\n");
06176    ast_cli(fd,    "                        In general, you match a trie node to a string character, from left to right. All possible matching chars\n");
06177    ast_cli(fd,    "                        are in a string vertically, separated by an unbroken string of '+' characters.\n\n");
06178    ast_rdlock_contexts();
06179 
06180    /* walk all contexts ... */
06181    while ( (c = ast_walk_contexts(c)) ) {
06182       int context_info_printed = 0;
06183 
06184       if (context && strcmp(ast_get_context_name(c), context))
06185          continue;   /* skip this one, name doesn't match */
06186 
06187       dpc->context_existence = 1;
06188 
06189       if (!c->pattern_tree)
06190          ast_exists_extension(NULL, c->name, "s", 1, ""); /* do this to force the trie to built, if it is not already */
06191 
06192       ast_rdlock_context(c);
06193 
06194       dpc->total_context++;
06195       ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
06196          ast_get_context_name(c), ast_get_context_registrar(c));
06197       context_info_printed = 1;
06198 
06199       if (c->pattern_tree)
06200       {
06201          cli_match_char_tree(c->pattern_tree, " ", fd);
06202       } else {
06203          ast_cli(fd,"\n     No Pattern Trie present. Perhaps the context is empty...or there is trouble...\n\n");
06204       }
06205 
06206       ast_unlock_context(c);
06207 
06208       /* if we print something in context, make an empty line */
06209       if (context_info_printed)
06210          ast_cli(fd, "\n");
06211    }
06212    ast_unlock_contexts();
06213 
06214    return (dpc->total_exten == old_total_exten) ? -1 : res;
06215 }
06216 
06217 static char *handle_show_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06218 {
06219    char *exten = NULL, *context = NULL;
06220    /* Variables used for different counters */
06221    struct dialplan_counters counters;
06222    const char *incstack[AST_PBX_MAX_STACK];
06223 
06224    switch (cmd) {
06225    case CLI_INIT:
06226       e->command = "dialplan show";
06227       e->usage =
06228          "Usage: dialplan show [[exten@]context]\n"
06229          "       Show dialplan\n";
06230       return NULL;
06231    case CLI_GENERATE:
06232       return complete_show_dialplan_context(a->line, a->word, a->pos, a->n);
06233    }
06234 
06235    memset(&counters, 0, sizeof(counters));
06236 
06237    if (a->argc != 2 && a->argc != 3)
06238       return CLI_SHOWUSAGE;
06239 
06240    /* we obtain [exten@]context? if yes, split them ... */
06241    if (a->argc == 3) {
06242       if (strchr(a->argv[2], '@')) {   /* split into exten & context */
06243          context = ast_strdupa(a->argv[2]);
06244          exten = strsep(&context, "@");
06245          /* change empty strings to NULL */
06246          if (ast_strlen_zero(exten))
06247             exten = NULL;
06248       } else { /* no '@' char, only context given */
06249          context = ast_strdupa(a->argv[2]);
06250       }
06251       if (ast_strlen_zero(context))
06252          context = NULL;
06253    }
06254    /* else Show complete dial plan, context and exten are NULL */
06255    show_dialplan_helper(a->fd, context, exten, &counters, NULL, 0, incstack);
06256 
06257    /* check for input failure and throw some error messages */
06258    if (context && !counters.context_existence) {
06259       ast_cli(a->fd, "There is no existence of '%s' context\n", context);
06260       return CLI_FAILURE;
06261    }
06262 
06263    if (exten && !counters.extension_existence) {
06264       if (context)
06265          ast_cli(a->fd, "There is no existence of %s@%s extension\n",
06266             exten, context);
06267       else
06268          ast_cli(a->fd,
06269             "There is no existence of '%s' extension in all contexts\n",
06270             exten);
06271       return CLI_FAILURE;
06272    }
06273 
06274    ast_cli(a->fd,"-= %d %s (%d %s) in %d %s. =-\n",
06275             counters.total_exten, counters.total_exten == 1 ? "extension" : "extensions",
06276             counters.total_prio, counters.total_prio == 1 ? "priority" : "priorities",
06277             counters.total_context, counters.total_context == 1 ? "context" : "contexts");
06278 
06279    /* everything ok */
06280    return CLI_SUCCESS;
06281 }
06282 
06283 /*! \brief Send ack once */
06284 static char *handle_debug_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06285 {
06286    char *exten = NULL, *context = NULL;
06287    /* Variables used for different counters */
06288    struct dialplan_counters counters;
06289    const char *incstack[AST_PBX_MAX_STACK];
06290 
06291    switch (cmd) {
06292    case CLI_INIT:
06293       e->command = "dialplan debug";
06294       e->usage =
06295          "Usage: dialplan debug [context]\n"
06296          "       Show dialplan context Trie(s). Usually only useful to folks debugging the deep internals of the fast pattern matcher\n";
06297       return NULL;
06298    case CLI_GENERATE:
06299       return complete_show_dialplan_context(a->line, a->word, a->pos, a->n);
06300    }
06301 
06302    memset(&counters, 0, sizeof(counters));
06303 
06304    if (a->argc != 2 && a->argc != 3)
06305       return CLI_SHOWUSAGE;
06306 
06307    /* we obtain [exten@]context? if yes, split them ... */
06308    /* note: we ignore the exten totally here .... */
06309    if (a->argc == 3) {
06310       if (strchr(a->argv[2], '@')) {   /* split into exten & context */
06311          context = ast_strdupa(a->argv[2]);
06312          exten = strsep(&context, "@");
06313          /* change empty strings to NULL */
06314          if (ast_strlen_zero(exten))
06315             exten = NULL;
06316       } else { /* no '@' char, only context given */
06317          context = ast_strdupa(a->argv[2]);
06318       }
06319       if (ast_strlen_zero(context))
06320          context = NULL;
06321    }
06322    /* else Show complete dial plan, context and exten are NULL */
06323    show_debug_helper(a->fd, context, exten, &counters, NULL, 0, incstack);
06324 
06325    /* check for input failure and throw some error messages */
06326    if (context && !counters.context_existence) {
06327       ast_cli(a->fd, "There is no existence of '%s' context\n", context);
06328       return CLI_FAILURE;
06329    }
06330 
06331 
06332    ast_cli(a->fd,"-= %d %s. =-\n",
06333          counters.total_context, counters.total_context == 1 ? "context" : "contexts");
06334 
06335    /* everything ok */
06336    return CLI_SUCCESS;
06337 }
06338 
06339 /*! \brief Send ack once */
06340 static void manager_dpsendack(struct mansession *s, const struct message *m)
06341 {
06342    astman_send_listack(s, m, "DialPlan list will follow", "start");
06343 }
06344 
06345 /*! \brief Show dialplan extensions
06346  * XXX this function is similar but not exactly the same as the CLI's
06347  * show dialplan. Must check whether the difference is intentional or not.
06348  */
06349 static int manager_show_dialplan_helper(struct mansession *s, const struct message *m,
06350                const char *actionidtext, const char *context,
06351                const char *exten, struct dialplan_counters *dpc,
06352                struct ast_include *rinclude)
06353 {
06354    struct ast_context *c;
06355    int res = 0, old_total_exten = dpc->total_exten;
06356 
06357    if (ast_strlen_zero(exten))
06358       exten = NULL;
06359    if (ast_strlen_zero(context))
06360       context = NULL;
06361 
06362    ast_debug(3, "manager_show_dialplan: Context: -%s- Extension: -%s-\n", context, exten);
06363 
06364    /* try to lock contexts */
06365    if (ast_rdlock_contexts()) {
06366       astman_send_error(s, m, "Failed to lock contexts");
06367       ast_log(LOG_WARNING, "Failed to lock contexts list for manager: listdialplan\n");
06368       return -1;
06369    }
06370 
06371    c = NULL;      /* walk all contexts ... */
06372    while ( (c = ast_walk_contexts(c)) ) {
06373       struct ast_exten *e;
06374       struct ast_include *i;
06375       struct ast_ignorepat *ip;
06376 
06377       if (context && strcmp(ast_get_context_name(c), context) != 0)
06378          continue;   /* not the name we want */
06379 
06380       dpc->context_existence = 1;
06381 
06382       ast_debug(3, "manager_show_dialplan: Found Context: %s \n", ast_get_context_name(c));
06383 
06384       if (ast_rdlock_context(c)) {  /* failed to lock */
06385          ast_debug(3, "manager_show_dialplan: Failed to lock context\n");
06386          continue;
06387       }
06388 
06389       /* XXX note- an empty context is not printed */
06390       e = NULL;      /* walk extensions in context  */
06391       while ( (e = ast_walk_context_extensions(c, e)) ) {
06392          struct ast_exten *p;
06393 
06394          /* looking for extension? is this our extension? */
06395          if (exten && !ast_extension_match(ast_get_extension_name(e), exten)) {
06396             /* not the one we are looking for, continue */
06397             ast_debug(3, "manager_show_dialplan: Skipping extension %s\n", ast_get_extension_name(e));
06398             continue;
06399          }
06400          ast_debug(3, "manager_show_dialplan: Found Extension: %s \n", ast_get_extension_name(e));
06401 
06402          dpc->extension_existence = 1;
06403 
06404          /* may we print context info? */
06405          dpc->total_context++;
06406          dpc->total_exten++;
06407 
06408          p = NULL;      /* walk next extension peers */
06409          while ( (p = ast_walk_extension_priorities(e, p)) ) {
06410             int prio = ast_get_extension_priority(p);
06411 
06412             dpc->total_prio++;
06413             if (!dpc->total_items++)
06414                manager_dpsendack(s, m);
06415             astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
06416             astman_append(s, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c), ast_get_extension_name(e) );
06417 
06418             /* XXX maybe make this conditional, if p != e ? */
06419             if (ast_get_extension_label(p))
06420                astman_append(s, "ExtensionLabel: %s\r\n", ast_get_extension_label(p));
06421 
06422             if (prio == PRIORITY_HINT) {
06423                astman_append(s, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(p));
06424             } else {
06425                astman_append(s, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio, ast_get_extension_app(p), (char *) ast_get_extension_app_data(p));
06426             }
06427             astman_append(s, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e));
06428          }
06429       }
06430 
06431       i = NULL;      /* walk included and write info ... */
06432       while ( (i = ast_walk_context_includes(c, i)) ) {
06433          if (exten) {
06434             /* Check all includes for the requested extension */
06435             manager_show_dialplan_helper(s, m, actionidtext, ast_get_include_name(i), exten, dpc, i);
06436          } else {
06437             if (!dpc->total_items++)
06438                manager_dpsendack(s, m);
06439             astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
06440             astman_append(s, "Context: %s\r\nIncludeContext: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_include_name(i), ast_get_include_registrar(i));
06441             astman_append(s, "\r\n");
06442             ast_debug(3, "manager_show_dialplan: Found Included context: %s \n", ast_get_include_name(i));
06443          }
06444       }
06445 
06446       ip = NULL;  /* walk ignore patterns and write info ... */
06447       while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
06448          const char *ipname = ast_get_ignorepat_name(ip);
06449          char ignorepat[AST_MAX_EXTENSION];
06450 
06451          snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
06452          if (!exten || ast_extension_match(ignorepat, exten)) {
06453             if (!dpc->total_items++)
06454                manager_dpsendack(s, m);
06455             astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
06456             astman_append(s, "Context: %s\r\nIgnorePattern: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ipname, ast_get_ignorepat_registrar(ip));
06457             astman_append(s, "\r\n");
06458          }
06459       }
06460       if (!rinclude) {
06461          struct ast_sw *sw = NULL;
06462          while ( (sw = ast_walk_context_switches(c, sw)) ) {
06463             if (!dpc->total_items++)
06464                manager_dpsendack(s, m);
06465             astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
06466             astman_append(s, "Context: %s\r\nSwitch: %s/%s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_registrar(sw));  
06467             astman_append(s, "\r\n");
06468             ast_debug(3, "manager_show_dialplan: Found Switch : %s \n", ast_get_switch_name(sw));
06469          }
06470       }
06471 
06472       ast_unlock_context(c);
06473    }
06474    ast_unlock_contexts();
06475 
06476    if (dpc->total_exten == old_total_exten) {
06477       ast_debug(3, "manager_show_dialplan: Found nothing new\n");
06478       /* Nothing new under the sun */
06479       return -1;
06480    } else {
06481       return res;
06482    }
06483 }
06484 
06485 /*! \brief  Manager listing of dial plan */
06486 static int manager_show_dialplan(struct mansession *s, const struct message *m)
06487 {
06488    const char *exten, *context;
06489    const char *id = astman_get_header(m, "ActionID");
06490    char idtext[256];
06491    int res;
06492 
06493    /* Variables used for different counters */
06494    struct dialplan_counters counters;
06495 
06496    if (!ast_strlen_zero(id))
06497       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06498    else
06499       idtext[0] = '\0';
06500 
06501    memset(&counters, 0, sizeof(counters));
06502 
06503    exten = astman_get_header(m, "Extension");
06504    context = astman_get_header(m, "Context");
06505 
06506    res = manager_show_dialplan_helper(s, m, idtext, context, exten, &counters, NULL);
06507 
06508    if (context && !counters.context_existence) {
06509       char errorbuf[BUFSIZ];
06510 
06511       snprintf(errorbuf, sizeof(errorbuf), "Did not find context %s", context);
06512       astman_send_error(s, m, errorbuf);
06513       return 0;
06514    }
06515    if (exten && !counters.extension_existence) {
06516       char errorbuf[BUFSIZ];
06517 
06518       if (context)
06519          snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s@%s", exten, context);
06520       else
06521          snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s in any context", exten);
06522       astman_send_error(s, m, errorbuf);
06523       return 0;
06524    }
06525 
06526    astman_append(s, "Event: ShowDialPlanComplete\r\n"
06527       "EventList: Complete\r\n"
06528       "ListItems: %d\r\n"
06529       "ListExtensions: %d\r\n"
06530       "ListPriorities: %d\r\n"
06531       "ListContexts: %d\r\n"
06532       "%s"
06533       "\r\n", counters.total_items, counters.total_exten, counters.total_prio, counters.total_context, idtext);
06534 
06535    /* everything ok */
06536    return 0;
06537 }
06538 
06539 /*! \brief CLI support for listing global variables in a parseable way */
06540 static char *handle_show_globals(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06541 {
06542    int i = 0;
06543    struct ast_var_t *newvariable;
06544 
06545    switch (cmd) {
06546    case CLI_INIT:
06547       e->command = "dialplan show globals";
06548       e->usage =
06549          "Usage: dialplan show globals\n"
06550          "       List current global dialplan variables and their values\n";
06551       return NULL;
06552    case CLI_GENERATE:
06553       return NULL;
06554    }
06555 
06556    ast_rwlock_rdlock(&globalslock);
06557    AST_LIST_TRAVERSE (&globals, newvariable, entries) {
06558       i++;
06559       ast_cli(a->fd, "   %s=%s\n", ast_var_name(newvariable), ast_var_value(newvariable));
06560    }
06561    ast_rwlock_unlock(&globalslock);
06562    ast_cli(a->fd, "\n    -- %d variable(s)\n", i);
06563 
06564    return CLI_SUCCESS;
06565 }
06566 
06567 #ifdef AST_DEVMODE
06568 static char *handle_show_device2extenstate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06569 {
06570    struct ast_devstate_aggregate agg;
06571    int i, j, exten, combined;
06572 
06573    switch (cmd) {
06574    case CLI_INIT:
06575       e->command = "core show device2extenstate";
06576       e->usage =
06577          "Usage: core show device2extenstate\n"
06578          "       Lists device state to extension state combinations.\n";
06579    case CLI_GENERATE:
06580       return NULL;
06581    }
06582    for (i = 0; i < AST_DEVICE_TOTAL; i++) {
06583       for (j = 0; j < AST_DEVICE_TOTAL; j++) {
06584          ast_devstate_aggregate_init(&agg);
06585          ast_devstate_aggregate_add(&agg, i);
06586          ast_devstate_aggregate_add(&agg, j);
06587          combined = ast_devstate_aggregate_result(&agg);
06588          exten = ast_devstate_to_extenstate(combined);
06589          ast_cli(a->fd, "\n Exten:%14s  CombinedDevice:%12s  Dev1:%12s  Dev2:%12s", ast_extension_state2str(exten), ast_devstate_str(combined), ast_devstate_str(j), ast_devstate_str(i));
06590       }
06591    }
06592    ast_cli(a->fd, "\n");
06593    return CLI_SUCCESS;
06594 }
06595 #endif
06596 
06597 /*! \brief CLI support for listing chanvar's variables in a parseable way */
06598 static char *handle_show_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06599 {
06600    struct ast_channel *chan = NULL;
06601    struct ast_str *vars = ast_str_alloca(BUFSIZ * 4); /* XXX large because we might have lots of channel vars */
06602 
06603    switch (cmd) {
06604    case CLI_INIT:
06605       e->command = "dialplan show chanvar";
06606       e->usage =
06607          "Usage: dialplan show chanvar <channel>\n"
06608          "       List current channel variables and their values\n";
06609       return NULL;
06610    case CLI_GENERATE:
06611       return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
06612    }
06613 
06614    if (a->argc != e->args + 1)
06615       return CLI_SHOWUSAGE;
06616 
06617    if (!(chan = ast_channel_get_by_name(a->argv[e->args]))) {
06618       ast_cli(a->fd, "Channel '%s' not found\n", a->argv[e->args]);
06619       return CLI_FAILURE;
06620    }
06621 
06622    pbx_builtin_serialize_variables(chan, &vars);
06623 
06624    if (ast_str_strlen(vars)) {
06625       ast_cli(a->fd, "\nVariables for channel %s:\n%s\n", a->argv[e->args], ast_str_buffer(vars));
06626    }
06627 
06628    chan = ast_channel_unref(chan);
06629 
06630    return CLI_SUCCESS;
06631 }
06632 
06633 static char *handle_set_global(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06634 {
06635    switch (cmd) {
06636    case CLI_INIT:
06637       e->command = "dialplan set global";
06638       e->usage =
06639          "Usage: dialplan set global <name> <value>\n"
06640          "       Set global dialplan variable <name> to <value>\n";
06641       return NULL;
06642    case CLI_GENERATE:
06643       return NULL;
06644    }
06645 
06646    if (a->argc != e->args + 2)
06647       return CLI_SHOWUSAGE;
06648 
06649    pbx_builtin_setvar_helper(NULL, a->argv[3], a->argv[4]);
06650    ast_cli(a->fd, "\n    -- Global variable '%s' set to '%s'\n", a->argv[3], a->argv[4]);
06651 
06652    return CLI_SUCCESS;
06653 }
06654 
06655 static char *handle_set_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06656 {
06657    struct ast_channel *chan;
06658    const char *chan_name, *var_name, *var_value;
06659 
06660    switch (cmd) {
06661    case CLI_INIT:
06662       e->command = "dialplan set chanvar";
06663       e->usage =
06664          "Usage: dialplan set chanvar <channel> <varname> <value>\n"
06665          "       Set channel variable <varname> to <value>\n";
06666       return NULL;
06667    case CLI_GENERATE:
06668       return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
06669    }
06670 
06671    if (a->argc != e->args + 3)
06672       return CLI_SHOWUSAGE;
06673 
06674    chan_name = a->argv[e->args];
06675    var_name = a->argv[e->args + 1];
06676    var_value = a->argv[e->args + 2];
06677 
06678    if (!(chan = ast_channel_get_by_name(chan_name))) {
06679       ast_cli(a->fd, "Channel '%s' not found\n", chan_name);
06680       return CLI_FAILURE;
06681    }
06682 
06683    pbx_builtin_setvar_helper(chan, var_name, var_value);
06684 
06685    chan = ast_channel_unref(chan);
06686 
06687    ast_cli(a->fd, "\n    -- Channel variable '%s' set to '%s' for '%s'\n",  var_name, var_value, chan_name);
06688 
06689    return CLI_SUCCESS;
06690 }
06691 
06692 static char *handle_set_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06693 {
06694    int oldval = 0;
06695 
06696    switch (cmd) {
06697    case CLI_INIT:
06698       e->command = "dialplan set extenpatternmatchnew true";
06699       e->usage =
06700          "Usage: dialplan set extenpatternmatchnew true|false\n"
06701          "       Use the NEW extension pattern matching algorithm, true or false.\n";
06702       return NULL;
06703    case CLI_GENERATE:
06704       return NULL;
06705    }
06706 
06707    if (a->argc != 4)
06708       return CLI_SHOWUSAGE;
06709 
06710    oldval =  pbx_set_extenpatternmatchnew(1);
06711 
06712    if (oldval)
06713       ast_cli(a->fd, "\n    -- Still using the NEW pattern match algorithm for extension names in the dialplan.\n");
06714    else
06715       ast_cli(a->fd, "\n    -- Switched to using the NEW pattern match algorithm for extension names in the dialplan.\n");
06716 
06717    return CLI_SUCCESS;
06718 }
06719 
06720 static char *handle_unset_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06721 {
06722    int oldval = 0;
06723 
06724    switch (cmd) {
06725    case CLI_INIT:
06726       e->command = "dialplan set extenpatternmatchnew false";
06727       e->usage =
06728          "Usage: dialplan set extenpatternmatchnew true|false\n"
06729          "       Use the NEW extension pattern matching algorithm, true or false.\n";
06730       return NULL;
06731    case CLI_GENERATE:
06732       return NULL;
06733    }
06734 
06735    if (a->argc != 4)
06736       return CLI_SHOWUSAGE;
06737 
06738    oldval =  pbx_set_extenpatternmatchnew(0);
06739 
06740    if (!oldval)
06741       ast_cli(a->fd, "\n    -- Still using the OLD pattern match algorithm for extension names in the dialplan.\n");
06742    else
06743       ast_cli(a->fd, "\n    -- Switched to using the OLD pattern match algorithm for extension names in the dialplan.\n");
06744 
06745    return CLI_SUCCESS;
06746 }
06747 
06748 /*
06749  * CLI entries for upper commands ...
06750  */
06751 static struct ast_cli_entry pbx_cli[] = {
06752    AST_CLI_DEFINE(handle_show_applications, "Shows registered dialplan applications"),
06753    AST_CLI_DEFINE(handle_show_functions, "Shows registered dialplan functions"),
06754    AST_CLI_DEFINE(handle_show_switches, "Show alternative switches"),
06755    AST_CLI_DEFINE(handle_show_hints, "Show dialplan hints"),
06756    AST_CLI_DEFINE(handle_show_hint, "Show dialplan hint"),
06757    AST_CLI_DEFINE(handle_show_globals, "Show global dialplan variables"),
06758 #ifdef AST_DEVMODE
06759    AST_CLI_DEFINE(handle_show_device2extenstate, "Show expected exten state from multiple device states"),
06760 #endif
06761    AST_CLI_DEFINE(handle_show_chanvar, "Show channel variables"),
06762    AST_CLI_DEFINE(handle_show_function, "Describe a specific dialplan function"),
06763    AST_CLI_DEFINE(handle_show_application, "Describe a specific dialplan application"),
06764    AST_CLI_DEFINE(handle_set_global, "Set global dialplan variable"),
06765    AST_CLI_DEFINE(handle_set_chanvar, "Set a channel variable"),
06766    AST_CLI_DEFINE(handle_show_dialplan, "Show dialplan"),
06767    AST_CLI_DEFINE(handle_debug_dialplan, "Show fast extension pattern matching data structures"),
06768    AST_CLI_DEFINE(handle_unset_extenpatternmatchnew, "Use the Old extension pattern matching algorithm."),
06769    AST_CLI_DEFINE(handle_set_extenpatternmatchnew, "Use the New extension pattern matching algorithm."),
06770 };
06771 
06772 static void unreference_cached_app(struct ast_app *app)
06773 {
06774    struct ast_context *context = NULL;
06775    struct ast_exten *eroot = NULL, *e = NULL;
06776 
06777    ast_rdlock_contexts();
06778    while ((context = ast_walk_contexts(context))) {
06779       while ((eroot = ast_walk_context_extensions(context, eroot))) {
06780          while ((e = ast_walk_extension_priorities(eroot, e))) {
06781             if (e->cached_app == app)
06782                e->cached_app = NULL;
06783          }
06784       }
06785    }
06786    ast_unlock_contexts();
06787 
06788    return;
06789 }
06790 
06791 int ast_unregister_application(const char *app)
06792 {
06793    struct ast_app *tmp;
06794 
06795    AST_RWLIST_WRLOCK(&apps);
06796    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, tmp, list) {
06797       if (!strcasecmp(app, tmp->name)) {
06798          unreference_cached_app(tmp);
06799          AST_RWLIST_REMOVE_CURRENT(list);
06800          ast_verb(2, "Unregistered application '%s'\n", tmp->name);
06801          ast_string_field_free_memory(tmp);
06802          ast_free(tmp);
06803          break;
06804       }
06805    }
06806    AST_RWLIST_TRAVERSE_SAFE_END;
06807    AST_RWLIST_UNLOCK(&apps);
06808 
06809    return tmp ? 0 : -1;
06810 }
06811 
06812 struct ast_context *ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar)
06813 {
06814    struct ast_context *tmp, **local_contexts;
06815    struct fake_context search;
06816    int length = sizeof(struct ast_context) + strlen(name) + 1;
06817 
06818    if (!contexts_table) {
06819       contexts_table = ast_hashtab_create(17,
06820                                  ast_hashtab_compare_contexts,
06821                                  ast_hashtab_resize_java,
06822                                  ast_hashtab_newsize_java,
06823                                  ast_hashtab_hash_contexts,
06824                                  0);
06825    }
06826 
06827    ast_copy_string(search.name, name, sizeof(search.name));
06828    if (!extcontexts) {
06829       ast_rdlock_contexts();
06830       local_contexts = &contexts;
06831       tmp = ast_hashtab_lookup(contexts_table, &search);
06832       ast_unlock_contexts();
06833       if (tmp) {
06834          tmp->refcount++;
06835          return tmp;
06836       }
06837    } else { /* local contexts just in a linked list; search there for the new context; slow, linear search, but not frequent */
06838       local_contexts = extcontexts;
06839       tmp = ast_hashtab_lookup(exttable, &search);
06840       if (tmp) {
06841          tmp->refcount++;
06842          return tmp;
06843       }
06844    }
06845 
06846    if ((tmp = ast_calloc(1, length))) {
06847       ast_rwlock_init(&tmp->lock);
06848       ast_mutex_init(&tmp->macrolock);
06849       strcpy(tmp->name, name);
06850       tmp->root = NULL;
06851       tmp->root_table = NULL;
06852       tmp->registrar = ast_strdup(registrar);
06853       tmp->includes = NULL;
06854       tmp->ignorepats = NULL;
06855       tmp->refcount = 1;
06856    } else {
06857       ast_log(LOG_ERROR, "Danger! We failed to allocate a context for %s!\n", name);
06858       return NULL;
06859    }
06860 
06861    if (!extcontexts) {
06862       ast_wrlock_contexts();
06863       tmp->next = *local_contexts;
06864       *local_contexts = tmp;
06865       ast_hashtab_insert_safe(contexts_table, tmp); /*put this context into the tree */
06866       ast_unlock_contexts();
06867       ast_debug(1, "Registered context '%s'(%p) in table %p registrar: %s\n", tmp->name, tmp, contexts_table, registrar);
06868       ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar);
06869    } else {
06870       tmp->next = *local_contexts;
06871       if (exttable)
06872          ast_hashtab_insert_immediate(exttable, tmp); /*put this context into the tree */
06873 
06874       *local_contexts = tmp;
06875       ast_debug(1, "Registered context '%s'(%p) in local table %p; registrar: %s\n", tmp->name, tmp, exttable, registrar);
06876       ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar);
06877    }
06878    return tmp;
06879 }
06880 
06881 void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar);
06882 
06883 struct store_hint {
06884    char *context;
06885    char *exten;
06886    AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks;
06887    int laststate;
06888    AST_LIST_ENTRY(store_hint) list;
06889    char data[1];
06890 };
06891 
06892 AST_LIST_HEAD(store_hints, store_hint);
06893 
06894 static void context_merge_incls_swits_igps_other_registrars(struct ast_context *new, struct ast_context *old, const char *registrar)
06895 {
06896    struct ast_include *i;
06897    struct ast_ignorepat *ip;
06898    struct ast_sw *sw;
06899 
06900    ast_verb(3, "merging incls/swits/igpats from old(%s) to new(%s) context, registrar = %s\n", ast_get_context_name(old), ast_get_context_name(new), registrar);
06901    /* copy in the includes, switches, and ignorepats */
06902    /* walk through includes */
06903    for (i = NULL; (i = ast_walk_context_includes(old, i)) ; ) {
06904       if (strcmp(ast_get_include_registrar(i), registrar) == 0)
06905          continue; /* not mine */
06906       ast_context_add_include2(new, ast_get_include_name(i), ast_get_include_registrar(i));
06907    }
06908 
06909    /* walk through switches */
06910    for (sw = NULL; (sw = ast_walk_context_switches(old, sw)) ; ) {
06911       if (strcmp(ast_get_switch_registrar(sw), registrar) == 0)
06912          continue; /* not mine */
06913       ast_context_add_switch2(new, ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_eval(sw), ast_get_switch_registrar(sw));
06914    }
06915 
06916    /* walk thru ignorepats ... */
06917    for (ip = NULL; (ip = ast_walk_context_ignorepats(old, ip)); ) {
06918       if (strcmp(ast_get_ignorepat_registrar(ip), registrar) == 0)
06919          continue; /* not mine */
06920       ast_context_add_ignorepat2(new, ast_get_ignorepat_name(ip), ast_get_ignorepat_registrar(ip));
06921    }
06922 }
06923 
06924 
06925 /* the purpose of this routine is to duplicate a context, with all its substructure,
06926    except for any extens that have a matching registrar */
06927 static void context_merge(struct ast_context **extcontexts, struct ast_hashtab *exttable, struct ast_context *context, const char *registrar)
06928 {
06929    struct ast_context *new = ast_hashtab_lookup(exttable, context); /* is there a match in the new set? */
06930    struct ast_exten *exten_item, *prio_item, *new_exten_item, *new_prio_item;
06931    struct ast_hashtab_iter *exten_iter;
06932    struct ast_hashtab_iter *prio_iter;
06933    int insert_count = 0;
06934    int first = 1;
06935 
06936    /* We'll traverse all the extensions/prios, and see which are not registrar'd with
06937       the current registrar, and copy them to the new context. If the new context does not
06938       exist, we'll create it "on demand". If no items are in this context to copy, then we'll
06939       only create the empty matching context if the old one meets the criteria */
06940 
06941    if (context->root_table) {
06942       exten_iter = ast_hashtab_start_traversal(context->root_table);
06943       while ((exten_item=ast_hashtab_next(exten_iter))) {
06944          if (new) {
06945             new_exten_item = ast_hashtab_lookup(new->root_table, exten_item);
06946          } else {
06947             new_exten_item = NULL;
06948          }
06949          prio_iter = ast_hashtab_start_traversal(exten_item->peer_table);
06950          while ((prio_item=ast_hashtab_next(prio_iter))) {
06951             int res1;
06952             char *dupdstr;
06953 
06954             if (new_exten_item) {
06955                new_prio_item = ast_hashtab_lookup(new_exten_item->peer_table, prio_item);
06956             } else {
06957                new_prio_item = NULL;
06958             }
06959             if (strcmp(prio_item->registrar,registrar) == 0) {
06960                continue;
06961             }
06962             /* make sure the new context exists, so we have somewhere to stick this exten/prio */
06963             if (!new) {
06964                new = ast_context_find_or_create(extcontexts, exttable, context->name, prio_item->registrar); /* a new context created via priority from a different context in the old dialplan, gets its registrar from the prio's registrar */
06965             }
06966 
06967             /* copy in the includes, switches, and ignorepats */
06968             if (first) { /* but, only need to do this once */
06969                context_merge_incls_swits_igps_other_registrars(new, context, registrar);
06970                first = 0;
06971             }
06972 
06973             if (!new) {
06974                ast_log(LOG_ERROR,"Could not allocate a new context for %s in merge_and_delete! Danger!\n", context->name);
06975                return; /* no sense continuing. */
06976             }
06977             /* we will not replace existing entries in the new context with stuff from the old context.
06978                but, if this is because of some sort of registrar conflict, we ought to say something... */
06979 
06980             dupdstr = ast_strdup(prio_item->data);
06981 
06982             res1 = ast_add_extension2(new, 0, prio_item->exten, prio_item->priority, prio_item->label, 
06983                                 prio_item->matchcid ? prio_item->cidmatch : NULL, prio_item->app, dupdstr, prio_item->datad, prio_item->registrar);
06984             if (!res1 && new_exten_item && new_prio_item){
06985                ast_verb(3,"Dropping old dialplan item %s/%s/%d [%s(%s)] (registrar=%s) due to conflict with new dialplan\n",
06986                      context->name, prio_item->exten, prio_item->priority, prio_item->app, (char*)prio_item->data, prio_item->registrar);
06987             } else {
06988                /* we do NOT pass the priority data from the old to the new -- we pass a copy of it, so no changes to the current dialplan take place,
06989                 and no double frees take place, either! */
06990                insert_count++;
06991             }
06992          }
06993          ast_hashtab_end_traversal(prio_iter);
06994       }
06995       ast_hashtab_end_traversal(exten_iter);
06996    }
06997 
06998    if (!insert_count && !new && (strcmp(context->registrar, registrar) != 0 ||
06999         (strcmp(context->registrar, registrar) == 0 && context->refcount > 1))) {
07000       /* we could have given it the registrar of the other module who incremented the refcount,
07001          but that's not available, so we give it the registrar we know about */
07002       new = ast_context_find_or_create(extcontexts, exttable, context->name, context->registrar);
07003 
07004       /* copy in the includes, switches, and ignorepats */
07005       context_merge_incls_swits_igps_other_registrars(new, context, registrar);
07006    }
07007 }
07008 
07009 
07010 /* XXX this does not check that multiple contexts are merged */
07011 void ast_merge_contexts_and_delete(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *registrar)
07012 {
07013    double ft;
07014    struct ast_context *tmp, *oldcontextslist;
07015    struct ast_hashtab *oldtable;
07016    struct store_hints store = AST_LIST_HEAD_INIT_VALUE;
07017    struct store_hint *this;
07018    struct ast_hint *hint;
07019    struct ast_exten *exten;
07020    int length;
07021    struct ast_state_cb *thiscb;
07022    struct ast_hashtab_iter *iter;
07023 
07024    /* it is very important that this function hold the hint list lock _and_ the conlock
07025       during its operation; not only do we need to ensure that the list of contexts
07026       and extensions does not change, but also that no hint callbacks (watchers) are
07027       added or removed during the merge/delete process
07028 
07029       in addition, the locks _must_ be taken in this order, because there are already
07030       other code paths that use this order
07031    */
07032 
07033    struct timeval begintime, writelocktime, endlocktime, enddeltime;
07034 
07035    begintime = ast_tvnow();
07036    ast_rdlock_contexts();
07037    iter = ast_hashtab_start_traversal(contexts_table);
07038    while ((tmp = ast_hashtab_next(iter))) {
07039       context_merge(extcontexts, exttable, tmp, registrar);
07040    }
07041    ast_hashtab_end_traversal(iter);
07042 
07043    AST_RWLIST_WRLOCK(&hints);
07044    writelocktime = ast_tvnow();
07045 
07046    /* preserve all watchers for hints */
07047    AST_RWLIST_TRAVERSE(&hints, hint, list) {
07048       if (!AST_LIST_EMPTY(&hint->callbacks)) {
07049          length = strlen(hint->exten->exten) + strlen(hint->exten->parent->name) + 2 + sizeof(*this);
07050          if (!(this = ast_calloc(1, length)))
07051             continue;
07052          /* this removes all the callbacks from the hint into this. */
07053          AST_LIST_APPEND_LIST(&this->callbacks, &hint->callbacks, entry);
07054          this->laststate = hint->laststate;
07055          this->context = this->data;
07056          strcpy(this->data, hint->exten->parent->name);
07057          this->exten = this->data + strlen(this->context) + 1;
07058          strcpy(this->exten, hint->exten->exten);
07059          AST_LIST_INSERT_HEAD(&store, this, list);
07060       }
07061    }
07062 
07063    /* save the old table and list */
07064    oldtable = contexts_table;
07065    oldcontextslist = contexts;
07066 
07067    /* move in the new table and list */
07068    contexts_table = exttable;
07069    contexts = *extcontexts;
07070 
07071    /* restore the watchers for hints that can be found; notify those that
07072       cannot be restored
07073    */
07074    while ((this = AST_LIST_REMOVE_HEAD(&store, list))) {
07075       struct pbx_find_info q = { .stacklen = 0 };
07076       exten = pbx_find_extension(NULL, NULL, &q, this->context, this->exten, PRIORITY_HINT, NULL, "", E_MATCH);
07077       /* If this is a pattern, dynamically create a new extension for this
07078        * particular match.  Note that this will only happen once for each
07079        * individual extension, because the pattern will no longer match first.
07080        */
07081       if (exten && exten->exten[0] == '_') {
07082          ast_add_extension_nolock(exten->parent->name, 0, this->exten, PRIORITY_HINT, NULL,
07083             0, exten->app, ast_strdup(exten->data), ast_free_ptr, exten->registrar);
07084          /* rwlocks are not recursive locks */
07085          exten = ast_hint_extension_nolock(NULL, this->context, this->exten);
07086       }
07087 
07088       /* Find the hint in the list of hints */
07089       AST_RWLIST_TRAVERSE(&hints, hint, list) {
07090          if (hint->exten == exten)
07091             break;
07092       }
07093       if (!exten || !hint) {
07094          /* this hint has been removed, notify the watchers */
07095          while ((thiscb = AST_LIST_REMOVE_HEAD(&this->callbacks, entry))) {
07096             thiscb->callback(this->context, this->exten, AST_EXTENSION_REMOVED, thiscb->data);
07097             ast_free(thiscb);
07098          }
07099       } else {
07100          AST_LIST_APPEND_LIST(&hint->callbacks, &this->callbacks, entry);
07101          hint->laststate = this->laststate;
07102       }
07103       ast_free(this);
07104    }
07105 
07106    AST_RWLIST_UNLOCK(&hints);
07107    ast_unlock_contexts();
07108    endlocktime = ast_tvnow();
07109 
07110    /* the old list and hashtab no longer are relevant, delete them while the rest of asterisk
07111       is now freely using the new stuff instead */
07112 
07113    ast_hashtab_destroy(oldtable, NULL);
07114 
07115    for (tmp = oldcontextslist; tmp; ) {
07116       struct ast_context *next;  /* next starting point */
07117       next = tmp->next;
07118       __ast_internal_context_destroy(tmp);
07119       tmp = next;
07120    }
07121    enddeltime = ast_tvnow();
07122 
07123    ft = ast_tvdiff_us(writelocktime, begintime);
07124    ft /= 1000000.0;
07125    ast_verb(3,"Time to scan old dialplan and merge leftovers back into the new: %8.6f sec\n", ft);
07126 
07127    ft = ast_tvdiff_us(endlocktime, writelocktime);
07128    ft /= 1000000.0;
07129    ast_verb(3,"Time to restore hints and swap in new dialplan: %8.6f sec\n", ft);
07130 
07131    ft = ast_tvdiff_us(enddeltime, endlocktime);
07132    ft /= 1000000.0;
07133    ast_verb(3,"Time to delete the old dialplan: %8.6f sec\n", ft);
07134 
07135    ft = ast_tvdiff_us(enddeltime, begintime);
07136    ft /= 1000000.0;
07137    ast_verb(3,"Total time merge_contexts_delete: %8.6f sec\n", ft);
07138    return;
07139 }
07140 
07141 /*
07142  * errno values
07143  *  EBUSY  - can't lock
07144  *  ENOENT - no existence of context
07145  */
07146 int ast_context_add_include(const char *context, const char *include, const char *registrar)
07147 {
07148    int ret = -1;
07149    struct ast_context *c = find_context_locked(context);
07150 
07151    if (c) {
07152       ret = ast_context_add_include2(c, include, registrar);
07153       ast_unlock_contexts();
07154    }
07155    return ret;
07156 }
07157 
07158 /*! \brief Helper for get_range.
07159  * return the index of the matching entry, starting from 1.
07160  * If names is not supplied, try numeric values.
07161  */
07162 static int lookup_name(const char *s, const char * const names[], int max)
07163 {
07164    int i;
07165 
07166    if (names && *s > '9') {
07167       for (i = 0; names[i]; i++) {
07168          if (!strcasecmp(s, names[i])) {
07169             return i;
07170          }
07171       }
07172    }
07173 
07174    /* Allow months and weekdays to be specified as numbers, as well */
07175    if (sscanf(s, "%2d", &i) == 1 && i >= 1 && i <= max) {
07176       /* What the array offset would have been: "1" would be at offset 0 */
07177       return i - 1;
07178    }
07179    return -1; /* error return */
07180 }
07181 
07182 /*! \brief helper function to return a range up to max (7, 12, 31 respectively).
07183  * names, if supplied, is an array of names that should be mapped to numbers.
07184  */
07185 static unsigned get_range(char *src, int max, const char * const names[], const char *msg)
07186 {
07187    int start, end; /* start and ending position */
07188    unsigned int mask = 0;
07189    char *part;
07190 
07191    /* Check for whole range */
07192    if (ast_strlen_zero(src) || !strcmp(src, "*")) {
07193       return (1 << max) - 1;
07194    }
07195 
07196    while ((part = strsep(&src, "&"))) {
07197       /* Get start and ending position */
07198       char *endpart = strchr(part, '-');
07199       if (endpart) {
07200          *endpart++ = '\0';
07201       }
07202       /* Find the start */
07203       if ((start = lookup_name(part, names, max)) < 0) {
07204          ast_log(LOG_WARNING, "Invalid %s '%s', skipping element\n", msg, part);
07205          continue;
07206       }
07207       if (endpart) { /* find end of range */
07208          if ((end = lookup_name(endpart, names, max)) < 0) {
07209             ast_log(LOG_WARNING, "Invalid end %s '%s', skipping element\n", msg, endpart);
07210             continue;
07211          }
07212       } else {
07213          end = start;
07214       }
07215       /* Fill the mask. Remember that ranges are cyclic */
07216       mask |= (1 << end);   /* initialize with last element */
07217       while (start != end) {
07218          mask |= (1 << start);
07219          if (++start >= max) {
07220             start = 0;
07221          }
07222       }
07223    }
07224    return mask;
07225 }
07226 
07227 /*! \brief store a bitmask of valid times, one bit each 1 minute */
07228 static void get_timerange(struct ast_timing *i, char *times)
07229 {
07230    char *endpart, *part;
07231    int x;
07232    int st_h, st_m;
07233    int endh, endm;
07234    int minute_start, minute_end;
07235 
07236    /* start disabling all times, fill the fields with 0's, as they may contain garbage */
07237    memset(i->minmask, 0, sizeof(i->minmask));
07238 
07239    /* 1-minute per bit */
07240    /* Star is all times */
07241    if (ast_strlen_zero(times) || !strcmp(times, "*")) {
07242       /* 48, because each hour takes 2 integers; 30 bits each */
07243       for (x = 0; x < 48; x++) {
07244          i->minmask[x] = 0x3fffffff; /* 30 bits */
07245       }
07246       return;
07247    }
07248    /* Otherwise expect a range */
07249    while ((part = strsep(&times, "&"))) {
07250       if (!(endpart = strchr(part, '-'))) {
07251          if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) {
07252             ast_log(LOG_WARNING, "%s isn't a valid time.\n", part);
07253             continue;
07254          }
07255          i->minmask[st_h * 2 + (st_m >= 30 ? 1 : 0)] |= (1 << (st_m % 30));
07256          continue;
07257       }
07258       *endpart++ = '\0';
07259       /* why skip non digits? Mostly to skip spaces */
07260       while (*endpart && !isdigit(*endpart)) {
07261          endpart++;
07262       }
07263       if (!*endpart) {
07264          ast_log(LOG_WARNING, "Invalid time range starting with '%s-'.\n", part);
07265          continue;
07266       }
07267       if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) {
07268          ast_log(LOG_WARNING, "'%s' isn't a valid start time.\n", part);
07269          continue;
07270       }
07271       if (sscanf(endpart, "%2d:%2d", &endh, &endm) != 2 || endh < 0 || endh > 23 || endm < 0 || endm > 59) {
07272          ast_log(LOG_WARNING, "'%s' isn't a valid end time.\n", endpart);
07273          continue;
07274       }
07275       minute_start = st_h * 60 + st_m;
07276       minute_end = endh * 60 + endm;
07277       /* Go through the time and enable each appropriate bit */
07278       for (x = minute_start; x != minute_end; x = (x + 1) % (24 * 60)) {
07279          i->minmask[x / 30] |= (1 << (x % 30));
07280       }
07281       /* Do the last one */
07282       i->minmask[x / 30] |= (1 << (x % 30));
07283    }
07284    /* All done */
07285    return;
07286 }
07287 
07288 static const char * const days[] =
07289 {
07290    "sun",
07291    "mon",
07292    "tue",
07293    "wed",
07294    "thu",
07295    "fri",
07296    "sat",
07297    NULL,
07298 };
07299 
07300 static const char * const months[] =
07301 {
07302    "jan",
07303    "feb",
07304    "mar",
07305    "apr",
07306    "may",
07307    "jun",
07308    "jul",
07309    "aug",
07310    "sep",
07311    "oct",
07312    "nov",
07313    "dec",
07314    NULL,
07315 };
07316 
07317 int ast_build_timing(struct ast_timing *i, const char *info_in)
07318 {
07319    char *info_save, *info;
07320    int j, num_fields, last_sep = -1;
07321 
07322    /* Check for empty just in case */
07323    if (ast_strlen_zero(info_in)) {
07324       return 0;
07325    }
07326 
07327    /* make a copy just in case we were passed a static string */
07328    info_save = info = ast_strdupa(info_in);
07329 
07330    /* count the number of fields in the timespec */
07331    for (j = 0, num_fields = 1; info[j] != '\0'; j++) {
07332       if (info[j] == ',') {
07333          last_sep = j;
07334          num_fields++;
07335       }
07336    }
07337 
07338    /* save the timezone, if it is specified */
07339    if (num_fields == 5) {
07340       i->timezone = ast_strdup(info + last_sep + 1);
07341    } else {
07342       i->timezone = NULL;
07343    }
07344 
07345    /* Assume everything except time */
07346    i->monthmask = 0xfff;   /* 12 bits */
07347    i->daymask = 0x7fffffffU; /* 31 bits */
07348    i->dowmask = 0x7f; /* 7 bits */
07349    /* on each call, use strsep() to move info to the next argument */
07350    get_timerange(i, strsep(&info, "|,"));
07351    if (info)
07352       i->dowmask = get_range(strsep(&info, "|,"), 7, days, "day of week");
07353    if (info)
07354       i->daymask = get_range(strsep(&info, "|,"), 31, NULL, "day");
07355    if (info)
07356       i->monthmask = get_range(strsep(&info, "|,"), 12, months, "month");
07357    return 1;
07358 }
07359 
07360 int ast_check_timing(const struct ast_timing *i)
07361 {
07362    return ast_check_timing2(i, ast_tvnow());
07363 }
07364 
07365 int ast_check_timing2(const struct ast_timing *i, const struct timeval tv)
07366 {
07367    struct ast_tm tm;
07368 
07369    ast_localtime(&tv, &tm, i->timezone);
07370 
07371    /* If it's not the right month, return */
07372    if (!(i->monthmask & (1 << tm.tm_mon)))
07373       return 0;
07374 
07375    /* If it's not that time of the month.... */
07376    /* Warning, tm_mday has range 1..31! */
07377    if (!(i->daymask & (1 << (tm.tm_mday-1))))
07378       return 0;
07379 
07380    /* If it's not the right day of the week */
07381    if (!(i->dowmask & (1 << tm.tm_wday)))
07382       return 0;
07383 
07384    /* Sanity check the hour just to be safe */
07385    if ((tm.tm_hour < 0) || (tm.tm_hour > 23)) {
07386       ast_log(LOG_WARNING, "Insane time...\n");
07387       return 0;
07388    }
07389 
07390    /* Now the tough part, we calculate if it fits
07391       in the right time based on min/hour */
07392    if (!(i->minmask[tm.tm_hour * 2 + (tm.tm_min >= 30 ? 1 : 0)] & (1 << (tm.tm_min >= 30 ? tm.tm_min - 30 : tm.tm_min))))
07393       return 0;
07394 
07395    /* If we got this far, then we're good */
07396    return 1;
07397 }
07398 
07399 int ast_destroy_timing(struct ast_timing *i)
07400 {
07401    if (i->timezone) {
07402       ast_free(i->timezone);
07403       i->timezone = NULL;
07404    }
07405    return 0;
07406 }
07407 /*
07408  * errno values
07409  *  ENOMEM - out of memory
07410  *  EBUSY  - can't lock
07411  *  EEXIST - already included
07412  *  EINVAL - there is no existence of context for inclusion
07413  */
07414 int ast_context_add_include2(struct ast_context *con, const char *value,
07415    const char *registrar)
07416 {
07417    struct ast_include *new_include;
07418    char *c;
07419    struct ast_include *i, *il = NULL; /* include, include_last */
07420    int length;
07421    char *p;
07422 
07423    length = sizeof(struct ast_include);
07424    length += 2 * (strlen(value) + 1);
07425 
07426    /* allocate new include structure ... */
07427    if (!(new_include = ast_calloc(1, length)))
07428       return -1;
07429    /* Fill in this structure. Use 'p' for assignments, as the fields
07430     * in the structure are 'const char *'
07431     */
07432    p = new_include->stuff;
07433    new_include->name = p;
07434    strcpy(p, value);
07435    p += strlen(value) + 1;
07436    new_include->rname = p;
07437    strcpy(p, value);
07438    /* Strip off timing info, and process if it is there */
07439    if ( (c = strchr(p, ',')) ) {
07440       *c++ = '\0';
07441       new_include->hastime = ast_build_timing(&(new_include->timing), c);
07442    }
07443    new_include->next      = NULL;
07444    new_include->registrar = registrar;
07445 
07446    ast_wrlock_context(con);
07447 
07448    /* ... go to last include and check if context is already included too... */
07449    for (i = con->includes; i; i = i->next) {
07450       if (!strcasecmp(i->name, new_include->name)) {
07451          ast_destroy_timing(&(new_include->timing));
07452          ast_free(new_include);
07453          ast_unlock_context(con);
07454          errno = EEXIST;
07455          return -1;
07456       }
07457       il = i;
07458    }
07459 
07460    /* ... include new context into context list, unlock, return */
07461    if (il)
07462       il->next = new_include;
07463    else
07464       con->includes = new_include;
07465    ast_verb(3, "Including context '%s' in context '%s'\n", new_include->name, ast_get_context_name(con));
07466 
07467    ast_unlock_context(con);
07468 
07469    return 0;
07470 }
07471 
07472 /*
07473  * errno values
07474  *  EBUSY  - can't lock
07475  *  ENOENT - no existence of context
07476  */
07477 int ast_context_add_switch(const char *context, const char *sw, const char *data, int eval, const char *registrar)
07478 {
07479    int ret = -1;
07480    struct ast_context *c = find_context_locked(context);
07481 
07482    if (c) { /* found, add switch to this context */
07483       ret = ast_context_add_switch2(c, sw, data, eval, registrar);
07484       ast_unlock_contexts();
07485    }
07486    return ret;
07487 }
07488 
07489 /*
07490  * errno values
07491  *  ENOMEM - out of memory
07492  *  EBUSY  - can't lock
07493  *  EEXIST - already included
07494  *  EINVAL - there is no existence of context for inclusion
07495  */
07496 int ast_context_add_switch2(struct ast_context *con, const char *value,
07497    const char *data, int eval, const char *registrar)
07498 {
07499    struct ast_sw *new_sw;
07500    struct ast_sw *i;
07501    int length;
07502    char *p;
07503 
07504    length = sizeof(struct ast_sw);
07505    length += strlen(value) + 1;
07506    if (data)
07507       length += strlen(data);
07508    length++;
07509 
07510    /* allocate new sw structure ... */
07511    if (!(new_sw = ast_calloc(1, length)))
07512       return -1;
07513    /* ... fill in this structure ... */
07514    p = new_sw->stuff;
07515    new_sw->name = p;
07516    strcpy(new_sw->name, value);
07517    p += strlen(value) + 1;
07518    new_sw->data = p;
07519    if (data) {
07520       strcpy(new_sw->data, data);
07521       p += strlen(data) + 1;
07522    } else {
07523       strcpy(new_sw->data, "");
07524       p++;
07525    }
07526    new_sw->eval     = eval;
07527    new_sw->registrar = registrar;
07528 
07529    /* ... try to lock this context ... */
07530    ast_wrlock_context(con);
07531 
07532    /* ... go to last sw and check if context is already swd too... */
07533    AST_LIST_TRAVERSE(&con->alts, i, list) {
07534       if (!strcasecmp(i->name, new_sw->name) && !strcasecmp(i->data, new_sw->data)) {
07535          ast_free(new_sw);
07536          ast_unlock_context(con);
07537          errno = EEXIST;
07538          return -1;
07539       }
07540    }
07541 
07542    /* ... sw new context into context list, unlock, return */
07543    AST_LIST_INSERT_TAIL(&con->alts, new_sw, list);
07544 
07545    ast_verb(3, "Including switch '%s/%s' in context '%s'\n", new_sw->name, new_sw->data, ast_get_context_name(con));
07546 
07547    ast_unlock_context(con);
07548 
07549    return 0;
07550 }
07551 
07552 /*
07553  * EBUSY  - can't lock
07554  * ENOENT - there is not context existence
07555  */
07556 int ast_context_remove_ignorepat(const char *context, const char *ignorepat, const char *registrar)
07557 {
07558    int ret = -1;
07559    struct ast_context *c = find_context_locked(context);
07560 
07561    if (c) {
07562       ret = ast_context_remove_ignorepat2(c, ignorepat, registrar);
07563       ast_unlock_contexts();
07564    }
07565    return ret;
07566 }
07567 
07568 int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat, const char *registrar)
07569 {
07570    struct ast_ignorepat *ip, *ipl = NULL;
07571 
07572    ast_wrlock_context(con);
07573 
07574    for (ip = con->ignorepats; ip; ip = ip->next) {
07575       if (!strcmp(ip->pattern, ignorepat) &&
07576          (!registrar || (registrar == ip->registrar))) {
07577          if (ipl) {
07578             ipl->next = ip->next;
07579             ast_free(ip);
07580          } else {
07581             con->ignorepats = ip->next;
07582             ast_free(ip);
07583          }
07584          ast_unlock_context(con);
07585          return 0;
07586       }
07587       ipl = ip;
07588    }
07589 
07590    ast_unlock_context(con);
07591    errno = EINVAL;
07592    return -1;
07593 }
07594 
07595 /*
07596  * EBUSY - can't lock
07597  * ENOENT - there is no existence of context
07598  */
07599 int ast_context_add_ignorepat(const char *context, const char *value, const char *registrar)
07600 {
07601    int ret = -1;
07602    struct ast_context *c = find_context_locked(context);
07603 
07604    if (c) {
07605       ret = ast_context_add_ignorepat2(c, value, registrar);
07606       ast_unlock_contexts();
07607    }
07608    return ret;
07609 }
07610 
07611 int ast_context_add_ignorepat2(struct ast_context *con, const char *value, const char *registrar)
07612 {
07613    struct ast_ignorepat *ignorepat, *ignorepatc, *ignorepatl = NULL;
07614    int length;
07615    char *pattern;
07616    length = sizeof(struct ast_ignorepat);
07617    length += strlen(value) + 1;
07618    if (!(ignorepat = ast_calloc(1, length)))
07619       return -1;
07620    /* The cast to char * is because we need to write the initial value.
07621     * The field is not supposed to be modified otherwise.  Also, gcc 4.2
07622     * sees the cast as dereferencing a type-punned pointer and warns about
07623     * it.  This is the workaround (we're telling gcc, yes, that's really
07624     * what we wanted to do).
07625     */
07626    pattern = (char *) ignorepat->pattern;
07627    strcpy(pattern, value);
07628    ignorepat->next = NULL;
07629    ignorepat->registrar = registrar;
07630    ast_wrlock_context(con);
07631    for (ignorepatc = con->ignorepats; ignorepatc; ignorepatc = ignorepatc->next) {
07632       ignorepatl = ignorepatc;
07633       if (!strcasecmp(ignorepatc->pattern, value)) {
07634          /* Already there */
07635          ast_unlock_context(con);
07636          errno = EEXIST;
07637          return -1;
07638       }
07639    }
07640    if (ignorepatl)
07641       ignorepatl->next = ignorepat;
07642    else
07643       con->ignorepats = ignorepat;
07644    ast_unlock_context(con);
07645    return 0;
07646 
07647 }
07648 
07649 int ast_ignore_pattern(const char *context, const char *pattern)
07650 {
07651    struct ast_context *con = ast_context_find(context);
07652    if (con) {
07653       struct ast_ignorepat *pat;
07654       for (pat = con->ignorepats; pat; pat = pat->next) {
07655          if (ast_extension_match(pat->pattern, pattern))
07656             return 1;
07657       }
07658    }
07659 
07660    return 0;
07661 }
07662 
07663 /*
07664  * ast_add_extension_nolock -- use only in situations where the conlock is already held
07665  * ENOENT  - no existence of context
07666  *
07667  */
07668 static int ast_add_extension_nolock(const char *context, int replace, const char *extension,
07669    int priority, const char *label, const char *callerid,
07670    const char *application, void *data, void (*datad)(void *), const char *registrar)
07671 {
07672    int ret = -1;
07673    struct ast_context *c = find_context(context);
07674 
07675    if (c) {
07676       ret = ast_add_extension2_lockopt(c, replace, extension, priority, label, callerid,
07677          application, data, datad, registrar, 0, 0);
07678    }
07679 
07680    return ret;
07681 }
07682 /*
07683  * EBUSY   - can't lock
07684  * ENOENT  - no existence of context
07685  *
07686  */
07687 int ast_add_extension(const char *context, int replace, const char *extension,
07688    int priority, const char *label, const char *callerid,
07689    const char *application, void *data, void (*datad)(void *), const char *registrar)
07690 {
07691    int ret = -1;
07692    struct ast_context *c = find_context_locked(context);
07693 
07694    if (c) {
07695       ret = ast_add_extension2(c, replace, extension, priority, label, callerid,
07696          application, data, datad, registrar);
07697       ast_unlock_contexts();
07698    }
07699 
07700    return ret;
07701 }
07702 
07703 int ast_explicit_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
07704 {
07705    if (!chan)
07706       return -1;
07707 
07708    ast_channel_lock(chan);
07709 
07710    if (!ast_strlen_zero(context))
07711       ast_copy_string(chan->context, context, sizeof(chan->context));
07712    if (!ast_strlen_zero(exten))
07713       ast_copy_string(chan->exten, exten, sizeof(chan->exten));
07714    if (priority > -1) {
07715       chan->priority = priority;
07716       /* see flag description in channel.h for explanation */
07717       if (ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP))
07718          chan->priority--;
07719    }
07720 
07721    ast_channel_unlock(chan);
07722 
07723    return 0;
07724 }
07725 
07726 int ast_async_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
07727 {
07728    int res = 0;
07729 
07730    ast_channel_lock(chan);
07731 
07732    if (chan->pbx) { /* This channel is currently in the PBX */
07733       ast_explicit_goto(chan, context, exten, priority + 1);
07734       ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
07735    } else {
07736       /* In order to do it when the channel doesn't really exist within
07737          the PBX, we have to make a new channel, masquerade, and start the PBX
07738          at the new location */
07739       struct ast_channel *tmpchan = ast_channel_alloc(0, chan->_state, 0, 0, chan->accountcode, chan->exten, chan->context, chan->linkedid, chan->amaflags, "AsyncGoto/%s", chan->name);
07740       if (!tmpchan) {
07741          res = -1;
07742       } else {
07743          if (chan->cdr) {
07744             ast_cdr_discard(tmpchan->cdr);
07745             tmpchan->cdr = ast_cdr_dup(chan->cdr);  /* share the love */
07746          }
07747          /* Make formats okay */
07748          tmpchan->readformat = chan->readformat;
07749          tmpchan->writeformat = chan->writeformat;
07750          /* Setup proper location */
07751          ast_explicit_goto(tmpchan,
07752             S_OR(context, chan->context), S_OR(exten, chan->exten), priority);
07753 
07754          /* Masquerade into temp channel */
07755          if (ast_channel_masquerade(tmpchan, chan)) {
07756             /* Failed to set up the masquerade.  It's probably chan_local
07757              * in the middle of optimizing itself out.  Sad. :( */
07758             ast_hangup(tmpchan);
07759             tmpchan = NULL;
07760             res = -1;
07761          } else {
07762             /* it may appear odd to unlock chan here since the masquerade is on
07763              * tmpchan, but no channel locks should be held when doing a masquerade
07764              * since a masquerade requires a lock on the channels ao2 container. */
07765             ast_channel_unlock(chan);
07766             ast_do_masquerade(tmpchan);
07767             ast_channel_lock(chan);
07768             /* Start the PBX going on our stolen channel */
07769             if (ast_pbx_start(tmpchan)) {
07770                ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmpchan->name);
07771                ast_hangup(tmpchan);
07772                res = -1;
07773             }
07774          }
07775       }
07776    }
07777    ast_channel_unlock(chan);
07778    return res;
07779 }
07780 
07781 int ast_async_goto_by_name(const char *channame, const char *context, const char *exten, int priority)
07782 {
07783    struct ast_channel *chan;
07784    int res = -1;
07785 
07786    if ((chan = ast_channel_get_by_name(channame))) {
07787       res = ast_async_goto(chan, context, exten, priority);
07788       chan = ast_channel_unref(chan);
07789    }
07790 
07791    return res;
07792 }
07793 
07794 /*! \brief copy a string skipping whitespace */
07795 static int ext_strncpy(char *dst, const char *src, int len)
07796 {
07797    int count = 0;
07798    int insquares = 0;
07799 
07800    while (*src && (count < len - 1)) {
07801       if (*src == '[') {
07802          insquares = 1;
07803       } else if (*src == ']') {
07804          insquares = 0;
07805       } else if (*src == ' ' && !insquares) {
07806          src++;
07807          continue;
07808       }
07809       *dst = *src;
07810       dst++;
07811       src++;
07812       count++;
07813    }
07814    *dst = '\0';
07815 
07816    return count;
07817 }
07818 
07819 /*!
07820  * \brief add the extension in the priority chain.
07821  * \retval 0 on success.
07822  * \retval -1 on failure.
07823 */
07824 static int add_pri(struct ast_context *con, struct ast_exten *tmp,
07825    struct ast_exten *el, struct ast_exten *e, int replace)
07826 {
07827    return add_pri_lockopt(con, tmp, el, e, replace, 1);
07828 }
07829 
07830 /*!
07831  * \brief add the extension in the priority chain.
07832  * \retval 0 on success.
07833  * \retval -1 on failure.
07834 */
07835 static int add_pri_lockopt(struct ast_context *con, struct ast_exten *tmp,
07836    struct ast_exten *el, struct ast_exten *e, int replace, int lockhints)
07837 {
07838    struct ast_exten *ep;
07839    struct ast_exten *eh=e;
07840 
07841    for (ep = NULL; e ; ep = e, e = e->peer) {
07842       if (e->priority >= tmp->priority)
07843          break;
07844    }
07845    if (!e) {   /* go at the end, and ep is surely set because the list is not empty */
07846       ast_hashtab_insert_safe(eh->peer_table, tmp);
07847 
07848       if (tmp->label) {
07849          ast_hashtab_insert_safe(eh->peer_label_table, tmp);
07850       }
07851       ep->peer = tmp;
07852       return 0;   /* success */
07853    }
07854    if (e->priority == tmp->priority) {
07855       /* Can't have something exactly the same.  Is this a
07856          replacement?  If so, replace, otherwise, bonk. */
07857       if (!replace) {
07858          ast_log(LOG_WARNING, "Unable to register extension '%s', priority %d in '%s', already in use\n", tmp->exten, tmp->priority, con->name);
07859          if (tmp->datad) {
07860             tmp->datad(tmp->data);
07861             /* if you free this, null it out */
07862             tmp->data = NULL;
07863          }
07864 
07865          ast_free(tmp);
07866          return -1;
07867       }
07868       /* we are replacing e, so copy the link fields and then update
07869        * whoever pointed to e to point to us
07870        */
07871       tmp->next = e->next; /* not meaningful if we are not first in the peer list */
07872       tmp->peer = e->peer; /* always meaningful */
07873       if (ep)  {     /* We're in the peer list, just insert ourselves */
07874          ast_hashtab_remove_object_via_lookup(eh->peer_table,e);
07875 
07876          if (e->label) {
07877             ast_hashtab_remove_object_via_lookup(eh->peer_label_table,e);
07878          }
07879 
07880          ast_hashtab_insert_safe(eh->peer_table,tmp);
07881          if (tmp->label) {
07882             ast_hashtab_insert_safe(eh->peer_label_table,tmp);
07883          }
07884 
07885          ep->peer = tmp;
07886       } else if (el) {     /* We're the first extension. Take over e's functions */
07887          struct match_char *x = add_exten_to_pattern_tree(con, e, 1);
07888          tmp->peer_table = e->peer_table;
07889          tmp->peer_label_table = e->peer_label_table;
07890          ast_hashtab_remove_object_via_lookup(tmp->peer_table,e);
07891          ast_hashtab_insert_safe(tmp->peer_table,tmp);
07892          if (e->label) {
07893             ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e);
07894          }
07895          if (tmp->label) {
07896             ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
07897          }
07898 
07899          ast_hashtab_remove_object_via_lookup(con->root_table, e);
07900          ast_hashtab_insert_safe(con->root_table, tmp);
07901          el->next = tmp;
07902          /* The pattern trie points to this exten; replace the pointer,
07903             and all will be well */
07904          if (x) { /* if the trie isn't formed yet, don't sweat this */
07905             if (x->exten) { /* this test for safety purposes */
07906                x->exten = tmp; /* replace what would become a bad pointer */
07907             } else {
07908                ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
07909             }
07910          }
07911       } else {       /* We're the very first extension.  */
07912          struct match_char *x = add_exten_to_pattern_tree(con, e, 1);
07913          ast_hashtab_remove_object_via_lookup(con->root_table, e);
07914          ast_hashtab_insert_safe(con->root_table, tmp);
07915          tmp->peer_table = e->peer_table;
07916          tmp->peer_label_table = e->peer_label_table;
07917          ast_hashtab_remove_object_via_lookup(tmp->peer_table, e);
07918          ast_hashtab_insert_safe(tmp->peer_table, tmp);
07919          if (e->label) {
07920             ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e);
07921          }
07922          if (tmp->label) {
07923             ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
07924          }
07925 
07926          ast_hashtab_remove_object_via_lookup(con->root_table, e);
07927          ast_hashtab_insert_safe(con->root_table, tmp);
07928          con->root = tmp;
07929          /* The pattern trie points to this exten; replace the pointer,
07930             and all will be well */
07931          if (x) { /* if the trie isn't formed yet; no problem */
07932             if (x->exten) { /* this test for safety purposes */
07933                x->exten = tmp; /* replace what would become a bad pointer */
07934             } else {
07935                ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
07936             }
07937          }
07938       }
07939       if (tmp->priority == PRIORITY_HINT)
07940          ast_change_hint(e,tmp);
07941       /* Destroy the old one */
07942       if (e->datad)
07943          e->datad(e->data);
07944       ast_free(e);
07945    } else { /* Slip ourselves in just before e */
07946       tmp->peer = e;
07947       tmp->next = e->next; /* extension chain, or NULL if e is not the first extension */
07948       if (ep) {         /* Easy enough, we're just in the peer list */
07949          if (tmp->label) {
07950             ast_hashtab_insert_safe(eh->peer_label_table, tmp);
07951          }
07952          ast_hashtab_insert_safe(eh->peer_table, tmp);
07953          ep->peer = tmp;
07954       } else {       /* we are the first in some peer list, so link in the ext list */
07955          tmp->peer_table = e->peer_table;
07956          tmp->peer_label_table = e->peer_label_table;
07957          e->peer_table = 0;
07958          e->peer_label_table = 0;
07959          ast_hashtab_insert_safe(tmp->peer_table, tmp);
07960          if (tmp->label) {
07961             ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
07962          }
07963          ast_hashtab_remove_object_via_lookup(con->root_table, e);
07964          ast_hashtab_insert_safe(con->root_table, tmp);
07965          if (el)
07966             el->next = tmp;   /* in the middle... */
07967          else
07968             con->root = tmp; /* ... or at the head */
07969          e->next = NULL;   /* e is no more at the head, so e->next must be reset */
07970       }
07971       /* And immediately return success. */
07972       if (tmp->priority == PRIORITY_HINT) {
07973          if (lockhints) {
07974             ast_add_hint(tmp);
07975          } else {
07976             ast_add_hint_nolock(tmp);
07977          }
07978       }
07979    }
07980    return 0;
07981 }
07982 
07983 /*! \brief
07984  * Main interface to add extensions to the list for out context.
07985  *
07986  * We sort extensions in order of matching preference, so that we can
07987  * stop the search as soon as we find a suitable match.
07988  * This ordering also takes care of wildcards such as '.' (meaning
07989  * "one or more of any character") and '!' (which is 'earlymatch',
07990  * meaning "zero or more of any character" but also impacts the
07991  * return value from CANMATCH and EARLYMATCH.
07992  *
07993  * The extension match rules defined in the devmeeting 2006.05.05 are
07994  * quite simple: WE SELECT THE LONGEST MATCH.
07995  * In detail, "longest" means the number of matched characters in
07996  * the extension. In case of ties (e.g. _XXX and 333) in the length
07997  * of a pattern, we give priority to entries with the smallest cardinality
07998  * (e.g, [5-9] comes before [2-8] before the former has only 5 elements,
07999  * while the latter has 7, etc.
08000  * In case of same cardinality, the first element in the range counts.
08001  * If we still have a tie, any final '!' will make this as a possibly
08002  * less specific pattern.
08003  *
08004  * EBUSY - can't lock
08005  * EEXIST - extension with the same priority exist and no replace is set
08006  *
08007  */
08008 int ast_add_extension2(struct ast_context *con,
08009    int replace, const char *extension, int priority, const char *label, const char *callerid,
08010    const char *application, void *data, void (*datad)(void *),
08011    const char *registrar)
08012 {
08013    return ast_add_extension2_lockopt(con, replace, extension, priority, label, callerid, application, data, datad, registrar, 1, 1);
08014 }
08015 
08016 /*! \brief
08017  * Does all the work of ast_add_extension2, but adds two args, to determine if
08018  * context and hint locking should be done. In merge_and_delete, we need to do
08019  * this without locking, as the locks are already held.
08020  */
08021 static int ast_add_extension2_lockopt(struct ast_context *con,
08022    int replace, const char *extension, int priority, const char *label, const char *callerid,
08023    const char *application, void *data, void (*datad)(void *),
08024    const char *registrar, int lockconts, int lockhints)
08025 {
08026    /*
08027     * Sort extensions (or patterns) according to the rules indicated above.
08028     * These are implemented by the function ext_cmp()).
08029     * All priorities for the same ext/pattern/cid are kept in a list,
08030     * using the 'peer' field  as a link field..
08031     */
08032    struct ast_exten *tmp, *tmp2, *e, *el = NULL;
08033    int res;
08034    int length;
08035    char *p;
08036    char expand_buf[VAR_BUF_SIZE];
08037    struct ast_exten dummy_exten = {0};
08038    char dummy_name[1024];
08039 
08040    if (ast_strlen_zero(extension)) {
08041       ast_log(LOG_ERROR,"You have to be kidding-- add exten '' to context %s? Figure out a name and call me back. Action ignored.\n",
08042             con->name);
08043       return -1;
08044    }
08045 
08046    /* If we are adding a hint evalulate in variables and global variables */
08047    if (priority == PRIORITY_HINT && strstr(application, "${") && !strstr(extension, "_")) {
08048       struct ast_channel *c = ast_dummy_channel_alloc();
08049       ast_copy_string(c->exten, extension, sizeof(c->exten));
08050       ast_copy_string(c->context, con->name, sizeof(c->context));
08051 
08052       pbx_substitute_variables_helper(c, application, expand_buf, sizeof(expand_buf));
08053       application = expand_buf;
08054       ast_channel_release(c);
08055    }
08056 
08057    length = sizeof(struct ast_exten);
08058    length += strlen(extension) + 1;
08059    length += strlen(application) + 1;
08060    if (label)
08061       length += strlen(label) + 1;
08062    if (callerid)
08063       length += strlen(callerid) + 1;
08064    else
08065       length ++;  /* just the '\0' */
08066 
08067    /* Be optimistic:  Build the extension structure first */
08068    if (!(tmp = ast_calloc(1, length)))
08069       return -1;
08070 
08071    if (ast_strlen_zero(label)) /* let's turn empty labels to a null ptr */
08072       label = 0;
08073 
08074    /* use p as dst in assignments, as the fields are const char * */
08075    p = tmp->stuff;
08076    if (label) {
08077       tmp->label = p;
08078       strcpy(p, label);
08079       p += strlen(label) + 1;
08080    }
08081    tmp->exten = p;
08082    p += ext_strncpy(p, extension, strlen(extension) + 1) + 1;
08083    tmp->priority = priority;
08084    tmp->cidmatch = p;   /* but use p for assignments below */
08085 
08086    /* Blank callerid and NULL callerid are two SEPARATE things.  Do NOT confuse the two!!! */
08087    if (callerid) {
08088       p += ext_strncpy(p, callerid, strlen(callerid) + 1) + 1;
08089       tmp->matchcid = 1;
08090    } else {
08091       *p++ = '\0';
08092       tmp->matchcid = 0;
08093    }
08094    tmp->app = p;
08095    strcpy(p, application);
08096    tmp->parent = con;
08097    tmp->data = data;
08098    tmp->datad = datad;
08099    tmp->registrar = registrar;
08100 
08101    if (lockconts) {
08102       ast_wrlock_context(con);
08103    }
08104 
08105    if (con->pattern_tree) { /* usually, on initial load, the pattern_tree isn't formed until the first find_exten; so if we are adding
08106                         an extension, and the trie exists, then we need to incrementally add this pattern to it. */
08107       ast_copy_string(dummy_name, extension, sizeof(dummy_name));
08108       dummy_exten.exten = dummy_name;
08109       dummy_exten.matchcid = 0;
08110       dummy_exten.cidmatch = 0;
08111       tmp2 = ast_hashtab_lookup(con->root_table, &dummy_exten);
08112       if (!tmp2) {
08113          /* hmmm, not in the trie; */
08114          add_exten_to_pattern_tree(con, tmp, 0);
08115          ast_hashtab_insert_safe(con->root_table, tmp); /* for the sake of completeness */
08116       }
08117    }
08118    res = 0; /* some compilers will think it is uninitialized otherwise */
08119    for (e = con->root; e; el = e, e = e->next) {   /* scan the extension list */
08120       res = ext_cmp(e->exten, tmp->exten);
08121       if (res == 0) { /* extension match, now look at cidmatch */
08122          if (!e->matchcid && !tmp->matchcid)
08123             res = 0;
08124          else if (tmp->matchcid && !e->matchcid)
08125             res = 1;
08126          else if (e->matchcid && !tmp->matchcid)
08127             res = -1;
08128          else
08129             res = ext_cmp(e->cidmatch, tmp->cidmatch);
08130       }
08131       if (res >= 0)
08132          break;
08133    }
08134    if (e && res == 0) { /* exact match, insert in the pri chain */
08135       res = add_pri(con, tmp, el, e, replace);
08136       if (lockconts) {
08137          ast_unlock_context(con);
08138       }
08139       if (res < 0) {
08140          errno = EEXIST;   /* XXX do we care ? */
08141          return 0; /* XXX should we return -1 maybe ? */
08142       }
08143    } else {
08144       /*
08145        * not an exact match, this is the first entry with this pattern,
08146        * so insert in the main list right before 'e' (if any)
08147        */
08148       tmp->next = e;
08149       if (el) {  /* there is another exten already in this context */
08150          el->next = tmp;
08151          tmp->peer_table = ast_hashtab_create(13,
08152                      hashtab_compare_exten_numbers,
08153                      ast_hashtab_resize_java,
08154                      ast_hashtab_newsize_java,
08155                      hashtab_hash_priority,
08156                      0);
08157          tmp->peer_label_table = ast_hashtab_create(7,
08158                         hashtab_compare_exten_labels,
08159                         ast_hashtab_resize_java,
08160                         ast_hashtab_newsize_java,
08161                         hashtab_hash_labels,
08162                         0);
08163          if (label) {
08164             ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
08165          }
08166          ast_hashtab_insert_safe(tmp->peer_table, tmp);
08167       } else {  /* this is the first exten in this context */
08168          if (!con->root_table)
08169             con->root_table = ast_hashtab_create(27,
08170                                        hashtab_compare_extens,
08171                                        ast_hashtab_resize_java,
08172                                        ast_hashtab_newsize_java,
08173                                        hashtab_hash_extens,
08174                                        0);
08175          con->root = tmp;
08176          con->root->peer_table = ast_hashtab_create(13,
08177                         hashtab_compare_exten_numbers,
08178                         ast_hashtab_resize_java,
08179                         ast_hashtab_newsize_java,
08180                         hashtab_hash_priority,
08181                         0);
08182          con->root->peer_label_table = ast_hashtab_create(7,
08183                            hashtab_compare_exten_labels,
08184                            ast_hashtab_resize_java,
08185                            ast_hashtab_newsize_java,
08186                            hashtab_hash_labels,
08187                            0);
08188          if (label) {
08189             ast_hashtab_insert_safe(con->root->peer_label_table, tmp);
08190          }
08191          ast_hashtab_insert_safe(con->root->peer_table, tmp);
08192 
08193       }
08194       ast_hashtab_insert_safe(con->root_table, tmp);
08195       if (lockconts) {
08196          ast_unlock_context(con);
08197       }
08198       if (tmp->priority == PRIORITY_HINT) {
08199          if (lockhints) {
08200             ast_add_hint(tmp);
08201          } else {
08202             ast_add_hint_nolock(tmp);
08203          }
08204       }
08205    }
08206    if (option_debug) {
08207       if (tmp->matchcid) {
08208          ast_debug(1, "Added extension '%s' priority %d (CID match '%s') to %s (%p)\n",
08209                  tmp->exten, tmp->priority, tmp->cidmatch, con->name, con);
08210       } else {
08211          ast_debug(1, "Added extension '%s' priority %d to %s (%p)\n",
08212                  tmp->exten, tmp->priority, con->name, con);
08213       }
08214    }
08215 
08216    if (tmp->matchcid) {
08217       ast_verb(3, "Added extension '%s' priority %d (CID match '%s') to %s\n",
08218              tmp->exten, tmp->priority, tmp->cidmatch, con->name);
08219    } else {
08220       ast_verb(3, "Added extension '%s' priority %d to %s\n",
08221              tmp->exten, tmp->priority, con->name);
08222    }
08223 
08224    return 0;
08225 }
08226 
08227 struct async_stat {
08228    pthread_t p;
08229    struct ast_channel *chan;
08230    char context[AST_MAX_CONTEXT];
08231    char exten[AST_MAX_EXTENSION];
08232    int priority;
08233    int timeout;
08234    char app[AST_MAX_EXTENSION];
08235    char appdata[1024];
08236 };
08237 
08238 static void *async_wait(void *data)
08239 {
08240    struct async_stat *as = data;
08241    struct ast_channel *chan = as->chan;
08242    int timeout = as->timeout;
08243    int res;
08244    struct ast_frame *f;
08245    struct ast_app *app;
08246 
08247    while (timeout && (chan->_state != AST_STATE_UP)) {
08248       res = ast_waitfor(chan, timeout);
08249       if (res < 1)
08250          break;
08251       if (timeout > -1)
08252          timeout = res;
08253       f = ast_read(chan);
08254       if (!f)
08255          break;
08256       if (f->frametype == AST_FRAME_CONTROL) {
08257          if ((f->subclass.integer == AST_CONTROL_BUSY)  ||
08258              (f->subclass.integer == AST_CONTROL_CONGESTION) ) {
08259             ast_frfree(f);
08260             break;
08261          }
08262       }
08263       ast_frfree(f);
08264    }
08265    if (chan->_state == AST_STATE_UP) {
08266       if (!ast_strlen_zero(as->app)) {
08267          app = pbx_findapp(as->app);
08268          if (app) {
08269             ast_verb(3, "Launching %s(%s) on %s\n", as->app, as->appdata, chan->name);
08270             pbx_exec(chan, app, as->appdata);
08271          } else
08272             ast_log(LOG_WARNING, "No such application '%s'\n", as->app);
08273       } else {
08274          if (!ast_strlen_zero(as->context))
08275             ast_copy_string(chan->context, as->context, sizeof(chan->context));
08276          if (!ast_strlen_zero(as->exten))
08277             ast_copy_string(chan->exten, as->exten, sizeof(chan->exten));
08278          if (as->priority > 0)
08279             chan->priority = as->priority;
08280          /* Run the PBX */
08281          if (ast_pbx_run(chan)) {
08282             ast_log(LOG_ERROR, "Failed to start PBX on %s\n", chan->name);
08283          } else {
08284             /* PBX will have taken care of this */
08285             chan = NULL;
08286          }
08287       }
08288    }
08289    ast_free(as);
08290    if (chan)
08291       ast_hangup(chan);
08292    return NULL;
08293 }
08294 
08295 /*!
08296  * \brief Function to post an empty cdr after a spool call fails.
08297  * \note This function posts an empty cdr for a failed spool call
08298 */
08299 static int ast_pbx_outgoing_cdr_failed(void)
08300 {
08301    /* allocate a channel */
08302    struct ast_channel *chan = ast_dummy_channel_alloc();
08303 
08304    if (!chan)
08305       return -1;  /* failure */
08306 
08307    chan->cdr = ast_cdr_alloc();
08308    if (!chan->cdr) {
08309       /* allocation of the cdr failed */
08310       chan = ast_channel_release(chan);   /* free the channel */
08311       return -1;                /* return failure */
08312    }
08313 
08314    /* allocation of the cdr was successful */
08315    ast_cdr_init(chan->cdr, chan);  /* initialize our channel's cdr */
08316    ast_cdr_start(chan->cdr);       /* record the start and stop time */
08317    ast_cdr_end(chan->cdr);
08318    ast_cdr_failed(chan->cdr);      /* set the status to failed */
08319    ast_cdr_detach(chan->cdr);      /* post and free the record */
08320    chan->cdr = NULL;
08321    chan = ast_channel_release(chan);         /* free the channel */
08322 
08323    return 0;  /* success */
08324 }
08325 
08326 int ast_pbx_outgoing_exten(const char *type, format_t format, void *data, int timeout, const char *context, const char *exten, int priority, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **channel)
08327 {
08328    struct ast_channel *chan;
08329    struct async_stat *as;
08330    int res = -1, cdr_res = -1;
08331    struct outgoing_helper oh;
08332 
08333    if (synchronous) {
08334       oh.context = context;
08335       oh.exten = exten;
08336       oh.priority = priority;
08337       oh.cid_num = cid_num;
08338       oh.cid_name = cid_name;
08339       oh.account = account;
08340       oh.vars = vars;
08341       oh.parent_channel = NULL;
08342 
08343       chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
08344       if (channel) {
08345          *channel = chan;
08346          if (chan)
08347             ast_channel_lock(chan);
08348       }
08349       if (chan) {
08350          if (chan->_state == AST_STATE_UP) {
08351                res = 0;
08352             ast_verb(4, "Channel %s was answered.\n", chan->name);
08353 
08354             if (synchronous > 1) {
08355                if (channel)
08356                   ast_channel_unlock(chan);
08357                if (ast_pbx_run(chan)) {
08358                   ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
08359                   if (channel)
08360                      *channel = NULL;
08361                   ast_hangup(chan);
08362                   chan = NULL;
08363                   res = -1;
08364                }
08365             } else {
08366                if (ast_pbx_start(chan)) {
08367                   ast_log(LOG_ERROR, "Unable to start PBX on %s\n", chan->name);
08368                   if (channel) {
08369                      *channel = NULL;
08370                      ast_channel_unlock(chan);
08371                   }
08372                   ast_hangup(chan);
08373                   res = -1;
08374                }
08375                chan = NULL;
08376             }
08377          } else {
08378             ast_verb(4, "Channel %s was never answered.\n", chan->name);
08379 
08380             if (chan->cdr) { /* update the cdr */
08381                /* here we update the status of the call, which sould be busy.
08382                 * if that fails then we set the status to failed */
08383                if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
08384                   ast_cdr_failed(chan->cdr);
08385             }
08386 
08387             if (channel) {
08388                *channel = NULL;
08389                ast_channel_unlock(chan);
08390             }
08391             ast_hangup(chan);
08392             chan = NULL;
08393          }
08394       }
08395 
08396       if (res < 0) { /* the call failed for some reason */
08397          if (*reason == 0) { /* if the call failed (not busy or no answer)
08398                         * update the cdr with the failed message */
08399             cdr_res = ast_pbx_outgoing_cdr_failed();
08400             if (cdr_res != 0) {
08401                res = cdr_res;
08402                goto outgoing_exten_cleanup;
08403             }
08404          }
08405 
08406          /* create a fake channel and execute the "failed" extension (if it exists) within the requested context */
08407          /* check if "failed" exists */
08408          if (ast_exists_extension(chan, context, "failed", 1, NULL)) {
08409             chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", NULL, 0, "OutgoingSpoolFailed");
08410             if (chan) {
08411                char failed_reason[4] = "";
08412                if (!ast_strlen_zero(context))
08413                   ast_copy_string(chan->context, context, sizeof(chan->context));
08414                set_ext_pri(chan, "failed", 1);
08415                ast_set_variables(chan, vars);
08416                snprintf(failed_reason, sizeof(failed_reason), "%d", *reason);
08417                pbx_builtin_setvar_helper(chan, "REASON", failed_reason);
08418                if (account)
08419                   ast_cdr_setaccount(chan, account);
08420                if (ast_pbx_run(chan)) {
08421                   ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
08422                   ast_hangup(chan);
08423                }
08424                chan = NULL;
08425             }
08426          }
08427       }
08428    } else {
08429       if (!(as = ast_calloc(1, sizeof(*as)))) {
08430          res = -1;
08431          goto outgoing_exten_cleanup;
08432       }
08433       chan = ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name);
08434       if (channel) {
08435          *channel = chan;
08436          if (chan)
08437             ast_channel_lock(chan);
08438       }
08439       if (!chan) {
08440          ast_free(as);
08441          res = -1;
08442          goto outgoing_exten_cleanup;
08443       }
08444       as->chan = chan;
08445       ast_copy_string(as->context, context, sizeof(as->context));
08446       set_ext_pri(as->chan,  exten, priority);
08447       as->timeout = timeout;
08448       ast_set_variables(chan, vars);
08449       if (account)
08450          ast_cdr_setaccount(chan, account);
08451       if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
08452          ast_log(LOG_WARNING, "Failed to start async wait\n");
08453          ast_free(as);
08454          if (channel) {
08455             *channel = NULL;
08456             ast_channel_unlock(chan);
08457          }
08458          ast_hangup(chan);
08459          res = -1;
08460          goto outgoing_exten_cleanup;
08461       }
08462       res = 0;
08463    }
08464 outgoing_exten_cleanup:
08465    ast_variables_destroy(vars);
08466    return res;
08467 }
08468 
08469 struct app_tmp {
08470    char app[256];
08471    char data[256];
08472    struct ast_channel *chan;
08473    pthread_t t;
08474 };
08475 
08476 /*! \brief run the application and free the descriptor once done */
08477 static void *ast_pbx_run_app(void *data)
08478 {
08479    struct app_tmp *tmp = data;
08480    struct ast_app *app;
08481    app = pbx_findapp(tmp->app);
08482    if (app) {
08483       ast_verb(4, "Launching %s(%s) on %s\n", tmp->app, tmp->data, tmp->chan->name);
08484       pbx_exec(tmp->chan, app, tmp->data);
08485    } else
08486       ast_log(LOG_WARNING, "No such application '%s'\n", tmp->app);
08487    ast_hangup(tmp->chan);
08488    ast_free(tmp);
08489    return NULL;
08490 }
08491 
08492 int ast_pbx_outgoing_app(const char *type, format_t format, void *data, int timeout, const char *app, const char *appdata, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **locked_channel)
08493 {
08494    struct ast_channel *chan;
08495    struct app_tmp *tmp;
08496    int res = -1, cdr_res = -1;
08497    struct outgoing_helper oh;
08498 
08499    memset(&oh, 0, sizeof(oh));
08500    oh.vars = vars;
08501    oh.account = account;
08502 
08503    if (locked_channel)
08504       *locked_channel = NULL;
08505    if (ast_strlen_zero(app)) {
08506       res = -1;
08507       goto outgoing_app_cleanup;
08508    }
08509    if (synchronous) {
08510       chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
08511       if (chan) {
08512          ast_set_variables(chan, vars);
08513          if (account)
08514             ast_cdr_setaccount(chan, account);
08515          if (chan->_state == AST_STATE_UP) {
08516             res = 0;
08517             ast_verb(4, "Channel %s was answered.\n", chan->name);
08518             tmp = ast_calloc(1, sizeof(*tmp));
08519             if (!tmp)
08520                res = -1;
08521             else {
08522                ast_copy_string(tmp->app, app, sizeof(tmp->app));
08523                if (appdata)
08524                   ast_copy_string(tmp->data, appdata, sizeof(tmp->data));
08525                tmp->chan = chan;
08526                if (synchronous > 1) {
08527                   if (locked_channel)
08528                      ast_channel_unlock(chan);
08529                   ast_pbx_run_app(tmp);
08530                } else {
08531                   if (locked_channel)
08532                      ast_channel_lock(chan);
08533                   if (ast_pthread_create_detached(&tmp->t, NULL, ast_pbx_run_app, tmp)) {
08534                      ast_log(LOG_WARNING, "Unable to spawn execute thread on %s: %s\n", chan->name, strerror(errno));
08535                      ast_free(tmp);
08536                      if (locked_channel)
08537                         ast_channel_unlock(chan);
08538                      ast_hangup(chan);
08539                      res = -1;
08540                   } else {
08541                      if (locked_channel)
08542                         *locked_channel = chan;
08543                   }
08544                }
08545             }
08546          } else {
08547             ast_verb(4, "Channel %s was never answered.\n", chan->name);
08548             if (chan->cdr) { /* update the cdr */
08549                /* here we update the status of the call, which sould be busy.
08550                 * if that fails then we set the status to failed */
08551                if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
08552                   ast_cdr_failed(chan->cdr);
08553             }
08554             ast_hangup(chan);
08555          }
08556       }
08557 
08558       if (res < 0) { /* the call failed for some reason */
08559          if (*reason == 0) { /* if the call failed (not busy or no answer)
08560                         * update the cdr with the failed message */
08561             cdr_res = ast_pbx_outgoing_cdr_failed();
08562             if (cdr_res != 0) {
08563                res = cdr_res;
08564                goto outgoing_app_cleanup;
08565             }
08566          }
08567       }
08568 
08569    } else {
08570       struct async_stat *as;
08571       if (!(as = ast_calloc(1, sizeof(*as)))) {
08572          res = -1;
08573          goto outgoing_app_cleanup;
08574       }
08575       chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
08576       if (!chan) {
08577          ast_free(as);
08578          res = -1;
08579          goto outgoing_app_cleanup;
08580       }
08581       as->chan = chan;
08582       ast_copy_string(as->app, app, sizeof(as->app));
08583       if (appdata)
08584          ast_copy_string(as->appdata,  appdata, sizeof(as->appdata));
08585       as->timeout = timeout;
08586       ast_set_variables(chan, vars);
08587       if (account)
08588          ast_cdr_setaccount(chan, account);
08589       /* Start a new thread, and get something handling this channel. */
08590       if (locked_channel)
08591          ast_channel_lock(chan);
08592       if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
08593          ast_log(LOG_WARNING, "Failed to start async wait\n");
08594          ast_free(as);
08595          if (locked_channel)
08596             ast_channel_unlock(chan);
08597          ast_hangup(chan);
08598          res = -1;
08599          goto outgoing_app_cleanup;
08600       } else {
08601          if (locked_channel)
08602             *locked_channel = chan;
08603       }
08604       res = 0;
08605    }
08606 outgoing_app_cleanup:
08607    ast_variables_destroy(vars);
08608    return res;
08609 }
08610 
08611 /* this is the guts of destroying a context --
08612    freeing up the structure, traversing and destroying the
08613    extensions, switches, ignorepats, includes, etc. etc. */
08614 
08615 static void __ast_internal_context_destroy( struct ast_context *con)
08616 {
08617    struct ast_include *tmpi;
08618    struct ast_sw *sw;
08619    struct ast_exten *e, *el, *en;
08620    struct ast_ignorepat *ipi;
08621    struct ast_context *tmp = con;
08622 
08623    for (tmpi = tmp->includes; tmpi; ) { /* Free includes */
08624       struct ast_include *tmpil = tmpi;
08625       tmpi = tmpi->next;
08626       ast_free(tmpil);
08627    }
08628    for (ipi = tmp->ignorepats; ipi; ) { /* Free ignorepats */
08629       struct ast_ignorepat *ipl = ipi;
08630       ipi = ipi->next;
08631       ast_free(ipl);
08632    }
08633    if (tmp->registrar)
08634       ast_free(tmp->registrar);
08635 
08636    /* destroy the hash tabs */
08637    if (tmp->root_table) {
08638       ast_hashtab_destroy(tmp->root_table, 0);
08639    }
08640    /* and destroy the pattern tree */
08641    if (tmp->pattern_tree)
08642       destroy_pattern_tree(tmp->pattern_tree);
08643 
08644    while ((sw = AST_LIST_REMOVE_HEAD(&tmp->alts, list)))
08645       ast_free(sw);
08646    for (e = tmp->root; e;) {
08647       for (en = e->peer; en;) {
08648          el = en;
08649          en = en->peer;
08650          destroy_exten(el);
08651       }
08652       el = e;
08653       e = e->next;
08654       destroy_exten(el);
08655    }
08656    tmp->root = NULL;
08657    ast_rwlock_destroy(&tmp->lock);
08658    ast_free(tmp);
08659 }
08660 
08661 
08662 void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar)
08663 {
08664    struct ast_context *tmp, *tmpl=NULL;
08665    struct ast_exten *exten_item, *prio_item;
08666 
08667    for (tmp = list; tmp; ) {
08668       struct ast_context *next = NULL; /* next starting point */
08669          /* The following code used to skip forward to the next
08670             context with matching registrar, but this didn't
08671             make sense; individual priorities registrar'd to
08672             the matching registrar could occur in any context! */
08673       ast_debug(1, "Investigate ctx %s %s\n", tmp->name, tmp->registrar);
08674       if (con) {
08675          for (; tmp; tmpl = tmp, tmp = tmp->next) { /* skip to the matching context */
08676             ast_debug(1, "check ctx %s %s\n", tmp->name, tmp->registrar);
08677             if ( !strcasecmp(tmp->name, con->name) ) {
08678                break;   /* found it */
08679             }
08680          }
08681       }
08682 
08683       if (!tmp)   /* not found, we are done */
08684          break;
08685       ast_wrlock_context(tmp);
08686 
08687       if (registrar) {
08688          /* then search thru and remove any extens that match registrar. */
08689          struct ast_hashtab_iter *exten_iter;
08690          struct ast_hashtab_iter *prio_iter;
08691          struct ast_ignorepat *ip, *ipl = NULL, *ipn = NULL;
08692          struct ast_include *i, *pi = NULL, *ni = NULL;
08693          struct ast_sw *sw = NULL;
08694 
08695          /* remove any ignorepats whose registrar matches */
08696          for (ip = tmp->ignorepats; ip; ip = ipn) {
08697             ipn = ip->next;
08698             if (!strcmp(ip->registrar, registrar)) {
08699                if (ipl) {
08700                   ipl->next = ip->next;
08701                   ast_free(ip);
08702                   continue; /* don't change ipl */
08703                } else {
08704                   tmp->ignorepats = ip->next;
08705                   ast_free(ip);
08706                   continue; /* don't change ipl */
08707                }
08708             }
08709             ipl = ip;
08710          }
08711          /* remove any includes whose registrar matches */
08712          for (i = tmp->includes; i; i = ni) {
08713             ni = i->next;
08714             if (strcmp(i->registrar, registrar) == 0) {
08715                /* remove from list */
08716                if (pi) {
08717                   pi->next = i->next;
08718                   /* free include */
08719                   ast_free(i);
08720                   continue; /* don't change pi */
08721                } else {
08722                   tmp->includes = i->next;
08723                   /* free include */
08724                   ast_free(i);
08725                   continue; /* don't change pi */
08726                }
08727             }
08728             pi = i;
08729          }
08730          /* remove any switches whose registrar matches */
08731          AST_LIST_TRAVERSE_SAFE_BEGIN(&tmp->alts, sw, list) {
08732             if (strcmp(sw->registrar,registrar) == 0) {
08733                AST_LIST_REMOVE_CURRENT(list);
08734                ast_free(sw);
08735             }
08736          }
08737          AST_LIST_TRAVERSE_SAFE_END;
08738 
08739          if (tmp->root_table) { /* it is entirely possible that the context is EMPTY */
08740             exten_iter = ast_hashtab_start_traversal(tmp->root_table);
08741             while ((exten_item=ast_hashtab_next(exten_iter))) {
08742                int end_traversal = 1;
08743                prio_iter = ast_hashtab_start_traversal(exten_item->peer_table);
08744                while ((prio_item=ast_hashtab_next(prio_iter))) {
08745                   char extension[AST_MAX_EXTENSION];
08746                   char cidmatch[AST_MAX_EXTENSION];
08747                   if (!prio_item->registrar || strcmp(prio_item->registrar, registrar) != 0) {
08748                      continue;
08749                   }
08750                   ast_verb(3, "Remove %s/%s/%d, registrar=%s; con=%s(%p); con->root=%p\n",
08751                          tmp->name, prio_item->exten, prio_item->priority, registrar, con? con->name : "<nil>", con, con? con->root_table: NULL);
08752                   /* set matchcid to 1 to insure we get a direct match, and NULL registrar to make sure no wildcarding is done */
08753                   ast_copy_string(extension, prio_item->exten, sizeof(extension));
08754                   if (prio_item->cidmatch) {
08755                      ast_copy_string(cidmatch, prio_item->cidmatch, sizeof(cidmatch));
08756                   }
08757                   end_traversal &= ast_context_remove_extension_callerid2(tmp, extension, prio_item->priority, prio_item->cidmatch ? cidmatch : NULL, 1, NULL, 1);
08758                }
08759                /* Explanation:
08760                 * ast_context_remove_extension_callerid2 will destroy the extension that it comes across. This
08761                 * destruction includes destroying the exten's peer_table, which we are currently traversing. If
08762                 * ast_context_remove_extension_callerid2 ever should return '0' then this means we have destroyed
08763                 * the hashtable which we are traversing, and thus calling ast_hashtab_end_traversal will result
08764                 * in reading invalid memory. Thus, if we detect that we destroyed the hashtable, then we will simply
08765                 * free the iterator
08766                 */
08767                if (end_traversal) {
08768                   ast_hashtab_end_traversal(prio_iter);
08769                } else {
08770                   ast_free(prio_iter);
08771                }
08772             }
08773             ast_hashtab_end_traversal(exten_iter);
08774          }
08775 
08776          /* delete the context if it's registrar matches, is empty, has refcount of 1, */
08777          /* it's not empty, if it has includes, ignorepats, or switches that are registered from
08778             another registrar. It's not empty if there are any extensions */
08779          if (strcmp(tmp->registrar, registrar) == 0 && tmp->refcount < 2 && !tmp->root && !tmp->ignorepats && !tmp->includes && AST_LIST_EMPTY(&tmp->alts)) {
08780             ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar);
08781             ast_hashtab_remove_this_object(contexttab, tmp);
08782 
08783             next = tmp->next;
08784             if (tmpl)
08785                tmpl->next = next;
08786             else
08787                contexts = next;
08788             /* Okay, now we're safe to let it go -- in a sense, we were
08789                ready to let it go as soon as we locked it. */
08790             ast_unlock_context(tmp);
08791             __ast_internal_context_destroy(tmp);
08792          } else {
08793             ast_debug(1,"Couldn't delete ctx %s/%s; refc=%d; tmp.root=%p\n", tmp->name, tmp->registrar,
08794                     tmp->refcount, tmp->root);
08795             ast_unlock_context(tmp);
08796             next = tmp->next;
08797             tmpl = tmp;
08798          }
08799       } else if (con) {
08800          ast_verb(3, "Deleting context %s registrar=%s\n", tmp->name, tmp->registrar);
08801          ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar);
08802          ast_hashtab_remove_this_object(contexttab, tmp);
08803 
08804          next = tmp->next;
08805          if (tmpl)
08806             tmpl->next = next;
08807          else
08808             contexts = next;
08809          /* Okay, now we're safe to let it go -- in a sense, we were
08810             ready to let it go as soon as we locked it. */
08811          ast_unlock_context(tmp);
08812          __ast_internal_context_destroy(tmp);
08813       }
08814 
08815       /* if we have a specific match, we are done, otherwise continue */
08816       tmp = con ? NULL : next;
08817    }
08818 }
08819 
08820 void ast_context_destroy(struct ast_context *con, const char *registrar)
08821 {
08822    ast_wrlock_contexts();
08823    __ast_context_destroy(contexts, contexts_table, con,registrar);
08824    ast_unlock_contexts();
08825 }
08826 
08827 static void wait_for_hangup(struct ast_channel *chan, const void *data)
08828 {
08829    int res;
08830    struct ast_frame *f;
08831    double waitsec;
08832    int waittime;
08833 
08834    if (ast_strlen_zero(data) || (sscanf(data, "%30lg", &waitsec) != 1) || (waitsec < 0))
08835       waitsec = -1;
08836    if (waitsec > -1) {
08837       waittime = waitsec * 1000.0;
08838       ast_safe_sleep(chan, waittime);
08839    } else do {
08840       res = ast_waitfor(chan, -1);
08841       if (res < 0)
08842          return;
08843       f = ast_read(chan);
08844       if (f)
08845          ast_frfree(f);
08846    } while(f);
08847 }
08848 
08849 /*!
08850  * \ingroup applications
08851  */
08852 static int pbx_builtin_proceeding(struct ast_channel *chan, const char *data)
08853 {
08854    ast_indicate(chan, AST_CONTROL_PROCEEDING);
08855    return 0;
08856 }
08857 
08858 /*!
08859  * \ingroup applications
08860  */
08861 static int pbx_builtin_progress(struct ast_channel *chan, const char *data)
08862 {
08863    ast_indicate(chan, AST_CONTROL_PROGRESS);
08864    return 0;
08865 }
08866 
08867 /*!
08868  * \ingroup applications
08869  */
08870 static int pbx_builtin_ringing(struct ast_channel *chan, const char *data)
08871 {
08872    ast_indicate(chan, AST_CONTROL_RINGING);
08873    return 0;
08874 }
08875 
08876 /*!
08877  * \ingroup applications
08878  */
08879 static int pbx_builtin_busy(struct ast_channel *chan, const char *data)
08880 {
08881    ast_indicate(chan, AST_CONTROL_BUSY);
08882    /* Don't change state of an UP channel, just indicate
08883       busy in audio */
08884    if (chan->_state != AST_STATE_UP) {
08885       ast_setstate(chan, AST_STATE_BUSY);
08886       ast_cdr_busy(chan->cdr);
08887    }
08888    wait_for_hangup(chan, data);
08889    return -1;
08890 }
08891 
08892 /*!
08893  * \ingroup applications
08894  */
08895 static int pbx_builtin_congestion(struct ast_channel *chan, const char *data)
08896 {
08897    ast_indicate(chan, AST_CONTROL_CONGESTION);
08898    /* Don't change state of an UP channel, just indicate
08899       congestion in audio */
08900    if (chan->_state != AST_STATE_UP)
08901       ast_setstate(chan, AST_STATE_BUSY);
08902    wait_for_hangup(chan, data);
08903    return -1;
08904 }
08905 
08906 /*!
08907  * \ingroup applications
08908  */
08909 static int pbx_builtin_answer(struct ast_channel *chan, const char *data)
08910 {
08911    int delay = 0;
08912    int answer_cdr = 1;
08913    char *parse;
08914    AST_DECLARE_APP_ARGS(args,
08915       AST_APP_ARG(delay);
08916       AST_APP_ARG(answer_cdr);
08917    );
08918 
08919    if (ast_strlen_zero(data)) {
08920       return __ast_answer(chan, 0, 1);
08921    }
08922 
08923    parse = ast_strdupa(data);
08924 
08925    AST_STANDARD_APP_ARGS(args, parse);
08926 
08927    if (!ast_strlen_zero(args.delay) && (chan->_state != AST_STATE_UP))
08928       delay = atoi(data);
08929 
08930    if (delay < 0) {
08931       delay = 0;
08932    }
08933 
08934    if (!ast_strlen_zero(args.answer_cdr) && !strcasecmp(args.answer_cdr, "nocdr")) {
08935       answer_cdr = 0;
08936    }
08937 
08938    return __ast_answer(chan, delay, answer_cdr);
08939 }
08940 
08941 static int pbx_builtin_incomplete(struct ast_channel *chan, const char *data)
08942 {
08943    const char *options = data;
08944    int answer = 1;
08945 
08946    /* Some channels can receive DTMF in unanswered state; some cannot */
08947    if (!ast_strlen_zero(options) && strchr(options, 'n')) {
08948       answer = 0;
08949    }
08950 
08951    /* If the channel is hungup, stop waiting */
08952    if (ast_check_hangup(chan)) {
08953       return -1;
08954    } else if (chan->_state != AST_STATE_UP && answer) {
08955       __ast_answer(chan, 0, 1);
08956    }
08957 
08958    return AST_PBX_INCOMPLETE;
08959 }
08960 
08961 AST_APP_OPTIONS(resetcdr_opts, {
08962    AST_APP_OPTION('w', AST_CDR_FLAG_POSTED),
08963    AST_APP_OPTION('a', AST_CDR_FLAG_LOCKED),
08964    AST_APP_OPTION('v', AST_CDR_FLAG_KEEP_VARS),
08965    AST_APP_OPTION('e', AST_CDR_FLAG_POST_ENABLE),
08966 });
08967 
08968 /*!
08969  * \ingroup applications
08970  */
08971 static int pbx_builtin_resetcdr(struct ast_channel *chan, const char *data)
08972 {
08973    char *args;
08974    struct ast_flags flags = { 0 };
08975 
08976    if (!ast_strlen_zero(data)) {
08977       args = ast_strdupa(data);
08978       ast_app_parse_options(resetcdr_opts, &flags, NULL, args);
08979    }
08980 
08981    ast_cdr_reset(chan->cdr, &flags);
08982 
08983    return 0;
08984 }
08985 
08986 /*!
08987  * \ingroup applications
08988  */
08989 static int pbx_builtin_setamaflags(struct ast_channel *chan, const char *data)
08990 {
08991    /* Copy the AMA Flags as specified */
08992    ast_cdr_setamaflags(chan, data ? data : "");
08993    return 0;
08994 }
08995 
08996 /*!
08997  * \ingroup applications
08998  */
08999 static int pbx_builtin_hangup(struct ast_channel *chan, const char *data)
09000 {
09001    ast_set_hangupsource(chan, "dialplan/builtin", 0);
09002 
09003    if (!ast_strlen_zero(data)) {
09004       int cause;
09005       char *endptr;
09006 
09007       if ((cause = ast_str2cause(data)) > -1) {
09008          chan->hangupcause = cause;
09009          return -1;
09010       }
09011 
09012       cause = strtol((const char *) data, &endptr, 10);
09013       if (cause != 0 || (data != endptr)) {
09014          chan->hangupcause = cause;
09015          return -1;
09016       }
09017 
09018       ast_log(LOG_WARNING, "Invalid cause given to Hangup(): \"%s\"\n", (char *) data);
09019    }
09020 
09021    if (!chan->hangupcause) {
09022       chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
09023    }
09024 
09025    return -1;
09026 }
09027 
09028 /*!
09029  * \ingroup functions
09030  */
09031 static int testtime_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
09032 {
09033    struct ast_tm tm;
09034    struct timeval tv;
09035    char *remainder, result[30], timezone[80];
09036 
09037    /* Turn off testing? */
09038    if (!pbx_checkcondition(value)) {
09039       pbx_builtin_setvar_helper(chan, "TESTTIME", NULL);
09040       return 0;
09041    }
09042 
09043    /* Parse specified time */
09044    if (!(remainder = ast_strptime(value, "%Y/%m/%d %H:%M:%S", &tm))) {
09045       return -1;
09046    }
09047    sscanf(remainder, "%79s", timezone);
09048    tv = ast_mktime(&tm, S_OR(timezone, NULL));
09049 
09050    snprintf(result, sizeof(result), "%ld", (long) tv.tv_sec);
09051    pbx_builtin_setvar_helper(chan, "__TESTTIME", result);
09052    return 0;
09053 }
09054 
09055 static struct ast_custom_function testtime_function = {
09056    .name = "TESTTIME",
09057    .write = testtime_write,
09058 };
09059 
09060 /*!
09061  * \ingroup applications
09062  */
09063 static int pbx_builtin_gotoiftime(struct ast_channel *chan, const char *data)
09064 {
09065    char *s, *ts, *branch1, *branch2, *branch;
09066    struct ast_timing timing;
09067    const char *ctime;
09068    struct timeval tv = ast_tvnow();
09069    long timesecs;
09070 
09071    if (ast_strlen_zero(data)) {
09072       ast_log(LOG_WARNING, "GotoIfTime requires an argument:\n  <time range>,<days of week>,<days of month>,<months>[,<timezone>]?'labeliftrue':'labeliffalse'\n");
09073       return -1;
09074    }
09075 
09076    ts = s = ast_strdupa(data);
09077 
09078    if (chan) {
09079       ast_channel_lock(chan);
09080       if ((ctime = pbx_builtin_getvar_helper(chan, "TESTTIME")) && sscanf(ctime, "%ld", &timesecs) == 1) {
09081          tv.tv_sec = timesecs;
09082       } else if (ctime) {
09083          ast_log(LOG_WARNING, "Using current time to evaluate\n");
09084          /* Reset when unparseable */
09085          pbx_builtin_setvar_helper(chan, "TESTTIME", NULL);
09086       }
09087       ast_channel_unlock(chan);
09088    }
09089    /* Separate the Goto path */
09090    strsep(&ts, "?");
09091    branch1 = strsep(&ts,":");
09092    branch2 = strsep(&ts,"");
09093 
09094    /* struct ast_include include contained garbage here, fixed by zeroing it on get_timerange */
09095    if (ast_build_timing(&timing, s) && ast_check_timing2(&timing, tv)) {
09096       branch = branch1;
09097    } else {
09098       branch = branch2;
09099    }
09100    ast_destroy_timing(&timing);
09101 
09102    if (ast_strlen_zero(branch)) {
09103       ast_debug(1, "Not taking any branch\n");
09104       return 0;
09105    }
09106 
09107    return pbx_builtin_goto(chan, branch);
09108 }
09109 
09110 /*!
09111  * \ingroup applications
09112  */
09113 static int pbx_builtin_execiftime(struct ast_channel *chan, const char *data)
09114 {
09115    char *s, *appname;
09116    struct ast_timing timing;
09117    struct ast_app *app;
09118    static const char * const usage = "ExecIfTime requires an argument:\n  <time range>,<days of week>,<days of month>,<months>[,<timezone>]?<appname>[(<appargs>)]";
09119 
09120    if (ast_strlen_zero(data)) {
09121       ast_log(LOG_WARNING, "%s\n", usage);
09122       return -1;
09123    }
09124 
09125    appname = ast_strdupa(data);
09126 
09127    s = strsep(&appname, "?"); /* Separate the timerange and application name/data */
09128    if (!appname) {   /* missing application */
09129       ast_log(LOG_WARNING, "%s\n", usage);
09130       return -1;
09131    }
09132 
09133    if (!ast_build_timing(&timing, s)) {
09134       ast_log(LOG_WARNING, "Invalid Time Spec: %s\nCorrect usage: %s\n", s, usage);
09135       ast_destroy_timing(&timing);
09136       return -1;
09137    }
09138 
09139    if (!ast_check_timing(&timing))  { /* outside the valid time window, just return */
09140       ast_destroy_timing(&timing);
09141       return 0;
09142    }
09143    ast_destroy_timing(&timing);
09144 
09145    /* now split appname(appargs) */
09146    if ((s = strchr(appname, '('))) {
09147       char *e;
09148       *s++ = '\0';
09149       if ((e = strrchr(s, ')')))
09150          *e = '\0';
09151       else
09152          ast_log(LOG_WARNING, "Failed to find closing parenthesis\n");
09153    }
09154 
09155 
09156    if ((app = pbx_findapp(appname))) {
09157       return pbx_exec(chan, app, S_OR(s, ""));
09158    } else {
09159       ast_log(LOG_WARNING, "Cannot locate application %s\n", appname);
09160       return -1;
09161    }
09162 }
09163 
09164 /*!
09165  * \ingroup applications
09166  */
09167 static int pbx_builtin_wait(struct ast_channel *chan, const char *data)
09168 {
09169    int ms;
09170 
09171    /* Wait for "n" seconds */
09172    if (!ast_app_parse_timelen(data, &ms, TIMELEN_SECONDS) && ms > 0) {
09173       return ast_safe_sleep(chan, ms);
09174    }
09175    return 0;
09176 }
09177 
09178 /*!
09179  * \ingroup applications
09180  */
09181 static int pbx_builtin_waitexten(struct ast_channel *chan, const char *data)
09182 {
09183    int ms, res;
09184    struct ast_flags flags = {0};
09185    char *opts[1] = { NULL };
09186    char *parse;
09187    AST_DECLARE_APP_ARGS(args,
09188       AST_APP_ARG(timeout);
09189       AST_APP_ARG(options);
09190    );
09191 
09192    if (!ast_strlen_zero(data)) {
09193       parse = ast_strdupa(data);
09194       AST_STANDARD_APP_ARGS(args, parse);
09195    } else
09196       memset(&args, 0, sizeof(args));
09197 
09198    if (args.options)
09199       ast_app_parse_options(waitexten_opts, &flags, opts, args.options);
09200 
09201    if (ast_test_flag(&flags, WAITEXTEN_MOH) && !opts[0] ) {
09202       ast_log(LOG_WARNING, "The 'm' option has been specified for WaitExten without a class.\n"); 
09203    } else if (ast_test_flag(&flags, WAITEXTEN_MOH)) {
09204       ast_indicate_data(chan, AST_CONTROL_HOLD, S_OR(opts[0], NULL), strlen(opts[0]));
09205    } else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE)) {
09206       struct ast_tone_zone_sound *ts = ast_get_indication_tone(chan->zone, "dial");
09207       if (ts) {
09208          ast_playtones_start(chan, 0, ts->data, 0);
09209          ts = ast_tone_zone_sound_unref(ts);
09210       } else {
09211          ast_tonepair_start(chan, 350, 440, 0, 0);
09212       }
09213    }
09214    /* Wait for "n" seconds */
09215    if (!ast_app_parse_timelen(args.timeout, &ms, TIMELEN_SECONDS) && ms > 0) {
09216       /* Yay! */
09217    } else if (chan->pbx) {
09218       ms = chan->pbx->rtimeoutms;
09219    } else {
09220       ms = 10000;
09221    }
09222 
09223    res = ast_waitfordigit(chan, ms);
09224    if (!res) {
09225       if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 1,
09226          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
09227          ast_verb(3, "Timeout on %s, continuing...\n", chan->name);
09228       } else if (chan->_softhangup == AST_SOFTHANGUP_TIMEOUT) {
09229          ast_verb(3, "Call timeout on %s, checking for 'T'\n", chan->name);
09230          res = -1;
09231       } else if (ast_exists_extension(chan, chan->context, "t", 1,
09232          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
09233          ast_verb(3, "Timeout on %s, going to 't'\n", chan->name);
09234          set_ext_pri(chan, "t", 0); /* 0 will become 1, next time through the loop */
09235       } else {
09236          ast_log(LOG_WARNING, "Timeout but no rule 't' in context '%s'\n", chan->context);
09237          res = -1;
09238       }
09239    }
09240 
09241    if (ast_test_flag(&flags, WAITEXTEN_MOH))
09242       ast_indicate(chan, AST_CONTROL_UNHOLD);
09243    else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE))
09244       ast_playtones_stop(chan);
09245 
09246    return res;
09247 }
09248 
09249 /*!
09250  * \ingroup applications
09251  */
09252 static int pbx_builtin_background(struct ast_channel *chan, const char *data)
09253 {
09254    int res = 0;
09255    int mres = 0;
09256    struct ast_flags flags = {0};
09257    char *parse, exten[2] = "";
09258    AST_DECLARE_APP_ARGS(args,
09259       AST_APP_ARG(filename);
09260       AST_APP_ARG(options);
09261       AST_APP_ARG(lang);
09262       AST_APP_ARG(context);
09263    );
09264 
09265    if (ast_strlen_zero(data)) {
09266       ast_log(LOG_WARNING, "Background requires an argument (filename)\n");
09267       return -1;
09268    }
09269 
09270    parse = ast_strdupa(data);
09271 
09272    AST_STANDARD_APP_ARGS(args, parse);
09273 
09274    if (ast_strlen_zero(args.lang))
09275       args.lang = (char *)chan->language; /* XXX this is const */
09276 
09277    if (ast_strlen_zero(args.context)) {
09278       const char *context;
09279       ast_channel_lock(chan);
09280       if ((context = pbx_builtin_getvar_helper(chan, "MACRO_CONTEXT"))) {
09281          args.context = ast_strdupa(context);
09282       } else {
09283          args.context = chan->context;
09284       }
09285       ast_channel_unlock(chan);
09286    }
09287 
09288    if (args.options) {
09289       if (!strcasecmp(args.options, "skip"))
09290          flags.flags = BACKGROUND_SKIP;
09291       else if (!strcasecmp(args.options, "noanswer"))
09292          flags.flags = BACKGROUND_NOANSWER;
09293       else
09294          ast_app_parse_options(background_opts, &flags, NULL, args.options);
09295    }
09296 
09297    /* Answer if need be */
09298    if (chan->_state != AST_STATE_UP) {
09299       if (ast_test_flag(&flags, BACKGROUND_SKIP)) {
09300          goto done;
09301       } else if (!ast_test_flag(&flags, BACKGROUND_NOANSWER)) {
09302          res = ast_answer(chan);
09303       }
09304    }
09305 
09306    if (!res) {
09307       char *back = ast_strip(args.filename);
09308       char *front;
09309 
09310       ast_stopstream(chan);      /* Stop anything playing */
09311       /* Stream the list of files */
09312       while (!res && (front = strsep(&back, "&")) ) {
09313          if ( (res = ast_streamfile(chan, front, args.lang)) ) {
09314             ast_log(LOG_WARNING, "ast_streamfile failed on %s for %s\n", chan->name, (char*)data);
09315             res = 0;
09316             mres = 1;
09317             break;
09318          }
09319          if (ast_test_flag(&flags, BACKGROUND_PLAYBACK)) {
09320             res = ast_waitstream(chan, "");
09321          } else if (ast_test_flag(&flags, BACKGROUND_MATCHEXTEN)) {
09322             res = ast_waitstream_exten(chan, args.context);
09323          } else {
09324             res = ast_waitstream(chan, AST_DIGIT_ANY);
09325          }
09326          ast_stopstream(chan);
09327       }
09328    }
09329 
09330    /*
09331     * If the single digit DTMF is an extension in the specified context, then
09332     * go there and signal no DTMF.  Otherwise, we should exit with that DTMF.
09333     * If we're in Macro, we'll exit and seek that DTMF as the beginning of an
09334     * extension in the Macro's calling context.  If we're not in Macro, then
09335     * we'll simply seek that extension in the calling context.  Previously,
09336     * someone complained about the behavior as it related to the interior of a
09337     * Gosub routine, and the fix (#14011) inadvertently broke FreePBX
09338     * (#14940).  This change should fix both of these situations, but with the
09339     * possible incompatibility that if a single digit extension does not exist
09340     * (but a longer extension COULD have matched), it would have previously
09341     * gone immediately to the "i" extension, but will now need to wait for a
09342     * timeout.
09343     *
09344     * Later, we had to add a flag to disable this workaround, because AGI
09345     * users can EXEC Background and reasonably expect that the DTMF code will
09346     * be returned (see #16434).
09347     */
09348    if (!ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS)
09349       && (exten[0] = res)
09350       && ast_canmatch_extension(chan, args.context, exten, 1,
09351          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
09352       && !ast_matchmore_extension(chan, args.context, exten, 1,
09353          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
09354       snprintf(chan->exten, sizeof(chan->exten), "%c", res);
09355       ast_copy_string(chan->context, args.context, sizeof(chan->context));
09356       chan->priority = 0;
09357       res = 0;
09358    }
09359 done:
09360    pbx_builtin_setvar_helper(chan, "BACKGROUNDSTATUS", mres ? "FAILED" : "SUCCESS");
09361    return res;
09362 }
09363 
09364 /*! Goto
09365  * \ingroup applications
09366  */
09367 static int pbx_builtin_goto(struct ast_channel *chan, const char *data)
09368 {
09369    int res = ast_parseable_goto(chan, data);
09370    if (!res)
09371       ast_verb(3, "Goto (%s,%s,%d)\n", chan->context, chan->exten, chan->priority + 1);
09372    return res;
09373 }
09374 
09375 
09376 int pbx_builtin_serialize_variables(struct ast_channel *chan, struct ast_str **buf)
09377 {
09378    struct ast_var_t *variables;
09379    const char *var, *val;
09380    int total = 0;
09381 
09382    if (!chan)
09383       return 0;
09384 
09385    ast_str_reset(*buf);
09386 
09387    ast_channel_lock(chan);
09388 
09389    AST_LIST_TRAVERSE(&chan->varshead, variables, entries) {
09390       if ((var = ast_var_name(variables)) && (val = ast_var_value(variables))
09391          /* && !ast_strlen_zero(var) && !ast_strlen_zero(val) */
09392          ) {
09393          if (ast_str_append(buf, 0, "%s=%s\n", var, val) < 0) {
09394             ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
09395             break;
09396          } else
09397             total++;
09398       } else
09399          break;
09400    }
09401 
09402    ast_channel_unlock(chan);
09403 
09404    return total;
09405 }
09406 
09407 const char *pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
09408 {
09409    struct ast_var_t *variables;
09410    const char *ret = NULL;
09411    int i;
09412    struct varshead *places[2] = { NULL, &globals };
09413 
09414    if (!name)
09415       return NULL;
09416 
09417    if (chan) {
09418       ast_channel_lock(chan);
09419       places[0] = &chan->varshead;
09420    }
09421 
09422    for (i = 0; i < 2; i++) {
09423       if (!places[i])
09424          continue;
09425       if (places[i] == &globals)
09426          ast_rwlock_rdlock(&globalslock);
09427       AST_LIST_TRAVERSE(places[i], variables, entries) {
09428          if (!strcmp(name, ast_var_name(variables))) {
09429             ret = ast_var_value(variables);
09430             break;
09431          }
09432       }
09433       if (places[i] == &globals)
09434          ast_rwlock_unlock(&globalslock);
09435       if (ret)
09436          break;
09437    }
09438 
09439    if (chan)
09440       ast_channel_unlock(chan);
09441 
09442    return ret;
09443 }
09444 
09445 void pbx_builtin_pushvar_helper(struct ast_channel *chan, const char *name, const char *value)
09446 {
09447    struct ast_var_t *newvariable;
09448    struct varshead *headp;
09449 
09450    if (name[strlen(name)-1] == ')') {
09451       char *function = ast_strdupa(name);
09452 
09453       ast_log(LOG_WARNING, "Cannot push a value onto a function\n");
09454       ast_func_write(chan, function, value);
09455       return;
09456    }
09457 
09458    if (chan) {
09459       ast_channel_lock(chan);
09460       headp = &chan->varshead;
09461    } else {
09462       ast_rwlock_wrlock(&globalslock);
09463       headp = &globals;
09464    }
09465 
09466    if (value) {
09467       if (headp == &globals)
09468          ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value);
09469       newvariable = ast_var_assign(name, value);
09470       AST_LIST_INSERT_HEAD(headp, newvariable, entries);
09471    }
09472 
09473    if (chan)
09474       ast_channel_unlock(chan);
09475    else
09476       ast_rwlock_unlock(&globalslock);
09477 }
09478 
09479 int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
09480 {
09481    struct ast_var_t *newvariable;
09482    struct varshead *headp;
09483    const char *nametail = name;
09484 
09485    if (name[strlen(name) - 1] == ')') {
09486       char *function = ast_strdupa(name);
09487 
09488       return ast_func_write(chan, function, value);
09489    }
09490 
09491    if (chan) {
09492       ast_channel_lock(chan);
09493       headp = &chan->varshead;
09494    } else {
09495       ast_rwlock_wrlock(&globalslock);
09496       headp = &globals;
09497    }
09498 
09499    /* For comparison purposes, we have to strip leading underscores */
09500    if (*nametail == '_') {
09501       nametail++;
09502       if (*nametail == '_')
09503          nametail++;
09504    }
09505 
09506    AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
09507       if (strcmp(ast_var_name(newvariable), nametail) == 0) {
09508          /* there is already such a variable, delete it */
09509          AST_LIST_REMOVE_CURRENT(entries);
09510          ast_var_delete(newvariable);
09511          break;
09512       }
09513    }
09514    AST_LIST_TRAVERSE_SAFE_END;
09515 
09516    if (value) {
09517       if (headp == &globals)
09518          ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value);
09519       newvariable = ast_var_assign(name, value);
09520       AST_LIST_INSERT_HEAD(headp, newvariable, entries);
09521       manager_event(EVENT_FLAG_DIALPLAN, "VarSet",
09522          "Channel: %s\r\n"
09523          "Variable: %s\r\n"
09524          "Value: %s\r\n"
09525          "Uniqueid: %s\r\n",
09526          chan ? chan->name : "none", name, value,
09527          chan ? chan->uniqueid : "none");
09528    }
09529 
09530    if (chan)
09531       ast_channel_unlock(chan);
09532    else
09533       ast_rwlock_unlock(&globalslock);
09534    return 0;
09535 }
09536 
09537 int pbx_builtin_setvar(struct ast_channel *chan, const char *data)
09538 {
09539    char *name, *value, *mydata;
09540 
09541    if (ast_compat_app_set) {
09542       return pbx_builtin_setvar_multiple(chan, data);
09543    }
09544 
09545    if (ast_strlen_zero(data)) {
09546       ast_log(LOG_WARNING, "Set requires one variable name/value pair.\n");
09547       return 0;
09548    }
09549 
09550    mydata = ast_strdupa(data);
09551    name = strsep(&mydata, "=");
09552    value = mydata;
09553    if (!value) {
09554       ast_log(LOG_WARNING, "Set requires an '=' to be a valid assignment.\n");
09555       return 0;
09556    }
09557 
09558    if (strchr(name, ' ')) {
09559       ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", name, mydata);
09560    }
09561 
09562    pbx_builtin_setvar_helper(chan, name, value);
09563 
09564    return 0;
09565 }
09566 
09567 int pbx_builtin_setvar_multiple(struct ast_channel *chan, const char *vdata)
09568 {
09569    char *data;
09570    int x;
09571    AST_DECLARE_APP_ARGS(args,
09572       AST_APP_ARG(pair)[24];
09573    );
09574    AST_DECLARE_APP_ARGS(pair,
09575       AST_APP_ARG(name);
09576       AST_APP_ARG(value);
09577    );
09578 
09579    if (ast_strlen_zero(vdata)) {
09580       ast_log(LOG_WARNING, "MSet requires at least one variable name/value pair.\n");
09581       return 0;
09582    }
09583 
09584    data = ast_strdupa(vdata);
09585    AST_STANDARD_APP_ARGS(args, data);
09586 
09587    for (x = 0; x < args.argc; x++) {
09588       AST_NONSTANDARD_APP_ARGS(pair, args.pair[x], '=');
09589       if (pair.argc == 2) {
09590          pbx_builtin_setvar_helper(chan, pair.name, pair.value);
09591          if (strchr(pair.name, ' '))
09592             ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", pair.name, pair.value);
09593       } else if (!chan) {
09594          ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '='\n", pair.name);
09595       } else {
09596          ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '=' (in %s@%s:%d\n", pair.name, chan->exten, chan->context, chan->priority);
09597       }
09598    }
09599 
09600    return 0;
09601 }
09602 
09603 int pbx_builtin_importvar(struct ast_channel *chan, const char *data)
09604 {
09605    char *name;
09606    char *value;
09607    char *channel;
09608    char tmp[VAR_BUF_SIZE];
09609    static int deprecation_warning = 0;
09610 
09611    if (ast_strlen_zero(data)) {
09612       ast_log(LOG_WARNING, "Ignoring, since there is no variable to set\n");
09613       return 0;
09614    }
09615    tmp[0] = 0;
09616    if (!deprecation_warning) {
09617       ast_log(LOG_WARNING, "ImportVar is deprecated.  Please use Set(varname=${IMPORT(channel,variable)}) instead.\n");
09618       deprecation_warning = 1;
09619    }
09620 
09621    value = ast_strdupa(data);
09622    name = strsep(&value,"=");
09623    channel = strsep(&value,",");
09624    if (channel && value && name) { /*! \todo XXX should do !ast_strlen_zero(..) of the args ? */
09625       struct ast_channel *chan2 = ast_channel_get_by_name(channel);
09626       if (chan2) {
09627          char *s = alloca(strlen(value) + 4);
09628          if (s) {
09629             sprintf(s, "${%s}", value);
09630             pbx_substitute_variables_helper(chan2, s, tmp, sizeof(tmp) - 1);
09631          }
09632          chan2 = ast_channel_unref(chan2);
09633       }
09634       pbx_builtin_setvar_helper(chan, name, tmp);
09635    }
09636 
09637    return(0);
09638 }
09639 
09640 static int pbx_builtin_noop(struct ast_channel *chan, const char *data)
09641 {
09642    return 0;
09643 }
09644 
09645 void pbx_builtin_clear_globals(void)
09646 {
09647    struct ast_var_t *vardata;
09648 
09649    ast_rwlock_wrlock(&globalslock);
09650    while ((vardata = AST_LIST_REMOVE_HEAD(&globals, entries)))
09651       ast_var_delete(vardata);
09652    ast_rwlock_unlock(&globalslock);
09653 }
09654 
09655 int pbx_checkcondition(const char *condition)
09656 {
09657    int res;
09658    if (ast_strlen_zero(condition)) {                /* NULL or empty strings are false */
09659       return 0;
09660    } else if (sscanf(condition, "%30d", &res) == 1) { /* Numbers are evaluated for truth */
09661       return res;
09662    } else {                                         /* Strings are true */
09663       return 1;
09664    }
09665 }
09666 
09667 static int pbx_builtin_gotoif(struct ast_channel *chan, const char *data)
09668 {
09669    char *condition, *branch1, *branch2, *branch;
09670    char *stringp;
09671 
09672    if (ast_strlen_zero(data)) {
09673       ast_log(LOG_WARNING, "Ignoring, since there is no variable to check\n");
09674       return 0;
09675    }
09676 
09677    stringp = ast_strdupa(data);
09678    condition = strsep(&stringp,"?");
09679    branch1 = strsep(&stringp,":");
09680    branch2 = strsep(&stringp,"");
09681    branch = pbx_checkcondition(condition) ? branch1 : branch2;
09682 
09683    if (ast_strlen_zero(branch)) {
09684       ast_debug(1, "Not taking any branch\n");
09685       return 0;
09686    }
09687 
09688    return pbx_builtin_goto(chan, branch);
09689 }
09690 
09691 static int pbx_builtin_saynumber(struct ast_channel *chan, const char *data)
09692 {
09693    char tmp[256];
09694    char *number = tmp;
09695    char *options;
09696 
09697    if (ast_strlen_zero(data)) {
09698       ast_log(LOG_WARNING, "SayNumber requires an argument (number)\n");
09699       return -1;
09700    }
09701    ast_copy_string(tmp, data, sizeof(tmp));
09702    strsep(&number, ",");
09703    options = strsep(&number, ",");
09704    if (options) {
09705       if ( strcasecmp(options, "f") && strcasecmp(options, "m") &&
09706          strcasecmp(options, "c") && strcasecmp(options, "n") ) {
09707          ast_log(LOG_WARNING, "SayNumber gender option is either 'f', 'm', 'c' or 'n'\n");
09708          return -1;
09709       }
09710    }
09711 
09712    if (ast_say_number(chan, atoi(tmp), "", chan->language, options)) {
09713       ast_log(LOG_WARNING, "We were unable to say the number %s, is it too large?\n", tmp);
09714    }
09715 
09716    return 0;
09717 }
09718 
09719 static int pbx_builtin_saydigits(struct ast_channel *chan, const char *data)
09720 {
09721    int res = 0;
09722 
09723    if (data)
09724       res = ast_say_digit_str(chan, data, "", chan->language);
09725    return res;
09726 }
09727 
09728 static int pbx_builtin_saycharacters(struct ast_channel *chan, const char *data)
09729 {
09730    int res = 0;
09731 
09732    if (data)
09733       res = ast_say_character_str(chan, data, "", chan->language);
09734    return res;
09735 }
09736 
09737 static int pbx_builtin_sayphonetic(struct ast_channel *chan, const char *data)
09738 {
09739    int res = 0;
09740 
09741    if (data)
09742       res = ast_say_phonetic_str(chan, data, "", chan->language);
09743    return res;
09744 }
09745 
09746 static void device_state_cb(const struct ast_event *event, void *unused)
09747 {
09748    const char *device;
09749    struct statechange *sc;
09750 
09751    device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
09752    if (ast_strlen_zero(device)) {
09753       ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
09754       return;
09755    }
09756 
09757    if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(device) + 1)))
09758       return;
09759    strcpy(sc->dev, device);
09760    if (ast_taskprocessor_push(device_state_tps, handle_statechange, sc) < 0) {
09761       ast_free(sc);
09762    }
09763 }
09764 
09765 /*!
09766  * \internal
09767  * \brief Implements the hints data provider.
09768  */
09769 static int hints_data_provider_get(const struct ast_data_search *search,
09770    struct ast_data *data_root)
09771 {
09772    struct ast_data *data_hint;
09773    struct ast_hint *hint;
09774    int watchers;
09775    struct ast_state_cb *watcher;
09776 
09777    AST_RWLIST_RDLOCK(&hints);
09778    if (AST_RWLIST_EMPTY(&hints)) {
09779       AST_RWLIST_UNLOCK(&hints);
09780       return 0;
09781    }
09782 
09783    AST_RWLIST_TRAVERSE(&hints, hint, list) {
09784       watchers = 0;
09785       AST_LIST_TRAVERSE(&hint->callbacks, watcher, entry) {
09786          watchers++;
09787       }
09788       data_hint = ast_data_add_node(data_root, "hint");
09789       if (!data_hint) {
09790          continue;
09791       }
09792       ast_data_add_str(data_hint, "extension", ast_get_extension_name(hint->exten));
09793       ast_data_add_str(data_hint, "context", ast_get_context_name(ast_get_extension_context(hint->exten)));
09794       ast_data_add_str(data_hint, "application", ast_get_extension_app(hint->exten));
09795       ast_data_add_str(data_hint, "state", ast_extension_state2str(hint->laststate));
09796       ast_data_add_int(data_hint, "watchers", watchers);
09797 
09798       if (!ast_data_search_match(search, data_hint)) {
09799          ast_data_remove_node(data_root, data_hint);
09800       }
09801    }
09802    AST_RWLIST_UNLOCK(&hints);
09803 
09804    return 0;
09805 }
09806 
09807 static const struct ast_data_handler hints_data_provider = {
09808    .version = AST_DATA_HANDLER_VERSION,
09809    .get = hints_data_provider_get
09810 };
09811 
09812 static const struct ast_data_entry pbx_data_providers[] = {
09813    AST_DATA_ENTRY("asterisk/core/hints", &hints_data_provider),
09814 };
09815 
09816 int load_pbx(void)
09817 {
09818    int x;
09819 
09820    /* Initialize the PBX */
09821    ast_verb(1, "Asterisk PBX Core Initializing\n");
09822    if (!(device_state_tps = ast_taskprocessor_get("pbx-core", 0))) {
09823       ast_log(LOG_WARNING, "failed to create pbx-core taskprocessor\n");
09824    }
09825 
09826    ast_verb(1, "Registering builtin applications:\n");
09827    ast_cli_register_multiple(pbx_cli, ARRAY_LEN(pbx_cli));
09828    ast_data_register_multiple_core(pbx_data_providers, ARRAY_LEN(pbx_data_providers));
09829    __ast_custom_function_register(&exception_function, NULL);
09830    __ast_custom_function_register(&testtime_function, NULL);
09831 
09832    /* Register builtin applications */
09833    for (x = 0; x < ARRAY_LEN(builtins); x++) {
09834       ast_verb(1, "[%s]\n", builtins[x].name);
09835       if (ast_register_application2(builtins[x].name, builtins[x].execute, NULL, NULL, NULL)) {
09836          ast_log(LOG_ERROR, "Unable to register builtin application '%s'\n", builtins[x].name);
09837          return -1;
09838       }
09839    }
09840 
09841    /* Register manager application */
09842    ast_manager_register_xml("ShowDialPlan", EVENT_FLAG_CONFIG | EVENT_FLAG_REPORTING, manager_show_dialplan);
09843 
09844    if (!(device_state_sub = ast_event_subscribe(AST_EVENT_DEVICE_STATE, device_state_cb, "pbx Device State Change", NULL,
09845          AST_EVENT_IE_END))) {
09846       return -1;
09847    }
09848 
09849    return 0;
09850 }
09851 
09852 /*
09853  * Lock context list functions ...
09854  */
09855 int ast_wrlock_contexts()
09856 {
09857    return ast_mutex_lock(&conlock);
09858 }
09859 
09860 int ast_rdlock_contexts()
09861 {
09862    return ast_mutex_lock(&conlock);
09863 }
09864 
09865 int ast_unlock_contexts()
09866 {
09867    return ast_mutex_unlock(&conlock);
09868 }
09869 
09870 /*
09871  * Lock context ...
09872  */
09873 int ast_wrlock_context(struct ast_context *con)
09874 {
09875    return ast_rwlock_wrlock(&con->lock);
09876 }
09877 
09878 int ast_rdlock_context(struct ast_context *con)
09879 {
09880    return ast_rwlock_rdlock(&con->lock);
09881 }
09882 
09883 int ast_unlock_context(struct ast_context *con)
09884 {
09885    return ast_rwlock_unlock(&con->lock);
09886 }
09887 
09888 /*
09889  * Name functions ...
09890  */
09891 const char *ast_get_context_name(struct ast_context *con)
09892 {
09893    return con ? con->name : NULL;
09894 }
09895 
09896 struct ast_context *ast_get_extension_context(struct ast_exten *exten)
09897 {
09898    return exten ? exten->parent : NULL;
09899 }
09900 
09901 const char *ast_get_extension_name(struct ast_exten *exten)
09902 {
09903    return exten ? exten->exten : NULL;
09904 }
09905 
09906 const char *ast_get_extension_label(struct ast_exten *exten)
09907 {
09908    return exten ? exten->label : NULL;
09909 }
09910 
09911 const char *ast_get_include_name(struct ast_include *inc)
09912 {
09913    return inc ? inc->name : NULL;
09914 }
09915 
09916 const char *ast_get_ignorepat_name(struct ast_ignorepat *ip)
09917 {
09918    return ip ? ip->pattern : NULL;
09919 }
09920 
09921 int ast_get_extension_priority(struct ast_exten *exten)
09922 {
09923    return exten ? exten->priority : -1;
09924 }
09925 
09926 /*
09927  * Registrar info functions ...
09928  */
09929 const char *ast_get_context_registrar(struct ast_context *c)
09930 {
09931    return c ? c->registrar : NULL;
09932 }
09933 
09934 const char *ast_get_extension_registrar(struct ast_exten *e)
09935 {
09936    return e ? e->registrar : NULL;
09937 }
09938 
09939 const char *ast_get_include_registrar(struct ast_include *i)
09940 {
09941    return i ? i->registrar : NULL;
09942 }
09943 
09944 const char *ast_get_ignorepat_registrar(struct ast_ignorepat *ip)
09945 {
09946    return ip ? ip->registrar : NULL;
09947 }
09948 
09949 int ast_get_extension_matchcid(struct ast_exten *e)
09950 {
09951    return e ? e->matchcid : 0;
09952 }
09953 
09954 const char *ast_get_extension_cidmatch(struct ast_exten *e)
09955 {
09956    return e ? e->cidmatch : NULL;
09957 }
09958 
09959 const char *ast_get_extension_app(struct ast_exten *e)
09960 {
09961    return e ? e->app : NULL;
09962 }
09963 
09964 void *ast_get_extension_app_data(struct ast_exten *e)
09965 {
09966    return e ? e->data : NULL;
09967 }
09968 
09969 const char *ast_get_switch_name(struct ast_sw *sw)
09970 {
09971    return sw ? sw->name : NULL;
09972 }
09973 
09974 const char *ast_get_switch_data(struct ast_sw *sw)
09975 {
09976    return sw ? sw->data : NULL;
09977 }
09978 
09979 int ast_get_switch_eval(struct ast_sw *sw)
09980 {
09981    return sw->eval;
09982 }
09983 
09984 const char *ast_get_switch_registrar(struct ast_sw *sw)
09985 {
09986    return sw ? sw->registrar : NULL;
09987 }
09988 
09989 /*
09990  * Walking functions ...
09991  */
09992 struct ast_context *ast_walk_contexts(struct ast_context *con)
09993 {
09994    return con ? con->next : contexts;
09995 }
09996 
09997 struct ast_exten *ast_walk_context_extensions(struct ast_context *con,
09998    struct ast_exten *exten)
09999 {
10000    if (!exten)
10001       return con ? con->root : NULL;
10002    else
10003       return exten->next;
10004 }
10005 
10006 struct ast_sw *ast_walk_context_switches(struct ast_context *con,
10007    struct ast_sw *sw)
10008 {
10009    if (!sw)
10010       return con ? AST_LIST_FIRST(&con->alts) : NULL;
10011    else
10012       return AST_LIST_NEXT(sw, list);
10013 }
10014 
10015 struct ast_exten *ast_walk_extension_priorities(struct ast_exten *exten,
10016    struct ast_exten *priority)
10017 {
10018    return priority ? priority->peer : exten;
10019 }
10020 
10021 struct ast_include *ast_walk_context_includes(struct ast_context *con,
10022    struct ast_include *inc)
10023 {
10024    if (!inc)
10025       return con ? con->includes : NULL;
10026    else
10027       return inc->next;
10028 }
10029 
10030 struct ast_ignorepat *ast_walk_context_ignorepats(struct ast_context *con,
10031    struct ast_ignorepat *ip)
10032 {
10033    if (!ip)
10034       return con ? con->ignorepats : NULL;
10035    else
10036       return ip->next;
10037 }
10038 
10039 int ast_context_verify_includes(struct ast_context *con)
10040 {
10041    struct ast_include *inc = NULL;
10042    int res = 0;
10043 
10044    while ( (inc = ast_walk_context_includes(con, inc)) ) {
10045       if (ast_context_find(inc->rname))
10046          continue;
10047 
10048       res = -1;
10049       ast_log(LOG_WARNING, "Context '%s' tries to include nonexistent context '%s'\n",
10050          ast_get_context_name(con), inc->rname);
10051       break;
10052    }
10053 
10054    return res;
10055 }
10056 
10057 
10058 static int __ast_goto_if_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, int async)
10059 {
10060    int (*goto_func)(struct ast_channel *chan, const char *context, const char *exten, int priority);
10061 
10062    if (!chan)
10063       return -2;
10064 
10065    if (context == NULL)
10066       context = chan->context;
10067    if (exten == NULL)
10068       exten = chan->exten;
10069 
10070    goto_func = (async) ? ast_async_goto : ast_explicit_goto;
10071    if (ast_exists_extension(chan, context, exten, priority,
10072       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)))
10073       return goto_func(chan, context, exten, priority);
10074    else {
10075       return AST_PBX_GOTO_FAILED;
10076    }
10077 }
10078 
10079 int ast_goto_if_exists(struct ast_channel *chan, const char* context, const char *exten, int priority)
10080 {
10081    return __ast_goto_if_exists(chan, context, exten, priority, 0);
10082 }
10083 
10084 int ast_async_goto_if_exists(struct ast_channel *chan, const char * context, const char *exten, int priority)
10085 {
10086    return __ast_goto_if_exists(chan, context, exten, priority, 1);
10087 }
10088 
10089 static int pbx_parseable_goto(struct ast_channel *chan, const char *goto_string, int async)
10090 {
10091    char *exten, *pri, *context;
10092    char *stringp;
10093    int ipri;
10094    int mode = 0;
10095 
10096    if (ast_strlen_zero(goto_string)) {
10097       ast_log(LOG_WARNING, "Goto requires an argument ([[context,]extension,]priority)\n");
10098       return -1;
10099    }
10100    stringp = ast_strdupa(goto_string);
10101    context = strsep(&stringp, ","); /* guaranteed non-null */
10102    exten = strsep(&stringp, ",");
10103    pri = strsep(&stringp, ",");
10104    if (!exten) {  /* Only a priority in this one */
10105       pri = context;
10106       exten = NULL;
10107       context = NULL;
10108    } else if (!pri) {   /* Only an extension and priority in this one */
10109       pri = exten;
10110       exten = context;
10111       context = NULL;
10112    }
10113    if (*pri == '+') {
10114       mode = 1;
10115       pri++;
10116    } else if (*pri == '-') {
10117       mode = -1;
10118       pri++;
10119    }
10120    if (sscanf(pri, "%30d", &ipri) != 1) {
10121       ipri = ast_findlabel_extension(chan, context ? context : chan->context,
10122          exten ? exten : chan->exten, pri,
10123          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL));
10124       if (ipri < 1) {
10125          ast_log(LOG_WARNING, "Priority '%s' must be a number > 0, or valid label\n", pri);
10126          return -1;
10127       } else
10128          mode = 0;
10129    }
10130    /* At this point we have a priority and maybe an extension and a context */
10131 
10132    if (mode)
10133       ipri = chan->priority + (ipri * mode);
10134 
10135    if (async)
10136       ast_async_goto(chan, context, exten, ipri);
10137    else
10138       ast_explicit_goto(chan, context, exten, ipri);
10139 
10140    return 0;
10141 
10142 }
10143 
10144 int ast_parseable_goto(struct ast_channel *chan, const char *goto_string)
10145 {
10146    return pbx_parseable_goto(chan, goto_string, 0);
10147 }
10148 
10149 int ast_async_parseable_goto(struct ast_channel *chan, const char *goto_string)
10150 {
10151    return pbx_parseable_goto(chan, goto_string, 1);
10152 }
10153 
10154 char *ast_complete_applications(const char *line, const char *word, int state)
10155 {
10156    struct ast_app *app = NULL;
10157    int which = 0;
10158    char *ret = NULL;
10159    size_t wordlen = strlen(word);
10160 
10161    AST_RWLIST_RDLOCK(&apps);
10162    AST_RWLIST_TRAVERSE(&apps, app, list) {
10163       if (!strncasecmp(word, app->name, wordlen) && ++which > state) {
10164          ret = ast_strdup(app->name);
10165          break;
10166       }
10167    }
10168    AST_RWLIST_UNLOCK(&apps);
10169 
10170    return ret;
10171 }

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