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