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

Generated on Sat Mar 26 11:08:46 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9