Sun Oct 16 2011 08:41:27

Asterisk developer's documentation


app_dial.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 dial() & retrydial() - Trivial application to dial a channel and send an URL on answer
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * \ingroup applications
00026  */
00027 
00028 /*** MODULEINFO
00029    <depend>chan_local</depend>
00030    <support_level>core</support_level>
00031  ***/
00032 
00033 
00034 #include "asterisk.h"
00035 
00036 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 331635 $")
00037 
00038 #include <sys/time.h>
00039 #include <sys/signal.h>
00040 #include <sys/stat.h>
00041 #include <netinet/in.h>
00042 
00043 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
00044 #include "asterisk/lock.h"
00045 #include "asterisk/file.h"
00046 #include "asterisk/channel.h"
00047 #include "asterisk/pbx.h"
00048 #include "asterisk/module.h"
00049 #include "asterisk/translate.h"
00050 #include "asterisk/say.h"
00051 #include "asterisk/config.h"
00052 #include "asterisk/features.h"
00053 #include "asterisk/musiconhold.h"
00054 #include "asterisk/callerid.h"
00055 #include "asterisk/utils.h"
00056 #include "asterisk/app.h"
00057 #include "asterisk/causes.h"
00058 #include "asterisk/rtp_engine.h"
00059 #include "asterisk/cdr.h"
00060 #include "asterisk/manager.h"
00061 #include "asterisk/privacy.h"
00062 #include "asterisk/stringfields.h"
00063 #include "asterisk/global_datastores.h"
00064 #include "asterisk/dsp.h"
00065 #include "asterisk/cel.h"
00066 #include "asterisk/aoc.h"
00067 #include "asterisk/ccss.h"
00068 #include "asterisk/indications.h"
00069 #include "asterisk/framehook.h"
00070 
00071 /*** DOCUMENTATION
00072    <application name="Dial" language="en_US">
00073       <synopsis>
00074          Attempt to connect to another device or endpoint and bridge the call.
00075       </synopsis>
00076       <syntax>
00077          <parameter name="Technology/Resource" required="true" argsep="&amp;">
00078             <argument name="Technology/Resource" required="true">
00079                <para>Specification of the device(s) to dial.  These must be in the format of
00080                <literal>Technology/Resource</literal>, where <replaceable>Technology</replaceable>
00081                represents a particular channel driver, and <replaceable>Resource</replaceable>
00082                represents a resource available to that particular channel driver.</para>
00083             </argument>
00084             <argument name="Technology2/Resource2" required="false" multiple="true">
00085                <para>Optional extra devices to dial in parallel</para>
00086                <para>If you need more then one enter them as
00087                Technology2/Resource2&amp;Technology3/Resourse3&amp;.....</para>
00088             </argument>
00089          </parameter>
00090          <parameter name="timeout" required="false">
00091             <para>Specifies the number of seconds we attempt to dial the specified devices</para>
00092             <para>If not specified, this defaults to 136 years.</para>
00093          </parameter>
00094          <parameter name="options" required="false">
00095             <optionlist>
00096             <option name="A">
00097                <argument name="x" required="true">
00098                   <para>The file to play to the called party</para>
00099                </argument>
00100                <para>Play an announcement to the called party, where <replaceable>x</replaceable> is the prompt to be played</para>
00101             </option>
00102             <option name="a">
00103                <para>Immediately answer the calling channel when the called channel answers in
00104                all cases. Normally, the calling channel is answered when the called channel
00105                answers, but when options such as A() and M() are used, the calling channel is
00106                not answered until all actions on the called channel (such as playing an
00107                announcement) are completed.  This option can be used to answer the calling
00108                channel before doing anything on the called channel. You will rarely need to use
00109                this option, the default behavior is adequate in most cases.</para>
00110             </option>
00111             <option name="C">
00112                <para>Reset the call detail record (CDR) for this call.</para>
00113             </option>
00114             <option name="c">
00115                <para>If the Dial() application cancels this call, always set the flag to tell the channel
00116                driver that the call is answered elsewhere.</para>
00117             </option>
00118             <option name="d">
00119                <para>Allow the calling user to dial a 1 digit extension while waiting for
00120                a call to be answered. Exit to that extension if it exists in the
00121                current context, or the context defined in the <variable>EXITCONTEXT</variable> variable,
00122                if it exists.</para>
00123             </option>
00124             <option name="D" argsep=":">
00125                <argument name="called" />
00126                <argument name="calling" />
00127                <argument name="progress" />
00128                <para>Send the specified DTMF strings <emphasis>after</emphasis> the called
00129                party has answered, but before the call gets bridged. The 
00130                <replaceable>called</replaceable> DTMF string is sent to the called party, and the 
00131                <replaceable>calling</replaceable> DTMF string is sent to the calling party. Both arguments 
00132                can be used alone.  If <replaceable>progress</replaceable> is specified, its DTMF is sent
00133                immediately after receiving a PROGRESS message.</para>
00134             </option>
00135             <option name="e">
00136                <para>Execute the <literal>h</literal> extension for peer after the call ends</para>
00137             </option>
00138             <option name="f">
00139                <argument name="x" required="false" />
00140                <para>If <replaceable>x</replaceable> is not provided, force the CallerID sent on a call-forward or
00141                deflection to the dialplan extension of this Dial() using a dialplan <literal>hint</literal>.
00142                For example, some PSTNs do not allow CallerID to be set to anything
00143                other than the numbers assigned to you.
00144                If <replaceable>x</replaceable> is provided, force the CallerID sent to <replaceable>x</replaceable>.</para>
00145             </option>
00146             <option name="F" argsep="^">
00147                <argument name="context" required="false" />
00148                <argument name="exten" required="false" />
00149                <argument name="priority" required="true" />
00150                <para>When the caller hangs up, transfer the called party
00151                to the specified destination and continue execution at that location.</para>
00152             </option>
00153             <option name="F">
00154                <para>Proceed with dialplan execution at the next priority in the current extension if the
00155                source channel hangs up.</para>
00156             </option>
00157             <option name="g">
00158                <para>Proceed with dialplan execution at the next priority in the current extension if the
00159                destination channel hangs up.</para>
00160             </option>
00161             <option name="G" argsep="^">
00162                <argument name="context" required="false" />
00163                <argument name="exten" required="false" />
00164                <argument name="priority" required="true" />
00165                <para>If the call is answered, transfer the calling party to
00166                the specified <replaceable>priority</replaceable> and the called party to the specified 
00167                <replaceable>priority</replaceable> plus one.</para>
00168                <note>
00169                   <para>You cannot use any additional action post answer options in conjunction with this option.</para>
00170                </note>
00171             </option>
00172             <option name="h">
00173                <para>Allow the called party to hang up by sending the <literal>*</literal> DTMF digit.</para>
00174             </option>
00175             <option name="H">
00176                <para>Allow the calling party to hang up by hitting the <literal>*</literal> DTMF digit.</para>
00177             </option>
00178             <option name="i">
00179                <para>Asterisk will ignore any forwarding requests it may receive on this dial attempt.</para>
00180             </option>
00181             <option name="I">
00182                <para>Asterisk will ignore any connected line update requests or redirecting party update
00183                requests it may receiveon this dial attempt.</para>
00184             </option>
00185             <option name="k">
00186                <para>Allow the called party to enable parking of the call by sending
00187                the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
00188             </option>
00189             <option name="K">
00190                <para>Allow the calling party to enable parking of the call by sending
00191                the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
00192             </option>
00193             <option name="L" argsep=":">
00194                <argument name="x" required="true">
00195                   <para>Maximum call time, in milliseconds</para>
00196                </argument>
00197                <argument name="y">
00198                   <para>Warning time, in milliseconds</para>
00199                </argument>
00200                <argument name="z">
00201                   <para>Repeat time, in milliseconds</para>
00202                </argument>
00203                <para>Limit the call to <replaceable>x</replaceable> milliseconds. Play a warning when <replaceable>y</replaceable> milliseconds are
00204                left. Repeat the warning every <replaceable>z</replaceable> milliseconds until time expires.</para>
00205                <para>This option is affected by the following variables:</para>
00206                <variablelist>
00207                   <variable name="LIMIT_PLAYAUDIO_CALLER">
00208                      <value name="yes" default="true" />
00209                      <value name="no" />
00210                      <para>If set, this variable causes Asterisk to play the prompts to the caller.</para>
00211                   </variable>
00212                   <variable name="LIMIT_PLAYAUDIO_CALLEE">
00213                      <value name="yes" />
00214                      <value name="no" default="true"/>
00215                      <para>If set, this variable causes Asterisk to play the prompts to the callee.</para>
00216                   </variable>
00217                   <variable name="LIMIT_TIMEOUT_FILE">
00218                      <value name="filename"/>
00219                      <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play when the timeout is reached.
00220                      If not set, the time remaining will be announced.</para>
00221                   </variable>
00222                   <variable name="LIMIT_CONNECT_FILE">
00223                      <value name="filename"/>
00224                      <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play when the call begins.
00225                      If not set, the time remaining will be announced.</para>
00226                   </variable>
00227                   <variable name="LIMIT_WARNING_FILE">
00228                      <value name="filename"/>
00229                      <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play as
00230                      a warning when time <replaceable>x</replaceable> is reached. If not set, the time remaining will be announced.</para>
00231                   </variable>
00232                </variablelist>
00233             </option>
00234             <option name="m">
00235                <argument name="class" required="false"/>
00236                <para>Provide hold music to the calling party until a requested
00237                channel answers. A specific music on hold <replaceable>class</replaceable>
00238                (as defined in <filename>musiconhold.conf</filename>) can be specified.</para>
00239             </option>
00240             <option name="M" argsep="^">
00241                <argument name="macro" required="true">
00242                   <para>Name of the macro that should be executed.</para>
00243                </argument>
00244                <argument name="arg" multiple="true">
00245                   <para>Macro arguments</para>
00246                </argument>
00247                <para>Execute the specified <replaceable>macro</replaceable> for the <emphasis>called</emphasis> channel 
00248                before connecting to the calling channel. Arguments can be specified to the Macro
00249                using <literal>^</literal> as a delimiter. The macro can set the variable
00250                <variable>MACRO_RESULT</variable> to specify the following actions after the macro is
00251                finished executing:</para>
00252                <variablelist>
00253                   <variable name="MACRO_RESULT">
00254                      <para>If set, this action will be taken after the macro finished executing.</para>
00255                      <value name="ABORT">
00256                         Hangup both legs of the call
00257                      </value>
00258                      <value name="CONGESTION">
00259                         Behave as if line congestion was encountered
00260                      </value>
00261                      <value name="BUSY">
00262                         Behave as if a busy signal was encountered
00263                      </value>
00264                      <value name="CONTINUE">
00265                         Hangup the called party and allow the calling party to continue dialplan execution at the next priority
00266                      </value>
00267                      <!-- TODO: Fix this syntax up, once we've figured out how to specify the GOTO syntax -->
00268                      <value name="GOTO:&lt;context&gt;^&lt;exten&gt;^&lt;priority&gt;">
00269                         Transfer the call to the specified destination.
00270                      </value>
00271                   </variable>
00272                </variablelist>
00273                <note>
00274                   <para>You cannot use any additional action post answer options in conjunction
00275                   with this option. Also, pbx services are not run on the peer (called) channel,
00276                   so you will not be able to set timeouts via the TIMEOUT() function in this macro.</para>
00277                </note>
00278                <warning><para>Be aware of the limitations that macros have, specifically with regards to use of
00279                the <literal>WaitExten</literal> application. For more information, see the documentation for
00280                Macro()</para></warning>
00281             </option>
00282             <option name="n">
00283                     <argument name="delete">
00284                        <para>With <replaceable>delete</replaceable> either not specified or set to <literal>0</literal>,
00285                   the recorded introduction will not be deleted if the caller hangs up while the remote party has not
00286                   yet answered.</para>
00287                   <para>With <replaceable>delete</replaceable> set to <literal>1</literal>, the introduction will
00288                   always be deleted.</para>
00289                </argument>
00290                <para>This option is a modifier for the call screening/privacy mode. (See the 
00291                <literal>p</literal> and <literal>P</literal> options.) It specifies
00292                that no introductions are to be saved in the <directory>priv-callerintros</directory>
00293                directory.</para>
00294             </option>
00295             <option name="N">
00296                <para>This option is a modifier for the call screening/privacy mode. It specifies
00297                that if Caller*ID is present, do not screen the call.</para>
00298             </option>
00299             <option name="o">
00300                <argument name="x" required="false" />
00301                <para>If <replaceable>x</replaceable> is not provided, specify that the CallerID that was present on the
00302                <emphasis>calling</emphasis> channel be stored as the CallerID on the <emphasis>called</emphasis> channel.
00303                This was the behavior of Asterisk 1.0 and earlier.
00304                If <replaceable>x</replaceable> is provided, specify the CallerID stored on the <emphasis>called</emphasis> channel.
00305                Note that o(${CALLERID(all)}) is similar to option o without the parameter.</para>
00306             </option>
00307             <option name="O">
00308                <argument name="mode">
00309                   <para>With <replaceable>mode</replaceable> either not specified or set to <literal>1</literal>,
00310                   the originator hanging up will cause the phone to ring back immediately.</para>
00311                   <para>With <replaceable>mode</replaceable> set to <literal>2</literal>, when the operator 
00312                   flashes the trunk, it will ring their phone back.</para>
00313                </argument>
00314                <para>Enables <emphasis>operator services</emphasis> mode.  This option only
00315                works when bridging a DAHDI channel to another DAHDI channel
00316                only. if specified on non-DAHDI interfaces, it will be ignored.
00317                When the destination answers (presumably an operator services
00318                station), the originator no longer has control of their line.
00319                They may hang up, but the switch will not release their line
00320                until the destination party (the operator) hangs up.</para>
00321             </option>
00322             <option name="p">
00323                <para>This option enables screening mode. This is basically Privacy mode
00324                without memory.</para>
00325             </option>
00326             <option name="P">
00327                <argument name="x" />
00328                <para>Enable privacy mode. Use <replaceable>x</replaceable> as the family/key in the AstDB database if
00329                it is provided. The current extension is used if a database family/key is not specified.</para>
00330             </option>
00331             <option name="r">
00332                <para>Default: Indicate ringing to the calling party, even if the called party isn't actually ringing. Pass no audio to the calling
00333                party until the called channel has answered.</para>
00334                <argument name="tone" required="false">
00335                   <para>Indicate progress to calling party. Send audio 'tone' from indications.conf</para>
00336                </argument>
00337             </option>
00338             <option name="S">
00339                <argument name="x" required="true" />
00340                <para>Hang up the call <replaceable>x</replaceable> seconds <emphasis>after</emphasis> the called party has
00341                answered the call.</para>
00342             </option>
00343             <option name="s">
00344                <argument name="x" required="true" />
00345                <para>Force the outgoing callerid tag parameter to be set to the string <replaceable>x</replaceable>.</para>
00346                <para>Works with the f option.</para>
00347             </option>
00348             <option name="t">
00349                <para>Allow the called party to transfer the calling party by sending the
00350                DTMF sequence defined in <filename>features.conf</filename>. This setting does not perform policy enforcement on
00351                transfers initiated by other methods.</para>
00352             </option>
00353             <option name="T">
00354                <para>Allow the calling party to transfer the called party by sending the
00355                DTMF sequence defined in <filename>features.conf</filename>. This setting does not perform policy enforcement on
00356                transfers initiated by other methods.</para>
00357             </option>
00358             <option name="U" argsep="^">
00359                <argument name="x" required="true">
00360                   <para>Name of the subroutine to execute via Gosub</para>
00361                </argument>
00362                <argument name="arg" multiple="true" required="false">
00363                   <para>Arguments for the Gosub routine</para>
00364                </argument>
00365                <para>Execute via Gosub the routine <replaceable>x</replaceable> for the <emphasis>called</emphasis> channel before connecting
00366                to the calling channel. Arguments can be specified to the Gosub
00367                using <literal>^</literal> as a delimiter. The Gosub routine can set the variable
00368                <variable>GOSUB_RESULT</variable> to specify the following actions after the Gosub returns.</para>
00369                <variablelist>
00370                   <variable name="GOSUB_RESULT">
00371                      <value name="ABORT">
00372                         Hangup both legs of the call.
00373                      </value>
00374                      <value name="CONGESTION">
00375                         Behave as if line congestion was encountered.
00376                      </value>
00377                      <value name="BUSY">
00378                         Behave as if a busy signal was encountered.
00379                      </value>
00380                      <value name="CONTINUE">
00381                         Hangup the called party and allow the calling party
00382                         to continue dialplan execution at the next priority.
00383                      </value>
00384                      <!-- TODO: Fix this syntax up, once we've figured out how to specify the GOTO syntax -->
00385                      <value name="GOTO:&lt;context&gt;^&lt;exten&gt;^&lt;priority&gt;">
00386                         Transfer the call to the specified priority. Optionally, an extension, or
00387                         extension and priority can be specified.
00388                      </value>
00389                   </variable>
00390                </variablelist>
00391                <note>
00392                   <para>You cannot use any additional action post answer options in conjunction
00393                   with this option. Also, pbx services are not run on the peer (called) channel,
00394                   so you will not be able to set timeouts via the TIMEOUT() function in this routine.</para>
00395                </note>
00396             </option>
00397             <option name="u">
00398                <argument name = "x" required="true">
00399                   <para>Force the outgoing callerid presentation indicator parameter to be set
00400                   to one of the values passed in <replaceable>x</replaceable>:
00401                   <literal>allowed_not_screened</literal>
00402                   <literal>allowed_passed_screen</literal>
00403                   <literal>allowed_failed_screen</literal>
00404                   <literal>allowed</literal>
00405                   <literal>prohib_not_screened</literal>
00406                   <literal>prohib_passed_screen</literal>
00407                   <literal>prohib_failed_screen</literal>
00408                   <literal>prohib</literal>
00409                   <literal>unavailable</literal></para>
00410                </argument>
00411                <para>Works with the f option.</para>
00412             </option>
00413             <option name="w">
00414                <para>Allow the called party to enable recording of the call by sending
00415                the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
00416             </option>
00417             <option name="W">
00418                <para>Allow the calling party to enable recording of the call by sending
00419                the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
00420             </option>
00421             <option name="x">
00422                <para>Allow the called party to enable recording of the call by sending
00423                the DTMF sequence defined for one-touch automixmonitor in <filename>features.conf</filename>.</para>
00424             </option>
00425             <option name="X">
00426                <para>Allow the calling party to enable recording of the call by sending
00427                the DTMF sequence defined for one-touch automixmonitor in <filename>features.conf</filename>.</para>
00428             </option>
00429             <option name="z">
00430                <para>On a call forward, cancel any dial timeout which has been set for this call.</para>
00431             </option>
00432             </optionlist>
00433          </parameter>
00434          <parameter name="URL">
00435             <para>The optional URL will be sent to the called party if the channel driver supports it.</para>
00436          </parameter>
00437       </syntax>
00438       <description>
00439          <para>This application will place calls to one or more specified channels. As soon
00440          as one of the requested channels answers, the originating channel will be
00441          answered, if it has not already been answered. These two channels will then
00442          be active in a bridged call. All other channels that were requested will then
00443          be hung up.</para>
00444 
00445          <para>Unless there is a timeout specified, the Dial application will wait
00446          indefinitely until one of the called channels answers, the user hangs up, or
00447          if all of the called channels are busy or unavailable. Dialplan executing will
00448          continue if no requested channels can be called, or if the timeout expires.
00449          This application will report normal termination if the originating channel
00450          hangs up, or if the call is bridged and either of the parties in the bridge
00451          ends the call.</para>
00452          <para>If the <variable>OUTBOUND_GROUP</variable> variable is set, all peer channels created by this
00453          application will be put into that group (as in Set(GROUP()=...).
00454          If the <variable>OUTBOUND_GROUP_ONCE</variable> variable is set, all peer channels created by this
00455          application will be put into that group (as in Set(GROUP()=...). Unlike OUTBOUND_GROUP,
00456          however, the variable will be unset after use.</para>
00457 
00458          <para>This application sets the following channel variables:</para>
00459          <variablelist>
00460             <variable name="DIALEDTIME">
00461                <para>This is the time from dialing a channel until when it is disconnected.</para>
00462             </variable>
00463             <variable name="ANSWEREDTIME">
00464                <para>This is the amount of time for actual call.</para>
00465             </variable>
00466             <variable name="DIALSTATUS">
00467                <para>This is the status of the call</para>
00468                <value name="CHANUNAVAIL" />
00469                <value name="CONGESTION" />
00470                <value name="NOANSWER" />
00471                <value name="BUSY" />
00472                <value name="ANSWER" />
00473                <value name="CANCEL" />
00474                <value name="DONTCALL">
00475                   For the Privacy and Screening Modes.
00476                   Will be set if the called party chooses to send the calling party to the 'Go Away' script.
00477                </value>
00478                <value name="TORTURE">
00479                   For the Privacy and Screening Modes.
00480                   Will be set if the called party chooses to send the calling party to the 'torture' script.
00481                </value>
00482                <value name="INVALIDARGS" />
00483             </variable>
00484          </variablelist>
00485       </description>
00486    </application>
00487    <application name="RetryDial" language="en_US">
00488       <synopsis>
00489          Place a call, retrying on failure allowing an optional exit extension.
00490       </synopsis>
00491       <syntax>
00492          <parameter name="announce" required="true">
00493             <para>Filename of sound that will be played when no channel can be reached</para>
00494          </parameter>
00495          <parameter name="sleep" required="true">
00496             <para>Number of seconds to wait after a dial attempt failed before a new attempt is made</para>
00497          </parameter>
00498          <parameter name="retries" required="true">
00499             <para>Number of retries</para>
00500             <para>When this is reached flow will continue at the next priority in the dialplan</para>
00501          </parameter>
00502          <parameter name="dialargs" required="true">
00503             <para>Same format as arguments provided to the Dial application</para>
00504          </parameter>
00505       </syntax>
00506       <description>
00507          <para>This application will attempt to place a call using the normal Dial application.
00508          If no channel can be reached, the <replaceable>announce</replaceable> file will be played.
00509          Then, it will wait <replaceable>sleep</replaceable> number of seconds before retrying the call.
00510          After <replaceable>retries</replaceable> number of attempts, the calling channel will continue at the next priority in the dialplan.
00511          If the <replaceable>retries</replaceable> setting is set to 0, this application will retry endlessly.
00512          While waiting to retry a call, a 1 digit extension may be dialed. If that
00513          extension exists in either the context defined in <variable>EXITCONTEXT</variable> or the current
00514          one, The call will jump to that extension immediately.
00515          The <replaceable>dialargs</replaceable> are specified in the same format that arguments are provided
00516          to the Dial application.</para>
00517       </description>
00518    </application>
00519  ***/
00520 
00521 static const char app[] = "Dial";
00522 static const char rapp[] = "RetryDial";
00523 
00524 enum {
00525    OPT_ANNOUNCE =          (1 << 0),
00526    OPT_RESETCDR =          (1 << 1),
00527    OPT_DTMF_EXIT =         (1 << 2),
00528    OPT_SENDDTMF =          (1 << 3),
00529    OPT_FORCECLID =         (1 << 4),
00530    OPT_GO_ON =             (1 << 5),
00531    OPT_CALLEE_HANGUP =     (1 << 6),
00532    OPT_CALLER_HANGUP =     (1 << 7),
00533    OPT_ORIGINAL_CLID =     (1 << 8),
00534    OPT_DURATION_LIMIT =    (1 << 9),
00535    OPT_MUSICBACK =         (1 << 10),
00536    OPT_CALLEE_MACRO =      (1 << 11),
00537    OPT_SCREEN_NOINTRO =    (1 << 12),
00538    OPT_SCREEN_NOCALLERID = (1 << 13),
00539    OPT_IGNORE_CONNECTEDLINE = (1 << 14),
00540    OPT_SCREENING =         (1 << 15),
00541    OPT_PRIVACY =           (1 << 16),
00542    OPT_RINGBACK =          (1 << 17),
00543    OPT_DURATION_STOP =     (1 << 18),
00544    OPT_CALLEE_TRANSFER =   (1 << 19),
00545    OPT_CALLER_TRANSFER =   (1 << 20),
00546    OPT_CALLEE_MONITOR =    (1 << 21),
00547    OPT_CALLER_MONITOR =    (1 << 22),
00548    OPT_GOTO =              (1 << 23),
00549    OPT_OPERMODE =          (1 << 24),
00550    OPT_CALLEE_PARK =       (1 << 25),
00551    OPT_CALLER_PARK =       (1 << 26),
00552    OPT_IGNORE_FORWARDING = (1 << 27),
00553    OPT_CALLEE_GOSUB =      (1 << 28),
00554    OPT_CALLEE_MIXMONITOR = (1 << 29),
00555    OPT_CALLER_MIXMONITOR = (1 << 30),
00556 };
00557 
00558 /* flags are now 64 bits, so keep it up! */
00559 #define DIAL_STILLGOING      (1LLU << 31)
00560 #define DIAL_NOFORWARDHTML   (1LLU << 32)
00561 #define DIAL_CALLERID_ABSENT (1LLU << 33) /* TRUE if caller id is not available for connected line. */
00562 #define OPT_CANCEL_ELSEWHERE (1LLU << 34)
00563 #define OPT_PEER_H           (1LLU << 35)
00564 #define OPT_CALLEE_GO_ON     (1LLU << 36)
00565 #define OPT_CANCEL_TIMEOUT   (1LLU << 37)
00566 #define OPT_FORCE_CID_TAG    (1LLU << 38)
00567 #define OPT_FORCE_CID_PRES   (1LLU << 39)
00568 #define OPT_CALLER_ANSWER    (1LLU << 40)
00569 
00570 enum {
00571    OPT_ARG_ANNOUNCE = 0,
00572    OPT_ARG_SENDDTMF,
00573    OPT_ARG_GOTO,
00574    OPT_ARG_DURATION_LIMIT,
00575    OPT_ARG_MUSICBACK,
00576    OPT_ARG_CALLEE_MACRO,
00577    OPT_ARG_RINGBACK,
00578    OPT_ARG_CALLEE_GOSUB,
00579    OPT_ARG_CALLEE_GO_ON,
00580    OPT_ARG_PRIVACY,
00581    OPT_ARG_DURATION_STOP,
00582    OPT_ARG_OPERMODE,
00583    OPT_ARG_SCREEN_NOINTRO,
00584    OPT_ARG_ORIGINAL_CLID,
00585    OPT_ARG_FORCECLID,
00586    OPT_ARG_FORCE_CID_TAG,
00587    OPT_ARG_FORCE_CID_PRES,
00588    /* note: this entry _MUST_ be the last one in the enum */
00589    OPT_ARG_ARRAY_SIZE,
00590 };
00591 
00592 AST_APP_OPTIONS(dial_exec_options, BEGIN_OPTIONS
00593    AST_APP_OPTION_ARG('A', OPT_ANNOUNCE, OPT_ARG_ANNOUNCE),
00594    AST_APP_OPTION('a', OPT_CALLER_ANSWER),
00595    AST_APP_OPTION('C', OPT_RESETCDR),
00596    AST_APP_OPTION('c', OPT_CANCEL_ELSEWHERE),
00597    AST_APP_OPTION('d', OPT_DTMF_EXIT),
00598    AST_APP_OPTION_ARG('D', OPT_SENDDTMF, OPT_ARG_SENDDTMF),
00599    AST_APP_OPTION('e', OPT_PEER_H),
00600    AST_APP_OPTION_ARG('f', OPT_FORCECLID, OPT_ARG_FORCECLID),
00601    AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
00602    AST_APP_OPTION('g', OPT_GO_ON),
00603    AST_APP_OPTION_ARG('G', OPT_GOTO, OPT_ARG_GOTO),
00604    AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
00605    AST_APP_OPTION('H', OPT_CALLER_HANGUP),
00606    AST_APP_OPTION('i', OPT_IGNORE_FORWARDING),
00607    AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
00608    AST_APP_OPTION('k', OPT_CALLEE_PARK),
00609    AST_APP_OPTION('K', OPT_CALLER_PARK),
00610    AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
00611    AST_APP_OPTION_ARG('m', OPT_MUSICBACK, OPT_ARG_MUSICBACK),
00612    AST_APP_OPTION_ARG('M', OPT_CALLEE_MACRO, OPT_ARG_CALLEE_MACRO),
00613    AST_APP_OPTION_ARG('n', OPT_SCREEN_NOINTRO, OPT_ARG_SCREEN_NOINTRO),
00614    AST_APP_OPTION('N', OPT_SCREEN_NOCALLERID),
00615    AST_APP_OPTION_ARG('o', OPT_ORIGINAL_CLID, OPT_ARG_ORIGINAL_CLID),
00616    AST_APP_OPTION_ARG('O', OPT_OPERMODE, OPT_ARG_OPERMODE),
00617    AST_APP_OPTION('p', OPT_SCREENING),
00618    AST_APP_OPTION_ARG('P', OPT_PRIVACY, OPT_ARG_PRIVACY),
00619    AST_APP_OPTION_ARG('r', OPT_RINGBACK, OPT_ARG_RINGBACK),
00620    AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
00621    AST_APP_OPTION_ARG('s', OPT_FORCE_CID_TAG, OPT_ARG_FORCE_CID_TAG),
00622    AST_APP_OPTION_ARG('u', OPT_FORCE_CID_PRES, OPT_ARG_FORCE_CID_PRES),
00623    AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
00624    AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
00625    AST_APP_OPTION_ARG('U', OPT_CALLEE_GOSUB, OPT_ARG_CALLEE_GOSUB),
00626    AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
00627    AST_APP_OPTION('W', OPT_CALLER_MONITOR),
00628    AST_APP_OPTION('x', OPT_CALLEE_MIXMONITOR),
00629    AST_APP_OPTION('X', OPT_CALLER_MIXMONITOR),
00630    AST_APP_OPTION('z', OPT_CANCEL_TIMEOUT),
00631 END_OPTIONS );
00632 
00633 #define CAN_EARLY_BRIDGE(flags,chan,peer) (!ast_test_flag64(flags, OPT_CALLEE_HANGUP | \
00634    OPT_CALLER_HANGUP | OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER | \
00635    OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR | OPT_CALLEE_PARK |  \
00636    OPT_CALLER_PARK | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB) && \
00637    !chan->audiohooks && !peer->audiohooks && \
00638    ast_framehook_list_is_empty(chan->framehooks) && ast_framehook_list_is_empty(peer->framehooks))
00639 
00640 /*
00641  * The list of active channels
00642  */
00643 struct chanlist {
00644    struct chanlist *next;
00645    struct ast_channel *chan;
00646    uint64_t flags;
00647    /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
00648    struct ast_party_connected_line connected;
00649    /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
00650    unsigned int pending_connected_update:1;
00651    struct ast_aoc_decoded *aoc_s_rate_list;
00652 };
00653 
00654 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str *featurecode);
00655 
00656 static void chanlist_free(struct chanlist *outgoing)
00657 {
00658    ast_party_connected_line_free(&outgoing->connected);
00659    ast_aoc_destroy_decoded(outgoing->aoc_s_rate_list);
00660    ast_free(outgoing);
00661 }
00662 
00663 static void hanguptree(struct chanlist *outgoing, struct ast_channel *exception, int answered_elsewhere)
00664 {
00665    /* Hang up a tree of stuff */
00666    struct chanlist *oo;
00667    while (outgoing) {
00668       /* Hangup any existing lines we have open */
00669       if (outgoing->chan && (outgoing->chan != exception)) {
00670          if (answered_elsewhere) {
00671             /* The flag is used for local channel inheritance and stuff */
00672             ast_set_flag(outgoing->chan, AST_FLAG_ANSWERED_ELSEWHERE);
00673             /* This is for the channel drivers */
00674             outgoing->chan->hangupcause = AST_CAUSE_ANSWERED_ELSEWHERE;
00675          }
00676          ast_hangup(outgoing->chan);
00677       }
00678       oo = outgoing;
00679       outgoing = outgoing->next;
00680       chanlist_free(oo);
00681    }
00682 }
00683 
00684 #define AST_MAX_WATCHERS 256
00685 
00686 /*
00687  * argument to handle_cause() and other functions.
00688  */
00689 struct cause_args {
00690    struct ast_channel *chan;
00691    int busy;
00692    int congestion;
00693    int nochan;
00694 };
00695 
00696 static void handle_cause(int cause, struct cause_args *num)
00697 {
00698    struct ast_cdr *cdr = num->chan->cdr;
00699 
00700    switch(cause) {
00701    case AST_CAUSE_BUSY:
00702       if (cdr)
00703          ast_cdr_busy(cdr);
00704       num->busy++;
00705       break;
00706 
00707    case AST_CAUSE_CONGESTION:
00708       if (cdr)
00709          ast_cdr_failed(cdr);
00710       num->congestion++;
00711       break;
00712 
00713    case AST_CAUSE_NO_ROUTE_DESTINATION:
00714    case AST_CAUSE_UNREGISTERED:
00715       if (cdr)
00716          ast_cdr_failed(cdr);
00717       num->nochan++;
00718       break;
00719 
00720    case AST_CAUSE_NO_ANSWER:
00721       if (cdr) {
00722          ast_cdr_noanswer(cdr);
00723       }
00724       break;
00725    case AST_CAUSE_NORMAL_CLEARING:
00726       break;
00727 
00728    default:
00729       num->nochan++;
00730       break;
00731    }
00732 }
00733 
00734 static int onedigit_goto(struct ast_channel *chan, const char *context, char exten, int pri)
00735 {
00736    char rexten[2] = { exten, '\0' };
00737 
00738    if (context) {
00739       if (!ast_goto_if_exists(chan, context, rexten, pri))
00740          return 1;
00741    } else {
00742       if (!ast_goto_if_exists(chan, chan->context, rexten, pri))
00743          return 1;
00744       else if (!ast_strlen_zero(chan->macrocontext)) {
00745          if (!ast_goto_if_exists(chan, chan->macrocontext, rexten, pri))
00746             return 1;
00747       }
00748    }
00749    return 0;
00750 }
00751 
00752 /* do not call with chan lock held */
00753 static const char *get_cid_name(char *name, int namelen, struct ast_channel *chan)
00754 {
00755    const char *context;
00756    const char *exten;
00757 
00758    ast_channel_lock(chan);
00759    context = ast_strdupa(S_OR(chan->macrocontext, chan->context));
00760    exten = ast_strdupa(S_OR(chan->macroexten, chan->exten));
00761    ast_channel_unlock(chan);
00762 
00763    return ast_get_hint(NULL, 0, name, namelen, chan, context, exten) ? name : "";
00764 }
00765 
00766 static void senddialevent(struct ast_channel *src, struct ast_channel *dst, const char *dialstring)
00767 {
00768    struct ast_channel *chans[] = { src, dst };
00769    ast_manager_event_multichan(EVENT_FLAG_CALL, "Dial", 2, chans,
00770       "SubEvent: Begin\r\n"
00771       "Channel: %s\r\n"
00772       "Destination: %s\r\n"
00773       "CallerIDNum: %s\r\n"
00774       "CallerIDName: %s\r\n"
00775       "ConnectedLineNum: %s\r\n"
00776       "ConnectedLineName: %s\r\n"
00777       "UniqueID: %s\r\n"
00778       "DestUniqueID: %s\r\n"
00779       "Dialstring: %s\r\n",
00780       src->name, dst->name,
00781       S_COR(src->caller.id.number.valid, src->caller.id.number.str, "<unknown>"),
00782       S_COR(src->caller.id.name.valid, src->caller.id.name.str, "<unknown>"),
00783       S_COR(src->connected.id.number.valid, src->connected.id.number.str, "<unknown>"),
00784       S_COR(src->connected.id.name.valid, src->connected.id.name.str, "<unknown>"),
00785       src->uniqueid, dst->uniqueid,
00786       dialstring ? dialstring : "");
00787 }
00788 
00789 static void senddialendevent(struct ast_channel *src, const char *dialstatus)
00790 {
00791    ast_manager_event(src, EVENT_FLAG_CALL, "Dial",
00792       "SubEvent: End\r\n"
00793       "Channel: %s\r\n"
00794       "UniqueID: %s\r\n"
00795       "DialStatus: %s\r\n",
00796       src->name, src->uniqueid, dialstatus);
00797 }
00798 
00799 /*!
00800  * helper function for wait_for_answer()
00801  *
00802  * XXX this code is highly suspicious, as it essentially overwrites
00803  * the outgoing channel without properly deleting it.
00804  *
00805  * \todo eventually this function should be intergrated into and replaced by ast_call_forward() 
00806  */
00807 static void do_forward(struct chanlist *o,
00808    struct cause_args *num, struct ast_flags64 *peerflags, int single, int *to,
00809    struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
00810 {
00811    char tmpchan[256];
00812    struct ast_channel *original = o->chan;
00813    struct ast_channel *c = o->chan; /* the winner */
00814    struct ast_channel *in = num->chan; /* the input channel */
00815    char *stuff;
00816    char *tech;
00817    int cause;
00818    struct ast_party_caller caller;
00819 
00820    ast_copy_string(tmpchan, c->call_forward, sizeof(tmpchan));
00821    if ((stuff = strchr(tmpchan, '/'))) {
00822       *stuff++ = '\0';
00823       tech = tmpchan;
00824    } else {
00825       const char *forward_context;
00826       ast_channel_lock(c);
00827       forward_context = pbx_builtin_getvar_helper(c, "FORWARD_CONTEXT");
00828       if (ast_strlen_zero(forward_context)) {
00829          forward_context = NULL;
00830       }
00831       snprintf(tmpchan, sizeof(tmpchan), "%s@%s", c->call_forward, forward_context ? forward_context : c->context);
00832       ast_channel_unlock(c);
00833       stuff = tmpchan;
00834       tech = "Local";
00835    }
00836 
00837    ast_cel_report_event(in, AST_CEL_FORWARD, NULL, c->call_forward, NULL);
00838 
00839    /* Before processing channel, go ahead and check for forwarding */
00840    ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, c->name);
00841    /* If we have been told to ignore forwards, just set this channel to null and continue processing extensions normally */
00842    if (ast_test_flag64(peerflags, OPT_IGNORE_FORWARDING)) {
00843       ast_verb(3, "Forwarding %s to '%s/%s' prevented.\n", in->name, tech, stuff);
00844       c = o->chan = NULL;
00845       cause = AST_CAUSE_BUSY;
00846    } else {
00847       /* Setup parameters */
00848       c = o->chan = ast_request(tech, in->nativeformats, in, stuff, &cause);
00849       if (c) {
00850          if (single)
00851             ast_channel_make_compatible(o->chan, in);
00852          ast_channel_inherit_variables(in, o->chan);
00853          ast_channel_datastore_inherit(in, o->chan);
00854          /* When a call is forwarded, we don't want to track new interfaces
00855           * dialed for CC purposes. Setting the done flag will ensure that
00856           * any Dial operations that happen later won't record CC interfaces.
00857           */
00858          ast_ignore_cc(o->chan);
00859          ast_log(LOG_NOTICE, "Not accepting call completion offers from call-forward recipient %s\n", o->chan->name);
00860       } else
00861          ast_log(LOG_NOTICE,
00862             "Forwarding failed to create channel to dial '%s/%s' (cause = %d)\n",
00863             tech, stuff, cause);
00864    }
00865    if (!c) {
00866       ast_clear_flag64(o, DIAL_STILLGOING);
00867       handle_cause(cause, num);
00868       ast_hangup(original);
00869    } else {
00870       struct ast_party_redirecting redirecting;
00871 
00872       if (single && CAN_EARLY_BRIDGE(peerflags, c, in)) {
00873          ast_rtp_instance_early_bridge_make_compatible(c, in);
00874       }
00875 
00876       ast_channel_set_redirecting(c, &original->redirecting, NULL);
00877       ast_channel_lock(c);
00878       while (ast_channel_trylock(in)) {
00879          CHANNEL_DEADLOCK_AVOIDANCE(c);
00880       }
00881       if (!c->redirecting.from.number.valid
00882          || ast_strlen_zero(c->redirecting.from.number.str)) {
00883          /*
00884           * The call was not previously redirected so it is
00885           * now redirected from this number.
00886           */
00887          ast_party_number_free(&c->redirecting.from.number);
00888          ast_party_number_init(&c->redirecting.from.number);
00889          c->redirecting.from.number.valid = 1;
00890          c->redirecting.from.number.str =
00891             ast_strdup(S_OR(in->macroexten, in->exten));
00892       }
00893 
00894       c->dialed.transit_network_select = in->dialed.transit_network_select;
00895 
00896       /* Determine CallerID to store in outgoing channel. */
00897       ast_party_caller_set_init(&caller, &c->caller);
00898       if (ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
00899          caller.id = *stored_clid;
00900          ast_channel_set_caller_event(c, &caller, NULL);
00901       } else if (ast_strlen_zero(S_COR(c->caller.id.number.valid,
00902          c->caller.id.number.str, NULL))) {
00903          /*
00904           * The new channel has no preset CallerID number by the channel
00905           * driver.  Use the dialplan extension and hint name.
00906           */
00907          caller.id = *stored_clid;
00908          ast_channel_set_caller_event(c, &caller, NULL);
00909       }
00910 
00911       /* Determine CallerID for outgoing channel to send. */
00912       if (ast_test_flag64(o, OPT_FORCECLID)) {
00913          struct ast_party_connected_line connected;
00914 
00915          ast_party_connected_line_init(&connected);
00916          connected.id = *forced_clid;
00917          ast_party_connected_line_copy(&c->connected, &connected);
00918       } else {
00919          ast_connected_line_copy_from_caller(&c->connected, &in->caller);
00920       }
00921 
00922       ast_string_field_set(c, accountcode, in->accountcode);
00923 
00924       c->appl = "AppDial";
00925       c->data = "(Outgoing Line)";
00926       /*
00927        * We must unlock c before calling ast_channel_redirecting_macro, because
00928        * we put c into autoservice there. That is pretty much a guaranteed
00929        * deadlock. This is why the handling of c's lock may seem a bit unusual
00930        * here.
00931        */
00932       ast_party_redirecting_init(&redirecting);
00933       ast_party_redirecting_copy(&redirecting, &c->redirecting);
00934       ast_channel_unlock(c);
00935       if (ast_channel_redirecting_macro(c, in, &redirecting, 1, 0)) {
00936          ast_channel_update_redirecting(in, &redirecting, NULL);
00937       }
00938       ast_party_redirecting_free(&redirecting);
00939       ast_channel_unlock(in);
00940 
00941       ast_clear_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE);
00942       if (ast_test_flag64(peerflags, OPT_CANCEL_TIMEOUT)) {
00943          *to = -1;
00944       }
00945 
00946       if (ast_call(c, stuff, 0)) {
00947          ast_log(LOG_NOTICE, "Forwarding failed to dial '%s/%s'\n",
00948             tech, stuff);
00949          ast_clear_flag64(o, DIAL_STILLGOING);
00950          ast_hangup(original);
00951          ast_hangup(c);
00952          c = o->chan = NULL;
00953          num->nochan++;
00954       } else {
00955          ast_channel_lock(c);
00956          while (ast_channel_trylock(in)) {
00957             CHANNEL_DEADLOCK_AVOIDANCE(c);
00958          }
00959          senddialevent(in, c, stuff);
00960          ast_channel_unlock(in);
00961          ast_channel_unlock(c);
00962          /* Hangup the original channel now, in case we needed it */
00963          ast_hangup(original);
00964       }
00965       if (single) {
00966          ast_indicate(in, -1);
00967       }
00968    }
00969 }
00970 
00971 /* argument used for some functions. */
00972 struct privacy_args {
00973    int sentringing;
00974    int privdb_val;
00975    char privcid[256];
00976    char privintro[1024];
00977    char status[256];
00978 };
00979 
00980 static struct ast_channel *wait_for_answer(struct ast_channel *in,
00981    struct chanlist *outgoing, int *to, struct ast_flags64 *peerflags,
00982    char *opt_args[],
00983    struct privacy_args *pa,
00984    const struct cause_args *num_in, int *result, char *dtmf_progress,
00985    const int ignore_cc,
00986    struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
00987 {
00988    struct cause_args num = *num_in;
00989    int prestart = num.busy + num.congestion + num.nochan;
00990    int orig = *to;
00991    struct ast_channel *peer = NULL;
00992    /* single is set if only one destination is enabled */
00993    int single = outgoing && !outgoing->next;
00994 #ifdef HAVE_EPOLL
00995    struct chanlist *epollo;
00996 #endif
00997    struct ast_party_connected_line connected_caller;
00998    struct ast_str *featurecode = ast_str_alloca(FEATURE_MAX_LEN + 1);
00999    int cc_recall_core_id;
01000    int is_cc_recall;
01001    int cc_frame_received = 0;
01002    int num_ringing = 0;
01003 
01004    ast_party_connected_line_init(&connected_caller);
01005    if (single) {
01006       /* Turn off hold music, etc */
01007       if (!ast_test_flag64(outgoing, OPT_MUSICBACK | OPT_RINGBACK)) {
01008          ast_deactivate_generator(in);
01009          /* If we are calling a single channel, and not providing ringback or music, */
01010          /* then, make them compatible for in-band tone purpose */
01011          if (ast_channel_make_compatible(outgoing->chan, in) < 0) {
01012             /* If these channels can not be made compatible, 
01013              * there is no point in continuing.  The bridge
01014              * will just fail if it gets that far.
01015              */
01016             *to = -1;
01017             strcpy(pa->status, "CONGESTION");
01018             ast_cdr_failed(in->cdr);
01019             return NULL;
01020          }
01021       }
01022 
01023       if (!ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE) && !ast_test_flag64(outgoing, DIAL_CALLERID_ABSENT)) {
01024          ast_channel_lock(outgoing->chan);
01025          ast_connected_line_copy_from_caller(&connected_caller, &outgoing->chan->caller);
01026          ast_channel_unlock(outgoing->chan);
01027          connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
01028          ast_channel_update_connected_line(in, &connected_caller, NULL);
01029          ast_party_connected_line_free(&connected_caller);
01030       }
01031    }
01032 
01033    is_cc_recall = ast_cc_is_recall(in, &cc_recall_core_id, NULL);
01034 
01035 #ifdef HAVE_EPOLL
01036    for (epollo = outgoing; epollo; epollo = epollo->next)
01037       ast_poll_channel_add(in, epollo->chan);
01038 #endif
01039 
01040    while (*to && !peer) {
01041       struct chanlist *o;
01042       int pos = 0; /* how many channels do we handle */
01043       int numlines = prestart;
01044       struct ast_channel *winner;
01045       struct ast_channel *watchers[AST_MAX_WATCHERS];
01046 
01047       watchers[pos++] = in;
01048       for (o = outgoing; o; o = o->next) {
01049          /* Keep track of important channels */
01050          if (ast_test_flag64(o, DIAL_STILLGOING) && o->chan)
01051             watchers[pos++] = o->chan;
01052          numlines++;
01053       }
01054       if (pos == 1) { /* only the input channel is available */
01055          if (numlines == (num.busy + num.congestion + num.nochan)) {
01056             ast_verb(2, "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
01057             if (num.busy)
01058                strcpy(pa->status, "BUSY");
01059             else if (num.congestion)
01060                strcpy(pa->status, "CONGESTION");
01061             else if (num.nochan)
01062                strcpy(pa->status, "CHANUNAVAIL");
01063          } else {
01064             ast_verb(3, "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
01065          }
01066          *to = 0;
01067          if (is_cc_recall) {
01068             ast_cc_failed(cc_recall_core_id, "Everyone is busy/congested for the recall. How sad");
01069          }
01070          return NULL;
01071       }
01072       winner = ast_waitfor_n(watchers, pos, to);
01073       for (o = outgoing; o; o = o->next) {
01074          struct ast_frame *f;
01075          struct ast_channel *c = o->chan;
01076 
01077          if (c == NULL)
01078             continue;
01079          if (ast_test_flag64(o, DIAL_STILLGOING) && c->_state == AST_STATE_UP) {
01080             if (!peer) {
01081                ast_verb(3, "%s answered %s\n", c->name, in->name);
01082                if (!single && !ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
01083                   if (o->pending_connected_update) {
01084                      if (ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
01085                         ast_channel_update_connected_line(in, &o->connected, NULL);
01086                      }
01087                   } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
01088                      ast_channel_lock(c);
01089                      ast_connected_line_copy_from_caller(&connected_caller, &c->caller);
01090                      ast_channel_unlock(c);
01091                      connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
01092                      ast_channel_update_connected_line(in, &connected_caller, NULL);
01093                      ast_party_connected_line_free(&connected_caller);
01094                   }
01095                }
01096                if (o->aoc_s_rate_list) {
01097                   size_t encoded_size;
01098                   struct ast_aoc_encoded *encoded;
01099                   if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
01100                      ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
01101                      ast_aoc_destroy_encoded(encoded);
01102                   }
01103                }
01104                peer = c;
01105                ast_copy_flags64(peerflags, o,
01106                   OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
01107                   OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
01108                   OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
01109                   OPT_CALLEE_PARK | OPT_CALLER_PARK |
01110                   OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
01111                   DIAL_NOFORWARDHTML);
01112                ast_string_field_set(c, dialcontext, "");
01113                ast_copy_string(c->exten, "", sizeof(c->exten));
01114             }
01115             continue;
01116          }
01117          if (c != winner)
01118             continue;
01119          /* here, o->chan == c == winner */
01120          if (!ast_strlen_zero(c->call_forward)) {
01121             pa->sentringing = 0;
01122             if (!ignore_cc && (f = ast_read(c))) {
01123                if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_CC) {
01124                   /* This channel is forwarding the call, and is capable of CC, so
01125                    * be sure to add the new device interface to the list
01126                    */
01127                   ast_handle_cc_control_frame(in, c, f->data.ptr);
01128                }
01129                ast_frfree(f);
01130             }
01131             do_forward(o, &num, peerflags, single, to, forced_clid, stored_clid);
01132             continue;
01133          }
01134          f = ast_read(winner);
01135          if (!f) {
01136             in->hangupcause = c->hangupcause;
01137 #ifdef HAVE_EPOLL
01138             ast_poll_channel_del(in, c);
01139 #endif
01140             ast_hangup(c);
01141             c = o->chan = NULL;
01142             ast_clear_flag64(o, DIAL_STILLGOING);
01143             handle_cause(in->hangupcause, &num);
01144             continue;
01145          }
01146          if (f->frametype == AST_FRAME_CONTROL) {
01147             switch (f->subclass.integer) {
01148             case AST_CONTROL_ANSWER:
01149                /* This is our guy if someone answered. */
01150                if (!peer) {
01151                   ast_verb(3, "%s answered %s\n", c->name, in->name);
01152                   if (!single && !ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
01153                      if (o->pending_connected_update) {
01154                         if (ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
01155                            ast_channel_update_connected_line(in, &o->connected, NULL);
01156                         }
01157                      } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
01158                         ast_channel_lock(c);
01159                         ast_connected_line_copy_from_caller(&connected_caller, &c->caller);
01160                         ast_channel_unlock(c);
01161                         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
01162                         ast_channel_update_connected_line(in, &connected_caller, NULL);
01163                         ast_party_connected_line_free(&connected_caller);
01164                      }
01165                   }
01166                   if (o->aoc_s_rate_list) {
01167                      size_t encoded_size;
01168                      struct ast_aoc_encoded *encoded;
01169                      if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
01170                         ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
01171                         ast_aoc_destroy_encoded(encoded);
01172                      }
01173                   }
01174                   peer = c;
01175                   if (peer->cdr) {
01176                      peer->cdr->answer = ast_tvnow();
01177                      peer->cdr->disposition = AST_CDR_ANSWERED;
01178                   }
01179                   ast_copy_flags64(peerflags, o,
01180                      OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
01181                      OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
01182                      OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
01183                      OPT_CALLEE_PARK | OPT_CALLER_PARK |
01184                      OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
01185                      DIAL_NOFORWARDHTML);
01186                   ast_string_field_set(c, dialcontext, "");
01187                   ast_copy_string(c->exten, "", sizeof(c->exten));
01188                   if (CAN_EARLY_BRIDGE(peerflags, in, peer))
01189                      /* Setup early bridge if appropriate */
01190                      ast_channel_early_bridge(in, peer);
01191                }
01192                /* If call has been answered, then the eventual hangup is likely to be normal hangup */
01193                in->hangupcause = AST_CAUSE_NORMAL_CLEARING;
01194                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
01195                break;
01196             case AST_CONTROL_BUSY:
01197                ast_verb(3, "%s is busy\n", c->name);
01198                in->hangupcause = c->hangupcause;
01199                ast_hangup(c);
01200                c = o->chan = NULL;
01201                ast_clear_flag64(o, DIAL_STILLGOING);
01202                handle_cause(AST_CAUSE_BUSY, &num);
01203                break;
01204             case AST_CONTROL_CONGESTION:
01205                ast_verb(3, "%s is circuit-busy\n", c->name);
01206                in->hangupcause = c->hangupcause;
01207                ast_hangup(c);
01208                c = o->chan = NULL;
01209                ast_clear_flag64(o, DIAL_STILLGOING);
01210                handle_cause(AST_CAUSE_CONGESTION, &num);
01211                break;
01212             case AST_CONTROL_RINGING:
01213                /* This is a tricky area to get right when using a native
01214                 * CC agent. The reason is that we do the best we can to send only a
01215                 * single ringing notification to the caller.
01216                 *
01217                 * Call completion complicates the logic used here. CCNR is typically
01218                 * offered during a ringing message. Let's say that party A calls
01219                 * parties B, C, and D. B and C do not support CC requests, but D
01220                 * does. If we were to receive a ringing notification from B before
01221                 * the others, then we would end up sending a ringing message to
01222                 * A with no CCNR offer present.
01223                 *
01224                 * The approach that we have taken is that if we receive a ringing
01225                 * response from a party and no CCNR offer is present, we need to
01226                 * wait. Specifically, we need to wait until either a) a called party
01227                 * offers CCNR in its ringing response or b) all called parties have
01228                 * responded in some way to our call and none offers CCNR.
01229                 *
01230                 * The drawback to this is that if one of the parties has a delayed
01231                 * response or, god forbid, one just plain doesn't respond to our
01232                 * outgoing call, then this will result in a significant delay between
01233                 * when the caller places the call and hears ringback.
01234                 *
01235                 * Note also that if CC is disabled for this call, then it is perfectly
01236                 * fine for ringing frames to get sent through.
01237                 */
01238                ++num_ringing;
01239                if (ignore_cc || cc_frame_received || num_ringing == numlines) {
01240                   ast_verb(3, "%s is ringing\n", c->name);
01241                   /* Setup early media if appropriate */
01242                   if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
01243                      ast_channel_early_bridge(in, c);
01244                   if (!(pa->sentringing) && !ast_test_flag64(outgoing, OPT_MUSICBACK) && ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
01245                      ast_indicate(in, AST_CONTROL_RINGING);
01246                      pa->sentringing++;
01247                   }
01248                }
01249                break;
01250             case AST_CONTROL_PROGRESS:
01251                ast_verb(3, "%s is making progress passing it to %s\n", c->name, in->name);
01252                /* Setup early media if appropriate */
01253                if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
01254                   ast_channel_early_bridge(in, c);
01255                if (!ast_test_flag64(outgoing, OPT_RINGBACK)) {
01256                   if (single || (!single && !pa->sentringing)) {
01257                      ast_indicate(in, AST_CONTROL_PROGRESS);
01258                   }
01259                }
01260                if (!ast_strlen_zero(dtmf_progress)) {
01261                   ast_verb(3,
01262                      "Sending DTMF '%s' to the called party as result of receiving a PROGRESS message.\n",
01263                      dtmf_progress);
01264                   ast_dtmf_stream(c, in, dtmf_progress, 250, 0);
01265                }
01266                break;
01267             case AST_CONTROL_VIDUPDATE:
01268                ast_verb(3, "%s requested a video update, passing it to %s\n", c->name, in->name);
01269                ast_indicate(in, AST_CONTROL_VIDUPDATE);
01270                break;
01271             case AST_CONTROL_SRCUPDATE:
01272                ast_verb(3, "%s requested a source update, passing it to %s\n", c->name, in->name);
01273                ast_indicate(in, AST_CONTROL_SRCUPDATE);
01274                break;
01275             case AST_CONTROL_CONNECTED_LINE:
01276                if (ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
01277                   ast_verb(3, "Connected line update to %s prevented.\n", in->name);
01278                } else if (!single) {
01279                   struct ast_party_connected_line connected;
01280                   ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n", c->name, in->name);
01281                   ast_party_connected_line_set_init(&connected, &o->connected);
01282                   ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
01283                   ast_party_connected_line_set(&o->connected, &connected, NULL);
01284                   ast_party_connected_line_free(&connected);
01285                   o->pending_connected_update = 1;
01286                } else {
01287                   if (ast_channel_connected_line_macro(c, in, f, 1, 1)) {
01288                      ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
01289                   }
01290                }
01291                break;
01292             case AST_CONTROL_AOC:
01293                {
01294                   struct ast_aoc_decoded *decoded = ast_aoc_decode(f->data.ptr, f->datalen, o->chan);
01295                   if (decoded && (ast_aoc_get_msg_type(decoded) == AST_AOC_S)) {
01296                      ast_aoc_destroy_decoded(o->aoc_s_rate_list);
01297                      o->aoc_s_rate_list = decoded;
01298                   } else {
01299                      ast_aoc_destroy_decoded(decoded);
01300                   }
01301                }
01302                break;
01303             case AST_CONTROL_REDIRECTING:
01304                if (ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
01305                   ast_verb(3, "Redirecting update to %s prevented.\n", in->name);
01306                } else if (single) {
01307                   ast_verb(3, "%s redirecting info has changed, passing it to %s\n", c->name, in->name);
01308                   if (ast_channel_redirecting_macro(c, in, f, 1, 1)) {
01309                      ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
01310                   }
01311                   pa->sentringing = 0;
01312                }
01313                break;
01314             case AST_CONTROL_PROCEEDING:
01315                ast_verb(3, "%s is proceeding passing it to %s\n", c->name, in->name);
01316                if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
01317                   ast_channel_early_bridge(in, c);
01318                if (!ast_test_flag64(outgoing, OPT_RINGBACK))
01319                   ast_indicate(in, AST_CONTROL_PROCEEDING);
01320                break;
01321             case AST_CONTROL_HOLD:
01322                ast_verb(3, "Call on %s placed on hold\n", c->name);
01323                ast_indicate(in, AST_CONTROL_HOLD);
01324                break;
01325             case AST_CONTROL_UNHOLD:
01326                ast_verb(3, "Call on %s left from hold\n", c->name);
01327                ast_indicate(in, AST_CONTROL_UNHOLD);
01328                break;
01329             case AST_CONTROL_OFFHOOK:
01330             case AST_CONTROL_FLASH:
01331                /* Ignore going off hook and flash */
01332                break;
01333             case AST_CONTROL_CC:
01334                if (!ignore_cc) {
01335                   ast_handle_cc_control_frame(in, c, f->data.ptr);
01336                   cc_frame_received = 1;
01337                }
01338                break;
01339             case -1:
01340                if (!ast_test_flag64(outgoing, OPT_RINGBACK | OPT_MUSICBACK)) {
01341                   ast_verb(3, "%s stopped sounds\n", c->name);
01342                   ast_indicate(in, -1);
01343                   pa->sentringing = 0;
01344                }
01345                break;
01346             default:
01347                ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
01348             }
01349          } else if (single) {
01350             switch (f->frametype) {
01351             case AST_FRAME_VOICE:
01352             case AST_FRAME_IMAGE:
01353             case AST_FRAME_TEXT:
01354                if (ast_write(in, f)) {
01355                   ast_log(LOG_WARNING, "Unable to write frametype: %d\n",
01356                      f->frametype);
01357                }
01358                break;
01359             case AST_FRAME_HTML:
01360                if (!ast_test_flag64(outgoing, DIAL_NOFORWARDHTML)
01361                   && ast_channel_sendhtml(in, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
01362                   ast_log(LOG_WARNING, "Unable to send URL\n");
01363                }
01364                break;
01365             default:
01366                break;
01367             }
01368          }
01369          ast_frfree(f);
01370       } /* end for */
01371       if (winner == in) {
01372          struct ast_frame *f = ast_read(in);
01373 #if 0
01374          if (f && (f->frametype != AST_FRAME_VOICE))
01375             printf("Frame type: %d, %d\n", f->frametype, f->subclass);
01376          else if (!f || (f->frametype != AST_FRAME_VOICE))
01377             printf("Hangup received on %s\n", in->name);
01378 #endif
01379          if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
01380             /* Got hung up */
01381             *to = -1;
01382             strcpy(pa->status, "CANCEL");
01383             ast_cdr_noanswer(in->cdr);
01384             if (f) {
01385                if (f->data.uint32) {
01386                   in->hangupcause = f->data.uint32;
01387                }
01388                ast_frfree(f);
01389             }
01390             if (is_cc_recall) {
01391                ast_cc_completed(in, "CC completed, although the caller hung up (cancelled)");
01392             }
01393             return NULL;
01394          }
01395 
01396          /* now f is guaranteed non-NULL */
01397          if (f->frametype == AST_FRAME_DTMF) {
01398             if (ast_test_flag64(peerflags, OPT_DTMF_EXIT)) {
01399                const char *context;
01400                ast_channel_lock(in);
01401                context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
01402                if (onedigit_goto(in, context, (char) f->subclass.integer, 1)) {
01403                   ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
01404                   *to = 0;
01405                   ast_cdr_noanswer(in->cdr);
01406                   *result = f->subclass.integer;
01407                   strcpy(pa->status, "CANCEL");
01408                   ast_frfree(f);
01409                   ast_channel_unlock(in);
01410                   if (is_cc_recall) {
01411                      ast_cc_completed(in, "CC completed, but the caller used DTMF to exit");
01412                   }
01413                   return NULL;
01414                }
01415                ast_channel_unlock(in);
01416             }
01417 
01418             if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP) &&
01419                detect_disconnect(in, f->subclass.integer, featurecode)) {
01420                ast_verb(3, "User requested call disconnect.\n");
01421                *to = 0;
01422                strcpy(pa->status, "CANCEL");
01423                ast_cdr_noanswer(in->cdr);
01424                ast_frfree(f);
01425                if (is_cc_recall) {
01426                   ast_cc_completed(in, "CC completed, but the caller hung up with DTMF");
01427                }
01428                return NULL;
01429             }
01430          }
01431 
01432          /* Send the frame from the in channel to all outgoing channels. */
01433          for (o = outgoing; o; o = o->next) {
01434             if (!o->chan || !ast_test_flag64(o, DIAL_STILLGOING)) {
01435                /* This outgoing channel has died so don't send the frame to it. */
01436                continue;
01437             }
01438             switch (f->frametype) {
01439             case AST_FRAME_HTML:
01440                /* Forward HTML stuff */
01441                if (!ast_test_flag64(o, DIAL_NOFORWARDHTML)
01442                   && ast_channel_sendhtml(o->chan, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
01443                   ast_log(LOG_WARNING, "Unable to send URL\n");
01444                }
01445                break;
01446             case AST_FRAME_VOICE:
01447             case AST_FRAME_IMAGE:
01448             case AST_FRAME_TEXT:
01449             case AST_FRAME_DTMF_BEGIN:
01450             case AST_FRAME_DTMF_END:
01451                if (ast_write(o->chan, f)) {
01452                   ast_log(LOG_WARNING, "Unable to forward frametype: %d\n",
01453                      f->frametype);
01454                }
01455                break;
01456             case AST_FRAME_CONTROL:
01457                switch (f->subclass.integer) {
01458                case AST_CONTROL_HOLD:
01459                case AST_CONTROL_UNHOLD:
01460                case AST_CONTROL_VIDUPDATE:
01461                case AST_CONTROL_SRCUPDATE:
01462                   ast_verb(3, "%s requested special control %d, passing it to %s\n",
01463                      in->name, f->subclass.integer, o->chan->name);
01464                   ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
01465                   break;
01466                case AST_CONTROL_CONNECTED_LINE:
01467                   if (ast_channel_connected_line_macro(in, o->chan, f, 0, 1)) {
01468                      ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
01469                   }
01470                   break;
01471                case AST_CONTROL_REDIRECTING:
01472                   if (ast_channel_redirecting_macro(in, o->chan, f, 0, 1)) {
01473                      ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
01474                   }
01475                   break;
01476                default:
01477                   break;
01478                }
01479                break;
01480             default:
01481                break;
01482             }
01483          }
01484          ast_frfree(f);
01485       }
01486       if (!*to)
01487          ast_verb(3, "Nobody picked up in %d ms\n", orig);
01488       if (!*to || ast_check_hangup(in))
01489          ast_cdr_noanswer(in->cdr);
01490    }
01491 
01492 #ifdef HAVE_EPOLL
01493    for (epollo = outgoing; epollo; epollo = epollo->next) {
01494       if (epollo->chan)
01495          ast_poll_channel_del(in, epollo->chan);
01496    }
01497 #endif
01498 
01499    if (is_cc_recall) {
01500       ast_cc_completed(in, "Recall completed!");
01501    }
01502    return peer;
01503 }
01504 
01505 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str *featurecode)
01506 {
01507    struct ast_flags features = { AST_FEATURE_DISCONNECT }; /* only concerned with disconnect feature */
01508    struct ast_call_feature feature = { 0, };
01509    int res;
01510 
01511    ast_str_append(&featurecode, 1, "%c", code);
01512 
01513    res = ast_feature_detect(chan, &features, ast_str_buffer(featurecode), &feature);
01514 
01515    if (res != AST_FEATURE_RETURN_STOREDIGITS) {
01516       ast_str_reset(featurecode);
01517    }
01518    if (feature.feature_mask & AST_FEATURE_DISCONNECT) {
01519       return 1;
01520    }
01521 
01522    return 0;
01523 }
01524 
01525 static void replace_macro_delimiter(char *s)
01526 {
01527    for (; *s; s++)
01528       if (*s == '^')
01529          *s = ',';
01530 }
01531 
01532 /* returns true if there is a valid privacy reply */
01533 static int valid_priv_reply(struct ast_flags64 *opts, int res)
01534 {
01535    if (res < '1')
01536       return 0;
01537    if (ast_test_flag64(opts, OPT_PRIVACY) && res <= '5')
01538       return 1;
01539    if (ast_test_flag64(opts, OPT_SCREENING) && res <= '4')
01540       return 1;
01541    return 0;
01542 }
01543 
01544 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
01545    struct ast_flags64 *opts, char **opt_args, struct privacy_args *pa)
01546 {
01547 
01548    int res2;
01549    int loopcount = 0;
01550 
01551    /* Get the user's intro, store it in priv-callerintros/$CID,
01552       unless it is already there-- this should be done before the
01553       call is actually dialed  */
01554 
01555    /* all ring indications and moh for the caller has been halted as soon as the
01556       target extension was picked up. We are going to have to kill some
01557       time and make the caller believe the peer hasn't picked up yet */
01558 
01559    if (ast_test_flag64(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
01560       char *original_moh = ast_strdupa(chan->musicclass);
01561       ast_indicate(chan, -1);
01562       ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
01563       ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
01564       ast_string_field_set(chan, musicclass, original_moh);
01565    } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
01566       ast_indicate(chan, AST_CONTROL_RINGING);
01567       pa->sentringing++;
01568    }
01569 
01570    /* Start autoservice on the other chan ?? */
01571    res2 = ast_autoservice_start(chan);
01572    /* Now Stream the File */
01573    for (loopcount = 0; loopcount < 3; loopcount++) {
01574       if (res2 && loopcount == 0) /* error in ast_autoservice_start() */
01575          break;
01576       if (!res2) /* on timeout, play the message again */
01577          res2 = ast_play_and_wait(peer, "priv-callpending");
01578       if (!valid_priv_reply(opts, res2))
01579          res2 = 0;
01580       /* priv-callpending script:
01581          "I have a caller waiting, who introduces themselves as:"
01582       */
01583       if (!res2)
01584          res2 = ast_play_and_wait(peer, pa->privintro);
01585       if (!valid_priv_reply(opts, res2))
01586          res2 = 0;
01587       /* now get input from the called party, as to their choice */
01588       if (!res2) {
01589          /* XXX can we have both, or they are mutually exclusive ? */
01590          if (ast_test_flag64(opts, OPT_PRIVACY))
01591             res2 = ast_play_and_wait(peer, "priv-callee-options");
01592          if (ast_test_flag64(opts, OPT_SCREENING))
01593             res2 = ast_play_and_wait(peer, "screen-callee-options");
01594       }
01595       /*! \page DialPrivacy Dial Privacy scripts
01596       \par priv-callee-options script:
01597          "Dial 1 if you wish this caller to reach you directly in the future,
01598             and immediately connect to their incoming call
01599           Dial 2 if you wish to send this caller to voicemail now and
01600             forevermore.
01601           Dial 3 to send this caller to the torture menus, now and forevermore.
01602           Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
01603           Dial 5 to allow this caller to come straight thru to you in the future,
01604             but right now, just this once, send them to voicemail."
01605       \par screen-callee-options script:
01606          "Dial 1 if you wish to immediately connect to the incoming call
01607           Dial 2 if you wish to send this caller to voicemail.
01608           Dial 3 to send this caller to the torture menus.
01609           Dial 4 to send this caller to a simple "go away" menu.
01610       */
01611       if (valid_priv_reply(opts, res2))
01612          break;
01613       /* invalid option */
01614       res2 = ast_play_and_wait(peer, "vm-sorry");
01615    }
01616 
01617    if (ast_test_flag64(opts, OPT_MUSICBACK)) {
01618       ast_moh_stop(chan);
01619    } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
01620       ast_indicate(chan, -1);
01621       pa->sentringing = 0;
01622    }
01623    ast_autoservice_stop(chan);
01624    if (ast_test_flag64(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
01625       /* map keypresses to various things, the index is res2 - '1' */
01626       static const char * const _val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
01627       static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
01628       int i = res2 - '1';
01629       ast_verb(3, "--Set privacy database entry %s/%s to %s\n",
01630          opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
01631       ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
01632    }
01633    switch (res2) {
01634    case '1':
01635       break;
01636    case '2':
01637       ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
01638       break;
01639    case '3':
01640       ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
01641       break;
01642    case '4':
01643       ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
01644       break;
01645    case '5':
01646       /* XXX should we set status to DENY ? */
01647       if (ast_test_flag64(opts, OPT_PRIVACY))
01648          break;
01649       /* if not privacy, then 5 is the same as "default" case */
01650    default: /* bad input or -1 if failure to start autoservice */
01651       /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
01652       /* well, there seems basically two choices. Just patch the caller thru immediately,
01653            or,... put 'em thru to voicemail. */
01654       /* since the callee may have hung up, let's do the voicemail thing, no database decision */
01655       ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
01656       /* XXX should we set status to DENY ? */
01657       /* XXX what about the privacy flags ? */
01658       break;
01659    }
01660 
01661    if (res2 == '1') { /* the only case where we actually connect */
01662       /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll
01663          just clog things up, and it's not useful information, not being tied to a CID */
01664       if (strncmp(pa->privcid, "NOCALLERID", 10) == 0 || ast_test_flag64(opts, OPT_SCREEN_NOINTRO)) {
01665          ast_filedelete(pa->privintro, NULL);
01666          if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
01667             ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
01668          else
01669             ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
01670       }
01671       return 0; /* the good exit path */
01672    } else {
01673       ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
01674       return -1;
01675    }
01676 }
01677 
01678 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
01679 static int setup_privacy_args(struct privacy_args *pa,
01680    struct ast_flags64 *opts, char *opt_args[], struct ast_channel *chan)
01681 {
01682    char callerid[60];
01683    int res;
01684    char *l;
01685    int silencethreshold;
01686 
01687    if (chan->caller.id.number.valid
01688       && !ast_strlen_zero(chan->caller.id.number.str)) {
01689       l = ast_strdupa(chan->caller.id.number.str);
01690       ast_shrink_phone_number(l);
01691       if (ast_test_flag64(opts, OPT_PRIVACY) ) {
01692          ast_verb(3, "Privacy DB is '%s', clid is '%s'\n", opt_args[OPT_ARG_PRIVACY], l);
01693          pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
01694       } else {
01695          ast_verb(3, "Privacy Screening, clid is '%s'\n", l);
01696          pa->privdb_val = AST_PRIVACY_UNKNOWN;
01697       }
01698    } else {
01699       char *tnam, *tn2;
01700 
01701       tnam = ast_strdupa(chan->name);
01702       /* clean the channel name so slashes don't try to end up in disk file name */
01703       for (tn2 = tnam; *tn2; tn2++) {
01704          if (*tn2 == '/')  /* any other chars to be afraid of? */
01705             *tn2 = '=';
01706       }
01707       ast_verb(3, "Privacy-- callerid is empty\n");
01708 
01709       snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
01710       l = callerid;
01711       pa->privdb_val = AST_PRIVACY_UNKNOWN;
01712    }
01713 
01714    ast_copy_string(pa->privcid, l, sizeof(pa->privcid));
01715 
01716    if (strncmp(pa->privcid, "NOCALLERID", 10) != 0 && ast_test_flag64(opts, OPT_SCREEN_NOCALLERID)) {
01717       /* if callerid is set and OPT_SCREEN_NOCALLERID is set also */
01718       ast_verb(3, "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
01719       pa->privdb_val = AST_PRIVACY_ALLOW;
01720    } else if (ast_test_flag64(opts, OPT_SCREEN_NOCALLERID) && strncmp(pa->privcid, "NOCALLERID", 10) == 0) {
01721       ast_verb(3, "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
01722    }
01723    
01724    if (pa->privdb_val == AST_PRIVACY_DENY) {
01725       ast_verb(3, "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
01726       ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
01727       return 0;
01728    } else if (pa->privdb_val == AST_PRIVACY_KILL) {
01729       ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
01730       return 0; /* Is this right? */
01731    } else if (pa->privdb_val == AST_PRIVACY_TORTURE) {
01732       ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
01733       return 0; /* is this right??? */
01734    } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN) {
01735       /* Get the user's intro, store it in priv-callerintros/$CID,
01736          unless it is already there-- this should be done before the
01737          call is actually dialed  */
01738 
01739       /* make sure the priv-callerintros dir actually exists */
01740       snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
01741       if ((res = ast_mkdir(pa->privintro, 0755))) {
01742          ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(res));
01743          return -1;
01744       }
01745 
01746       snprintf(pa->privintro, sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
01747       if (ast_fileexists(pa->privintro, NULL, NULL ) > 0 && strncmp(pa->privcid, "NOCALLERID", 10) != 0) {
01748          /* the DELUX version of this code would allow this caller the
01749             option to hear and retape their previously recorded intro.
01750          */
01751       } else {
01752          int duration; /* for feedback from play_and_wait */
01753          /* the file doesn't exist yet. Let the caller submit his
01754             vocal intro for posterity */
01755          /* priv-recordintro script:
01756 
01757             "At the tone, please say your name:"
01758 
01759          */
01760          silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
01761          ast_answer(chan);
01762          res = ast_play_and_record(chan, "priv-recordintro", pa->privintro, 4, "sln", &duration, silencethreshold, 2000, 0);  /* NOTE: I've reduced the total time to 4 sec */
01763                            /* don't think we'll need a lock removed, we took care of
01764                               conflicts by naming the pa.privintro file */
01765          if (res == -1) {
01766             /* Delete the file regardless since they hung up during recording */
01767             ast_filedelete(pa->privintro, NULL);
01768             if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
01769                ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
01770             else
01771                ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
01772             return -1;
01773          }
01774          if (!ast_streamfile(chan, "vm-dialout", chan->language) )
01775             ast_waitstream(chan, "");
01776       }
01777    }
01778    return 1; /* success */
01779 }
01780 
01781 static void end_bridge_callback(void *data)
01782 {
01783    char buf[80];
01784    time_t end;
01785    struct ast_channel *chan = data;
01786 
01787    if (!chan->cdr) {
01788       return;
01789    }
01790 
01791    time(&end);
01792 
01793    ast_channel_lock(chan);
01794    if (chan->cdr->answer.tv_sec) {
01795       snprintf(buf, sizeof(buf), "%ld", (long) end - chan->cdr->answer.tv_sec);
01796       pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", buf);
01797    }
01798 
01799    if (chan->cdr->start.tv_sec) {
01800       snprintf(buf, sizeof(buf), "%ld", (long) end - chan->cdr->start.tv_sec);
01801       pbx_builtin_setvar_helper(chan, "DIALEDTIME", buf);
01802    }
01803    ast_channel_unlock(chan);
01804 }
01805 
01806 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator) {
01807    bconfig->end_bridge_callback_data = originator;
01808 }
01809 
01810 static int dial_handle_playtones(struct ast_channel *chan, const char *data)
01811 {
01812    struct ast_tone_zone_sound *ts = NULL;
01813    int res;
01814    const char *str = data;
01815 
01816    if (ast_strlen_zero(str)) {
01817       ast_debug(1,"Nothing to play\n");
01818       return -1;
01819    }
01820 
01821    ts = ast_get_indication_tone(chan->zone, str);
01822 
01823    if (ts && ts->data[0]) {
01824       res = ast_playtones_start(chan, 0, ts->data, 0);
01825    } else {
01826       res = -1;
01827    }
01828 
01829    if (ts) {
01830       ts = ast_tone_zone_sound_unref(ts);
01831    }
01832 
01833    if (res) {
01834       ast_log(LOG_WARNING, "Unable to start playtone \'%s\'\n", str);
01835    }
01836 
01837    return res;
01838 }
01839 
01840 static int dial_exec_full(struct ast_channel *chan, const char *data, struct ast_flags64 *peerflags, int *continue_exec)
01841 {
01842    int res = -1; /* default: error */
01843    char *rest, *cur; /* scan the list of destinations */
01844    struct chanlist *outgoing = NULL; /* list of destinations */
01845    struct ast_channel *peer;
01846    int to; /* timeout */
01847    struct cause_args num = { chan, 0, 0, 0 };
01848    int cause;
01849    char numsubst[256];
01850 
01851    struct ast_bridge_config config = { { 0, } };
01852    struct timeval calldurationlimit = { 0, };
01853    char *dtmfcalled = NULL, *dtmfcalling = NULL, *dtmf_progress=NULL;
01854    struct privacy_args pa = {
01855       .sentringing = 0,
01856       .privdb_val = 0,
01857       .status = "INVALIDARGS",
01858    };
01859    int sentringing = 0, moh = 0;
01860    const char *outbound_group = NULL;
01861    int result = 0;
01862    char *parse;
01863    int opermode = 0;
01864    int delprivintro = 0;
01865    AST_DECLARE_APP_ARGS(args,
01866       AST_APP_ARG(peers);
01867       AST_APP_ARG(timeout);
01868       AST_APP_ARG(options);
01869       AST_APP_ARG(url);
01870    );
01871    struct ast_flags64 opts = { 0, };
01872    char *opt_args[OPT_ARG_ARRAY_SIZE];
01873    struct ast_datastore *datastore = NULL;
01874    int fulldial = 0, num_dialed = 0;
01875    int ignore_cc = 0;
01876    char device_name[AST_CHANNEL_NAME];
01877    char forced_clid_name[AST_MAX_EXTENSION];
01878    char stored_clid_name[AST_MAX_EXTENSION];
01879    int force_forwards_only;   /*!< TRUE if force CallerID on call forward only. Legacy behaviour.*/
01880    /*!
01881     * \brief Forced CallerID party information to send.
01882     * \note This will not have any malloced strings so do not free it.
01883     */
01884    struct ast_party_id forced_clid;
01885    /*!
01886     * \brief Stored CallerID information if needed.
01887     *
01888     * \note If OPT_ORIGINAL_CLID set then this is the o option
01889     * CallerID.  Otherwise it is the dialplan extension and hint
01890     * name.
01891     *
01892     * \note This will not have any malloced strings so do not free it.
01893     */
01894    struct ast_party_id stored_clid;
01895    /*!
01896     * \brief CallerID party information to store.
01897     * \note This will not have any malloced strings so do not free it.
01898     */
01899    struct ast_party_caller caller;
01900 
01901    /* Reset all DIAL variables back to blank, to prevent confusion (in case we don't reset all of them). */
01902    pbx_builtin_setvar_helper(chan, "DIALSTATUS", "");
01903    pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", "");
01904    pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", "");
01905    pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", "");
01906    pbx_builtin_setvar_helper(chan, "DIALEDTIME", "");
01907 
01908    if (ast_strlen_zero(data)) {
01909       ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
01910       pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
01911       return -1;
01912    }
01913 
01914    parse = ast_strdupa(data);
01915 
01916    AST_STANDARD_APP_ARGS(args, parse);
01917 
01918    if (!ast_strlen_zero(args.options) &&
01919       ast_app_parse_options64(dial_exec_options, &opts, opt_args, args.options)) {
01920       pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
01921       goto done;
01922    }
01923 
01924    if (ast_strlen_zero(args.peers)) {
01925       ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
01926       pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
01927       goto done;
01928    }
01929 
01930    if (ast_cc_call_init(chan, &ignore_cc)) {
01931       goto done;
01932    }
01933 
01934    if (ast_test_flag64(&opts, OPT_SCREEN_NOINTRO) && !ast_strlen_zero(opt_args[OPT_ARG_SCREEN_NOINTRO])) {
01935       delprivintro = atoi(opt_args[OPT_ARG_SCREEN_NOINTRO]);
01936 
01937       if (delprivintro < 0 || delprivintro > 1) {
01938          ast_log(LOG_WARNING, "Unknown argument %d specified to n option, ignoring\n", delprivintro);
01939          delprivintro = 0;
01940       }
01941    }
01942 
01943    if (!ast_test_flag64(&opts, OPT_RINGBACK)) {
01944       opt_args[OPT_ARG_RINGBACK] = NULL;
01945    }
01946 
01947    if (ast_test_flag64(&opts, OPT_OPERMODE)) {
01948       opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
01949       ast_verb(3, "Setting operator services mode to %d.\n", opermode);
01950    }
01951 
01952    if (ast_test_flag64(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
01953       calldurationlimit.tv_sec = atoi(opt_args[OPT_ARG_DURATION_STOP]);
01954       if (!calldurationlimit.tv_sec) {
01955          ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
01956          pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
01957          goto done;
01958       }
01959       ast_verb(3, "Setting call duration limit to %.3lf seconds.\n", calldurationlimit.tv_sec + calldurationlimit.tv_usec / 1000000.0);
01960    }
01961 
01962    if (ast_test_flag64(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
01963       dtmf_progress = opt_args[OPT_ARG_SENDDTMF];
01964       dtmfcalled = strsep(&dtmf_progress, ":");
01965       dtmfcalling = strsep(&dtmf_progress, ":");
01966    }
01967 
01968    if (ast_test_flag64(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
01969       if (ast_bridge_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
01970          goto done;
01971    }
01972 
01973    /* Setup the forced CallerID information to send if used. */
01974    ast_party_id_init(&forced_clid);
01975    force_forwards_only = 0;
01976    if (ast_test_flag64(&opts, OPT_FORCECLID)) {
01977       if (ast_strlen_zero(opt_args[OPT_ARG_FORCECLID])) {
01978          ast_channel_lock(chan);
01979          forced_clid.number.str = ast_strdupa(S_OR(chan->macroexten, chan->exten));
01980          ast_channel_unlock(chan);
01981          forced_clid_name[0] = '\0';
01982          forced_clid.name.str = (char *) get_cid_name(forced_clid_name,
01983             sizeof(forced_clid_name), chan);
01984          force_forwards_only = 1;
01985       } else {
01986          /* Note: The opt_args[OPT_ARG_FORCECLID] string value is altered here. */
01987          ast_callerid_parse(opt_args[OPT_ARG_FORCECLID], &forced_clid.name.str,
01988             &forced_clid.number.str);
01989       }
01990       if (!ast_strlen_zero(forced_clid.name.str)) {
01991          forced_clid.name.valid = 1;
01992       }
01993       if (!ast_strlen_zero(forced_clid.number.str)) {
01994          forced_clid.number.valid = 1;
01995       }
01996    }
01997    if (ast_test_flag64(&opts, OPT_FORCE_CID_TAG)
01998       && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_TAG])) {
01999       forced_clid.tag = opt_args[OPT_ARG_FORCE_CID_TAG];
02000    }
02001    forced_clid.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
02002    if (ast_test_flag64(&opts, OPT_FORCE_CID_PRES)
02003       && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_PRES])) {
02004       int pres;
02005 
02006       pres = ast_parse_caller_presentation(opt_args[OPT_ARG_FORCE_CID_PRES]);
02007       if (0 <= pres) {
02008          forced_clid.number.presentation = pres;
02009       }
02010    }
02011 
02012    /* Setup the stored CallerID information if needed. */
02013    ast_party_id_init(&stored_clid);
02014    if (ast_test_flag64(&opts, OPT_ORIGINAL_CLID)) {
02015       if (ast_strlen_zero(opt_args[OPT_ARG_ORIGINAL_CLID])) {
02016          ast_channel_lock(chan);
02017          ast_party_id_set_init(&stored_clid, &chan->caller.id);
02018          if (!ast_strlen_zero(chan->caller.id.name.str)) {
02019             stored_clid.name.str = ast_strdupa(chan->caller.id.name.str);
02020          }
02021          if (!ast_strlen_zero(chan->caller.id.number.str)) {
02022             stored_clid.number.str = ast_strdupa(chan->caller.id.number.str);
02023          }
02024          if (!ast_strlen_zero(chan->caller.id.subaddress.str)) {
02025             stored_clid.subaddress.str = ast_strdupa(chan->caller.id.subaddress.str);
02026          }
02027          if (!ast_strlen_zero(chan->caller.id.tag)) {
02028             stored_clid.tag = ast_strdupa(chan->caller.id.tag);
02029          }
02030          ast_channel_unlock(chan);
02031       } else {
02032          /* Note: The opt_args[OPT_ARG_ORIGINAL_CLID] string value is altered here. */
02033          ast_callerid_parse(opt_args[OPT_ARG_ORIGINAL_CLID], &stored_clid.name.str,
02034             &stored_clid.number.str);
02035          if (!ast_strlen_zero(stored_clid.name.str)) {
02036             stored_clid.name.valid = 1;
02037          }
02038          if (!ast_strlen_zero(stored_clid.number.str)) {
02039             stored_clid.number.valid = 1;
02040          }
02041       }
02042    } else {
02043       /*
02044        * In case the new channel has no preset CallerID number by the
02045        * channel driver, setup the dialplan extension and hint name.
02046        */
02047       stored_clid_name[0] = '\0';
02048       stored_clid.name.str = (char *) get_cid_name(stored_clid_name,
02049          sizeof(stored_clid_name), chan);
02050       if (ast_strlen_zero(stored_clid.name.str)) {
02051          stored_clid.name.str = NULL;
02052       } else {
02053          stored_clid.name.valid = 1;
02054       }
02055       ast_channel_lock(chan);
02056       stored_clid.number.str = ast_strdupa(S_OR(chan->macroexten, chan->exten));
02057       stored_clid.number.valid = 1;
02058       ast_channel_unlock(chan);
02059    }
02060 
02061    if (ast_test_flag64(&opts, OPT_RESETCDR) && chan->cdr)
02062       ast_cdr_reset(chan->cdr, NULL);
02063    if (ast_test_flag64(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
02064       opt_args[OPT_ARG_PRIVACY] = ast_strdupa(chan->exten);
02065 
02066    if (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) {
02067       res = setup_privacy_args(&pa, &opts, opt_args, chan);
02068       if (res <= 0)
02069          goto out;
02070       res = -1; /* reset default */
02071    }
02072 
02073    if (ast_test_flag64(&opts, OPT_DTMF_EXIT) || ast_test_flag64(&opts, OPT_CALLER_HANGUP)) {
02074       __ast_answer(chan, 0, 0);
02075    }
02076 
02077    if (continue_exec)
02078       *continue_exec = 0;
02079 
02080    /* If a channel group has been specified, get it for use when we create peer channels */
02081 
02082    ast_channel_lock(chan);
02083    if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
02084       outbound_group = ast_strdupa(outbound_group);   
02085       pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
02086    } else if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP"))) {
02087       outbound_group = ast_strdupa(outbound_group);
02088    }
02089    ast_channel_unlock(chan);  
02090    ast_copy_flags64(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING | OPT_IGNORE_CONNECTEDLINE |
02091           OPT_CANCEL_TIMEOUT | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB | OPT_FORCECLID);
02092 
02093    /* loop through the list of dial destinations */
02094    rest = args.peers;
02095    while ((cur = strsep(&rest, "&")) ) {
02096       struct chanlist *tmp;
02097       struct ast_channel *tc; /* channel for this destination */
02098       /* Get a technology/[device:]number pair */
02099       char *number = cur;
02100       char *interface = ast_strdupa(number);
02101       char *tech = strsep(&number, "/");
02102       /* find if we already dialed this interface */
02103       struct ast_dialed_interface *di;
02104       AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
02105       num_dialed++;
02106       if (ast_strlen_zero(number)) {
02107          ast_log(LOG_WARNING, "Dial argument takes format (technology/[device:]number1)\n");
02108          goto out;
02109       }
02110       if (!(tmp = ast_calloc(1, sizeof(*tmp))))
02111          goto out;
02112       if (opts.flags) {
02113          ast_copy_flags64(tmp, &opts,
02114             OPT_CANCEL_ELSEWHERE |
02115             OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
02116             OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
02117             OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
02118             OPT_CALLEE_PARK | OPT_CALLER_PARK |
02119             OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
02120             OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID);
02121          ast_set2_flag64(tmp, args.url, DIAL_NOFORWARDHTML);
02122       }
02123       ast_copy_string(numsubst, number, sizeof(numsubst));
02124       /* Request the peer */
02125 
02126       ast_channel_lock(chan);
02127       datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL);
02128       /*
02129        * Seed the chanlist's connected line information with previously
02130        * acquired connected line info from the incoming channel.  The
02131        * previously acquired connected line info could have been set
02132        * through the CONNECTED_LINE dialplan function.
02133        */
02134       ast_party_connected_line_copy(&tmp->connected, &chan->connected);
02135       ast_channel_unlock(chan);
02136 
02137       if (datastore)
02138          dialed_interfaces = datastore->data;
02139       else {
02140          if (!(datastore = ast_datastore_alloc(&dialed_interface_info, NULL))) {
02141             ast_log(LOG_WARNING, "Unable to create channel datastore for dialed interfaces. Aborting!\n");
02142             chanlist_free(tmp);
02143             goto out;
02144          }
02145 
02146          datastore->inheritance = DATASTORE_INHERIT_FOREVER;
02147 
02148          if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
02149             ast_datastore_free(datastore);
02150             chanlist_free(tmp);
02151             goto out;
02152          }
02153 
02154          datastore->data = dialed_interfaces;
02155          AST_LIST_HEAD_INIT(dialed_interfaces);
02156 
02157          ast_channel_lock(chan);
02158          ast_channel_datastore_add(chan, datastore);
02159          ast_channel_unlock(chan);
02160       }
02161 
02162       AST_LIST_LOCK(dialed_interfaces);
02163       AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
02164          if (!strcasecmp(di->interface, interface)) {
02165             ast_log(LOG_WARNING, "Skipping dialing interface '%s' again since it has already been dialed\n",
02166                di->interface);
02167             break;
02168          }
02169       }
02170       AST_LIST_UNLOCK(dialed_interfaces);
02171 
02172       if (di) {
02173          fulldial++;
02174          chanlist_free(tmp);
02175          continue;
02176       }
02177 
02178       /* It is always ok to dial a Local interface.  We only keep track of
02179        * which "real" interfaces have been dialed.  The Local channel will
02180        * inherit this list so that if it ends up dialing a real interface,
02181        * it won't call one that has already been called. */
02182       if (strcasecmp(tech, "Local")) {
02183          if (!(di = ast_calloc(1, sizeof(*di) + strlen(interface)))) {
02184             AST_LIST_UNLOCK(dialed_interfaces);
02185             chanlist_free(tmp);
02186             goto out;
02187          }
02188          strcpy(di->interface, interface);
02189 
02190          AST_LIST_LOCK(dialed_interfaces);
02191          AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
02192          AST_LIST_UNLOCK(dialed_interfaces);
02193       }
02194 
02195       tc = ast_request(tech, chan->nativeformats, chan, numsubst, &cause);
02196       if (!tc) {
02197          /* If we can't, just go on to the next call */
02198          ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
02199             tech, cause, ast_cause2str(cause));
02200          handle_cause(cause, &num);
02201          if (!rest) /* we are on the last destination */
02202             chan->hangupcause = cause;
02203          chanlist_free(tmp);
02204          if (!ignore_cc && (cause == AST_CAUSE_BUSY || cause == AST_CAUSE_CONGESTION)) {
02205             if (!ast_cc_callback(chan, tech, numsubst, ast_cc_busy_interface)) {
02206                ast_cc_extension_monitor_add_dialstring(chan, interface, "");
02207             }
02208          }
02209          continue;
02210       }
02211       ast_channel_get_device_name(tc, device_name, sizeof(device_name));
02212       if (!ignore_cc) {
02213          ast_cc_extension_monitor_add_dialstring(chan, interface, device_name);
02214       }
02215       pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", numsubst);
02216 
02217       ast_channel_lock(tc);
02218       while (ast_channel_trylock(chan)) {
02219          CHANNEL_DEADLOCK_AVOIDANCE(tc);
02220       }
02221       /* Setup outgoing SDP to match incoming one */
02222       if (!outgoing && !rest && CAN_EARLY_BRIDGE(peerflags, chan, tc)) {
02223          ast_rtp_instance_early_bridge_make_compatible(tc, chan);
02224       }
02225       
02226       /* Inherit specially named variables from parent channel */
02227       ast_channel_inherit_variables(chan, tc);
02228       ast_channel_datastore_inherit(chan, tc);
02229 
02230       tc->appl = "AppDial";
02231       tc->data = "(Outgoing Line)";
02232       memset(&tc->whentohangup, 0, sizeof(tc->whentohangup));
02233 
02234       /* Determine CallerID to store in outgoing channel. */
02235       ast_party_caller_set_init(&caller, &tc->caller);
02236       if (ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
02237          caller.id = stored_clid;
02238          ast_channel_set_caller_event(tc, &caller, NULL);
02239          ast_set_flag64(tmp, DIAL_CALLERID_ABSENT);
02240       } else if (ast_strlen_zero(S_COR(tc->caller.id.number.valid,
02241          tc->caller.id.number.str, NULL))) {
02242          /*
02243           * The new channel has no preset CallerID number by the channel
02244           * driver.  Use the dialplan extension and hint name.
02245           */
02246          caller.id = stored_clid;
02247          if (!caller.id.name.valid
02248             && !ast_strlen_zero(S_COR(chan->connected.id.name.valid,
02249                chan->connected.id.name.str, NULL))) {
02250             /*
02251              * No hint name available.  We have a connected name supplied by
02252              * the dialplan we can use instead.
02253              */
02254             caller.id.name.valid = 1;
02255             caller.id.name = chan->connected.id.name;
02256          }
02257          ast_channel_set_caller_event(tc, &caller, NULL);
02258          ast_set_flag64(tmp, DIAL_CALLERID_ABSENT);
02259       } else if (ast_strlen_zero(S_COR(tc->caller.id.name.valid, tc->caller.id.name.str,
02260          NULL))) {
02261          /* The new channel has no preset CallerID name by the channel driver. */
02262          if (!ast_strlen_zero(S_COR(chan->connected.id.name.valid,
02263             chan->connected.id.name.str, NULL))) {
02264             /*
02265              * We have a connected name supplied by the dialplan we can
02266              * use instead.
02267              */
02268             caller.id.name.valid = 1;
02269             caller.id.name = chan->connected.id.name;
02270             ast_channel_set_caller_event(tc, &caller, NULL);
02271          }
02272       }
02273 
02274       /* Determine CallerID for outgoing channel to send. */
02275       if (ast_test_flag64(peerflags, OPT_FORCECLID) && !force_forwards_only) {
02276          struct ast_party_connected_line connected;
02277 
02278          ast_party_connected_line_set_init(&connected, &tc->connected);
02279          connected.id = forced_clid;
02280          ast_channel_set_connected_line(tc, &connected, NULL);
02281       } else {
02282          ast_connected_line_copy_from_caller(&tc->connected, &chan->caller);
02283       }
02284 
02285       ast_party_redirecting_copy(&tc->redirecting, &chan->redirecting);
02286 
02287       tc->dialed.transit_network_select = chan->dialed.transit_network_select;
02288 
02289       if (!ast_strlen_zero(chan->accountcode)) {
02290          ast_string_field_set(tc, peeraccount, chan->accountcode);
02291       }
02292       if (ast_strlen_zero(tc->musicclass))
02293          ast_string_field_set(tc, musicclass, chan->musicclass);
02294 
02295       /* Pass ADSI CPE and transfer capability */
02296       tc->adsicpe = chan->adsicpe;
02297       tc->transfercapability = chan->transfercapability;
02298 
02299       /* If we have an outbound group, set this peer channel to it */
02300       if (outbound_group)
02301          ast_app_group_set_channel(tc, outbound_group);
02302       /* If the calling channel has the ANSWERED_ELSEWHERE flag set, inherit it. This is to support local channels */
02303       if (ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE))
02304          ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
02305 
02306       /* Check if we're forced by configuration */
02307       if (ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE))
02308           ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
02309 
02310 
02311       /* Inherit context and extension */
02312       ast_string_field_set(tc, dialcontext, ast_strlen_zero(chan->macrocontext) ? chan->context : chan->macrocontext);
02313       if (!ast_strlen_zero(chan->macroexten))
02314          ast_copy_string(tc->exten, chan->macroexten, sizeof(tc->exten));
02315       else
02316          ast_copy_string(tc->exten, chan->exten, sizeof(tc->exten));
02317 
02318       ast_channel_unlock(tc);
02319       res = ast_call(tc, numsubst, 0); /* Place the call, but don't wait on the answer */
02320 
02321       /* Save the info in cdr's that we called them */
02322       if (chan->cdr)
02323          ast_cdr_setdestchan(chan->cdr, tc->name);
02324 
02325       /* check the results of ast_call */
02326       if (res) {
02327          /* Again, keep going even if there's an error */
02328          ast_debug(1, "ast call on peer returned %d\n", res);
02329          ast_verb(3, "Couldn't call %s/%s\n", tech, numsubst);
02330          if (tc->hangupcause) {
02331             chan->hangupcause = tc->hangupcause;
02332          }
02333          ast_channel_unlock(chan);
02334          ast_cc_call_failed(chan, tc, interface);
02335          ast_hangup(tc);
02336          tc = NULL;
02337          chanlist_free(tmp);
02338          continue;
02339       } else {
02340          senddialevent(chan, tc, numsubst);
02341          ast_verb(3, "Called %s/%s\n", tech, numsubst);
02342          ast_channel_unlock(chan);
02343       }
02344       /* Put them in the list of outgoing thingies...  We're ready now.
02345          XXX If we're forcibly removed, these outgoing calls won't get
02346          hung up XXX */
02347       ast_set_flag64(tmp, DIAL_STILLGOING);
02348       tmp->chan = tc;
02349       tmp->next = outgoing;
02350       outgoing = tmp;
02351       /* If this line is up, don't try anybody else */
02352       if (outgoing->chan->_state == AST_STATE_UP)
02353          break;
02354    }
02355    
02356    if (ast_strlen_zero(args.timeout)) {
02357       to = -1;
02358    } else {
02359       to = atoi(args.timeout);
02360       if (to > 0)
02361          to *= 1000;
02362       else {
02363          ast_log(LOG_WARNING, "Invalid timeout specified: '%s'. Setting timeout to infinite\n", args.timeout);
02364          to = -1;
02365       }
02366    }
02367 
02368    if (!outgoing) {
02369       strcpy(pa.status, "CHANUNAVAIL");
02370       if (fulldial == num_dialed) {
02371          res = -1;
02372          goto out;
02373       }
02374    } else {
02375       /* Our status will at least be NOANSWER */
02376       strcpy(pa.status, "NOANSWER");
02377       if (ast_test_flag64(outgoing, OPT_MUSICBACK)) {
02378          moh = 1;
02379          if (!ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
02380             char *original_moh = ast_strdupa(chan->musicclass);
02381             ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
02382             ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
02383             ast_string_field_set(chan, musicclass, original_moh);
02384          } else {
02385             ast_moh_start(chan, NULL, NULL);
02386          }
02387          ast_indicate(chan, AST_CONTROL_PROGRESS);
02388       } else if (ast_test_flag64(outgoing, OPT_RINGBACK)) {
02389          if (!ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
02390             if (dial_handle_playtones(chan, opt_args[OPT_ARG_RINGBACK])){
02391                ast_indicate(chan, AST_CONTROL_RINGING);
02392                sentringing++;
02393             } else {
02394                ast_indicate(chan, AST_CONTROL_PROGRESS);
02395             }
02396          } else {
02397             ast_indicate(chan, AST_CONTROL_RINGING);
02398             sentringing++;
02399          }
02400       }
02401    }
02402 
02403    peer = wait_for_answer(chan, outgoing, &to, peerflags, opt_args, &pa, &num, &result,
02404       dtmf_progress, ignore_cc, &forced_clid, &stored_clid);
02405 
02406    /* The ast_channel_datastore_remove() function could fail here if the
02407     * datastore was moved to another channel during a masquerade. If this is
02408     * the case, don't free the datastore here because later, when the channel
02409     * to which the datastore was moved hangs up, it will attempt to free this
02410     * datastore again, causing a crash
02411     */
02412    ast_channel_lock(chan);
02413    datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL); /* make sure we weren't cleaned up already */
02414    if (datastore && !ast_channel_datastore_remove(chan, datastore)) {
02415       ast_datastore_free(datastore);
02416    }
02417    ast_channel_unlock(chan);
02418    if (!peer) {
02419       if (result) {
02420          res = result;
02421       } else if (to) { /* Musta gotten hung up */
02422          res = -1;
02423       } else { /* Nobody answered, next please? */
02424          res = 0;
02425       }
02426 
02427       /* SIP, in particular, sends back this error code to indicate an
02428        * overlap dialled number needs more digits. */
02429       if (chan->hangupcause == AST_CAUSE_INVALID_NUMBER_FORMAT) {
02430          res = AST_PBX_INCOMPLETE;
02431       }
02432 
02433       /* almost done, although the 'else' block is 400 lines */
02434    } else {
02435       const char *number;
02436 
02437       if (ast_test_flag64(&opts, OPT_CALLER_ANSWER))
02438          ast_answer(chan);
02439 
02440       strcpy(pa.status, "ANSWER");
02441       pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
02442       /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
02443          we will always return with -1 so that it is hung up properly after the
02444          conversation.  */
02445       hanguptree(outgoing, peer, 1);
02446       outgoing = NULL;
02447       /* If appropriate, log that we have a destination channel and set the answer time */
02448       if (chan->cdr) {
02449          ast_cdr_setdestchan(chan->cdr, peer->name);
02450          ast_cdr_setanswer(chan->cdr, peer->cdr->answer);
02451       }
02452       if (peer->name)
02453          pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
02454       
02455       ast_channel_lock(peer);
02456       number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER"); 
02457       if (!number)
02458          number = numsubst;
02459       pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
02460       ast_channel_unlock(peer);
02461 
02462       if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
02463          ast_debug(1, "app_dial: sendurl=%s.\n", args.url);
02464          ast_channel_sendurl( peer, args.url );
02465       }
02466       if ( (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) && pa.privdb_val == AST_PRIVACY_UNKNOWN) {
02467          if (do_privacy(chan, peer, &opts, opt_args, &pa)) {
02468             res = 0;
02469             goto out;
02470          }
02471       }
02472       if (!ast_test_flag64(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
02473          res = 0;
02474       } else {
02475          int digit = 0;
02476          struct ast_channel *chans[2];
02477          struct ast_channel *active_chan;
02478 
02479          chans[0] = chan;
02480          chans[1] = peer;
02481 
02482          /* we need to stream the announcment while monitoring the caller for a hangup */
02483 
02484          /* stream the file */
02485          res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
02486          if (res) {
02487             res = 0;
02488             ast_log(LOG_ERROR, "error streaming file '%s' to callee\n", opt_args[OPT_ARG_ANNOUNCE]);
02489          }
02490 
02491          ast_set_flag(peer, AST_FLAG_END_DTMF_ONLY);
02492          while (peer->stream) {
02493             int ms;
02494 
02495             ms = ast_sched_wait(peer->sched);
02496 
02497             if (ms < 0 && !peer->timingfunc) {
02498                ast_stopstream(peer);
02499                break;
02500             }
02501             if (ms < 0)
02502                ms = 1000;
02503 
02504             active_chan = ast_waitfor_n(chans, 2, &ms);
02505             if (active_chan) {
02506                struct ast_frame *fr = ast_read(active_chan);
02507                if (!fr) {
02508                   ast_hangup(peer);
02509                   res = -1;
02510                   goto done;
02511                }
02512                switch(fr->frametype) {
02513                   case AST_FRAME_DTMF_END:
02514                      digit = fr->subclass.integer;
02515                      if (active_chan == peer && strchr(AST_DIGIT_ANY, res)) {
02516                         ast_stopstream(peer);
02517                         res = ast_senddigit(chan, digit, 0);
02518                      }
02519                      break;
02520                   case AST_FRAME_CONTROL:
02521                      switch (fr->subclass.integer) {
02522                         case AST_CONTROL_HANGUP:
02523                            ast_frfree(fr);
02524                            ast_hangup(peer);
02525                            res = -1;
02526                            goto done;
02527                         default:
02528                            break;
02529                      }
02530                      break;
02531                   default:
02532                      /* Ignore all others */
02533                      break;
02534                }
02535                ast_frfree(fr);
02536             }
02537             ast_sched_runq(peer->sched);
02538          }
02539          ast_clear_flag(peer, AST_FLAG_END_DTMF_ONLY);
02540       }
02541 
02542       if (chan && peer && ast_test_flag64(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
02543          /* chan and peer are going into the PBX, they both
02544           * should probably get CDR records. */
02545          ast_clear_flag(chan->cdr, AST_CDR_FLAG_DIALED);
02546          ast_clear_flag(peer->cdr, AST_CDR_FLAG_DIALED);
02547 
02548          replace_macro_delimiter(opt_args[OPT_ARG_GOTO]);
02549          ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
02550          /* peer goes to the same context and extension as chan, so just copy info from chan*/
02551          ast_copy_string(peer->context, chan->context, sizeof(peer->context));
02552          ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
02553          peer->priority = chan->priority + 2;
02554          ast_pbx_start(peer);
02555          hanguptree(outgoing, NULL, ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE) ? 1 : 0);
02556          if (continue_exec)
02557             *continue_exec = 1;
02558          res = 0;
02559          goto done;
02560       }
02561 
02562       if (ast_test_flag64(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
02563          struct ast_app *theapp;
02564          const char *macro_result;
02565 
02566          res = ast_autoservice_start(chan);
02567          if (res) {
02568             ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
02569             res = -1;
02570          }
02571 
02572          theapp = pbx_findapp("Macro");
02573 
02574          if (theapp && !res) { /* XXX why check res here ? */
02575             /* Set peer->exten and peer->context so that MACRO_EXTEN and MACRO_CONTEXT get set */
02576             ast_copy_string(peer->context, chan->context, sizeof(peer->context));
02577             ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
02578 
02579             replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_MACRO]);
02580             res = pbx_exec(peer, theapp, opt_args[OPT_ARG_CALLEE_MACRO]);
02581             ast_debug(1, "Macro exited with status %d\n", res);
02582             res = 0;
02583          } else {
02584             ast_log(LOG_ERROR, "Could not find application Macro\n");
02585             res = -1;
02586          }
02587 
02588          if (ast_autoservice_stop(chan) < 0) {
02589             res = -1;
02590          }
02591 
02592          ast_channel_lock(peer);
02593 
02594          if (!res && (macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
02595             char *macro_transfer_dest;
02596 
02597             if (!strcasecmp(macro_result, "BUSY")) {
02598                ast_copy_string(pa.status, macro_result, sizeof(pa.status));
02599                ast_set_flag64(peerflags, OPT_GO_ON);
02600                res = -1;
02601             } else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
02602                ast_copy_string(pa.status, macro_result, sizeof(pa.status));
02603                ast_set_flag64(peerflags, OPT_GO_ON);
02604                res = -1;
02605             } else if (!strcasecmp(macro_result, "CONTINUE")) {
02606                /* hangup peer and keep chan alive assuming the macro has changed
02607                   the context / exten / priority or perhaps
02608                   the next priority in the current exten is desired.
02609                */
02610                ast_set_flag64(peerflags, OPT_GO_ON);
02611                res = -1;
02612             } else if (!strcasecmp(macro_result, "ABORT")) {
02613                /* Hangup both ends unless the caller has the g flag */
02614                res = -1;
02615             } else if (!strncasecmp(macro_result, "GOTO:", 5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
02616                res = -1;
02617                /* perform a transfer to a new extension */
02618                if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
02619                   replace_macro_delimiter(macro_transfer_dest);
02620                   if (!ast_parseable_goto(chan, macro_transfer_dest))
02621                      ast_set_flag64(peerflags, OPT_GO_ON);
02622                }
02623             }
02624          }
02625 
02626          ast_channel_unlock(peer);
02627       }
02628 
02629       if (ast_test_flag64(&opts, OPT_CALLEE_GOSUB) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GOSUB])) {
02630          struct ast_app *theapp;
02631          const char *gosub_result;
02632          char *gosub_args, *gosub_argstart;
02633          int res9 = -1;
02634 
02635          res9 = ast_autoservice_start(chan);
02636          if (res9) {
02637             ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
02638             res9 = -1;
02639          }
02640 
02641          theapp = pbx_findapp("Gosub");
02642 
02643          if (theapp && !res9) {
02644             replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_GOSUB]);
02645 
02646             /* Set where we came from */
02647             ast_copy_string(peer->context, "app_dial_gosub_virtual_context", sizeof(peer->context));
02648             ast_copy_string(peer->exten, "s", sizeof(peer->exten));
02649             peer->priority = 0;
02650 
02651             gosub_argstart = strchr(opt_args[OPT_ARG_CALLEE_GOSUB], ',');
02652             if (gosub_argstart) {
02653                const char *what_is_s = "s";
02654                *gosub_argstart = 0;
02655                if (!ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "s", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL)) &&
02656                    ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "~~s~~", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL))) {
02657                   what_is_s = "~~s~~";
02658                }
02659                if (asprintf(&gosub_args, "%s,%s,1(%s)", opt_args[OPT_ARG_CALLEE_GOSUB], what_is_s, gosub_argstart + 1) < 0) {
02660                   ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
02661                   gosub_args = NULL;
02662                }
02663                *gosub_argstart = ',';
02664             } else {
02665                const char *what_is_s = "s";
02666                if (!ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "s", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL)) &&
02667                    ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "~~s~~", 1, S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL))) {
02668                   what_is_s = "~~s~~";
02669                }
02670                if (asprintf(&gosub_args, "%s,%s,1", opt_args[OPT_ARG_CALLEE_GOSUB], what_is_s) < 0) {
02671                   ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
02672                   gosub_args = NULL;
02673                }
02674             }
02675 
02676             if (gosub_args) {
02677                res9 = pbx_exec(peer, theapp, gosub_args);
02678                if (!res9) {
02679                   struct ast_pbx_args args;
02680                   /* A struct initializer fails to compile for this case ... */
02681                   memset(&args, 0, sizeof(args));
02682                   args.no_hangup_chan = 1;
02683                   ast_pbx_run_args(peer, &args);
02684                }
02685                ast_free(gosub_args);
02686                ast_debug(1, "Gosub exited with status %d\n", res9);
02687             } else {
02688                ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
02689             }
02690 
02691          } else if (!res9) {
02692             ast_log(LOG_ERROR, "Could not find application Gosub\n");
02693             res9 = -1;
02694          }
02695 
02696          if (ast_autoservice_stop(chan) < 0) {
02697             ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
02698             res9 = -1;
02699          }
02700          
02701          ast_channel_lock(peer);
02702 
02703          if (!res9 && (gosub_result = pbx_builtin_getvar_helper(peer, "GOSUB_RESULT"))) {
02704             char *gosub_transfer_dest;
02705             const char *gosub_retval = pbx_builtin_getvar_helper(peer, "GOSUB_RETVAL");
02706 
02707             /* Inherit return value from the peer, so it can be used in the master */
02708             if (gosub_retval) {
02709                pbx_builtin_setvar_helper(chan, "GOSUB_RETVAL", gosub_retval);
02710             }
02711 
02712             if (!strcasecmp(gosub_result, "BUSY")) {
02713                ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
02714                ast_set_flag64(peerflags, OPT_GO_ON);
02715                res = -1;
02716             } else if (!strcasecmp(gosub_result, "CONGESTION") || !strcasecmp(gosub_result, "CHANUNAVAIL")) {
02717                ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
02718                ast_set_flag64(peerflags, OPT_GO_ON);
02719                res = -1;
02720             } else if (!strcasecmp(gosub_result, "CONTINUE")) {
02721                /* hangup peer and keep chan alive assuming the macro has changed
02722                   the context / exten / priority or perhaps
02723                   the next priority in the current exten is desired.
02724                */
02725                ast_set_flag64(peerflags, OPT_GO_ON);
02726                res = -1;
02727             } else if (!strcasecmp(gosub_result, "ABORT")) {
02728                /* Hangup both ends unless the caller has the g flag */
02729                res = -1;
02730             } else if (!strncasecmp(gosub_result, "GOTO:", 5) && (gosub_transfer_dest = ast_strdupa(gosub_result + 5))) {
02731                res = -1;
02732                /* perform a transfer to a new extension */
02733                if (strchr(gosub_transfer_dest, '^')) { /* context^exten^priority*/
02734                   replace_macro_delimiter(gosub_transfer_dest);
02735                   if (!ast_parseable_goto(chan, gosub_transfer_dest))
02736                      ast_set_flag64(peerflags, OPT_GO_ON);
02737                }
02738             }
02739          }
02740 
02741          ast_channel_unlock(peer);  
02742       }
02743 
02744       if (!res) {
02745          if (!ast_tvzero(calldurationlimit)) {
02746             struct timeval whentohangup = calldurationlimit;
02747             peer->whentohangup = ast_tvadd(ast_tvnow(), whentohangup);
02748          }
02749          if (!ast_strlen_zero(dtmfcalled)) {
02750             ast_verb(3, "Sending DTMF '%s' to the called party.\n", dtmfcalled);
02751             res = ast_dtmf_stream(peer, chan, dtmfcalled, 250, 0);
02752          }
02753          if (!ast_strlen_zero(dtmfcalling)) {
02754             ast_verb(3, "Sending DTMF '%s' to the calling party.\n", dtmfcalling);
02755             res = ast_dtmf_stream(chan, peer, dtmfcalling, 250, 0);
02756          }
02757       }
02758 
02759       if (res) { /* some error */
02760          res = -1;
02761       } else {
02762          if (ast_test_flag64(peerflags, OPT_CALLEE_TRANSFER))
02763             ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
02764          if (ast_test_flag64(peerflags, OPT_CALLER_TRANSFER))
02765             ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
02766          if (ast_test_flag64(peerflags, OPT_CALLEE_HANGUP))
02767             ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
02768          if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP))
02769             ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
02770          if (ast_test_flag64(peerflags, OPT_CALLEE_MONITOR))
02771             ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
02772          if (ast_test_flag64(peerflags, OPT_CALLER_MONITOR))
02773             ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
02774          if (ast_test_flag64(peerflags, OPT_CALLEE_PARK))
02775             ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
02776          if (ast_test_flag64(peerflags, OPT_CALLER_PARK))
02777             ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
02778          if (ast_test_flag64(peerflags, OPT_CALLEE_MIXMONITOR))
02779             ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMIXMON);
02780          if (ast_test_flag64(peerflags, OPT_CALLER_MIXMONITOR))
02781             ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMIXMON);
02782          if (ast_test_flag64(peerflags, OPT_GO_ON))
02783             ast_set_flag(&(config.features_caller), AST_FEATURE_NO_H_EXTEN);
02784 
02785          config.end_bridge_callback = end_bridge_callback;
02786          config.end_bridge_callback_data = chan;
02787          config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
02788          
02789          if (moh) {
02790             moh = 0;
02791             ast_moh_stop(chan);
02792          } else if (sentringing) {
02793             sentringing = 0;
02794             ast_indicate(chan, -1);
02795          }
02796          /* Be sure no generators are left on it and reset the visible indication */
02797          ast_deactivate_generator(chan);
02798          chan->visible_indication = 0;
02799          /* Make sure channels are compatible */
02800          res = ast_channel_make_compatible(chan, peer);
02801          if (res < 0) {
02802             ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
02803             ast_hangup(peer);
02804             res = -1;
02805             goto done;
02806          }
02807          if (opermode) {
02808             struct oprmode oprmode;
02809 
02810             oprmode.peer = peer;
02811             oprmode.mode = opermode;
02812 
02813             ast_channel_setoption(chan, AST_OPTION_OPRMODE, &oprmode, sizeof(oprmode), 0);
02814          }
02815          res = ast_bridge_call(chan, peer, &config);
02816       }
02817 
02818       strcpy(peer->context, chan->context);
02819 
02820       if (ast_test_flag64(&opts, OPT_PEER_H)
02821          && ast_exists_extension(peer, peer->context, "h", 1,
02822             S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL))) {
02823          int autoloopflag;
02824          int found;
02825          int res9;
02826          
02827          strcpy(peer->exten, "h");
02828          peer->priority = 1;
02829          autoloopflag = ast_test_flag(peer, AST_FLAG_IN_AUTOLOOP); /* save value to restore at the end */
02830          ast_set_flag(peer, AST_FLAG_IN_AUTOLOOP);
02831 
02832          while ((res9 = ast_spawn_extension(peer, peer->context, peer->exten,
02833             peer->priority,
02834             S_COR(peer->caller.id.number.valid, peer->caller.id.number.str, NULL),
02835             &found, 1)) == 0) {
02836             peer->priority++;
02837          }
02838 
02839          if (found && res9) {
02840             /* Something bad happened, or a hangup has been requested. */
02841             ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
02842             ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
02843          }
02844          ast_set2_flag(peer, autoloopflag, AST_FLAG_IN_AUTOLOOP);  /* set it back the way it was */
02845       }
02846       if (!ast_check_hangup(peer) && ast_test_flag64(&opts, OPT_CALLEE_GO_ON)) {
02847          if(!ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GO_ON])) {
02848             replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_GO_ON]);
02849             ast_parseable_goto(peer, opt_args[OPT_ARG_CALLEE_GO_ON]);
02850          } else { /* F() */
02851             int res;
02852             res = ast_goto_if_exists(peer, chan->context, chan->exten, (chan->priority) + 1); 
02853             if (res == AST_PBX_GOTO_FAILED) {
02854                ast_hangup(peer);
02855                goto out;
02856             }
02857          }
02858          ast_pbx_start(peer);
02859       } else {
02860          if (!ast_check_hangup(chan))
02861             chan->hangupcause = peer->hangupcause;
02862          ast_hangup(peer);
02863       }
02864    }
02865 out:
02866    if (moh) {
02867       moh = 0;
02868       ast_moh_stop(chan);
02869    } else if (sentringing) {
02870       sentringing = 0;
02871       ast_indicate(chan, -1);
02872    }
02873 
02874    if (delprivintro && ast_fileexists(pa.privintro, NULL, NULL) > 0) {
02875       ast_filedelete(pa.privintro, NULL);
02876       if (ast_fileexists(pa.privintro, NULL, NULL) > 0) {
02877          ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa.privintro);
02878       } else {
02879          ast_verb(3, "Successfully deleted %s intro file\n", pa.privintro);
02880       }
02881    }
02882 
02883    ast_channel_early_bridge(chan, NULL);
02884    hanguptree(outgoing, NULL, 0); /* In this case, there's no answer anywhere */
02885    pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
02886    senddialendevent(chan, pa.status);
02887    ast_debug(1, "Exiting with DIALSTATUS=%s.\n", pa.status);
02888    
02889    if ((ast_test_flag64(peerflags, OPT_GO_ON)) && !ast_check_hangup(chan) && (res != AST_PBX_INCOMPLETE)) {
02890       if (!ast_tvzero(calldurationlimit))
02891          memset(&chan->whentohangup, 0, sizeof(chan->whentohangup));
02892       res = 0;
02893    }
02894 
02895 done:
02896    if (config.warning_sound) {
02897       ast_free((char *)config.warning_sound);
02898    }
02899    if (config.end_sound) {
02900       ast_free((char *)config.end_sound);
02901    }
02902    if (config.start_sound) {
02903       ast_free((char *)config.start_sound);
02904    }
02905    ast_ignore_cc(chan);
02906    return res;
02907 }
02908 
02909 static int dial_exec(struct ast_channel *chan, const char *data)
02910 {
02911    struct ast_flags64 peerflags;
02912 
02913    memset(&peerflags, 0, sizeof(peerflags));
02914 
02915    return dial_exec_full(chan, data, &peerflags, NULL);
02916 }
02917 
02918 static int retrydial_exec(struct ast_channel *chan, const char *data)
02919 {
02920    char *parse;
02921    const char *context = NULL;
02922    int sleepms = 0, loops = 0, res = -1;
02923    struct ast_flags64 peerflags = { 0, };
02924    AST_DECLARE_APP_ARGS(args,
02925       AST_APP_ARG(announce);
02926       AST_APP_ARG(sleep);
02927       AST_APP_ARG(retries);
02928       AST_APP_ARG(dialdata);
02929    );
02930 
02931    if (ast_strlen_zero(data)) {
02932       ast_log(LOG_WARNING, "RetryDial requires an argument!\n");
02933       return -1;
02934    }
02935 
02936    parse = ast_strdupa(data);
02937    AST_STANDARD_APP_ARGS(args, parse);
02938 
02939    if (!ast_strlen_zero(args.sleep) && (sleepms = atoi(args.sleep)))
02940       sleepms *= 1000;
02941 
02942    if (!ast_strlen_zero(args.retries)) {
02943       loops = atoi(args.retries);
02944    }
02945 
02946    if (!args.dialdata) {
02947       ast_log(LOG_ERROR, "%s requires a 4th argument (dialdata)\n", rapp);
02948       goto done;
02949    }
02950 
02951    if (sleepms < 1000)
02952       sleepms = 10000;
02953 
02954    if (!loops)
02955       loops = -1; /* run forever */
02956 
02957    ast_channel_lock(chan);
02958    context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
02959    context = !ast_strlen_zero(context) ? ast_strdupa(context) : NULL;
02960    ast_channel_unlock(chan);
02961 
02962    res = 0;
02963    while (loops) {
02964       int continue_exec;
02965 
02966       chan->data = "Retrying";
02967       if (ast_test_flag(chan, AST_FLAG_MOH))
02968          ast_moh_stop(chan);
02969 
02970       res = dial_exec_full(chan, args.dialdata, &peerflags, &continue_exec);
02971       if (continue_exec)
02972          break;
02973 
02974       if (res == 0) {
02975          if (ast_test_flag64(&peerflags, OPT_DTMF_EXIT)) {
02976             if (!ast_strlen_zero(args.announce)) {
02977                if (ast_fileexists(args.announce, NULL, chan->language) > 0) {
02978                   if (!(res = ast_streamfile(chan, args.announce, chan->language)))
02979                      ast_waitstream(chan, AST_DIGIT_ANY);
02980                } else
02981                   ast_log(LOG_WARNING, "Announce file \"%s\" specified in Retrydial does not exist\n", args.announce);
02982             }
02983             if (!res && sleepms) {
02984                if (!ast_test_flag(chan, AST_FLAG_MOH))
02985                   ast_moh_start(chan, NULL, NULL);
02986                res = ast_waitfordigit(chan, sleepms);
02987             }
02988          } else {
02989             if (!ast_strlen_zero(args.announce)) {
02990                if (ast_fileexists(args.announce, NULL, chan->language) > 0) {
02991                   if (!(res = ast_streamfile(chan, args.announce, chan->language)))
02992                      res = ast_waitstream(chan, "");
02993                } else
02994                   ast_log(LOG_WARNING, "Announce file \"%s\" specified in Retrydial does not exist\n", args.announce);
02995             }
02996             if (sleepms) {
02997                if (!ast_test_flag(chan, AST_FLAG_MOH))
02998                   ast_moh_start(chan, NULL, NULL);
02999                if (!res)
03000                   res = ast_waitfordigit(chan, sleepms);
03001             }
03002          }
03003       }
03004 
03005       if (res < 0 || res == AST_PBX_INCOMPLETE) {
03006          break;
03007       } else if (res > 0) { /* Trying to send the call elsewhere (1 digit ext) */
03008          if (onedigit_goto(chan, context, (char) res, 1)) {
03009             res = 0;
03010             break;
03011          }
03012       }
03013       loops--;
03014    }
03015    if (loops == 0)
03016       res = 0;
03017    else if (res == 1)
03018       res = 0;
03019 
03020    if (ast_test_flag(chan, AST_FLAG_MOH))
03021       ast_moh_stop(chan);
03022  done:
03023    return res;
03024 }
03025 
03026 static int unload_module(void)
03027 {
03028    int res;
03029    struct ast_context *con;
03030 
03031    res = ast_unregister_application(app);
03032    res |= ast_unregister_application(rapp);
03033 
03034    if ((con = ast_context_find("app_dial_gosub_virtual_context"))) {
03035       ast_context_remove_extension2(con, "s", 1, NULL, 0);
03036       ast_context_destroy(con, "app_dial"); /* leave nothing behind */
03037    }
03038 
03039    return res;
03040 }
03041 
03042 static int load_module(void)
03043 {
03044    int res;
03045    struct ast_context *con;
03046 
03047    con = ast_context_find_or_create(NULL, NULL, "app_dial_gosub_virtual_context", "app_dial");
03048    if (!con)
03049       ast_log(LOG_ERROR, "Dial virtual context 'app_dial_gosub_virtual_context' does not exist and unable to create\n");
03050    else
03051       ast_add_extension2(con, 1, "s", 1, NULL, NULL, "NoOp", ast_strdup(""), ast_free_ptr, "app_dial");
03052 
03053    res = ast_register_application_xml(app, dial_exec);
03054    res |= ast_register_application_xml(rapp, retrydial_exec);
03055 
03056    return res;
03057 }
03058 
03059 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialing Application");