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