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