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