Mismerged a bit.
[asterisk/asterisk.git] / apps / app_dial.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief dial() & retrydial() - Trivial application to dial a channel and send an URL on answer
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \ingroup applications
26  */
27
28 /*** MODULEINFO
29         <depend>chan_local</depend>
30  ***/
31
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <sys/time.h>
38 #include <sys/signal.h>
39 #include <sys/stat.h>
40 #include <netinet/in.h>
41
42 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
43 #include "asterisk/lock.h"
44 #include "asterisk/file.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/module.h"
48 #include "asterisk/translate.h"
49 #include "asterisk/say.h"
50 #include "asterisk/config.h"
51 #include "asterisk/features.h"
52 #include "asterisk/musiconhold.h"
53 #include "asterisk/callerid.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/app.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/rtp_engine.h"
58 #include "asterisk/cdr.h"
59 #include "asterisk/manager.h"
60 #include "asterisk/privacy.h"
61 #include "asterisk/stringfields.h"
62 #include "asterisk/global_datastores.h"
63 #include "asterisk/dsp.h"
64 #include "asterisk/cel.h"
65 #include "asterisk/indications.h"
66
67 /*** DOCUMENTATION
68         <application name="Dial" language="en_US">
69                 <synopsis>
70                         Attempt to connect to another device or endpoint and bridge the call.
71                 </synopsis>
72                 <syntax>
73                         <parameter name="Technology/Resource" required="true" argsep="&amp;">
74                                 <argument name="Technology/Resource" required="true">
75                                         <para>Specification of the device(s) to dial.  These must be in the format of
76                                         <literal>Technology/Resource</literal>, where <replaceable>Technology</replaceable>
77                                         represents a particular channel driver, and <replaceable>Resource</replaceable>
78                                         represents a resource available to that particular channel driver.</para>
79                                 </argument>
80                                 <argument name="Technology2/Resource2" required="false" multiple="true">
81                                         <para>Optional extra devices to dial in parallel</para>
82                                         <para>If you need more then one enter them as
83                                         Technology2/Resource2&amp;Technology3/Resourse3&amp;.....</para>
84                                 </argument>
85                         </parameter>
86                         <parameter name="timeout" required="false">
87                                 <para>Specifies the number of seconds we attempt to dial the specified devices</para>
88                                 <para>If not specified, this defaults to 136 years.</para>
89                         </parameter>
90                         <parameter name="options" required="false">
91                            <optionlist>
92                                 <option name="A">
93                                         <argument name="x" required="true">
94                                                 <para>The file to play to the called party</para>
95                                         </argument>
96                                         <para>Play an announcement to the called party, where <replaceable>x</replaceable> is the prompt to be played</para>
97                                 </option>
98                                 <option name="a">
99                                         <para>Immediately answer the calling channel when the called channel answers in
100                                         all cases. Normally, the calling channel is answered when the called channel
101                                         answers, but when options such as A() and M() are used, the calling channel is
102                                         not answered until all actions on the called channel (such as playing an
103                                         announcement) are completed.  This option can be used to answer the calling
104                                         channel before doing anything on the called channel. You will rarely need to use
105                                         this option, the default behavior is adequate in most cases.</para>
106                                 </option>
107                                 <option name="C">
108                                         <para>Reset the call detail record (CDR) for this call.</para>
109                                 </option>
110                                 <option name="c">
111                                         <para>If the Dial() application cancels this call, always set the flag to tell the channel
112                                         driver that the call is answered elsewhere.</para>
113                                 </option>
114                                 <option name="d">
115                                         <para>Allow the calling user to dial a 1 digit extension while waiting for
116                                         a call to be answered. Exit to that extension if it exists in the
117                                         current context, or the context defined in the <variable>EXITCONTEXT</variable> variable,
118                                         if it exists.</para>
119                                 </option>
120                                 <option name="D" argsep=":">
121                                         <argument name="called" />
122                                         <argument name="calling" />
123                                         <argument name="progress" />
124                                         <para>Send the specified DTMF strings <emphasis>after</emphasis> the called
125                                         party has answered, but before the call gets bridged. The 
126                                         <replaceable>called</replaceable> DTMF string is sent to the called party, and the 
127                                         <replaceable>calling</replaceable> DTMF string is sent to the calling party. Both arguments 
128                                         can be used alone.  If <replaceable>progress</replaceable> is specified, its DTMF is sent
129                                         immediately after receiving a PROGRESS message.</para>
130                                 </option>
131                                 <option name="e">
132                                         <para>Execute the <literal>h</literal> extension for peer after the call ends</para>
133                                 </option>
134                                 <option name="f">
135                                         <argument name="x" required="false" />
136                                         <para>If <replaceable>x</replaceable> is not provided, force the callerid of the <emphasis>calling</emphasis> 
137                                         channel to be set as the extension associated with the channel using a dialplan <literal>hint</literal>.
138                                         For example, some PSTNs do not allow CallerID to be set to anything
139                                         other than the number assigned to the caller. If <replaceable>x</replaceable> is provided, though, then
140                                         this option behaves quite differently. Any outgoing channel created will have its connected party information
141                                         set to <replaceable>x</replaceable></para>
142                                 </option>
143                                 <option name="F" argsep="^">
144                                         <argument name="context" required="false" />
145                                         <argument name="exten" required="false" />
146                                         <argument name="priority" required="true" />
147                                         <para>When the caller hangs up, transfer the called party
148                                         to the specified destination and continue execution at that location.</para>
149                                 </option>
150                                 <option name="F">
151                                         <para>Proceed with dialplan execution at the next priority in the current extension if the
152                                         source channel hangs up.</para>
153                                 </option>
154                                 <option name="g">
155                                         <para>Proceed with dialplan execution at the next priority in the current extension if the
156                                         destination channel hangs up.</para>
157                                 </option>
158                                 <option name="G" argsep="^">
159                                         <argument name="context" required="false" />
160                                         <argument name="exten" required="false" />
161                                         <argument name="priority" required="true" />
162                                         <para>If the call is answered, transfer the calling party to
163                                         the specified <replaceable>priority</replaceable> and the called party to the specified 
164                                         <replaceable>priority</replaceable> plus one.</para>
165                                         <note>
166                                                 <para>You cannot use any additional action post answer options in conjunction with this option.</para>
167                                         </note>
168                                 </option>
169                                 <option name="h">
170                                         <para>Allow the called party to hang up by sending the <literal>*</literal> DTMF digit.</para>
171                                 </option>
172                                 <option name="H">
173                                         <para>Allow the calling party to hang up by hitting the <literal>*</literal> DTMF digit.</para>
174                                 </option>
175                                 <option name="i">
176                                         <para>Asterisk will ignore any forwarding requests it may receive on this dial attempt.</para>
177                                 </option>
178                                 <option name="I">
179                                         <para>Asterisk will ignore any connected line update requests or redirecting party update
180                                         requests it may receiveon this dial attempt.</para>
181                                 </option>
182                                 <option name="k">
183                                         <para>Allow the called party to enable parking of the call by sending
184                                         the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
185                                 </option>
186                                 <option name="K">
187                                         <para>Allow the calling party to enable parking of the call by sending
188                                         the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
189                                 </option>
190                                 <option name="L" argsep=":">
191                                         <argument name="x" required="true">
192                                                 <para>Maximum call time, in milliseconds</para>
193                                         </argument>
194                                         <argument name="y">
195                                                 <para>Warning time, in milliseconds</para>
196                                         </argument>
197                                         <argument name="z">
198                                                 <para>Repeat time, in milliseconds</para>
199                                         </argument>
200                                         <para>Limit the call to <replaceable>x</replaceable> milliseconds. Play a warning when <replaceable>y</replaceable> milliseconds are
201                                         left. Repeat the warning every <replaceable>z</replaceable> milliseconds until time expires.</para>
202                                         <para>This option is affected by the following variables:</para>
203                                         <variablelist>
204                                                 <variable name="LIMIT_PLAYAUDIO_CALLER">
205                                                         <value name="yes" default="true" />
206                                                         <value name="no" />
207                                                         <para>If set, this variable causes Asterisk to play the prompts to the caller.</para>
208                                                 </variable>
209                                                 <variable name="LIMIT_PLAYAUDIO_CALLEE">
210                                                         <value name="yes" />
211                                                         <value name="no" default="true"/>
212                                                         <para>If set, this variable causes Asterisk to play the prompts to the callee.</para>
213                                                 </variable>
214                                                 <variable name="LIMIT_TIMEOUT_FILE">
215                                                         <value name="filename"/>
216                                                         <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play when the timeout is reached.
217                                                         If not set, the time remaining will be announced.</para>
218                                                 </variable>
219                                                 <variable name="LIMIT_CONNECT_FILE">
220                                                         <value name="filename"/>
221                                                         <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play when the call begins.
222                                                         If not set, the time remaining will be announced.</para>
223                                                 </variable>
224                                                 <variable name="LIMIT_WARNING_FILE">
225                                                         <value name="filename"/>
226                                                         <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play as
227                                                         a warning when time <replaceable>x</replaceable> is reached. If not set, the time remaining will be announced.</para>
228                                                 </variable>
229                                         </variablelist>
230                                 </option>
231                                 <option name="m">
232                                         <argument name="class" required="false"/>
233                                         <para>Provide hold music to the calling party until a requested
234                                         channel answers. A specific music on hold <replaceable>class</replaceable>
235                                         (as defined in <filename>musiconhold.conf</filename>) can be specified.</para>
236                                 </option>
237                                 <option name="M" argsep="^">
238                                         <argument name="macro" required="true">
239                                                 <para>Name of the macro that should be executed.</para>
240                                         </argument>
241                                         <argument name="arg" multiple="true">
242                                                 <para>Macro arguments</para>
243                                         </argument>
244                                         <para>Execute the specified <replaceable>macro</replaceable> for the <emphasis>called</emphasis> channel 
245                                         before connecting to the calling channel. Arguments can be specified to the Macro
246                                         using <literal>^</literal> as a delimiter. The macro can set the variable
247                                         <variable>MACRO_RESULT</variable> to specify the following actions after the macro is
248                                         finished executing:</para>
249                                         <variablelist>
250                                                 <variable name="MACRO_RESULT">
251                                                         <para>If set, this action will be taken after the macro finished executing.</para>
252                                                         <value name="ABORT">
253                                                                 Hangup both legs of the call
254                                                         </value>
255                                                         <value name="CONGESTION">
256                                                                 Behave as if line congestion was encountered
257                                                         </value>
258                                                         <value name="BUSY">
259                                                                 Behave as if a busy signal was encountered
260                                                         </value>
261                                                         <value name="CONTINUE">
262                                                                 Hangup the called party and allow the calling party to continue dialplan execution at the next priority
263                                                         </value>
264                                                         <!-- TODO: Fix this syntax up, once we've figured out how to specify the GOTO syntax -->
265                                                         <value name="GOTO:&lt;context&gt;^&lt;exten&gt;^&lt;priority&gt;">
266                                                                 Transfer the call to the specified destination.
267                                                         </value>
268                                                 </variable>
269                                         </variablelist>
270                                         <note>
271                                                 <para>You cannot use any additional action post answer options in conjunction
272                                                 with this option. Also, pbx services are not run on the peer (called) channel,
273                                                 so you will not be able to set timeouts via the TIMEOUT() function in this macro.</para>
274                                         </note>
275                                         <warning><para>Be aware of the limitations that macros have, specifically with regards to use of
276                                         the <literal>WaitExten</literal> application. For more information, see the documentation for
277                                         Macro()</para></warning>
278                                 </option>
279                                 <option name="n">
280                                         <argument name="delete">
281                                                 <para>With <replaceable>delete</replaceable> either not specified or set to <literal>0</literal>,
282                                                 the recorded introduction will not be deleted if the caller hangs up while the remote party has not
283                                                 yet answered.</para>
284                                                 <para>With <replaceable>delete</replaceable> set to <literal>1</literal>, the introduction will
285                                                 always be deleted.</para>
286                                         </argument>
287                                         <para>This option is a modifier for the call screening/privacy mode. (See the 
288                                         <literal>p</literal> and <literal>P</literal> options.) It specifies
289                                         that no introductions are to be saved in the <directory>priv-callerintros</directory>
290                                         directory.</para>
291                                 </option>
292                                 <option name="N">
293                                         <para>This option is a modifier for the call screening/privacy mode. It specifies
294                                         that if Caller*ID is present, do not screen the call.</para>
295                                 </option>
296                                 <option name="o">
297                                         <para>Specify that the Caller*ID that was present on the <emphasis>calling</emphasis> channel
298                                         be set as the Caller*ID on the <emphasis>called</emphasis> channel. This was the
299                                         behavior of Asterisk 1.0 and earlier.</para>
300                                 </option>
301                                 <option name="O">
302                                         <argument name="mode">
303                                                 <para>With <replaceable>mode</replaceable> either not specified or set to <literal>1</literal>,
304                                                 the originator hanging up will cause the phone to ring back immediately.</para>
305                                                 <para>With <replaceable>mode</replaceable> set to <literal>2</literal>, when the operator 
306                                                 flashes the trunk, it will ring their phone back.</para>
307                                         </argument>
308                                         <para>Enables <emphasis>operator services</emphasis> mode.  This option only
309                                         works when bridging a DAHDI channel to another DAHDI channel
310                                         only. if specified on non-DAHDI interfaces, it will be ignored.
311                                         When the destination answers (presumably an operator services
312                                         station), the originator no longer has control of their line.
313                                         They may hang up, but the switch will not release their line
314                                         until the destination party (the operator) hangs up.</para>
315                                 </option>
316                                 <option name="p">
317                                         <para>This option enables screening mode. This is basically Privacy mode
318                                         without memory.</para>
319                                 </option>
320                                 <option name="P">
321                                         <argument name="x" />
322                                         <para>Enable privacy mode. Use <replaceable>x</replaceable> as the family/key in the AstDB database if
323                                         it is provided. The current extension is used if a database family/key is not specified.</para>
324                                 </option>
325                                 <option name="r">
326                                         <para>Default: Indicate ringing to the calling party, even if the called party isn't actually ringing. Pass no audio to the calling
327                                         party until the called channel has answered.</para>
328                                         <argument name="tone" required="false">
329                                                 <para>Indicate progress to calling party. Send audio 'tone' from indications.conf</para>
330                                         </argument>
331                                 </option>
332                                 <option name="S">
333                                         <argument name="x" required="true" />
334                                         <para>Hang up the call <replaceable>x</replaceable> seconds <emphasis>after</emphasis> the called party has
335                                         answered the call.</para>
336                                 </option>
337                                 <option name="t">
338                                         <para>Allow the called party to transfer the calling party by sending the
339                                         DTMF sequence defined in <filename>features.conf</filename>.</para>
340                                 </option>
341                                 <option name="T">
342                                         <para>Allow the calling party to transfer the called party by sending the
343                                         DTMF sequence defined in <filename>features.conf</filename>.</para>
344                                 </option>
345                                 <option name="U" argsep="^">
346                                         <argument name="x" required="true">
347                                                 <para>Name of the subroutine to execute via Gosub</para>
348                                         </argument>
349                                         <argument name="arg" multiple="true" required="false">
350                                                 <para>Arguments for the Gosub routine</para>
351                                         </argument>
352                                         <para>Execute via Gosub the routine <replaceable>x</replaceable> for the <emphasis>called</emphasis> channel before connecting
353                                         to the calling channel. Arguments can be specified to the Gosub
354                                         using <literal>^</literal> as a delimiter. The Gosub routine can set the variable
355                                         <variable>GOSUB_RESULT</variable> to specify the following actions after the Gosub returns.</para>
356                                         <variablelist>
357                                                 <variable name="GOSUB_RESULT">
358                                                         <value name="ABORT">
359                                                                 Hangup both legs of the call.
360                                                         </value>
361                                                         <value name="CONGESTION">
362                                                                 Behave as if line congestion was encountered.
363                                                         </value>
364                                                         <value name="BUSY">
365                                                                 Behave as if a busy signal was encountered.
366                                                         </value>
367                                                         <value name="CONTINUE">
368                                                                 Hangup the called party and allow the calling party
369                                                                 to continue dialplan execution at the next priority.
370                                                         </value>
371                                                         <!-- TODO: Fix this syntax up, once we've figured out how to specify the GOTO syntax -->
372                                                         <value name="GOTO:&lt;context&gt;^&lt;exten&gt;^&lt;priority&gt;">
373                                                                 Transfer the call to the specified priority. Optionally, an extension, or
374                                                                 extension and priority can be specified.
375                                                         </value>
376                                                 </variable>
377                                         </variablelist>
378                                         <note>
379                                                 <para>You cannot use any additional action post answer options in conjunction
380                                                 with this option. Also, pbx services are not run on the peer (called) channel,
381                                                 so you will not be able to set timeouts via the TIMEOUT() function in this routine.</para>
382                                         </note>
383                                 </option>
384                                 <option name="w">
385                                         <para>Allow the called party to enable recording of the call by sending
386                                         the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
387                                 </option>
388                                 <option name="W">
389                                         <para>Allow the calling party to enable recording of the call by sending
390                                         the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
391                                 </option>
392                                 <option name="x">
393                                         <para>Allow the called party to enable recording of the call by sending
394                                         the DTMF sequence defined for one-touch automixmonitor in <filename>features.conf</filename>.</para>
395                                 </option>
396                                 <option name="X">
397                                         <para>Allow the calling party to enable recording of the call by sending
398                                         the DTMF sequence defined for one-touch automixmonitor in <filename>features.conf</filename>.</para>
399                                 </option>
400                                 <option name="z">
401                                         <para>On a call forward, cancel any dial timeout which has been set for this call.</para>
402                                 </option>
403                                 </optionlist>
404                         </parameter>
405                         <parameter name="URL">
406                                 <para>The optional URL will be sent to the called party if the channel driver supports it.</para>
407                         </parameter>
408                 </syntax>
409                 <description>
410                         <para>This application will place calls to one or more specified channels. As soon
411                         as one of the requested channels answers, the originating channel will be
412                         answered, if it has not already been answered. These two channels will then
413                         be active in a bridged call. All other channels that were requested will then
414                         be hung up.</para>
415
416                         <para>Unless there is a timeout specified, the Dial application will wait
417                         indefinitely until one of the called channels answers, the user hangs up, or
418                         if all of the called channels are busy or unavailable. Dialplan executing will
419                         continue if no requested channels can be called, or if the timeout expires.
420                         This application will report normal termination if the originating channel
421                         hangs up, or if the call is bridged and either of the parties in the bridge
422                         ends the call.</para>
423                         <para>If the <variable>OUTBOUND_GROUP</variable> variable is set, all peer channels created by this
424                         application will be put into that group (as in Set(GROUP()=...).
425                         If the <variable>OUTBOUND_GROUP_ONCE</variable> variable is set, all peer channels created by this
426                         application will be put into that group (as in Set(GROUP()=...). Unlike OUTBOUND_GROUP,
427                         however, the variable will be unset after use.</para>
428
429                         <para>This application sets the following channel variables:</para>
430                         <variablelist>
431                                 <variable name="DIALEDTIME">
432                                         <para>This is the time from dialing a channel until when it is disconnected.</para>
433                                 </variable>
434                                 <variable name="ANSWEREDTIME">
435                                         <para>This is the amount of time for actual call.</para>
436                                 </variable>
437                                 <variable name="DIALSTATUS">
438                                         <para>This is the status of the call</para>
439                                         <value name="CHANUNAVAIL" />
440                                         <value name="CONGESTION" />
441                                         <value name="NOANSWER" />
442                                         <value name="BUSY" />
443                                         <value name="ANSWER" />
444                                         <value name="CANCEL" />
445                                         <value name="DONTCALL">
446                                                 For the Privacy and Screening Modes.
447                                                 Will be set if the called party chooses to send the calling party to the 'Go Away' script.
448                                         </value>
449                                         <value name="TORTURE">
450                                                 For the Privacy and Screening Modes.
451                                                 Will be set if the called party chooses to send the calling party to the 'torture' script.
452                                         </value>
453                                         <value name="INVALIDARGS" />
454                                 </variable>
455                         </variablelist>
456                 </description>
457         </application>
458         <application name="RetryDial" language="en_US">
459                 <synopsis>
460                         Place a call, retrying on failure allowing an optional exit extension.
461                 </synopsis>
462                 <syntax>
463                         <parameter name="announce" required="true">
464                                 <para>Filename of sound that will be played when no channel can be reached</para>
465                         </parameter>
466                         <parameter name="sleep" required="true">
467                                 <para>Number of seconds to wait after a dial attempt failed before a new attempt is made</para>
468                         </parameter>
469                         <parameter name="retries" required="true">
470                                 <para>Number of retries</para>
471                                 <para>When this is reached flow will continue at the next priority in the dialplan</para>
472                         </parameter>
473                         <parameter name="dialargs" required="true">
474                                 <para>Same format as arguments provided to the Dial application</para>
475                         </parameter>
476                 </syntax>
477                 <description>
478                         <para>This application will attempt to place a call using the normal Dial application.
479                         If no channel can be reached, the <replaceable>announce</replaceable> file will be played.
480                         Then, it will wait <replaceable>sleep</replaceable> number of seconds before retrying the call.
481                         After <replaceable>retries</replaceable> number of attempts, the calling channel will continue at the next priority in the dialplan.
482                         If the <replaceable>retries</replaceable> setting is set to 0, this application will retry endlessly.
483                         While waiting to retry a call, a 1 digit extension may be dialed. If that
484                         extension exists in either the context defined in <variable>EXITCONTEXT</variable> or the current
485                         one, The call will jump to that extension immediately.
486                         The <replaceable>dialargs</replaceable> are specified in the same format that arguments are provided
487                         to the Dial application.</para>
488                 </description>
489         </application>
490  ***/
491
492 static const char app[] = "Dial";
493 static const char rapp[] = "RetryDial";
494
495 enum {
496         OPT_ANNOUNCE =          (1 << 0),
497         OPT_RESETCDR =          (1 << 1),
498         OPT_DTMF_EXIT =         (1 << 2),
499         OPT_SENDDTMF =          (1 << 3),
500         OPT_FORCECLID =         (1 << 4),
501         OPT_GO_ON =             (1 << 5),
502         OPT_CALLEE_HANGUP =     (1 << 6),
503         OPT_CALLER_HANGUP =     (1 << 7),
504         OPT_ORIGINAL_CLID =     (1 << 8),
505         OPT_DURATION_LIMIT =    (1 << 9),
506         OPT_MUSICBACK =         (1 << 10),
507         OPT_CALLEE_MACRO =      (1 << 11),
508         OPT_SCREEN_NOINTRO =    (1 << 12),
509         OPT_SCREEN_NOCALLERID = (1 << 13),
510         OPT_IGNORE_CONNECTEDLINE = (1 << 14),
511         OPT_SCREENING =         (1 << 15),
512         OPT_PRIVACY =           (1 << 16),
513         OPT_RINGBACK =          (1 << 17),
514         OPT_DURATION_STOP =     (1 << 18),
515         OPT_CALLEE_TRANSFER =   (1 << 19),
516         OPT_CALLER_TRANSFER =   (1 << 20),
517         OPT_CALLEE_MONITOR =    (1 << 21),
518         OPT_CALLER_MONITOR =    (1 << 22),
519         OPT_GOTO =              (1 << 23),
520         OPT_OPERMODE =          (1 << 24),
521         OPT_CALLEE_PARK =       (1 << 25),
522         OPT_CALLER_PARK =       (1 << 26),
523         OPT_IGNORE_FORWARDING = (1 << 27),
524         OPT_CALLEE_GOSUB =      (1 << 28),
525         OPT_CALLEE_MIXMONITOR = (1 << 29),
526         OPT_CALLER_MIXMONITOR = (1 << 30),
527         OPT_CALLER_ANSWER =     (1 << 31),
528 };
529
530 #define DIAL_STILLGOING      (1 << 31)
531 #define DIAL_NOFORWARDHTML   ((uint64_t)1 << 32) /* flags are now 64 bits, so keep it up! */
532 #define DIAL_NOCONNECTEDLINE ((uint64_t)1 << 33)
533 #define OPT_CANCEL_ELSEWHERE ((uint64_t)1 << 34)
534 #define OPT_PEER_H           ((uint64_t)1 << 35)
535 #define OPT_CALLEE_GO_ON     ((uint64_t)1 << 36)
536 #define OPT_CANCEL_TIMEOUT   ((uint64_t)1 << 37)
537
538 enum {
539         OPT_ARG_ANNOUNCE = 0,
540         OPT_ARG_SENDDTMF,
541         OPT_ARG_GOTO,
542         OPT_ARG_DURATION_LIMIT,
543         OPT_ARG_MUSICBACK,
544         OPT_ARG_CALLEE_MACRO,
545         OPT_ARG_RINGBACK,
546         OPT_ARG_CALLEE_GOSUB,
547         OPT_ARG_CALLEE_GO_ON,
548         OPT_ARG_PRIVACY,
549         OPT_ARG_DURATION_STOP,
550         OPT_ARG_OPERMODE,
551         OPT_ARG_SCREEN_NOINTRO,
552         OPT_ARG_FORCECLID,
553         /* note: this entry _MUST_ be the last one in the enum */
554         OPT_ARG_ARRAY_SIZE,
555 };
556
557 AST_APP_OPTIONS(dial_exec_options, BEGIN_OPTIONS
558         AST_APP_OPTION_ARG('A', OPT_ANNOUNCE, OPT_ARG_ANNOUNCE),
559         AST_APP_OPTION('a', OPT_CALLER_ANSWER),
560         AST_APP_OPTION('C', OPT_RESETCDR),
561         AST_APP_OPTION('c', OPT_CANCEL_ELSEWHERE),
562         AST_APP_OPTION('d', OPT_DTMF_EXIT),
563         AST_APP_OPTION_ARG('D', OPT_SENDDTMF, OPT_ARG_SENDDTMF),
564         AST_APP_OPTION('e', OPT_PEER_H),
565         AST_APP_OPTION_ARG('f', OPT_FORCECLID, OPT_ARG_FORCECLID),
566         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
567         AST_APP_OPTION('g', OPT_GO_ON),
568         AST_APP_OPTION_ARG('G', OPT_GOTO, OPT_ARG_GOTO),
569         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
570         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
571         AST_APP_OPTION('i', OPT_IGNORE_FORWARDING),
572         AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
573         AST_APP_OPTION('k', OPT_CALLEE_PARK),
574         AST_APP_OPTION('K', OPT_CALLER_PARK),
575         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
576         AST_APP_OPTION_ARG('m', OPT_MUSICBACK, OPT_ARG_MUSICBACK),
577         AST_APP_OPTION_ARG('M', OPT_CALLEE_MACRO, OPT_ARG_CALLEE_MACRO),
578         AST_APP_OPTION_ARG('n', OPT_SCREEN_NOINTRO, OPT_ARG_SCREEN_NOINTRO),
579         AST_APP_OPTION('N', OPT_SCREEN_NOCALLERID),
580         AST_APP_OPTION('o', OPT_ORIGINAL_CLID),
581         AST_APP_OPTION_ARG('O', OPT_OPERMODE, OPT_ARG_OPERMODE),
582         AST_APP_OPTION('p', OPT_SCREENING),
583         AST_APP_OPTION_ARG('P', OPT_PRIVACY, OPT_ARG_PRIVACY),
584         AST_APP_OPTION_ARG('r', OPT_RINGBACK, OPT_ARG_RINGBACK),
585         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
586         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
587         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
588         AST_APP_OPTION_ARG('U', OPT_CALLEE_GOSUB, OPT_ARG_CALLEE_GOSUB),
589         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
590         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
591         AST_APP_OPTION('x', OPT_CALLEE_MIXMONITOR),
592         AST_APP_OPTION('X', OPT_CALLER_MIXMONITOR),
593         AST_APP_OPTION('z', OPT_CANCEL_TIMEOUT),
594 END_OPTIONS );
595
596 #define CAN_EARLY_BRIDGE(flags,chan,peer) (!ast_test_flag64(flags, OPT_CALLEE_HANGUP | \
597         OPT_CALLER_HANGUP | OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER | \
598         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR | OPT_CALLEE_PARK |  \
599         OPT_CALLER_PARK | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB) && \
600         !chan->audiohooks && !peer->audiohooks)
601
602 /*
603  * The list of active channels
604  */
605 struct chanlist {
606         struct chanlist *next;
607         struct ast_channel *chan;
608         uint64_t flags;
609         struct ast_party_connected_line connected;
610 };
611
612 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str *featurecode);
613
614 static void chanlist_free(struct chanlist *outgoing)
615 {
616         ast_party_connected_line_free(&outgoing->connected);
617         ast_free(outgoing);
618 }
619
620 static void hanguptree(struct chanlist *outgoing, struct ast_channel *exception, int answered_elsewhere)
621 {
622         /* Hang up a tree of stuff */
623         struct chanlist *oo;
624         while (outgoing) {
625                 /* Hangup any existing lines we have open */
626                 if (outgoing->chan && (outgoing->chan != exception)) {
627                         if (answered_elsewhere) {
628                                 /* The flag is used for local channel inheritance and stuff */
629                                 ast_set_flag(outgoing->chan, AST_FLAG_ANSWERED_ELSEWHERE);
630                                 /* This is for the channel drivers */
631                                 outgoing->chan->hangupcause = AST_CAUSE_ANSWERED_ELSEWHERE;
632                         }
633                         ast_party_connected_line_free(&outgoing->connected);
634                         ast_hangup(outgoing->chan);
635                 }
636                 oo = outgoing;
637                 outgoing = outgoing->next;
638                 chanlist_free(oo);
639         }
640 }
641
642 #define AST_MAX_WATCHERS 256
643
644 /*
645  * argument to handle_cause() and other functions.
646  */
647 struct cause_args {
648         struct ast_channel *chan;
649         int busy;
650         int congestion;
651         int nochan;
652 };
653
654 static void handle_cause(int cause, struct cause_args *num)
655 {
656         struct ast_cdr *cdr = num->chan->cdr;
657
658         switch(cause) {
659         case AST_CAUSE_BUSY:
660                 if (cdr)
661                         ast_cdr_busy(cdr);
662                 num->busy++;
663                 break;
664
665         case AST_CAUSE_CONGESTION:
666                 if (cdr)
667                         ast_cdr_failed(cdr);
668                 num->congestion++;
669                 break;
670
671         case AST_CAUSE_NO_ROUTE_DESTINATION:
672         case AST_CAUSE_UNREGISTERED:
673                 if (cdr)
674                         ast_cdr_failed(cdr);
675                 num->nochan++;
676                 break;
677
678         case AST_CAUSE_NO_ANSWER:
679                 if (cdr) {
680                         ast_cdr_noanswer(cdr);
681                 }
682                 break;
683         case AST_CAUSE_NORMAL_CLEARING:
684                 break;
685
686         default:
687                 num->nochan++;
688                 break;
689         }
690 }
691
692 /* free the buffer if allocated, and set the pointer to the second arg */
693 #define S_REPLACE(s, new_val)           \
694         do {                            \
695                 if (s)                  \
696                         ast_free(s);    \
697                 s = (new_val);          \
698         } while (0)
699
700 static int onedigit_goto(struct ast_channel *chan, const char *context, char exten, int pri)
701 {
702         char rexten[2] = { exten, '\0' };
703
704         if (context) {
705                 if (!ast_goto_if_exists(chan, context, rexten, pri))
706                         return 1;
707         } else {
708                 if (!ast_goto_if_exists(chan, chan->context, rexten, pri))
709                         return 1;
710                 else if (!ast_strlen_zero(chan->macrocontext)) {
711                         if (!ast_goto_if_exists(chan, chan->macrocontext, rexten, pri))
712                                 return 1;
713                 }
714         }
715         return 0;
716 }
717
718 /* do not call with chan lock held */
719 static const char *get_cid_name(char *name, int namelen, struct ast_channel *chan)
720 {
721         const char *context;
722         const char *exten;
723
724         ast_channel_lock(chan);
725         context = ast_strdupa(S_OR(chan->macrocontext, chan->context));
726         exten = ast_strdupa(S_OR(chan->macroexten, chan->exten));
727         ast_channel_unlock(chan);
728
729         return ast_get_hint(NULL, 0, name, namelen, chan, context, exten) ? name : "";
730 }
731
732 static void senddialevent(struct ast_channel *src, struct ast_channel *dst, const char *dialstring)
733 {
734         struct ast_channel *chans[] = { src, dst };
735         ast_manager_event_multichan(EVENT_FLAG_CALL, "Dial", 2, chans,
736                 "SubEvent: Begin\r\n"
737                 "Channel: %s\r\n"
738                 "Destination: %s\r\n"
739                 "CallerIDNum: %s\r\n"
740                 "CallerIDName: %s\r\n"
741                 "UniqueID: %s\r\n"
742                 "DestUniqueID: %s\r\n"
743                 "Dialstring: %s\r\n",
744                 src->name, dst->name, S_OR(src->cid.cid_num, "<unknown>"),
745                 S_OR(src->cid.cid_name, "<unknown>"), src->uniqueid,
746                 dst->uniqueid, dialstring ? dialstring : "");
747 }
748
749 static void senddialendevent(struct ast_channel *src, const char *dialstatus)
750 {
751         ast_manager_event(src, EVENT_FLAG_CALL, "Dial",
752                 "SubEvent: End\r\n"
753                 "Channel: %s\r\n"
754                 "UniqueID: %s\r\n"
755                 "DialStatus: %s\r\n",
756                 src->name, src->uniqueid, dialstatus);
757 }
758
759 /*!
760  * helper function for wait_for_answer()
761  *
762  * XXX this code is highly suspicious, as it essentially overwrites
763  * the outgoing channel without properly deleting it.
764  *
765  * \todo eventually this function should be intergrated into and replaced by ast_call_forward() 
766  */
767 static void do_forward(struct chanlist *o,
768         struct cause_args *num, struct ast_flags64 *peerflags, int single, int *to)
769 {
770         char tmpchan[256];
771         struct ast_channel *original = o->chan;
772         struct ast_channel *c = o->chan; /* the winner */
773         struct ast_channel *in = num->chan; /* the input channel */
774         struct ast_party_redirecting *apr = &o->chan->redirecting;
775         struct ast_party_connected_line *apc = &o->chan->connected;
776         char *stuff;
777         char *tech;
778         int cause;
779
780         ast_copy_string(tmpchan, c->call_forward, sizeof(tmpchan));
781         if ((stuff = strchr(tmpchan, '/'))) {
782                 *stuff++ = '\0';
783                 tech = tmpchan;
784         } else {
785                 const char *forward_context;
786                 ast_channel_lock(c);
787                 forward_context = pbx_builtin_getvar_helper(c, "FORWARD_CONTEXT");
788                 if (ast_strlen_zero(forward_context)) {
789                         forward_context = NULL;
790                 }
791                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", c->call_forward, forward_context ? forward_context : c->context);
792                 ast_channel_unlock(c);
793                 stuff = tmpchan;
794                 tech = "Local";
795         }
796
797         ast_cel_report_event(in, AST_CEL_FORWARD, NULL, c->call_forward, NULL);
798
799         /* Before processing channel, go ahead and check for forwarding */
800         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, c->name);
801         /* If we have been told to ignore forwards, just set this channel to null and continue processing extensions normally */
802         if (ast_test_flag64(peerflags, OPT_IGNORE_FORWARDING)) {
803                 ast_verb(3, "Forwarding %s to '%s/%s' prevented.\n", in->name, tech, stuff);
804                 c = o->chan = NULL;
805                 cause = AST_CAUSE_BUSY;
806         } else {
807                 /* Setup parameters */
808                 c = o->chan = ast_request(tech, in->nativeformats, in, stuff, &cause);
809                 if (c) {
810                         if (single)
811                                 ast_channel_make_compatible(o->chan, in);
812                         ast_channel_inherit_variables(in, o->chan);
813                         ast_channel_datastore_inherit(in, o->chan);
814                 } else
815                         ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s' (cause = %d)\n", tech, stuff, cause);
816         }
817         if (!c) {
818                 ast_clear_flag64(o, DIAL_STILLGOING);
819                 handle_cause(cause, num);
820                 ast_hangup(original);
821         } else {
822                 if (single && CAN_EARLY_BRIDGE(peerflags, c, in)) {
823                         ast_rtp_instance_early_bridge_make_compatible(c, in);
824                 }
825
826                 c->cdrflags = in->cdrflags;
827
828                 ast_channel_set_redirecting(c, apr);
829                 ast_channel_lock(c);
830                 while (ast_channel_trylock(in)) {
831                         CHANNEL_DEADLOCK_AVOIDANCE(c);
832                 }
833                 S_REPLACE(c->cid.cid_rdnis, ast_strdup(S_OR(original->cid.cid_rdnis, S_OR(in->macroexten, in->exten))));
834
835                 c->cid.cid_tns = in->cid.cid_tns;
836
837                 if (ast_test_flag64(o, OPT_FORCECLID)) {
838                         S_REPLACE(c->cid.cid_num, ast_strdupa(S_OR(in->macroexten, in->exten)));
839                         S_REPLACE(c->cid.cid_name, NULL);
840                         ast_string_field_set(c, accountcode, c->accountcode);
841                 } else {
842                         ast_party_caller_copy(&c->cid, &in->cid);
843                         ast_string_field_set(c, accountcode, in->accountcode);
844                 }
845                 ast_party_connected_line_copy(&c->connected, apc);
846
847                 S_REPLACE(in->cid.cid_rdnis, ast_strdup(c->cid.cid_rdnis));
848                 ast_channel_update_redirecting(in, apr);
849
850                 ast_clear_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE);
851                 if (ast_test_flag64(peerflags, OPT_CANCEL_TIMEOUT)) {
852                         *to = -1;
853                 }
854
855                 ast_channel_unlock(in);
856                 ast_channel_unlock(c);
857
858                 if (ast_call(c, tmpchan, 0)) {
859                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
860                         ast_clear_flag64(o, DIAL_STILLGOING);
861                         ast_hangup(original);
862                         ast_hangup(c);
863                         c = o->chan = NULL;
864                         num->nochan++;
865                 } else {
866                         ast_channel_lock(c);
867                         while (ast_channel_trylock(in)) {
868                                 CHANNEL_DEADLOCK_AVOIDANCE(c);
869                         }
870                         senddialevent(in, c, stuff);
871                         if (!ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
872                                 char cidname[AST_MAX_EXTENSION] = "";
873                                 const char *tmpexten;
874                                 tmpexten = ast_strdupa(S_OR(in->macroexten, in->exten));
875                                 ast_channel_unlock(in);
876                                 ast_channel_unlock(c);
877                                 ast_set_callerid(c, tmpexten, get_cid_name(cidname, sizeof(cidname), in), NULL);
878                         } else {
879                                 ast_channel_unlock(in);
880                                 ast_channel_unlock(c);
881                         }
882                         /* Hangup the original channel now, in case we needed it */
883                         ast_hangup(original);
884                 }
885                 if (single) {
886                         ast_indicate(in, -1);
887                 }
888         }
889 }
890
891 /* argument used for some functions. */
892 struct privacy_args {
893         int sentringing;
894         int privdb_val;
895         char privcid[256];
896         char privintro[1024];
897         char status[256];
898 };
899
900 static struct ast_channel *wait_for_answer(struct ast_channel *in,
901         struct chanlist *outgoing, int *to, struct ast_flags64 *peerflags,
902         char *opt_args[],
903         struct privacy_args *pa,
904         const struct cause_args *num_in, int *result, char *dtmf_progress)
905 {
906         struct cause_args num = *num_in;
907         int prestart = num.busy + num.congestion + num.nochan;
908         int orig = *to;
909         struct ast_channel *peer = NULL;
910         /* single is set if only one destination is enabled */
911         int single = outgoing && !outgoing->next;
912 #ifdef HAVE_EPOLL
913         struct chanlist *epollo;
914 #endif
915         struct ast_party_connected_line connected_caller;
916         struct ast_str *featurecode = ast_str_alloca(FEATURE_MAX_LEN + 1);
917
918         ast_party_connected_line_init(&connected_caller);
919         if (single) {
920                 /* Turn off hold music, etc */
921                 if (!ast_test_flag64(outgoing, OPT_MUSICBACK | OPT_RINGBACK)) {
922                         ast_deactivate_generator(in);
923                         /* If we are calling a single channel, and not providing ringback or music, */
924                         /* then, make them compatible for in-band tone purpose */
925                         ast_channel_make_compatible(outgoing->chan, in);
926                 }
927
928                 if (!ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE) && !ast_test_flag64(outgoing, DIAL_NOCONNECTEDLINE)) {
929                         ast_channel_lock(outgoing->chan);
930                         ast_connected_line_copy_from_caller(&connected_caller, &outgoing->chan->cid);
931                         ast_channel_unlock(outgoing->chan);
932                         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
933                         ast_channel_update_connected_line(in, &connected_caller);
934                         ast_party_connected_line_free(&connected_caller);
935                 }
936         }
937
938 #ifdef HAVE_EPOLL
939         for (epollo = outgoing; epollo; epollo = epollo->next)
940                 ast_poll_channel_add(in, epollo->chan);
941 #endif
942
943         while (*to && !peer) {
944                 struct chanlist *o;
945                 int pos = 0; /* how many channels do we handle */
946                 int numlines = prestart;
947                 struct ast_channel *winner;
948                 struct ast_channel *watchers[AST_MAX_WATCHERS];
949
950                 watchers[pos++] = in;
951                 for (o = outgoing; o; o = o->next) {
952                         /* Keep track of important channels */
953                         if (ast_test_flag64(o, DIAL_STILLGOING) && o->chan)
954                                 watchers[pos++] = o->chan;
955                         numlines++;
956                 }
957                 if (pos == 1) { /* only the input channel is available */
958                         if (numlines == (num.busy + num.congestion + num.nochan)) {
959                                 ast_verb(2, "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
960                                 if (num.busy)
961                                         strcpy(pa->status, "BUSY");
962                                 else if (num.congestion)
963                                         strcpy(pa->status, "CONGESTION");
964                                 else if (num.nochan)
965                                         strcpy(pa->status, "CHANUNAVAIL");
966                         } else {
967                                 ast_verb(3, "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
968                         }
969                         *to = 0;
970                         return NULL;
971                 }
972                 winner = ast_waitfor_n(watchers, pos, to);
973                 for (o = outgoing; o; o = o->next) {
974                         struct ast_frame *f;
975                         struct ast_channel *c = o->chan;
976
977                         if (c == NULL)
978                                 continue;
979                         if (ast_test_flag64(o, DIAL_STILLGOING) && c->_state == AST_STATE_UP) {
980                                 if (!peer) {
981                                         ast_verb(3, "%s answered %s\n", c->name, in->name);
982                                         if (!single && !ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
983                                                 if (o->connected.id.number) {
984                                                         if (ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
985                                                                 ast_channel_update_connected_line(in, &o->connected);
986                                                         }
987                                                 } else if (!ast_test_flag64(o, DIAL_NOCONNECTEDLINE)) {
988                                                         ast_channel_lock(c);
989                                                         ast_connected_line_copy_from_caller(&connected_caller, &c->cid);
990                                                         ast_channel_unlock(c);
991                                                         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
992                                                         ast_channel_update_connected_line(in, &connected_caller);
993                                                         ast_party_connected_line_free(&connected_caller);
994                                                 }
995                                         }
996                                         peer = c;
997                                         ast_copy_flags64(peerflags, o,
998                                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
999                                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1000                                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1001                                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
1002                                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1003                                                 DIAL_NOFORWARDHTML);
1004                                         ast_string_field_set(c, dialcontext, "");
1005                                         ast_copy_string(c->exten, "", sizeof(c->exten));
1006                                 }
1007                                 continue;
1008                         }
1009                         if (c != winner)
1010                                 continue;
1011                         /* here, o->chan == c == winner */
1012                         if (!ast_strlen_zero(c->call_forward)) {
1013                                 pa->sentringing = 0;
1014                                 do_forward(o, &num, peerflags, single, to);
1015                                 continue;
1016                         }
1017                         f = ast_read(winner);
1018                         if (!f) {
1019                                 in->hangupcause = c->hangupcause;
1020 #ifdef HAVE_EPOLL
1021                                 ast_poll_channel_del(in, c);
1022 #endif
1023                                 ast_hangup(c);
1024                                 c = o->chan = NULL;
1025                                 ast_clear_flag64(o, DIAL_STILLGOING);
1026                                 handle_cause(in->hangupcause, &num);
1027                                 continue;
1028                         }
1029                         if (f->frametype == AST_FRAME_CONTROL) {
1030                                 switch (f->subclass.integer) {
1031                                 case AST_CONTROL_ANSWER:
1032                                         /* This is our guy if someone answered. */
1033                                         if (!peer) {
1034                                                 ast_verb(3, "%s answered %s\n", c->name, in->name);
1035                                                 if (!single && !ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
1036                                                         if (o->connected.id.number) {
1037                                                                 if (ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
1038                                                                         ast_channel_update_connected_line(in, &o->connected);
1039                                                                 }
1040                                                         } else if (!ast_test_flag64(o, DIAL_NOCONNECTEDLINE)) {
1041                                                                 ast_channel_lock(c);
1042                                                                 ast_connected_line_copy_from_caller(&connected_caller, &c->cid);
1043                                                                 ast_channel_unlock(c);
1044                                                                 connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1045                                                                 ast_channel_update_connected_line(in, &connected_caller);
1046                                                                 ast_party_connected_line_free(&connected_caller);
1047                                                         }
1048                                                 }
1049                                                 peer = c;
1050                                                 if (peer->cdr) {
1051                                                         peer->cdr->answer = ast_tvnow();
1052                                                         peer->cdr->disposition = AST_CDR_ANSWERED;
1053                                                 }
1054                                                 ast_copy_flags64(peerflags, o,
1055                                                         OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1056                                                         OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1057                                                         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1058                                                         OPT_CALLEE_PARK | OPT_CALLER_PARK |
1059                                                         OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1060                                                         DIAL_NOFORWARDHTML);
1061                                                 ast_string_field_set(c, dialcontext, "");
1062                                                 ast_copy_string(c->exten, "", sizeof(c->exten));
1063                                                 if (CAN_EARLY_BRIDGE(peerflags, in, peer))
1064                                                         /* Setup early bridge if appropriate */
1065                                                         ast_channel_early_bridge(in, peer);
1066                                         }
1067                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
1068                                         in->hangupcause = AST_CAUSE_NORMAL_CLEARING;
1069                                         c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
1070                                         break;
1071                                 case AST_CONTROL_BUSY:
1072                                         ast_verb(3, "%s is busy\n", c->name);
1073                                         in->hangupcause = c->hangupcause;
1074                                         ast_hangup(c);
1075                                         c = o->chan = NULL;
1076                                         ast_clear_flag64(o, DIAL_STILLGOING);
1077                                         handle_cause(AST_CAUSE_BUSY, &num);
1078                                         break;
1079                                 case AST_CONTROL_CONGESTION:
1080                                         ast_verb(3, "%s is circuit-busy\n", c->name);
1081                                         in->hangupcause = c->hangupcause;
1082                                         ast_hangup(c);
1083                                         c = o->chan = NULL;
1084                                         ast_clear_flag64(o, DIAL_STILLGOING);
1085                                         handle_cause(AST_CAUSE_CONGESTION, &num);
1086                                         break;
1087                                 case AST_CONTROL_RINGING:
1088                                         ast_verb(3, "%s is ringing\n", c->name);
1089                                         /* Setup early media if appropriate */
1090                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
1091                                                 ast_channel_early_bridge(in, c);
1092                                         if (!(pa->sentringing) && !ast_test_flag64(outgoing, OPT_MUSICBACK) && ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
1093                                                 ast_indicate(in, AST_CONTROL_RINGING);
1094                                                 pa->sentringing++;
1095                                         }
1096                                         break;
1097                                 case AST_CONTROL_PROGRESS:
1098                                         ast_verb(3, "%s is making progress passing it to %s\n", c->name, in->name);
1099                                         /* Setup early media if appropriate */
1100                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
1101                                                 ast_channel_early_bridge(in, c);
1102                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
1103                                                 if (single || (!single && !pa->sentringing)) {
1104                                                         ast_indicate(in, AST_CONTROL_PROGRESS);
1105                                                 }
1106                                                 if(!ast_strlen_zero(dtmf_progress)) {
1107                                                         ast_verb(3, "Sending DTMF '%s' to the called party as result of receiving a PROGRESS message.\n", dtmf_progress);
1108                                                         ast_dtmf_stream(c, in, dtmf_progress, 250, 0);
1109                                                 }
1110                                         break;
1111                                 case AST_CONTROL_VIDUPDATE:
1112                                         ast_verb(3, "%s requested a video update, passing it to %s\n", c->name, in->name);
1113                                         ast_indicate(in, AST_CONTROL_VIDUPDATE);
1114                                         break;
1115                                 case AST_CONTROL_SRCUPDATE:
1116                                         ast_verb(3, "%s requested a source update, passing it to %s\n", c->name, in->name);
1117                                         ast_indicate(in, AST_CONTROL_SRCUPDATE);
1118                                         break;
1119                                 case AST_CONTROL_CONNECTED_LINE:
1120                                         if (ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
1121                                                 ast_verb(3, "Connected line update to %s prevented.\n", in->name);
1122                                         } else if (!single) {
1123                                                 struct ast_party_connected_line connected;
1124                                                 ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n", c->name, in->name);
1125                                                 ast_party_connected_line_set_init(&connected, &o->connected);
1126                                                 ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
1127                                                 ast_party_connected_line_set(&o->connected, &connected);
1128                                                 ast_party_connected_line_free(&connected);
1129                                         } else {
1130                                                 if (ast_channel_connected_line_macro(c, in, f, 1, 1)) {
1131                                                         ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
1132                                                 }
1133                                         }
1134                                         break;
1135                                 case AST_CONTROL_REDIRECTING:
1136                                         if (ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
1137                                                 ast_verb(3, "Redirecting update to %s prevented.\n", in->name);
1138                                         } else {
1139                                                 ast_verb(3, "%s redirecting info has changed, passing it to %s\n", c->name, in->name);
1140                                                 ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
1141                                                 pa->sentringing = 0;
1142                                         }
1143                                         break;
1144                                 case AST_CONTROL_PROCEEDING:
1145                                         ast_verb(3, "%s is proceeding passing it to %s\n", c->name, in->name);
1146                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
1147                                                 ast_channel_early_bridge(in, c);
1148                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
1149                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
1150                                         break;
1151                                 case AST_CONTROL_HOLD:
1152                                         ast_verb(3, "Call on %s placed on hold\n", c->name);
1153                                         ast_indicate(in, AST_CONTROL_HOLD);
1154                                         break;
1155                                 case AST_CONTROL_UNHOLD:
1156                                         ast_verb(3, "Call on %s left from hold\n", c->name);
1157                                         ast_indicate(in, AST_CONTROL_UNHOLD);
1158                                         break;
1159                                 case AST_CONTROL_OFFHOOK:
1160                                 case AST_CONTROL_FLASH:
1161                                         /* Ignore going off hook and flash */
1162                                         break;
1163                                 case -1:
1164                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK | OPT_MUSICBACK)) {
1165                                                 ast_verb(3, "%s stopped sounds\n", c->name);
1166                                                 ast_indicate(in, -1);
1167                                                 pa->sentringing = 0;
1168                                         }
1169                                         break;
1170                                 default:
1171                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
1172                                 }
1173                         } else if (single) {
1174                                 switch (f->frametype) {
1175                                         case AST_FRAME_VOICE:
1176                                         case AST_FRAME_IMAGE:
1177                                         case AST_FRAME_TEXT:
1178                                                 if (ast_write(in, f)) {
1179                                                         ast_log(LOG_WARNING, "Unable to write frame\n");
1180                                                 }
1181                                                 break;
1182                                         case AST_FRAME_HTML:
1183                                                 if (!ast_test_flag64(outgoing, DIAL_NOFORWARDHTML) && ast_channel_sendhtml(in, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
1184                                                         ast_log(LOG_WARNING, "Unable to send URL\n");
1185                                                 }
1186                                                 break;
1187                                         default:
1188                                                 break;
1189                                 }
1190                         }
1191                         ast_frfree(f);
1192                 } /* end for */
1193                 if (winner == in) {
1194                         struct ast_frame *f = ast_read(in);
1195 #if 0
1196                         if (f && (f->frametype != AST_FRAME_VOICE))
1197                                 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1198                         else if (!f || (f->frametype != AST_FRAME_VOICE))
1199                                 printf("Hangup received on %s\n", in->name);
1200 #endif
1201                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
1202                                 /* Got hung up */
1203                                 *to = -1;
1204                                 strcpy(pa->status, "CANCEL");
1205                                 ast_cdr_noanswer(in->cdr);
1206                                 if (f) {
1207                                         if (f->data.uint32) {
1208                                                 in->hangupcause = f->data.uint32;
1209                                         }
1210                                         ast_frfree(f);
1211                                 }
1212                                 return NULL;
1213                         }
1214
1215                         /* now f is guaranteed non-NULL */
1216                         if (f->frametype == AST_FRAME_DTMF) {
1217                                 if (ast_test_flag64(peerflags, OPT_DTMF_EXIT)) {
1218                                         const char *context;
1219                                         ast_channel_lock(in);
1220                                         context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
1221                                         if (onedigit_goto(in, context, (char) f->subclass.integer, 1)) {
1222                                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
1223                                                 *to = 0;
1224                                                 ast_cdr_noanswer(in->cdr);
1225                                                 *result = f->subclass.integer;
1226                                                 strcpy(pa->status, "CANCEL");
1227                                                 ast_frfree(f);
1228                                                 ast_channel_unlock(in);
1229                                                 return NULL;
1230                                         }
1231                                         ast_channel_unlock(in);
1232                                 }
1233
1234                                 if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP) &&
1235                                         detect_disconnect(in, f->subclass.integer, featurecode)) {
1236                                         ast_verb(3, "User requested call disconnect.\n");
1237                                         *to = 0;
1238                                         strcpy(pa->status, "CANCEL");
1239                                         ast_cdr_noanswer(in->cdr);
1240                                         ast_frfree(f);
1241                                         return NULL;
1242                                 }
1243                         }
1244
1245                         /* Forward HTML stuff */
1246                         if (single && (f->frametype == AST_FRAME_HTML) && !ast_test_flag64(outgoing, DIAL_NOFORWARDHTML))
1247                                 if (ast_channel_sendhtml(outgoing->chan, f->subclass.integer, f->data.ptr, f->datalen) == -1)
1248                                         ast_log(LOG_WARNING, "Unable to send URL\n");
1249
1250                         if (single && ((f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_DTMF_BEGIN) || (f->frametype == AST_FRAME_DTMF_END)))  {
1251                                 if (ast_write(outgoing->chan, f))
1252                                         ast_log(LOG_WARNING, "Unable to forward voice or dtmf\n");
1253                         }
1254                         if (single && (f->frametype == AST_FRAME_CONTROL)) { 
1255                                 if ((f->subclass.integer == AST_CONTROL_HOLD) ||
1256                                     (f->subclass.integer == AST_CONTROL_UNHOLD) ||
1257                                     (f->subclass.integer == AST_CONTROL_VIDUPDATE) ||
1258                                     (f->subclass.integer == AST_CONTROL_SRCUPDATE) ||
1259                                     (f->subclass.integer == AST_CONTROL_REDIRECTING)) {
1260                                         ast_verb(3, "%s requested special control %d, passing it to %s\n", in->name, f->subclass.integer, outgoing->chan->name);
1261                                         ast_indicate_data(outgoing->chan, f->subclass.integer, f->data.ptr, f->datalen);
1262                                 } else if (f->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
1263                                         if (ast_channel_connected_line_macro(in, outgoing->chan, f, 0, 1)) {
1264                                                 ast_indicate_data(outgoing->chan, f->subclass.integer, f->data.ptr, f->datalen);
1265                                         }
1266                                 }
1267                         }
1268                         ast_frfree(f);
1269                 }
1270                 if (!*to)
1271                         ast_verb(3, "Nobody picked up in %d ms\n", orig);
1272                 if (!*to || ast_check_hangup(in))
1273                         ast_cdr_noanswer(in->cdr);
1274         }
1275
1276 #ifdef HAVE_EPOLL
1277         for (epollo = outgoing; epollo; epollo = epollo->next) {
1278                 if (epollo->chan)
1279                         ast_poll_channel_del(in, epollo->chan);
1280         }
1281 #endif
1282
1283         return peer;
1284 }
1285
1286 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str *featurecode)
1287 {
1288         struct ast_flags features = { AST_FEATURE_DISCONNECT }; /* only concerned with disconnect feature */
1289         struct ast_call_feature feature = { 0, };
1290         int res;
1291
1292         ast_str_append(&featurecode, 1, "%c", code);
1293
1294         res = ast_feature_detect(chan, &features, ast_str_buffer(featurecode), &feature);
1295
1296         if (res != AST_FEATURE_RETURN_STOREDIGITS) {
1297                 ast_str_reset(featurecode);
1298         }
1299         if (feature.feature_mask & AST_FEATURE_DISCONNECT) {
1300                 return 1;
1301         }
1302
1303         return 0;
1304 }
1305
1306 static void replace_macro_delimiter(char *s)
1307 {
1308         for (; *s; s++)
1309                 if (*s == '^')
1310                         *s = ',';
1311 }
1312
1313 /* returns true if there is a valid privacy reply */
1314 static int valid_priv_reply(struct ast_flags64 *opts, int res)
1315 {
1316         if (res < '1')
1317                 return 0;
1318         if (ast_test_flag64(opts, OPT_PRIVACY) && res <= '5')
1319                 return 1;
1320         if (ast_test_flag64(opts, OPT_SCREENING) && res <= '4')
1321                 return 1;
1322         return 0;
1323 }
1324
1325 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
1326         struct ast_flags64 *opts, char **opt_args, struct privacy_args *pa)
1327 {
1328
1329         int res2;
1330         int loopcount = 0;
1331
1332         /* Get the user's intro, store it in priv-callerintros/$CID,
1333            unless it is already there-- this should be done before the
1334            call is actually dialed  */
1335
1336         /* all ring indications and moh for the caller has been halted as soon as the
1337            target extension was picked up. We are going to have to kill some
1338            time and make the caller believe the peer hasn't picked up yet */
1339
1340         if (ast_test_flag64(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1341                 char *original_moh = ast_strdupa(chan->musicclass);
1342                 ast_indicate(chan, -1);
1343                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
1344                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1345                 ast_string_field_set(chan, musicclass, original_moh);
1346         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1347                 ast_indicate(chan, AST_CONTROL_RINGING);
1348                 pa->sentringing++;
1349         }
1350
1351         /* Start autoservice on the other chan ?? */
1352         res2 = ast_autoservice_start(chan);
1353         /* Now Stream the File */
1354         for (loopcount = 0; loopcount < 3; loopcount++) {
1355                 if (res2 && loopcount == 0) /* error in ast_autoservice_start() */
1356                         break;
1357                 if (!res2) /* on timeout, play the message again */
1358                         res2 = ast_play_and_wait(peer, "priv-callpending");
1359                 if (!valid_priv_reply(opts, res2))
1360                         res2 = 0;
1361                 /* priv-callpending script:
1362                    "I have a caller waiting, who introduces themselves as:"
1363                 */
1364                 if (!res2)
1365                         res2 = ast_play_and_wait(peer, pa->privintro);
1366                 if (!valid_priv_reply(opts, res2))
1367                         res2 = 0;
1368                 /* now get input from the called party, as to their choice */
1369                 if (!res2) {
1370                         /* XXX can we have both, or they are mutually exclusive ? */
1371                         if (ast_test_flag64(opts, OPT_PRIVACY))
1372                                 res2 = ast_play_and_wait(peer, "priv-callee-options");
1373                         if (ast_test_flag64(opts, OPT_SCREENING))
1374                                 res2 = ast_play_and_wait(peer, "screen-callee-options");
1375                 }
1376                 /*! \page DialPrivacy Dial Privacy scripts
1377                 \par priv-callee-options script:
1378                         "Dial 1 if you wish this caller to reach you directly in the future,
1379                                 and immediately connect to their incoming call
1380                          Dial 2 if you wish to send this caller to voicemail now and
1381                                 forevermore.
1382                          Dial 3 to send this caller to the torture menus, now and forevermore.
1383                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1384                          Dial 5 to allow this caller to come straight thru to you in the future,
1385                                 but right now, just this once, send them to voicemail."
1386                 \par screen-callee-options script:
1387                         "Dial 1 if you wish to immediately connect to the incoming call
1388                          Dial 2 if you wish to send this caller to voicemail.
1389                          Dial 3 to send this caller to the torture menus.
1390                          Dial 4 to send this caller to a simple "go away" menu.
1391                 */
1392                 if (valid_priv_reply(opts, res2))
1393                         break;
1394                 /* invalid option */
1395                 res2 = ast_play_and_wait(peer, "vm-sorry");
1396         }
1397
1398         if (ast_test_flag64(opts, OPT_MUSICBACK)) {
1399                 ast_moh_stop(chan);
1400         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1401                 ast_indicate(chan, -1);
1402                 pa->sentringing = 0;
1403         }
1404         ast_autoservice_stop(chan);
1405         if (ast_test_flag64(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
1406                 /* map keypresses to various things, the index is res2 - '1' */
1407                 static const char * const _val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
1408                 static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
1409                 int i = res2 - '1';
1410                 ast_verb(3, "--Set privacy database entry %s/%s to %s\n",
1411                         opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
1412                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
1413         }
1414         switch (res2) {
1415         case '1':
1416                 break;
1417         case '2':
1418                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1419                 break;
1420         case '3':
1421                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1422                 break;
1423         case '4':
1424                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1425                 break;
1426         case '5':
1427                 /* XXX should we set status to DENY ? */
1428                 if (ast_test_flag64(opts, OPT_PRIVACY))
1429                         break;
1430                 /* if not privacy, then 5 is the same as "default" case */
1431         default: /* bad input or -1 if failure to start autoservice */
1432                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1433                 /* well, there seems basically two choices. Just patch the caller thru immediately,
1434                           or,... put 'em thru to voicemail. */
1435                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1436                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1437                 /* XXX should we set status to DENY ? */
1438                 /* XXX what about the privacy flags ? */
1439                 break;
1440         }
1441
1442         if (res2 == '1') { /* the only case where we actually connect */
1443                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll
1444                    just clog things up, and it's not useful information, not being tied to a CID */
1445                 if (strncmp(pa->privcid, "NOCALLERID", 10) == 0 || ast_test_flag64(opts, OPT_SCREEN_NOINTRO)) {
1446                         ast_filedelete(pa->privintro, NULL);
1447                         if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1448                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1449                         else
1450                                 ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1451                 }
1452                 return 0; /* the good exit path */
1453         } else {
1454                 ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1455                 return -1;
1456         }
1457 }
1458
1459 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
1460 static int setup_privacy_args(struct privacy_args *pa,
1461         struct ast_flags64 *opts, char *opt_args[], struct ast_channel *chan)
1462 {
1463         char callerid[60];
1464         int res;
1465         char *l;
1466         int silencethreshold;
1467
1468         if (!ast_strlen_zero(chan->cid.cid_num)) {
1469                 l = ast_strdupa(chan->cid.cid_num);
1470                 ast_shrink_phone_number(l);
1471                 if (ast_test_flag64(opts, OPT_PRIVACY) ) {
1472                         ast_verb(3, "Privacy DB is '%s', clid is '%s'\n", opt_args[OPT_ARG_PRIVACY], l);
1473                         pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
1474                 } else {
1475                         ast_verb(3, "Privacy Screening, clid is '%s'\n", l);
1476                         pa->privdb_val = AST_PRIVACY_UNKNOWN;
1477                 }
1478         } else {
1479                 char *tnam, *tn2;
1480
1481                 tnam = ast_strdupa(chan->name);
1482                 /* clean the channel name so slashes don't try to end up in disk file name */
1483                 for (tn2 = tnam; *tn2; tn2++) {
1484                         if (*tn2 == '/')  /* any other chars to be afraid of? */
1485                                 *tn2 = '=';
1486                 }
1487                 ast_verb(3, "Privacy-- callerid is empty\n");
1488
1489                 snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
1490                 l = callerid;
1491                 pa->privdb_val = AST_PRIVACY_UNKNOWN;
1492         }
1493
1494         ast_copy_string(pa->privcid, l, sizeof(pa->privcid));
1495
1496         if (strncmp(pa->privcid, "NOCALLERID", 10) != 0 && ast_test_flag64(opts, OPT_SCREEN_NOCALLERID)) {
1497                 /* if callerid is set and OPT_SCREEN_NOCALLERID is set also */
1498                 ast_verb(3, "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
1499                 pa->privdb_val = AST_PRIVACY_ALLOW;
1500         } else if (ast_test_flag64(opts, OPT_SCREEN_NOCALLERID) && strncmp(pa->privcid, "NOCALLERID", 10) == 0) {
1501                 ast_verb(3, "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
1502         }
1503         
1504         if (pa->privdb_val == AST_PRIVACY_DENY) {
1505                 ast_verb(3, "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
1506                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1507                 return 0;
1508         } else if (pa->privdb_val == AST_PRIVACY_KILL) {
1509                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1510                 return 0; /* Is this right? */
1511         } else if (pa->privdb_val == AST_PRIVACY_TORTURE) {
1512                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1513                 return 0; /* is this right??? */
1514         } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN) {
1515                 /* Get the user's intro, store it in priv-callerintros/$CID,
1516                    unless it is already there-- this should be done before the
1517                    call is actually dialed  */
1518
1519                 /* make sure the priv-callerintros dir actually exists */
1520                 snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
1521                 if ((res = ast_mkdir(pa->privintro, 0755))) {
1522                         ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(res));
1523                         return -1;
1524                 }
1525
1526                 snprintf(pa->privintro, sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
1527                 if (ast_fileexists(pa->privintro, NULL, NULL ) > 0 && strncmp(pa->privcid, "NOCALLERID", 10) != 0) {
1528                         /* the DELUX version of this code would allow this caller the
1529                            option to hear and retape their previously recorded intro.
1530                         */
1531                 } else {
1532                         int duration; /* for feedback from play_and_wait */
1533                         /* the file doesn't exist yet. Let the caller submit his
1534                            vocal intro for posterity */
1535                         /* priv-recordintro script:
1536
1537                            "At the tone, please say your name:"
1538
1539                         */
1540                         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1541                         ast_answer(chan);
1542                         res = ast_play_and_record(chan, "priv-recordintro", pa->privintro, 4, "gsm", &duration, silencethreshold, 2000, 0);  /* NOTE: I've reduced the total time to 4 sec */
1543                                                                         /* don't think we'll need a lock removed, we took care of
1544                                                                            conflicts by naming the pa.privintro file */
1545                         if (res == -1) {
1546                                 /* Delete the file regardless since they hung up during recording */
1547                                 ast_filedelete(pa->privintro, NULL);
1548                                 if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1549                                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1550                                 else
1551                                         ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1552                                 return -1;
1553                         }
1554                         if (!ast_streamfile(chan, "vm-dialout", chan->language) )
1555                                 ast_waitstream(chan, "");
1556                 }
1557         }
1558         return 1; /* success */
1559 }
1560
1561 static void end_bridge_callback(void *data)
1562 {
1563         char buf[80];
1564         time_t end;
1565         struct ast_channel *chan = data;
1566
1567         if (!chan->cdr) {
1568                 return;
1569         }
1570
1571         time(&end);
1572
1573         ast_channel_lock(chan);
1574         if (chan->cdr->answer.tv_sec) {
1575                 snprintf(buf, sizeof(buf), "%ld", end - chan->cdr->answer.tv_sec);
1576                 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", buf);
1577         }
1578
1579         if (chan->cdr->start.tv_sec) {
1580                 snprintf(buf, sizeof(buf), "%ld", end - chan->cdr->start.tv_sec);
1581                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", buf);
1582         }
1583         ast_channel_unlock(chan);
1584 }
1585
1586 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator) {
1587         bconfig->end_bridge_callback_data = originator;
1588 }
1589
1590 static int dial_handle_playtones(struct ast_channel *chan, const char *data)
1591 {
1592         struct ast_tone_zone_sound *ts = NULL;
1593         int res;
1594         const char *str = data;
1595
1596         if (ast_strlen_zero(str)) {
1597                 ast_debug(1,"Nothing to play\n");
1598                 return -1;
1599         }
1600
1601         ts = ast_get_indication_tone(chan->zone, str);
1602
1603         if (ts && ts->data[0]) {
1604                 res = ast_playtones_start(chan, 0, ts->data, 0);
1605         } else {
1606                 res = -1;
1607         }
1608
1609         if (ts) {
1610                 ts = ast_tone_zone_sound_unref(ts);
1611         }
1612
1613         if (res) {
1614                 ast_log(LOG_WARNING, "Unable to start playtone \'%s\'\n", str);
1615         }
1616
1617         return res;
1618 }
1619
1620 static int dial_exec_full(struct ast_channel *chan, const char *data, struct ast_flags64 *peerflags, int *continue_exec)
1621 {
1622         int res = -1; /* default: error */
1623         char *rest, *cur; /* scan the list of destinations */
1624         struct chanlist *outgoing = NULL; /* list of destinations */
1625         struct ast_channel *peer;
1626         int to; /* timeout */
1627         struct cause_args num = { chan, 0, 0, 0 };
1628         int cause;
1629         char numsubst[256];
1630         char *cid_num = NULL, *cid_name = NULL;
1631
1632         struct ast_bridge_config config = { { 0, } };
1633         struct timeval calldurationlimit = { 0, };
1634         char *dtmfcalled = NULL, *dtmfcalling = NULL, *dtmf_progress=NULL;
1635         struct privacy_args pa = {
1636                 .sentringing = 0,
1637                 .privdb_val = 0,
1638                 .status = "INVALIDARGS",
1639         };
1640         int sentringing = 0, moh = 0;
1641         const char *outbound_group = NULL;
1642         int result = 0;
1643         char *parse;
1644         int opermode = 0;
1645         int delprivintro = 0;
1646         AST_DECLARE_APP_ARGS(args,
1647                 AST_APP_ARG(peers);
1648                 AST_APP_ARG(timeout);
1649                 AST_APP_ARG(options);
1650                 AST_APP_ARG(url);
1651         );
1652         struct ast_flags64 opts = { 0, };
1653         char *opt_args[OPT_ARG_ARRAY_SIZE];
1654         struct ast_datastore *datastore = NULL;
1655         int fulldial = 0, num_dialed = 0;
1656
1657         /* Reset all DIAL variables back to blank, to prevent confusion (in case we don't reset all of them). */
1658         pbx_builtin_setvar_helper(chan, "DIALSTATUS", "");
1659         pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", "");
1660         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", "");
1661         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", "");
1662         pbx_builtin_setvar_helper(chan, "DIALEDTIME", "");
1663
1664         if (ast_strlen_zero(data)) {
1665                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1666                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1667                 return -1;
1668         }
1669
1670         parse = ast_strdupa(data);
1671
1672         AST_STANDARD_APP_ARGS(args, parse);
1673
1674         if (!ast_strlen_zero(args.options) &&
1675                 ast_app_parse_options64(dial_exec_options, &opts, opt_args, args.options)) {
1676                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1677                 goto done;
1678         }
1679
1680         if (ast_strlen_zero(args.peers)) {
1681                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1682                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1683                 goto done;
1684         }
1685
1686         if (ast_test_flag64(&opts, OPT_SCREEN_NOINTRO) && !ast_strlen_zero(opt_args[OPT_ARG_SCREEN_NOINTRO])) {
1687                 delprivintro = atoi(opt_args[OPT_ARG_SCREEN_NOINTRO]);
1688
1689                 if (delprivintro < 0 || delprivintro > 1) {
1690                         ast_log(LOG_WARNING, "Unknown argument %d specified to n option, ignoring\n", delprivintro);
1691                         delprivintro = 0;
1692                 }
1693         }
1694
1695         if (!ast_test_flag64(&opts, OPT_RINGBACK)) {
1696                 opt_args[OPT_ARG_RINGBACK] = NULL;
1697         }
1698
1699         if (ast_test_flag64(&opts, OPT_OPERMODE)) {
1700                 opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
1701                 ast_verb(3, "Setting operator services mode to %d.\n", opermode);
1702         }
1703
1704         if (ast_test_flag64(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
1705                 calldurationlimit.tv_sec = atoi(opt_args[OPT_ARG_DURATION_STOP]);
1706                 if (!calldurationlimit.tv_sec) {
1707                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
1708                         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1709                         goto done;
1710                 }
1711                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n", calldurationlimit.tv_sec + calldurationlimit.tv_usec / 1000000.0);
1712         }
1713
1714         if (ast_test_flag64(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
1715                 dtmf_progress = opt_args[OPT_ARG_SENDDTMF];
1716                 dtmfcalled = strsep(&dtmf_progress, ":");
1717                 dtmfcalling = strsep(&dtmf_progress, ":");
1718         }
1719
1720         if (ast_test_flag64(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
1721                 if (ast_bridge_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
1722                         goto done;
1723         }
1724
1725         if (ast_test_flag64(&opts, OPT_FORCECLID) && !ast_strlen_zero(opt_args[OPT_ARG_FORCECLID]))
1726                 ast_callerid_parse(opt_args[OPT_ARG_FORCECLID], &cid_name, &cid_num);
1727         if (ast_test_flag64(&opts, OPT_RESETCDR) && chan->cdr)
1728                 ast_cdr_reset(chan->cdr, NULL);
1729         if (ast_test_flag64(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
1730                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(chan->exten);
1731
1732         if (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) {
1733                 res = setup_privacy_args(&pa, &opts, opt_args, chan);
1734                 if (res <= 0)
1735                         goto out;
1736                 res = -1; /* reset default */
1737         }
1738
1739         if (ast_test_flag64(&opts, OPT_DTMF_EXIT) || ast_test_flag64(&opts, OPT_CALLER_HANGUP)) {
1740                 __ast_answer(chan, 0, 0);
1741         }
1742
1743         if (continue_exec)
1744                 *continue_exec = 0;
1745
1746         /* If a channel group has been specified, get it for use when we create peer channels */
1747
1748         ast_channel_lock(chan);
1749         if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
1750                 outbound_group = ast_strdupa(outbound_group);   
1751                 pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
1752         } else if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP"))) {
1753                 outbound_group = ast_strdupa(outbound_group);
1754         }
1755         ast_channel_unlock(chan);       
1756         ast_copy_flags64(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING | OPT_IGNORE_CONNECTEDLINE |
1757                          OPT_CANCEL_TIMEOUT | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB | OPT_FORCECLID);
1758
1759         /* loop through the list of dial destinations */
1760         rest = args.peers;
1761         while ((cur = strsep(&rest, "&")) ) {
1762                 struct chanlist *tmp;
1763                 struct ast_channel *tc; /* channel for this destination */
1764                 /* Get a technology/[device:]number pair */
1765                 char *number = cur;
1766                 char *interface = ast_strdupa(number);
1767                 char *tech = strsep(&number, "/");
1768                 /* find if we already dialed this interface */
1769                 struct ast_dialed_interface *di;
1770                 AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
1771                 num_dialed++;
1772                 if (!number) {
1773                         ast_log(LOG_WARNING, "Dial argument takes format (technology/[device:]number1)\n");
1774                         goto out;
1775                 }
1776                 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1777                         goto out;
1778                 if (opts.flags) {
1779                         ast_copy_flags64(tmp, &opts,
1780                                 OPT_CANCEL_ELSEWHERE |
1781                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1782                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1783                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1784                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
1785                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1786                                 OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID);
1787                         ast_set2_flag64(tmp, args.url, DIAL_NOFORWARDHTML);
1788                 }
1789                 ast_copy_string(numsubst, number, sizeof(numsubst));
1790                 /* Request the peer */
1791
1792                 ast_channel_lock(chan);
1793                 datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL);
1794                 /* If the incoming channel has previously had connected line information
1795                  * set on it (perhaps through the CONNECTED_LINE dialplan function) then
1796                  * seed the calllist's connected line information with this previously
1797                  * acquired info
1798                  */
1799                 if (chan->connected.id.number) {
1800                         ast_party_connected_line_copy(&tmp->connected, &chan->connected);
1801                 }
1802                 ast_channel_unlock(chan);
1803
1804                 if (datastore)
1805                         dialed_interfaces = datastore->data;
1806                 else {
1807                         if (!(datastore = ast_datastore_alloc(&dialed_interface_info, NULL))) {
1808                                 ast_log(LOG_WARNING, "Unable to create channel datastore for dialed interfaces. Aborting!\n");
1809                                 chanlist_free(tmp);
1810                                 goto out;
1811                         }
1812
1813                         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
1814
1815                         if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
1816                                 ast_datastore_free(datastore);
1817                                 chanlist_free(tmp);
1818                                 goto out;
1819                         }
1820
1821                         datastore->data = dialed_interfaces;
1822                         AST_LIST_HEAD_INIT(dialed_interfaces);
1823
1824                         ast_channel_lock(chan);
1825                         ast_channel_datastore_add(chan, datastore);
1826                         ast_channel_unlock(chan);
1827                 }
1828
1829                 AST_LIST_LOCK(dialed_interfaces);
1830                 AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
1831                         if (!strcasecmp(di->interface, interface)) {
1832                                 ast_log(LOG_WARNING, "Skipping dialing interface '%s' again since it has already been dialed\n",
1833                                         di->interface);
1834                                 break;
1835                         }
1836                 }
1837                 AST_LIST_UNLOCK(dialed_interfaces);
1838
1839                 if (di) {
1840                         fulldial++;
1841                         chanlist_free(tmp);
1842                         continue;
1843                 }
1844
1845                 /* It is always ok to dial a Local interface.  We only keep track of
1846                  * which "real" interfaces have been dialed.  The Local channel will
1847                  * inherit this list so that if it ends up dialing a real interface,
1848                  * it won't call one that has already been called. */
1849                 if (strcasecmp(tech, "Local")) {
1850                         if (!(di = ast_calloc(1, sizeof(*di) + strlen(interface)))) {
1851                                 AST_LIST_UNLOCK(dialed_interfaces);
1852                                 chanlist_free(tmp);
1853                                 goto out;
1854                         }
1855                         strcpy(di->interface, interface);
1856
1857                         AST_LIST_LOCK(dialed_interfaces);
1858                         AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
1859                         AST_LIST_UNLOCK(dialed_interfaces);
1860                 }
1861
1862                 tc = ast_request(tech, chan->nativeformats, chan, numsubst, &cause);
1863                 if (!tc) {
1864                         /* If we can't, just go on to the next call */
1865                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
1866                                 tech, cause, ast_cause2str(cause));
1867                         handle_cause(cause, &num);
1868                         if (!rest) /* we are on the last destination */
1869                                 chan->hangupcause = cause;
1870                         chanlist_free(tmp);
1871                         continue;
1872                 }
1873                 pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", numsubst);
1874
1875                 ast_channel_lock(tc);
1876                 while (ast_channel_trylock(chan)) {
1877                         CHANNEL_DEADLOCK_AVOIDANCE(tc);
1878                 }
1879                 /* Setup outgoing SDP to match incoming one */
1880                 if (!outgoing && !rest && CAN_EARLY_BRIDGE(peerflags, chan, tc)) {
1881                         ast_rtp_instance_early_bridge_make_compatible(tc, chan);
1882                 }
1883                 
1884                 /* Inherit specially named variables from parent channel */
1885                 ast_channel_inherit_variables(chan, tc);
1886                 ast_channel_datastore_inherit(chan, tc);
1887
1888                 tc->appl = "AppDial";
1889                 tc->data = "(Outgoing Line)";
1890                 memset(&tc->whentohangup, 0, sizeof(tc->whentohangup));
1891
1892                 /* If the new channel has no callerid, try to guess what it should be */
1893                 if (ast_strlen_zero(tc->cid.cid_num)) {
1894                         if (!ast_strlen_zero(chan->connected.id.number)) {
1895                                 ast_set_callerid(tc, chan->connected.id.number, chan->connected.id.name, chan->connected.ani);
1896                         } else if (!ast_strlen_zero(chan->cid.cid_dnid)) {
1897                                 ast_set_callerid(tc, chan->cid.cid_dnid, NULL, NULL);
1898                         } else if (!ast_strlen_zero(S_OR(chan->macroexten, chan->exten))) {
1899                                 ast_set_callerid(tc, S_OR(chan->macroexten, chan->exten), NULL, NULL);
1900                         }
1901                         ast_set_flag64(tmp, DIAL_NOCONNECTEDLINE);
1902                 }
1903
1904                 if (ast_test_flag64(peerflags, OPT_FORCECLID) && !ast_strlen_zero(opt_args[OPT_ARG_FORCECLID])) {
1905                         struct ast_party_connected_line connected;
1906
1907                         ast_party_connected_line_set_init(&connected, &tmp->chan->connected);
1908                         connected.id.number = cid_num;
1909                         connected.id.name = cid_name;
1910                         connected.id.number_presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
1911                         ast_channel_set_connected_line(tmp->chan, &connected);
1912                 } else {
1913                         ast_connected_line_copy_from_caller(&tc->connected, &chan->cid);
1914                 }
1915
1916                 S_REPLACE(tc->cid.cid_rdnis, ast_strdup(chan->cid.cid_rdnis));
1917                 ast_party_redirecting_copy(&tc->redirecting, &chan->redirecting);
1918
1919                 tc->cid.cid_tns = chan->cid.cid_tns;
1920
1921                 if (!ast_strlen_zero(chan->accountcode)) {
1922                         ast_string_field_set(tc, peeraccount, chan->accountcode);
1923                 }
1924                 tc->cdrflags = chan->cdrflags;
1925                 if (ast_strlen_zero(tc->musicclass))
1926                         ast_string_field_set(tc, musicclass, chan->musicclass);
1927
1928                 /* Pass ADSI CPE and transfer capability */
1929                 tc->adsicpe = chan->adsicpe;
1930                 tc->transfercapability = chan->transfercapability;
1931
1932                 /* If we have an outbound group, set this peer channel to it */
1933                 if (outbound_group)
1934                         ast_app_group_set_channel(tc, outbound_group);
1935                 /* If the calling channel has the ANSWERED_ELSEWHERE flag set, inherit it. This is to support local channels */
1936                 if (ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE))
1937                         ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
1938
1939                 /* Check if we're forced by configuration */
1940                 if (ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE))
1941                          ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
1942
1943
1944                 /* Inherit context and extension */
1945                 ast_string_field_set(tc, dialcontext, ast_strlen_zero(chan->macrocontext) ? chan->context : chan->macrocontext);
1946                 if (!ast_strlen_zero(chan->macroexten))
1947                         ast_copy_string(tc->exten, chan->macroexten, sizeof(tc->exten));
1948                 else
1949                         ast_copy_string(tc->exten, chan->exten, sizeof(tc->exten));
1950
1951                 ast_channel_unlock(tc);
1952                 res = ast_call(tc, numsubst, 0); /* Place the call, but don't wait on the answer */
1953
1954                 /* Save the info in cdr's that we called them */
1955                 if (chan->cdr)
1956                         ast_cdr_setdestchan(chan->cdr, tc->name);
1957
1958                 /* check the results of ast_call */
1959                 if (res) {
1960                         /* Again, keep going even if there's an error */
1961                         ast_debug(1, "ast call on peer returned %d\n", res);
1962                         ast_verb(3, "Couldn't call %s\n", numsubst);
1963                         if (tc->hangupcause) {
1964                                 chan->hangupcause = tc->hangupcause;
1965                         }
1966                         ast_channel_unlock(chan);
1967                         ast_hangup(tc);
1968                         tc = NULL;
1969                         chanlist_free(tmp);
1970                         continue;
1971                 } else {
1972                         const char *tmpexten = ast_strdupa(S_OR(chan->macroexten, chan->exten));
1973                         senddialevent(chan, tc, numsubst);
1974                         ast_verb(3, "Called %s\n", numsubst);
1975                         ast_channel_unlock(chan);
1976                         if (!ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
1977                                 char cidname[AST_MAX_EXTENSION];
1978                                 ast_set_callerid(tc, tmpexten, get_cid_name(cidname, sizeof(cidname), chan), NULL);
1979                         }
1980                 }
1981                 /* Put them in the list of outgoing thingies...  We're ready now.
1982                    XXX If we're forcibly removed, these outgoing calls won't get
1983                    hung up XXX */
1984                 ast_set_flag64(tmp, DIAL_STILLGOING);
1985                 tmp->chan = tc;
1986                 tmp->next = outgoing;
1987                 outgoing = tmp;
1988                 /* If this line is up, don't try anybody else */
1989                 if (outgoing->chan->_state == AST_STATE_UP)
1990                         break;
1991         }
1992         
1993         if (ast_strlen_zero(args.timeout)) {
1994                 to = -1;
1995         } else {
1996                 to = atoi(args.timeout);
1997                 if (to > 0)
1998                         to *= 1000;
1999                 else {
2000                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'. Setting timeout to infinite\n", args.timeout);
2001                         to = -1;
2002                 }
2003         }
2004
2005         if (!outgoing) {
2006                 strcpy(pa.status, "CHANUNAVAIL");
2007                 if (fulldial == num_dialed) {
2008                         res = -1;
2009                         goto out;
2010                 }
2011         } else {
2012                 /* Our status will at least be NOANSWER */
2013                 strcpy(pa.status, "NOANSWER");
2014                 if (ast_test_flag64(outgoing, OPT_MUSICBACK)) {
2015                         moh = 1;
2016                         if (!ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
2017                                 char *original_moh = ast_strdupa(chan->musicclass);
2018                                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
2019                                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
2020                                 ast_string_field_set(chan, musicclass, original_moh);
2021                         } else {
2022                                 ast_moh_start(chan, NULL, NULL);
2023                         }
2024                         ast_indicate(chan, AST_CONTROL_PROGRESS);
2025                 } else if (ast_test_flag64(outgoing, OPT_RINGBACK)) {
2026                         if (!ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
2027                                 if (dial_handle_playtones(chan, opt_args[OPT_ARG_RINGBACK])){
2028                                         ast_indicate(chan, AST_CONTROL_RINGING);
2029                                         sentringing++;
2030                                 } else {
2031                                         ast_indicate(chan, AST_CONTROL_PROGRESS);
2032                                 }
2033                         } else {
2034                                 ast_indicate(chan, AST_CONTROL_RINGING);
2035                                 sentringing++;
2036                         }
2037                 }
2038         }
2039
2040         peer = wait_for_answer(chan, outgoing, &to, peerflags, opt_args, &pa, &num, &result, dtmf_progress);
2041
2042         /* The ast_channel_datastore_remove() function could fail here if the
2043          * datastore was moved to another channel during a masquerade. If this is
2044          * the case, don't free the datastore here because later, when the channel
2045          * to which the datastore was moved hangs up, it will attempt to free this
2046          * datastore again, causing a crash
2047          */
2048         if (!ast_channel_datastore_remove(chan, datastore))
2049                 ast_datastore_free(datastore);
2050         if (!peer) {
2051                 if (result) {
2052                         res = result;
2053                 } else if (to) { /* Musta gotten hung up */
2054                         res = -1;
2055                 } else { /* Nobody answered, next please? */
2056                         res = 0;
2057                 }
2058
2059                 /* SIP, in particular, sends back this error code to indicate an
2060                  * overlap dialled number needs more digits. */
2061                 if (chan->hangupcause == AST_CAUSE_INVALID_NUMBER_FORMAT) {
2062                         res = AST_PBX_INCOMPLETE;
2063                 }
2064
2065                 /* almost done, although the 'else' block is 400 lines */
2066         } else {
2067                 const char *number;
2068
2069                 if (ast_test_flag64(&opts, OPT_CALLER_ANSWER))
2070                         ast_answer(chan);
2071
2072                 strcpy(pa.status, "ANSWER");
2073                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2074                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
2075                    we will always return with -1 so that it is hung up properly after the
2076                    conversation.  */
2077                 hanguptree(outgoing, peer, 1);
2078                 outgoing = NULL;
2079                 /* If appropriate, log that we have a destination channel and set the answer time */
2080                 if (chan->cdr) {
2081                         ast_cdr_setdestchan(chan->cdr, peer->name);
2082                         ast_cdr_setanswer(chan->cdr, peer->cdr->answer);
2083                 }
2084                 if (peer->name)
2085                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
2086                 
2087                 ast_channel_lock(peer);
2088                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER"); 
2089                 if (!number)
2090                         number = numsubst;
2091                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
2092                 ast_channel_unlock(peer);
2093
2094                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
2095                         ast_debug(1, "app_dial: sendurl=%s.\n", args.url);
2096                         ast_channel_sendurl( peer, args.url );
2097                 }
2098                 if ( (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) && pa.privdb_val == AST_PRIVACY_UNKNOWN) {
2099                         if (do_privacy(chan, peer, &opts, opt_args, &pa)) {
2100                                 res = 0;
2101                                 goto out;
2102                         }
2103                 }
2104                 if (!ast_test_flag64(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
2105                         res = 0;
2106                 } else {
2107                         int digit = 0;
2108                         struct ast_channel *chans[2];
2109                         struct ast_channel *active_chan;
2110
2111                         chans[0] = chan;
2112                         chans[1] = peer;
2113
2114                         /* we need to stream the announcment while monitoring the caller for a hangup */
2115
2116                         /* stream the file */
2117                         res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
2118                         if (res) {
2119                                 res = 0;
2120                                 ast_log(LOG_ERROR, "error streaming file '%s' to callee\n", opt_args[OPT_ARG_ANNOUNCE]);
2121                         }
2122
2123                         ast_set_flag(peer, AST_FLAG_END_DTMF_ONLY);
2124                         while (peer->stream) {
2125                                 int ms;
2126
2127                                 ms = ast_sched_wait(peer->sched);
2128
2129                                 if (ms < 0 && !peer->timingfunc) {
2130                                         ast_stopstream(peer);
2131                                         break;
2132                                 }
2133                                 if (ms < 0)
2134                                         ms = 1000;
2135
2136                                 active_chan = ast_waitfor_n(chans, 2, &ms);
2137                                 if (active_chan) {
2138                                         struct ast_frame *fr = ast_read(active_chan);
2139                                         if (!fr) {
2140                                                 ast_hangup(peer);
2141                                                 res = -1;
2142                                                 goto done;
2143                                         }
2144                                         switch(fr->frametype) {
2145                                                 case AST_FRAME_DTMF_END:
2146                                                         digit = fr->subclass.integer;
2147                                                         if (active_chan == peer && strchr(AST_DIGIT_ANY, res)) {
2148                                                                 ast_stopstream(peer);
2149                                                                 res = ast_senddigit(chan, digit, 0);
2150                                                         }
2151                                                         break;
2152                                                 case AST_FRAME_CONTROL:
2153                                                         switch (fr->subclass.integer) {
2154                                                                 case AST_CONTROL_HANGUP:
2155                                                                         ast_frfree(fr);
2156                                                                         ast_hangup(peer);
2157                                                                         res = -1;
2158                                                                         goto done;
2159                                                                 default:
2160                                                                         break;
2161                                                         }
2162                                                         break;
2163                                                 default:
2164                                                         /* Ignore all others */
2165                                                         break;
2166                                         }
2167                                         ast_frfree(fr);
2168                                 }
2169                                 ast_sched_runq(peer->sched);
2170                         }
2171                         ast_clear_flag(peer, AST_FLAG_END_DTMF_ONLY);
2172                 }
2173
2174                 if (chan && peer && ast_test_flag64(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
2175                         replace_macro_delimiter(opt_args[OPT_ARG_GOTO]);
2176                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
2177                         /* peer goes to the same context and extension as chan, so just copy info from chan*/
2178                         ast_copy_string(peer->context, chan->context, sizeof(peer->context));
2179                         ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
2180                         peer->priority = chan->priority + 2;
2181                         ast_pbx_start(peer);
2182                         hanguptree(outgoing, NULL, ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE) ? 1 : 0);
2183                         if (continue_exec)
2184                                 *continue_exec = 1;
2185                         res = 0;
2186                         goto done;
2187                 }
2188
2189                 if (ast_test_flag64(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
2190                         struct ast_app *theapp;
2191                         const char *macro_result;
2192
2193                         res = ast_autoservice_start(chan);
2194                         if (res) {
2195                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2196                                 res = -1;
2197                         }
2198
2199                         theapp = pbx_findapp("Macro");
2200
2201                         if (theapp && !res) { /* XXX why check res here ? */
2202                                 /* Set peer->exten and peer->context so that MACRO_EXTEN and MACRO_CONTEXT get set */
2203                                 ast_copy_string(peer->context, chan->context, sizeof(peer->context));
2204                                 ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
2205
2206                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_MACRO]);
2207                                 res = pbx_exec(peer, theapp, opt_args[OPT_ARG_CALLEE_MACRO]);
2208                                 ast_debug(1, "Macro exited with status %d\n", res);
2209                                 res = 0;
2210                         } else {
2211                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
2212                                 res = -1;
2213                         }
2214
2215                         if (ast_autoservice_stop(chan) < 0) {
2216                                 res = -1;
2217                         }
2218
2219                         ast_channel_lock(peer);
2220
2221                         if (!res && (macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
2222                                 char *macro_transfer_dest;
2223
2224                                 if (!strcasecmp(macro_result, "BUSY")) {
2225                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
2226                                         ast_set_flag64(peerflags, OPT_GO_ON);
2227                                         res = -1;
2228                                 } else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
2229                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
2230                                         ast_set_flag64(peerflags, OPT_GO_ON);
2231                                         res = -1;
2232                                 } else if (!strcasecmp(macro_result, "CONTINUE")) {
2233                                         /* hangup peer and keep chan alive assuming the macro has changed
2234                                            the context / exten / priority or perhaps
2235                                            the next priority in the current exten is desired.
2236                                         */
2237                                         ast_set_flag64(peerflags, OPT_GO_ON);
2238                                         res = -1;
2239                                 } else if (!strcasecmp(macro_result, "ABORT")) {
2240                                         /* Hangup both ends unless the caller has the g flag */
2241                                         res = -1;
2242                                 } else if (!strncasecmp(macro_result, "GOTO:", 5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
2243                                         res = -1;
2244                                         /* perform a transfer to a new extension */
2245                                         if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
2246                                                 replace_macro_delimiter(macro_transfer_dest);
2247                                                 if (!ast_parseable_goto(chan, macro_transfer_dest))
2248                                                         ast_set_flag64(peerflags, OPT_GO_ON);
2249                                         }
2250                                 }
2251                         }
2252
2253                         ast_channel_unlock(peer);
2254                 }
2255
2256                 if (ast_test_flag64(&opts, OPT_CALLEE_GOSUB) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GOSUB])) {
2257                         struct ast_app *theapp;
2258                         const char *gosub_result;
2259                         char *gosub_args, *gosub_argstart;
2260                         int res9 = -1;
2261
2262                         res9 = ast_autoservice_start(chan);
2263                         if (res9) {
2264                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2265                                 res9 = -1;
2266                         }
2267
2268                         theapp = pbx_findapp("Gosub");
2269
2270                         if (theapp && !res9) {
2271                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_GOSUB]);
2272
2273                                 /* Set where we came from */
2274                                 ast_copy_string(peer->context, "app_dial_gosub_virtual_context", sizeof(peer->context));
2275                                 ast_copy_string(peer->exten, "s", sizeof(peer->exten));
2276                                 peer->priority = 0;
2277
2278                                 gosub_argstart = strchr(opt_args[OPT_ARG_CALLEE_GOSUB], ',');
2279                                 if (gosub_argstart) {
2280                                         *gosub_argstart = 0;
2281                                         if (asprintf(&gosub_args, "%s,s,1(%s)", opt_args[OPT_ARG_CALLEE_GOSUB], gosub_argstart + 1) < 0) {
2282                                                 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
2283                                                 gosub_args = NULL;
2284                                         }
2285                                         *gosub_argstart = ',';
2286                                 } else {
2287                                         if (asprintf(&gosub_args, "%s,s,1", opt_args[OPT_ARG_CALLEE_GOSUB]) < 0) {
2288                                                 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
2289                                                 gosub_args = NULL;
2290                                         }
2291                                 }
2292
2293                                 if (gosub_args) {
2294                                         res9 = pbx_exec(peer, theapp, gosub_args);
2295                                         if (!res9) {
2296                                                 struct ast_pbx_args args;
2297                                                 /* A struct initializer fails to compile for this case ... */
2298                                                 memset(&args, 0, sizeof(args));
2299                                                 args.no_hangup_chan = 1;
2300                                                 ast_pbx_run_args(peer, &args);
2301                                         }
2302                                         ast_free(gosub_args);
2303                                         ast_debug(1, "Gosub exited with status %d\n", res9);
2304                                 } else {
2305                                         ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
2306                                 }
2307
2308                         } else if (!res9) {
2309                                 ast_log(LOG_ERROR, "Could not find application Gosub\n");
2310                                 res9 = -1;
2311                         }
2312
2313                         if (ast_autoservice_stop(chan) < 0) {
2314                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2315                                 res9 = -1;
2316                         }
2317                         
2318                         ast_channel_lock(peer);
2319
2320                         if (!res9 && (gosub_result = pbx_builtin_getvar_helper(peer, "GOSUB_RESULT"))) {
2321                                 char *gosub_transfer_dest;
2322
2323                                 if (!strcasecmp(gosub_result, "BUSY")) {
2324                                         ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
2325                                         ast_set_flag64(peerflags, OPT_GO_ON);
2326                                         res9 = -1;
2327                                 } else if (!strcasecmp(gosub_result, "CONGESTION") || !strcasecmp(gosub_result, "CHANUNAVAIL")) {
2328                                         ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
2329                                         ast_set_flag64(peerflags, OPT_GO_ON);
2330                                         res9 = -1;
2331                                 } else if (!strcasecmp(gosub_result, "CONTINUE")) {
2332                                         /* hangup peer and keep chan alive assuming the macro has changed
2333                                            the context / exten / priority or perhaps
2334                                            the next priority in the current exten is desired.
2335                                         */
2336                                         ast_set_flag64(peerflags, OPT_GO_ON);
2337                                         res9 = -1;
2338                                 } else if (!strcasecmp(gosub_result, "ABORT")) {
2339                                         /* Hangup both ends unless the caller has the g flag */
2340                                         res9 = -1;
2341                                 } else if (!strncasecmp(gosub_result, "GOTO:", 5) && (gosub_transfer_dest = ast_strdupa(gosub_result + 5))) {
2342                                         res9 = -1;
2343                                         /* perform a transfer to a new extension */
2344                                         if (strchr(gosub_transfer_dest, '^')) { /* context^exten^priority*/
2345                                                 replace_macro_delimiter(gosub_transfer_dest);
2346                                                 if (!ast_parseable_goto(chan, gosub_transfer_dest))
2347                                                         ast_set_flag64(peerflags, OPT_GO_ON);
2348                                         }
2349                                 }
2350                         }
2351
2352                         ast_channel_unlock(peer);       
2353                 }
2354
2355                 if (!res) {
2356                         if (!ast_tvzero(calldurationlimit)) {
2357                                 struct timeval whentohangup = calldurationlimit;
2358                                 peer->whentohangup = ast_tvadd(ast_tvnow(), whentohangup);
2359                         }
2360                         if (!ast_strlen_zero(dtmfcalled)) {
2361                                 ast_verb(3, "Sending DTMF '%s' to the called party.\n", dtmfcalled);
2362                                 res = ast_dtmf_stream(peer, chan, dtmfcalled, 250, 0);
2363                         }
2364                         if (!ast_strlen_zero(dtmfcalling)) {
2365                                 ast_verb(3, "Sending DTMF '%s' to the calling party.\n", dtmfcalling);
2366                                 res = ast_dtmf_stream(chan, peer, dtmfcalling, 250, 0);
2367                         }
2368                 }
2369
2370                 if (res) { /* some error */
2371                         res = -1;
2372                 } else {
2373                         if (ast_test_flag64(peerflags, OPT_CALLEE_TRANSFER))
2374                                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
2375                         if (ast_test_flag64(peerflags, OPT_CALLER_TRANSFER))
2376                                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
2377                         if (ast_test_flag64(peerflags, OPT_CALLEE_HANGUP))
2378                                 ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
2379                         if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP))
2380                                 ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
2381                         if (ast_test_flag64(peerflags, OPT_CALLEE_MONITOR))
2382                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
2383                         if (ast_test_flag64(peerflags, OPT_CALLER_MONITOR))
2384                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
2385                         if (ast_test_flag64(peerflags, OPT_CALLEE_PARK))
2386                                 ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
2387                         if (ast_test_flag64(peerflags, OPT_CALLER_PARK))
2388                                 ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
2389                         if (ast_test_flag64(peerflags, OPT_CALLEE_MIXMONITOR))
2390                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMIXMON);
2391                         if (ast_test_flag64(peerflags, OPT_CALLER_MIXMONITOR))
2392                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMIXMON);
2393                         if (ast_test_flag64(peerflags, OPT_GO_ON))
2394                                 ast_set_flag(&(config.features_caller), AST_FEATURE_NO_H_EXTEN);
2395
2396                         config.end_bridge_callback = end_bridge_callback;
2397                         config.end_bridge_callback_data = chan;
2398                         config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
2399                         
2400                         if (moh) {
2401                                 moh = 0;
2402                                 ast_moh_stop(chan);
2403                         } else if (sentringing) {
2404                                 sentringing = 0;
2405                                 ast_indicate(chan, -1);
2406                         }
2407                         /* Be sure no generators are left on it */
2408                         ast_deactivate_generator(chan);
2409                         /* Make sure channels are compatible */
2410                         res = ast_channel_make_compatible(chan, peer);
2411                         if (res < 0) {
2412                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
2413                                 ast_hangup(peer);
2414                                 res = -1;
2415                                 goto done;
2416                         }
2417                         if (opermode) {
2418                                 struct oprmode oprmode;
2419
2420                                 oprmode.peer = peer;
2421                                 oprmode.mode = opermode;
2422
2423                                 ast_channel_setoption(chan, AST_OPTION_OPRMODE, &oprmode, sizeof(oprmode), 0);
2424                         }
2425                         res = ast_bridge_call(chan, peer, &config);
2426                 }
2427
2428                 strcpy(peer->context, chan->context);
2429
2430                 if (ast_test_flag64(&opts, OPT_PEER_H) && ast_exists_extension(peer, peer->context, "h", 1, peer->cid.cid_num)) {
2431                         int autoloopflag;
2432                         int found;
2433                         int res9;
2434                         
2435                         strcpy(peer->exten, "h");
2436                         peer->priority = 1;
2437                         autoloopflag = ast_test_flag(peer, AST_FLAG_IN_AUTOLOOP); /* save value to restore at the end */
2438                         ast_set_flag(peer, AST_FLAG_IN_AUTOLOOP);
2439
2440                         while ((res9 = ast_spawn_extension(peer, peer->context, peer->exten, peer->priority, peer->cid.cid_num, &found, 1)) == 0)
2441                                 peer->priority++;
2442
2443                         if (found && res9) {
2444                                 /* Something bad happened, or a hangup has been requested. */
2445                                 ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
2446                                 ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
2447                         }
2448                         ast_set2_flag(peer, autoloopflag, AST_FLAG_IN_AUTOLOOP);  /* set it back the way it was */
2449                 }
2450                 if (!ast_check_hangup(peer) && ast_test_flag64(&opts, OPT_CALLEE_GO_ON)) {
2451                         if(!ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GO_ON])) {
2452                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_GO_ON]);
2453                                 ast_parseable_goto(peer, opt_args[OPT_ARG_CALLEE_GO_ON]);
2454                         } else { /* F() */
2455                                 int res;
2456                                 res = ast_goto_if_exists(peer, chan->context, chan->exten, (chan->priority) + 1); 
2457                                 if (res == AST_PBX_GOTO_FAILED) {
2458                                         ast_hangup(peer);
2459                                         goto out;
2460                                 }
2461                         }
2462                         ast_pbx_start(peer);
2463                 } else {
2464                         if (!ast_check_hangup(chan))
2465                                 chan->hangupcause = peer->hangupcause;
2466                         ast_hangup(peer);
2467                 }
2468         }
2469 out:
2470         if (moh) {
2471                 moh = 0;
2472                 ast_moh_stop(chan);
2473         } else if (sentringing) {
2474                 sentringing = 0;
2475                 ast_indicate(chan, -1);
2476         }
2477
2478         if (delprivintro && ast_fileexists(pa.privintro, NULL, NULL) > 0) {
2479                 ast_filedelete(pa.privintro, NULL);
2480                 if (ast_fileexists(pa.privintro, NULL, NULL) > 0) {
2481                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa.privintro);
2482                 } else {
2483                         ast_verb(3, "Successfully deleted %s intro file\n", pa.privintro);
2484                 }
2485         }
2486
2487         ast_channel_early_bridge(chan, NULL);
2488         hanguptree(outgoing, NULL, 0); /* In this case, there's no answer anywhere */
2489         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2490         senddialendevent(chan, pa.status);
2491         ast_debug(1, "Exiting with DIALSTATUS=%s.\n", pa.status);
2492         
2493         if ((ast_test_flag64(peerflags, OPT_GO_ON)) && !ast_check_hangup(chan) && (res != AST_PBX_INCOMPLETE)) {
2494                 if (!ast_tvzero(calldurationlimit))
2495                         memset(&chan->whentohangup, 0, sizeof(chan->whentohangup));
2496                 res = 0;
2497         }
2498
2499 done:
2500         if (config.warning_sound) {
2501                 ast_free((char *)config.warning_sound);
2502         }
2503         if (config.end_sound) {
2504                 ast_free((char *)config.end_sound);
2505         }
2506         if (config.start_sound) {
2507                 ast_free((char *)config.start_sound);
2508         }
2509         return res;
2510 }
2511
2512 static int dial_exec(struct ast_channel *chan, const char *data)
2513 {
2514         struct ast_flags64 peerflags;
2515
2516         memset(&peerflags, 0, sizeof(peerflags));
2517
2518         return dial_exec_full(chan, data, &peerflags, NULL);
2519 }
2520
2521 static int retrydial_exec(struct ast_channel *chan, const char *data)
2522 {
2523         char *parse;
2524         const char *context = NULL;
2525         int sleepms = 0, loops = 0, res = -1;
2526         struct ast_flags64 peerflags = { 0, };
2527         AST_DECLARE_APP_ARGS(args,
2528                 AST_APP_ARG(announce);
2529                 AST_APP_ARG(sleep);
2530                 AST_APP_ARG(retries);
2531                 AST_APP_ARG(dialdata);
2532         );
2533
2534         if (ast_strlen_zero(data)) {
2535                 ast_log(LOG_WARNING, "RetryDial requires an argument!\n");
2536                 return -1;
2537         }
2538
2539         parse = ast_strdupa(data);
2540         AST_STANDARD_APP_ARGS(args, parse);
2541
2542         if (!ast_strlen_zero(args.sleep) && (sleepms = atoi(args.sleep)))
2543                 sleepms *= 1000;
2544
2545         if (!ast_strlen_zero(args.retries)) {
2546                 loops = atoi(args.retries);
2547         }
2548
2549         if (!args.dialdata) {
2550                 ast_log(LOG_ERROR, "%s requires a 4th argument (dialdata)\n", rapp);
2551                 goto done;
2552         }
2553
2554         if (sleepms < 1000)
2555                 sleepms = 10000;
2556
2557         if (!loops)
2558                 loops = -1; /* run forever */
2559
2560         ast_channel_lock(chan);
2561         context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
2562         context = !ast_strlen_zero(context) ? ast_strdupa(context) : NULL;
2563         ast_channel_unlock(chan);
2564
2565         res = 0;
2566         while (loops) {
2567                 int continue_exec;
2568
2569                 chan->data = "Retrying";
2570                 if (ast_test_flag(chan, AST_FLAG_MOH))
2571                         ast_moh_stop(chan);
2572
2573                 res = dial_exec_full(chan, args.dialdata, &peerflags, &continue_exec);
2574                 if (continue_exec)
2575                         break;
2576
2577                 if (res == 0) {
2578                         if (ast_test_flag64(&peerflags, OPT_DTMF_EXIT)) {
2579                                 if (!ast_strlen_zero(args.announce)) {
2580                                         if (ast_fileexists(args.announce, NULL, chan->language) > 0) {
2581                                                 if (!(res = ast_streamfile(chan, args.announce, chan->language)))
2582                                                         ast_waitstream(chan, AST_DIGIT_ANY);
2583                                         } else
2584                                                 ast_log(LOG_WARNING, "Announce file \"%s\" specified in Retrydial does not exist\n", args.announce);
<