Merged revisions 319529 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                 "UniqueID: %s\r\n"
772                 "DestUniqueID: %s\r\n"
773                 "Dialstring: %s\r\n",
774                 src->name, dst->name,
775                 S_COR(src->caller.id.number.valid, src->caller.id.number.str, "<unknown>"),
776                 S_COR(src->caller.id.name.valid, src->caller.id.name.str, "<unknown>"),
777                 src->uniqueid, dst->uniqueid,
778                 dialstring ? dialstring : "");
779 }
780
781 static void senddialendevent(struct ast_channel *src, const char *dialstatus)
782 {
783         ast_manager_event(src, EVENT_FLAG_CALL, "Dial",
784                 "SubEvent: End\r\n"
785                 "Channel: %s\r\n"
786                 "UniqueID: %s\r\n"
787                 "DialStatus: %s\r\n",
788                 src->name, src->uniqueid, dialstatus);
789 }
790
791 /*!
792  * helper function for wait_for_answer()
793  *
794  * XXX this code is highly suspicious, as it essentially overwrites
795  * the outgoing channel without properly deleting it.
796  *
797  * \todo eventually this function should be intergrated into and replaced by ast_call_forward() 
798  */
799 static void do_forward(struct chanlist *o,
800         struct cause_args *num, struct ast_flags64 *peerflags, int single, int *to,
801         struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
802 {
803         char tmpchan[256];
804         struct ast_channel *original = o->chan;
805         struct ast_channel *c = o->chan; /* the winner */
806         struct ast_channel *in = num->chan; /* the input channel */
807         char *stuff;
808         char *tech;
809         int cause;
810         struct ast_party_caller caller;
811
812         ast_copy_string(tmpchan, c->call_forward, sizeof(tmpchan));
813         if ((stuff = strchr(tmpchan, '/'))) {
814                 *stuff++ = '\0';
815                 tech = tmpchan;
816         } else {
817                 const char *forward_context;
818                 ast_channel_lock(c);
819                 forward_context = pbx_builtin_getvar_helper(c, "FORWARD_CONTEXT");
820                 if (ast_strlen_zero(forward_context)) {
821                         forward_context = NULL;
822                 }
823                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", c->call_forward, forward_context ? forward_context : c->context);
824                 ast_channel_unlock(c);
825                 stuff = tmpchan;
826                 tech = "Local";
827         }
828
829         ast_cel_report_event(in, AST_CEL_FORWARD, NULL, c->call_forward, NULL);
830
831         /* Before processing channel, go ahead and check for forwarding */
832         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, c->name);
833         /* If we have been told to ignore forwards, just set this channel to null and continue processing extensions normally */
834         if (ast_test_flag64(peerflags, OPT_IGNORE_FORWARDING)) {
835                 ast_verb(3, "Forwarding %s to '%s/%s' prevented.\n", in->name, tech, stuff);
836                 c = o->chan = NULL;
837                 cause = AST_CAUSE_BUSY;
838         } else {
839                 /* Setup parameters */
840                 c = o->chan = ast_request(tech, in->nativeformats, in, stuff, &cause);
841                 if (c) {
842                         if (single)
843                                 ast_channel_make_compatible(o->chan, in);
844                         ast_channel_inherit_variables(in, o->chan);
845                         ast_channel_datastore_inherit(in, o->chan);
846                         /* When a call is forwarded, we don't want to track new interfaces
847                          * dialed for CC purposes. Setting the done flag will ensure that
848                          * any Dial operations that happen later won't record CC interfaces.
849                          */
850                         ast_ignore_cc(o->chan);
851                         ast_log(LOG_NOTICE, "Not accepting call completion offers from call-forward recipient %s\n", o->chan->name);
852                 } else
853                         ast_log(LOG_NOTICE,
854                                 "Forwarding failed to create channel to dial '%s/%s' (cause = %d)\n",
855                                 tech, stuff, cause);
856         }
857         if (!c) {
858                 ast_clear_flag64(o, DIAL_STILLGOING);
859                 handle_cause(cause, num);
860                 ast_hangup(original);
861         } else {
862                 struct ast_party_redirecting redirecting;
863
864                 if (single && CAN_EARLY_BRIDGE(peerflags, c, in)) {
865                         ast_rtp_instance_early_bridge_make_compatible(c, in);
866                 }
867
868                 ast_channel_set_redirecting(c, &original->redirecting, NULL);
869                 ast_channel_lock(c);
870                 while (ast_channel_trylock(in)) {
871                         CHANNEL_DEADLOCK_AVOIDANCE(c);
872                 }
873                 if (!c->redirecting.from.number.valid
874                         || ast_strlen_zero(c->redirecting.from.number.str)) {
875                         /*
876                          * The call was not previously redirected so it is
877                          * now redirected from this number.
878                          */
879                         ast_party_number_free(&c->redirecting.from.number);
880                         ast_party_number_init(&c->redirecting.from.number);
881                         c->redirecting.from.number.valid = 1;
882                         c->redirecting.from.number.str =
883                                 ast_strdup(S_OR(in->macroexten, in->exten));
884                 }
885
886                 c->dialed.transit_network_select = in->dialed.transit_network_select;
887
888                 /* Determine CallerID to store in outgoing channel. */
889                 ast_party_caller_set_init(&caller, &c->caller);
890                 if (ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
891                         caller.id = *stored_clid;
892                         ast_channel_set_caller_event(c, &caller, NULL);
893                 } else if (ast_strlen_zero(S_COR(c->caller.id.number.valid,
894                         c->caller.id.number.str, NULL))) {
895                         /*
896                          * The new channel has no preset CallerID number by the channel
897                          * driver.  Use the dialplan extension and hint name.
898                          */
899                         caller.id = *stored_clid;
900                         ast_channel_set_caller_event(c, &caller, NULL);
901                 }
902
903                 /* Determine CallerID for outgoing channel to send. */
904                 if (ast_test_flag64(o, OPT_FORCECLID)) {
905                         struct ast_party_connected_line connected;
906
907                         ast_party_connected_line_init(&connected);
908                         connected.id = *forced_clid;
909                         ast_party_connected_line_copy(&c->connected, &connected);
910                 } else {
911                         ast_connected_line_copy_from_caller(&c->connected, &in->caller);
912                 }
913
914                 ast_string_field_set(c, accountcode, in->accountcode);
915
916                 c->appl = "AppDial";
917                 c->data = "(Outgoing Line)";
918                 /*
919                  * We must unlock c before calling ast_channel_redirecting_macro, because
920                  * we put c into autoservice there. That is pretty much a guaranteed
921                  * deadlock. This is why the handling of c's lock may seem a bit unusual
922                  * here.
923                  */
924                 ast_party_redirecting_init(&redirecting);
925                 ast_party_redirecting_copy(&redirecting, &c->redirecting);
926                 ast_channel_unlock(c);
927                 if (ast_channel_redirecting_macro(c, in, &redirecting, 1, 0)) {
928                         ast_channel_update_redirecting(in, &redirecting, NULL);
929                 }
930                 ast_party_redirecting_free(&redirecting);
931                 ast_channel_unlock(in);
932
933                 ast_clear_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE);
934                 if (ast_test_flag64(peerflags, OPT_CANCEL_TIMEOUT)) {
935                         *to = -1;
936                 }
937
938                 if (ast_call(c, stuff, 0)) {
939                         ast_log(LOG_NOTICE, "Forwarding failed to dial '%s/%s'\n",
940                                 tech, stuff);
941                         ast_clear_flag64(o, DIAL_STILLGOING);
942                         ast_hangup(original);
943                         ast_hangup(c);
944                         c = o->chan = NULL;
945                         num->nochan++;
946                 } else {
947                         ast_channel_lock(c);
948                         while (ast_channel_trylock(in)) {
949                                 CHANNEL_DEADLOCK_AVOIDANCE(c);
950                         }
951                         senddialevent(in, c, stuff);
952                         ast_channel_unlock(in);
953                         ast_channel_unlock(c);
954                         /* Hangup the original channel now, in case we needed it */
955                         ast_hangup(original);
956                 }
957                 if (single) {
958                         ast_indicate(in, -1);
959                 }
960         }
961 }
962
963 /* argument used for some functions. */
964 struct privacy_args {
965         int sentringing;
966         int privdb_val;
967         char privcid[256];
968         char privintro[1024];
969         char status[256];
970 };
971
972 static struct ast_channel *wait_for_answer(struct ast_channel *in,
973         struct chanlist *outgoing, int *to, struct ast_flags64 *peerflags,
974         char *opt_args[],
975         struct privacy_args *pa,
976         const struct cause_args *num_in, int *result, char *dtmf_progress,
977         const int ignore_cc,
978         struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
979 {
980         struct cause_args num = *num_in;
981         int prestart = num.busy + num.congestion + num.nochan;
982         int orig = *to;
983         struct ast_channel *peer = NULL;
984         /* single is set if only one destination is enabled */
985         int single = outgoing && !outgoing->next;
986 #ifdef HAVE_EPOLL
987         struct chanlist *epollo;
988 #endif
989         struct ast_party_connected_line connected_caller;
990         struct ast_str *featurecode = ast_str_alloca(FEATURE_MAX_LEN + 1);
991         int cc_recall_core_id;
992         int is_cc_recall;
993         int cc_frame_received = 0;
994         int num_ringing = 0;
995
996         ast_party_connected_line_init(&connected_caller);
997         if (single) {
998                 /* Turn off hold music, etc */
999                 if (!ast_test_flag64(outgoing, OPT_MUSICBACK | OPT_RINGBACK)) {
1000                         ast_deactivate_generator(in);
1001                         /* If we are calling a single channel, and not providing ringback or music, */
1002                         /* then, make them compatible for in-band tone purpose */
1003                         if (ast_channel_make_compatible(outgoing->chan, in) < 0) {
1004                                 /* If these channels can not be made compatible, 
1005                                  * there is no point in continuing.  The bridge
1006                                  * will just fail if it gets that far.
1007                                  */
1008                                 *to = -1;
1009                                 strcpy(pa->status, "CONGESTION");
1010                                 ast_cdr_failed(in->cdr);
1011                                 return NULL;
1012                         }
1013                 }
1014
1015                 if (!ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE) && !ast_test_flag64(outgoing, DIAL_CALLERID_ABSENT)) {
1016                         ast_channel_lock(outgoing->chan);
1017                         ast_connected_line_copy_from_caller(&connected_caller, &outgoing->chan->caller);
1018                         ast_channel_unlock(outgoing->chan);
1019                         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1020                         ast_channel_update_connected_line(in, &connected_caller, NULL);
1021                         ast_party_connected_line_free(&connected_caller);
1022                 }
1023         }
1024
1025         is_cc_recall = ast_cc_is_recall(in, &cc_recall_core_id, NULL);
1026
1027 #ifdef HAVE_EPOLL
1028         for (epollo = outgoing; epollo; epollo = epollo->next)
1029                 ast_poll_channel_add(in, epollo->chan);
1030 #endif
1031
1032         while (*to && !peer) {
1033                 struct chanlist *o;
1034                 int pos = 0; /* how many channels do we handle */
1035                 int numlines = prestart;
1036                 struct ast_channel *winner;
1037                 struct ast_channel *watchers[AST_MAX_WATCHERS];
1038
1039                 watchers[pos++] = in;
1040                 for (o = outgoing; o; o = o->next) {
1041                         /* Keep track of important channels */
1042                         if (ast_test_flag64(o, DIAL_STILLGOING) && o->chan)
1043                                 watchers[pos++] = o->chan;
1044                         numlines++;
1045                 }
1046                 if (pos == 1) { /* only the input channel is available */
1047                         if (numlines == (num.busy + num.congestion + num.nochan)) {
1048                                 ast_verb(2, "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
1049                                 if (num.busy)
1050                                         strcpy(pa->status, "BUSY");
1051                                 else if (num.congestion)
1052                                         strcpy(pa->status, "CONGESTION");
1053                                 else if (num.nochan)
1054                                         strcpy(pa->status, "CHANUNAVAIL");
1055                         } else {
1056                                 ast_verb(3, "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
1057                         }
1058                         *to = 0;
1059                         if (is_cc_recall) {
1060                                 ast_cc_failed(cc_recall_core_id, "Everyone is busy/congested for the recall. How sad");
1061                         }
1062                         return NULL;
1063                 }
1064                 winner = ast_waitfor_n(watchers, pos, to);
1065                 for (o = outgoing; o; o = o->next) {
1066                         struct ast_frame *f;
1067                         struct ast_channel *c = o->chan;
1068
1069                         if (c == NULL)
1070                                 continue;
1071                         if (ast_test_flag64(o, DIAL_STILLGOING) && c->_state == AST_STATE_UP) {
1072                                 if (!peer) {
1073                                         ast_verb(3, "%s answered %s\n", c->name, in->name);
1074                                         if (!single && !ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
1075                                                 if (o->pending_connected_update) {
1076                                                         if (ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
1077                                                                 ast_channel_update_connected_line(in, &o->connected, NULL);
1078                                                         }
1079                                                 } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1080                                                         ast_channel_lock(c);
1081                                                         ast_connected_line_copy_from_caller(&connected_caller, &c->caller);
1082                                                         ast_channel_unlock(c);
1083                                                         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1084                                                         ast_channel_update_connected_line(in, &connected_caller, NULL);
1085                                                         ast_party_connected_line_free(&connected_caller);
1086                                                 }
1087                                         }
1088                                         if (o->aoc_s_rate_list) {
1089                                                 size_t encoded_size;
1090                                                 struct ast_aoc_encoded *encoded;
1091                                                 if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
1092                                                         ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
1093                                                         ast_aoc_destroy_encoded(encoded);
1094                                                 }
1095                                         }
1096                                         peer = c;
1097                                         ast_copy_flags64(peerflags, o,
1098                                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1099                                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1100                                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1101                                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
1102                                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1103                                                 DIAL_NOFORWARDHTML);
1104                                         ast_string_field_set(c, dialcontext, "");
1105                                         ast_copy_string(c->exten, "", sizeof(c->exten));
1106                                 }
1107                                 continue;
1108                         }
1109                         if (c != winner)
1110                                 continue;
1111                         /* here, o->chan == c == winner */
1112                         if (!ast_strlen_zero(c->call_forward)) {
1113                                 pa->sentringing = 0;
1114                                 if (!ignore_cc && (f = ast_read(c))) {
1115                                         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_CC) {
1116                                                 /* This channel is forwarding the call, and is capable of CC, so
1117                                                  * be sure to add the new device interface to the list
1118                                                  */
1119                                                 ast_handle_cc_control_frame(in, c, f->data.ptr);
1120                                         }
1121                                         ast_frfree(f);
1122                                 }
1123                                 do_forward(o, &num, peerflags, single, to, forced_clid, stored_clid);
1124                                 continue;
1125                         }
1126                         f = ast_read(winner);
1127                         if (!f) {
1128                                 in->hangupcause = c->hangupcause;
1129 #ifdef HAVE_EPOLL
1130                                 ast_poll_channel_del(in, c);
1131 #endif
1132                                 ast_hangup(c);
1133                                 c = o->chan = NULL;
1134                                 ast_clear_flag64(o, DIAL_STILLGOING);
1135                                 handle_cause(in->hangupcause, &num);
1136                                 continue;
1137                         }
1138                         if (f->frametype == AST_FRAME_CONTROL) {
1139                                 switch (f->subclass.integer) {
1140                                 case AST_CONTROL_ANSWER:
1141                                         /* This is our guy if someone answered. */
1142                                         if (!peer) {
1143                                                 ast_verb(3, "%s answered %s\n", c->name, in->name);
1144                                                 if (!single && !ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
1145                                                         if (o->pending_connected_update) {
1146                                                                 if (ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
1147                                                                         ast_channel_update_connected_line(in, &o->connected, NULL);
1148                                                                 }
1149                                                         } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1150                                                                 ast_channel_lock(c);
1151                                                                 ast_connected_line_copy_from_caller(&connected_caller, &c->caller);
1152                                                                 ast_channel_unlock(c);
1153                                                                 connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1154                                                                 ast_channel_update_connected_line(in, &connected_caller, NULL);
1155                                                                 ast_party_connected_line_free(&connected_caller);
1156                                                         }
1157                                                 }
1158                                                 if (o->aoc_s_rate_list) {
1159                                                         size_t encoded_size;
1160                                                         struct ast_aoc_encoded *encoded;
1161                                                         if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
1162                                                                 ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
1163                                                                 ast_aoc_destroy_encoded(encoded);
1164                                                         }
1165                                                 }
1166                                                 peer = c;
1167                                                 if (peer->cdr) {
1168                                                         peer->cdr->answer = ast_tvnow();
1169                                                         peer->cdr->disposition = AST_CDR_ANSWERED;
1170                                                 }
1171                                                 ast_copy_flags64(peerflags, o,
1172                                                         OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1173                                                         OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1174                                                         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1175                                                         OPT_CALLEE_PARK | OPT_CALLER_PARK |
1176                                                         OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1177                                                         DIAL_NOFORWARDHTML);
1178                                                 ast_string_field_set(c, dialcontext, "");
1179                                                 ast_copy_string(c->exten, "", sizeof(c->exten));
1180                                                 if (CAN_EARLY_BRIDGE(peerflags, in, peer))
1181                                                         /* Setup early bridge if appropriate */
1182                                                         ast_channel_early_bridge(in, peer);
1183                                         }
1184                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
1185                                         in->hangupcause = AST_CAUSE_NORMAL_CLEARING;
1186                                         c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
1187                                         break;
1188                                 case AST_CONTROL_BUSY:
1189                                         ast_verb(3, "%s is busy\n", c->name);
1190                                         in->hangupcause = c->hangupcause;
1191                                         ast_hangup(c);
1192                                         c = o->chan = NULL;
1193                                         ast_clear_flag64(o, DIAL_STILLGOING);
1194                                         handle_cause(AST_CAUSE_BUSY, &num);
1195                                         break;
1196                                 case AST_CONTROL_CONGESTION:
1197                                         ast_verb(3, "%s is circuit-busy\n", c->name);
1198                                         in->hangupcause = c->hangupcause;
1199                                         ast_hangup(c);
1200                                         c = o->chan = NULL;
1201                                         ast_clear_flag64(o, DIAL_STILLGOING);
1202                                         handle_cause(AST_CAUSE_CONGESTION, &num);
1203                                         break;
1204                                 case AST_CONTROL_RINGING:
1205                                         /* This is a tricky area to get right when using a native
1206                                          * CC agent. The reason is that we do the best we can to send only a
1207                                          * single ringing notification to the caller.
1208                                          *
1209                                          * Call completion complicates the logic used here. CCNR is typically
1210                                          * offered during a ringing message. Let's say that party A calls
1211                                          * parties B, C, and D. B and C do not support CC requests, but D
1212                                          * does. If we were to receive a ringing notification from B before
1213                                          * the others, then we would end up sending a ringing message to
1214                                          * A with no CCNR offer present.
1215                                          *
1216                                          * The approach that we have taken is that if we receive a ringing
1217                                          * response from a party and no CCNR offer is present, we need to
1218                                          * wait. Specifically, we need to wait until either a) a called party
1219                                          * offers CCNR in its ringing response or b) all called parties have
1220                                          * responded in some way to our call and none offers CCNR.
1221                                          *
1222                                          * The drawback to this is that if one of the parties has a delayed
1223                                          * response or, god forbid, one just plain doesn't respond to our
1224                                          * outgoing call, then this will result in a significant delay between
1225                                          * when the caller places the call and hears ringback.
1226                                          *
1227                                          * Note also that if CC is disabled for this call, then it is perfectly
1228                                          * fine for ringing frames to get sent through.
1229                                          */
1230                                         ++num_ringing;
1231                                         if (ignore_cc || cc_frame_received || num_ringing == numlines) {
1232                                                 ast_verb(3, "%s is ringing\n", c->name);
1233                                                 /* Setup early media if appropriate */
1234                                                 if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
1235                                                         ast_channel_early_bridge(in, c);
1236                                                 if (!(pa->sentringing) && !ast_test_flag64(outgoing, OPT_MUSICBACK) && ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
1237                                                         ast_indicate(in, AST_CONTROL_RINGING);
1238                                                         pa->sentringing++;
1239                                                 }
1240                                         }
1241                                         break;
1242                                 case AST_CONTROL_PROGRESS:
1243                                         ast_verb(3, "%s is making progress passing it to %s\n", c->name, in->name);
1244                                         /* Setup early media if appropriate */
1245                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
1246                                                 ast_channel_early_bridge(in, c);
1247                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK)) {
1248                                                 if (single || (!single && !pa->sentringing)) {
1249                                                         ast_indicate(in, AST_CONTROL_PROGRESS);
1250                                                 }
1251                                         }
1252                                         if (!ast_strlen_zero(dtmf_progress)) {
1253                                                 ast_verb(3,
1254                                                         "Sending DTMF '%s' to the called party as result of receiving a PROGRESS message.\n",
1255                                                         dtmf_progress);
1256                                                 ast_dtmf_stream(c, in, dtmf_progress, 250, 0);
1257                                         }
1258                                         break;
1259                                 case AST_CONTROL_VIDUPDATE:
1260                                         ast_verb(3, "%s requested a video update, passing it to %s\n", c->name, in->name);
1261                                         ast_indicate(in, AST_CONTROL_VIDUPDATE);
1262                                         break;
1263                                 case AST_CONTROL_SRCUPDATE:
1264                                         ast_verb(3, "%s requested a source update, passing it to %s\n", c->name, in->name);
1265                                         ast_indicate(in, AST_CONTROL_SRCUPDATE);
1266                                         break;
1267                                 case AST_CONTROL_CONNECTED_LINE:
1268                                         if (ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
1269                                                 ast_verb(3, "Connected line update to %s prevented.\n", in->name);
1270                                         } else if (!single) {
1271                                                 struct ast_party_connected_line connected;
1272                                                 ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n", c->name, in->name);
1273                                                 ast_party_connected_line_set_init(&connected, &o->connected);
1274                                                 ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
1275                                                 ast_party_connected_line_set(&o->connected, &connected, NULL);
1276                                                 ast_party_connected_line_free(&connected);
1277                                                 o->pending_connected_update = 1;
1278                                         } else {
1279                                                 if (ast_channel_connected_line_macro(c, in, f, 1, 1)) {
1280                                                         ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
1281                                                 }
1282                                         }
1283                                         break;
1284                                 case AST_CONTROL_AOC:
1285                                         {
1286                                                 struct ast_aoc_decoded *decoded = ast_aoc_decode(f->data.ptr, f->datalen, o->chan);
1287                                                 if (decoded && (ast_aoc_get_msg_type(decoded) == AST_AOC_S)) {
1288                                                         ast_aoc_destroy_decoded(o->aoc_s_rate_list);
1289                                                         o->aoc_s_rate_list = decoded;
1290                                                 } else {
1291                                                         ast_aoc_destroy_decoded(decoded);
1292                                                 }
1293                                         }
1294                                         break;
1295                                 case AST_CONTROL_REDIRECTING:
1296                                         if (ast_test_flag64(peerflags, OPT_IGNORE_CONNECTEDLINE)) {
1297                                                 ast_verb(3, "Redirecting update to %s prevented.\n", in->name);
1298                                         } else if (single) {
1299                                                 ast_verb(3, "%s redirecting info has changed, passing it to %s\n", c->name, in->name);
1300                                                 if (ast_channel_redirecting_macro(c, in, f, 1, 1)) {
1301                                                         ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
1302                                                 }
1303                                                 pa->sentringing = 0;
1304                                         }
1305                                         break;
1306                                 case AST_CONTROL_PROCEEDING:
1307                                         ast_verb(3, "%s is proceeding passing it to %s\n", c->name, in->name);
1308                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
1309                                                 ast_channel_early_bridge(in, c);
1310                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
1311                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
1312                                         break;
1313                                 case AST_CONTROL_HOLD:
1314                                         ast_verb(3, "Call on %s placed on hold\n", c->name);
1315                                         ast_indicate(in, AST_CONTROL_HOLD);
1316                                         break;
1317                                 case AST_CONTROL_UNHOLD:
1318                                         ast_verb(3, "Call on %s left from hold\n", c->name);
1319                                         ast_indicate(in, AST_CONTROL_UNHOLD);
1320                                         break;
1321                                 case AST_CONTROL_OFFHOOK:
1322                                 case AST_CONTROL_FLASH:
1323                                         /* Ignore going off hook and flash */
1324                                         break;
1325                                 case AST_CONTROL_CC:
1326                                         if (!ignore_cc) {
1327                                                 ast_handle_cc_control_frame(in, c, f->data.ptr);
1328                                                 cc_frame_received = 1;
1329                                         }
1330                                         break;
1331                                 case -1:
1332                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK | OPT_MUSICBACK)) {
1333                                                 ast_verb(3, "%s stopped sounds\n", c->name);
1334                                                 ast_indicate(in, -1);
1335                                                 pa->sentringing = 0;
1336                                         }
1337                                         break;
1338                                 default:
1339                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
1340                                 }
1341                         } else if (single) {
1342                                 switch (f->frametype) {
1343                                 case AST_FRAME_VOICE:
1344                                 case AST_FRAME_IMAGE:
1345                                 case AST_FRAME_TEXT:
1346                                         if (ast_write(in, f)) {
1347                                                 ast_log(LOG_WARNING, "Unable to write frametype: %d\n",
1348                                                         f->frametype);
1349                                         }
1350                                         break;
1351                                 case AST_FRAME_HTML:
1352                                         if (!ast_test_flag64(outgoing, DIAL_NOFORWARDHTML)
1353                                                 && ast_channel_sendhtml(in, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
1354                                                 ast_log(LOG_WARNING, "Unable to send URL\n");
1355                                         }
1356                                         break;
1357                                 default:
1358                                         break;
1359                                 }
1360                         }
1361                         ast_frfree(f);
1362                 } /* end for */
1363                 if (winner == in) {
1364                         struct ast_frame *f = ast_read(in);
1365 #if 0
1366                         if (f && (f->frametype != AST_FRAME_VOICE))
1367                                 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1368                         else if (!f || (f->frametype != AST_FRAME_VOICE))
1369                                 printf("Hangup received on %s\n", in->name);
1370 #endif
1371                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
1372                                 /* Got hung up */
1373                                 *to = -1;
1374                                 strcpy(pa->status, "CANCEL");
1375                                 ast_cdr_noanswer(in->cdr);
1376                                 if (f) {
1377                                         if (f->data.uint32) {
1378                                                 in->hangupcause = f->data.uint32;
1379                                         }
1380                                         ast_frfree(f);
1381                                 }
1382                                 if (is_cc_recall) {
1383                                         ast_cc_completed(in, "CC completed, although the caller hung up (cancelled)");
1384                                 }
1385                                 return NULL;
1386                         }
1387
1388                         /* now f is guaranteed non-NULL */
1389                         if (f->frametype == AST_FRAME_DTMF) {
1390                                 if (ast_test_flag64(peerflags, OPT_DTMF_EXIT)) {
1391                                         const char *context;
1392                                         ast_channel_lock(in);
1393                                         context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
1394                                         if (onedigit_goto(in, context, (char) f->subclass.integer, 1)) {
1395                                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
1396                                                 *to = 0;
1397                                                 ast_cdr_noanswer(in->cdr);
1398                                                 *result = f->subclass.integer;
1399                                                 strcpy(pa->status, "CANCEL");
1400                                                 ast_frfree(f);
1401                                                 ast_channel_unlock(in);
1402                                                 if (is_cc_recall) {
1403                                                         ast_cc_completed(in, "CC completed, but the caller used DTMF to exit");
1404                                                 }
1405                                                 return NULL;
1406                                         }
1407                                         ast_channel_unlock(in);
1408                                 }
1409
1410                                 if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP) &&
1411                                         detect_disconnect(in, f->subclass.integer, featurecode)) {
1412                                         ast_verb(3, "User requested call disconnect.\n");
1413                                         *to = 0;
1414                                         strcpy(pa->status, "CANCEL");
1415                                         ast_cdr_noanswer(in->cdr);
1416                                         ast_frfree(f);
1417                                         if (is_cc_recall) {
1418                                                 ast_cc_completed(in, "CC completed, but the caller hung up with DTMF");
1419                                         }
1420                                         return NULL;
1421                                 }
1422                         }
1423
1424                         /* Send the frame from the in channel to all outgoing channels. */
1425                         for (o = outgoing; o; o = o->next) {
1426                                 if (!o->chan || !ast_test_flag64(o, DIAL_STILLGOING)) {
1427                                         /* This outgoing channel has died so don't send the frame to it. */
1428                                         continue;
1429                                 }
1430                                 switch (f->frametype) {
1431                                 case AST_FRAME_HTML:
1432                                         /* Forward HTML stuff */
1433                                         if (!ast_test_flag64(o, DIAL_NOFORWARDHTML)
1434                                                 && ast_channel_sendhtml(o->chan, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
1435                                                 ast_log(LOG_WARNING, "Unable to send URL\n");
1436                                         }
1437                                         break;
1438                                 case AST_FRAME_VOICE:
1439                                 case AST_FRAME_IMAGE:
1440                                 case AST_FRAME_TEXT:
1441                                 case AST_FRAME_DTMF_BEGIN:
1442                                 case AST_FRAME_DTMF_END:
1443                                         if (ast_write(o->chan, f)) {
1444                                                 ast_log(LOG_WARNING, "Unable to forward frametype: %d\n",
1445                                                         f->frametype);
1446                                         }
1447                                         break;
1448                                 case AST_FRAME_CONTROL:
1449                                         switch (f->subclass.integer) {
1450                                         case AST_CONTROL_HOLD:
1451                                         case AST_CONTROL_UNHOLD:
1452                                         case AST_CONTROL_VIDUPDATE:
1453                                         case AST_CONTROL_SRCUPDATE:
1454                                                 ast_verb(3, "%s requested special control %d, passing it to %s\n",
1455                                                         in->name, f->subclass.integer, o->chan->name);
1456                                                 ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
1457                                                 break;
1458                                         case AST_CONTROL_CONNECTED_LINE:
1459                                                 if (ast_channel_connected_line_macro(in, o->chan, f, 0, 1)) {
1460                                                         ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
1461                                                 }
1462                                                 break;
1463                                         case AST_CONTROL_REDIRECTING:
1464                                                 if (ast_channel_redirecting_macro(in, o->chan, f, 0, 1)) {
1465                                                         ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
1466                                                 }
1467                                                 break;
1468                                         default:
1469                                                 break;
1470                                         }
1471                                         break;
1472                                 default:
1473                                         break;
1474                                 }
1475                         }
1476                         ast_frfree(f);
1477                 }
1478                 if (!*to)
1479                         ast_verb(3, "Nobody picked up in %d ms\n", orig);
1480                 if (!*to || ast_check_hangup(in))
1481                         ast_cdr_noanswer(in->cdr);
1482         }
1483
1484 #ifdef HAVE_EPOLL
1485         for (epollo = outgoing; epollo; epollo = epollo->next) {
1486                 if (epollo->chan)
1487                         ast_poll_channel_del(in, epollo->chan);
1488         }
1489 #endif
1490
1491         if (is_cc_recall) {
1492                 ast_cc_completed(in, "Recall completed!");
1493         }
1494         return peer;
1495 }
1496
1497 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str *featurecode)
1498 {
1499         struct ast_flags features = { AST_FEATURE_DISCONNECT }; /* only concerned with disconnect feature */
1500         struct ast_call_feature feature = { 0, };
1501         int res;
1502
1503         ast_str_append(&featurecode, 1, "%c", code);
1504
1505         res = ast_feature_detect(chan, &features, ast_str_buffer(featurecode), &feature);
1506
1507         if (res != AST_FEATURE_RETURN_STOREDIGITS) {
1508                 ast_str_reset(featurecode);
1509         }
1510         if (feature.feature_mask & AST_FEATURE_DISCONNECT) {
1511                 return 1;
1512         }
1513
1514         return 0;
1515 }
1516
1517 static void replace_macro_delimiter(char *s)
1518 {
1519         for (; *s; s++)
1520                 if (*s == '^')
1521                         *s = ',';
1522 }
1523
1524 /* returns true if there is a valid privacy reply */
1525 static int valid_priv_reply(struct ast_flags64 *opts, int res)
1526 {
1527         if (res < '1')
1528                 return 0;
1529         if (ast_test_flag64(opts, OPT_PRIVACY) && res <= '5')
1530                 return 1;
1531         if (ast_test_flag64(opts, OPT_SCREENING) && res <= '4')
1532                 return 1;
1533         return 0;
1534 }
1535
1536 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
1537         struct ast_flags64 *opts, char **opt_args, struct privacy_args *pa)
1538 {
1539
1540         int res2;
1541         int loopcount = 0;
1542
1543         /* Get the user's intro, store it in priv-callerintros/$CID,
1544            unless it is already there-- this should be done before the
1545            call is actually dialed  */
1546
1547         /* all ring indications and moh for the caller has been halted as soon as the
1548            target extension was picked up. We are going to have to kill some
1549            time and make the caller believe the peer hasn't picked up yet */
1550
1551         if (ast_test_flag64(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1552                 char *original_moh = ast_strdupa(chan->musicclass);
1553                 ast_indicate(chan, -1);
1554                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
1555                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1556                 ast_string_field_set(chan, musicclass, original_moh);
1557         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1558                 ast_indicate(chan, AST_CONTROL_RINGING);
1559                 pa->sentringing++;
1560         }
1561
1562         /* Start autoservice on the other chan ?? */
1563         res2 = ast_autoservice_start(chan);
1564         /* Now Stream the File */
1565         for (loopcount = 0; loopcount < 3; loopcount++) {
1566                 if (res2 && loopcount == 0) /* error in ast_autoservice_start() */
1567                         break;
1568                 if (!res2) /* on timeout, play the message again */
1569                         res2 = ast_play_and_wait(peer, "priv-callpending");
1570                 if (!valid_priv_reply(opts, res2))
1571                         res2 = 0;
1572                 /* priv-callpending script:
1573                    "I have a caller waiting, who introduces themselves as:"
1574                 */
1575                 if (!res2)
1576                         res2 = ast_play_and_wait(peer, pa->privintro);
1577                 if (!valid_priv_reply(opts, res2))
1578                         res2 = 0;
1579                 /* now get input from the called party, as to their choice */
1580                 if (!res2) {
1581                         /* XXX can we have both, or they are mutually exclusive ? */
1582                         if (ast_test_flag64(opts, OPT_PRIVACY))
1583                                 res2 = ast_play_and_wait(peer, "priv-callee-options");
1584                         if (ast_test_flag64(opts, OPT_SCREENING))
1585                                 res2 = ast_play_and_wait(peer, "screen-callee-options");
1586                 }
1587                 /*! \page DialPrivacy Dial Privacy scripts
1588                 \par priv-callee-options script:
1589                         "Dial 1 if you wish this caller to reach you directly in the future,
1590                                 and immediately connect to their incoming call
1591                          Dial 2 if you wish to send this caller to voicemail now and
1592                                 forevermore.
1593                          Dial 3 to send this caller to the torture menus, now and forevermore.
1594                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1595                          Dial 5 to allow this caller to come straight thru to you in the future,
1596                                 but right now, just this once, send them to voicemail."
1597                 \par screen-callee-options script:
1598                         "Dial 1 if you wish to immediately connect to the incoming call
1599                          Dial 2 if you wish to send this caller to voicemail.
1600                          Dial 3 to send this caller to the torture menus.
1601                          Dial 4 to send this caller to a simple "go away" menu.
1602                 */
1603                 if (valid_priv_reply(opts, res2))
1604                         break;
1605                 /* invalid option */
1606                 res2 = ast_play_and_wait(peer, "vm-sorry");
1607         }
1608
1609         if (ast_test_flag64(opts, OPT_MUSICBACK)) {
1610                 ast_moh_stop(chan);
1611         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1612                 ast_indicate(chan, -1);
1613                 pa->sentringing = 0;
1614         }
1615         ast_autoservice_stop(chan);
1616         if (ast_test_flag64(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
1617                 /* map keypresses to various things, the index is res2 - '1' */
1618                 static const char * const _val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
1619                 static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
1620                 int i = res2 - '1';
1621                 ast_verb(3, "--Set privacy database entry %s/%s to %s\n",
1622                         opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
1623                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
1624         }
1625         switch (res2) {
1626         case '1':
1627                 break;
1628         case '2':
1629                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1630                 break;
1631         case '3':
1632                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1633                 break;
1634         case '4':
1635                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1636                 break;
1637         case '5':
1638                 /* XXX should we set status to DENY ? */
1639                 if (ast_test_flag64(opts, OPT_PRIVACY))
1640                         break;
1641                 /* if not privacy, then 5 is the same as "default" case */
1642         default: /* bad input or -1 if failure to start autoservice */
1643                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1644                 /* well, there seems basically two choices. Just patch the caller thru immediately,
1645                           or,... put 'em thru to voicemail. */
1646                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1647                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1648                 /* XXX should we set status to DENY ? */
1649                 /* XXX what about the privacy flags ? */
1650                 break;
1651         }
1652
1653         if (res2 == '1') { /* the only case where we actually connect */
1654                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll
1655                    just clog things up, and it's not useful information, not being tied to a CID */
1656                 if (strncmp(pa->privcid, "NOCALLERID", 10) == 0 || ast_test_flag64(opts, OPT_SCREEN_NOINTRO)) {
1657                         ast_filedelete(pa->privintro, NULL);
1658                         if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1659                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1660                         else
1661                                 ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1662                 }
1663                 return 0; /* the good exit path */
1664         } else {
1665                 ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1666                 return -1;
1667         }
1668 }
1669
1670 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
1671 static int setup_privacy_args(struct privacy_args *pa,
1672         struct ast_flags64 *opts, char *opt_args[], struct ast_channel *chan)
1673 {
1674         char callerid[60];
1675         int res;
1676         char *l;
1677         int silencethreshold;
1678
1679         if (chan->caller.id.number.valid
1680                 && !ast_strlen_zero(chan->caller.id.number.str)) {
1681                 l = ast_strdupa(chan->caller.id.number.str);
1682                 ast_shrink_phone_number(l);
1683                 if (ast_test_flag64(opts, OPT_PRIVACY) ) {
1684                         ast_verb(3, "Privacy DB is '%s', clid is '%s'\n", opt_args[OPT_ARG_PRIVACY], l);
1685                         pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
1686                 } else {
1687                         ast_verb(3, "Privacy Screening, clid is '%s'\n", l);
1688                         pa->privdb_val = AST_PRIVACY_UNKNOWN;
1689                 }
1690         } else {
1691                 char *tnam, *tn2;
1692
1693                 tnam = ast_strdupa(chan->name);
1694                 /* clean the channel name so slashes don't try to end up in disk file name */
1695                 for (tn2 = tnam; *tn2; tn2++) {
1696                         if (*tn2 == '/')  /* any other chars to be afraid of? */
1697                                 *tn2 = '=';
1698                 }
1699                 ast_verb(3, "Privacy-- callerid is empty\n");
1700
1701                 snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
1702                 l = callerid;
1703                 pa->privdb_val = AST_PRIVACY_UNKNOWN;
1704         }
1705
1706         ast_copy_string(pa->privcid, l, sizeof(pa->privcid));
1707
1708         if (strncmp(pa->privcid, "NOCALLERID", 10) != 0 && ast_test_flag64(opts, OPT_SCREEN_NOCALLERID)) {
1709                 /* if callerid is set and OPT_SCREEN_NOCALLERID is set also */
1710                 ast_verb(3, "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
1711                 pa->privdb_val = AST_PRIVACY_ALLOW;
1712         } else if (ast_test_flag64(opts, OPT_SCREEN_NOCALLERID) && strncmp(pa->privcid, "NOCALLERID", 10) == 0) {
1713                 ast_verb(3, "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
1714         }
1715         
1716         if (pa->privdb_val == AST_PRIVACY_DENY) {
1717                 ast_verb(3, "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
1718                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1719                 return 0;
1720         } else if (pa->privdb_val == AST_PRIVACY_KILL) {
1721                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1722                 return 0; /* Is this right? */
1723         } else if (pa->privdb_val == AST_PRIVACY_TORTURE) {
1724                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1725                 return 0; /* is this right??? */
1726         } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN) {
1727                 /* Get the user's intro, store it in priv-callerintros/$CID,
1728                    unless it is already there-- this should be done before the
1729                    call is actually dialed  */
1730
1731                 /* make sure the priv-callerintros dir actually exists */
1732                 snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
1733                 if ((res = ast_mkdir(pa->privintro, 0755))) {
1734                         ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(res));
1735                         return -1;
1736                 }
1737
1738                 snprintf(pa->privintro, sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
1739                 if (ast_fileexists(pa->privintro, NULL, NULL ) > 0 && strncmp(pa->privcid, "NOCALLERID", 10) != 0) {
1740                         /* the DELUX version of this code would allow this caller the
1741                            option to hear and retape their previously recorded intro.
1742                         */
1743                 } else {
1744                         int duration; /* for feedback from play_and_wait */
1745                         /* the file doesn't exist yet. Let the caller submit his
1746                            vocal intro for posterity */
1747                         /* priv-recordintro script:
1748
1749                            "At the tone, please say your name:"
1750
1751                         */
1752                         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1753                         ast_answer(chan);
1754                         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 */
1755                                                                         /* don't think we'll need a lock removed, we took care of
1756                                                                            conflicts by naming the pa.privintro file */
1757                         if (res == -1) {
1758                                 /* Delete the file regardless since they hung up during recording */
1759                                 ast_filedelete(pa->privintro, NULL);
1760                                 if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1761                                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1762                                 else
1763                                         ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1764                                 return -1;
1765                         }
1766                         if (!ast_streamfile(chan, "vm-dialout", chan->language) )
1767                                 ast_waitstream(chan, "");
1768                 }
1769         }
1770         return 1; /* success */
1771 }
1772
1773 static void end_bridge_callback(void *data)
1774 {
1775         char buf[80];
1776         time_t end;
1777         struct ast_channel *chan = data;
1778
1779         if (!chan->cdr) {
1780                 return;
1781         }
1782
1783         time(&end);
1784
1785         ast_channel_lock(chan);
1786         if (chan->cdr->answer.tv_sec) {
1787                 snprintf(buf, sizeof(buf), "%ld", (long) end - chan->cdr->answer.tv_sec);
1788                 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", buf);
1789         }
1790
1791         if (chan->cdr->start.tv_sec) {
1792                 snprintf(buf, sizeof(buf), "%ld", (long) end - chan->cdr->start.tv_sec);
1793                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", buf);
1794         }
1795         ast_channel_unlock(chan);
1796 }
1797
1798 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator) {
1799         bconfig->end_bridge_callback_data = originator;
1800 }
1801
1802 static int dial_handle_playtones(struct ast_channel *chan, const char *data)
1803 {
1804         struct ast_tone_zone_sound *ts = NULL;
1805         int res;
1806         const char *str = data;
1807
1808         if (ast_strlen_zero(str)) {
1809                 ast_debug(1,"Nothing to play\n");
1810                 return -1;
1811         }
1812
1813         ts = ast_get_indication_tone(chan->zone, str);
1814
1815         if (ts && ts->data[0]) {
1816                 res = ast_playtones_start(chan, 0, ts->data, 0);
1817         } else {
1818                 res = -1;
1819         }
1820
1821         if (ts) {
1822                 ts = ast_tone_zone_sound_unref(ts);
1823         }
1824
1825         if (res) {
1826                 ast_log(LOG_WARNING, "Unable to start playtone \'%s\'\n", str);
1827         }
1828
1829         return res;
1830 }
1831
1832 static int dial_exec_full(struct ast_channel *chan, const char *data, struct ast_flags64 *peerflags, int *continue_exec)
1833 {
1834         int res = -1; /* default: error */
1835         char *rest, *cur; /* scan the list of destinations */
1836         struct chanlist *outgoing = NULL; /* list of destinations */
1837         struct ast_channel *peer;
1838         int to; /* timeout */
1839         struct cause_args num = { chan, 0, 0, 0 };
1840         int cause;
1841         char numsubst[256];
1842
1843         struct ast_bridge_config config = { { 0, } };
1844         struct timeval calldurationlimit = { 0, };
1845         char *dtmfcalled = NULL, *dtmfcalling = NULL, *dtmf_progress=NULL;
1846         struct privacy_args pa = {
1847                 .sentringing = 0,
1848                 .privdb_val = 0,
1849                 .status = "INVALIDARGS",
1850         };
1851         int sentringing = 0, moh = 0;
1852         const char *outbound_group = NULL;
1853         int result = 0;
1854         char *parse;
1855         int opermode = 0;
1856         int delprivintro = 0;
1857         AST_DECLARE_APP_ARGS(args,
1858                 AST_APP_ARG(peers);
1859                 AST_APP_ARG(timeout);
1860                 AST_APP_ARG(options);
1861                 AST_APP_ARG(url);
1862         );
1863         struct ast_flags64 opts = { 0, };
1864         char *opt_args[OPT_ARG_ARRAY_SIZE];
1865         struct ast_datastore *datastore = NULL;
1866         int fulldial = 0, num_dialed = 0;
1867         int ignore_cc = 0;
1868         char device_name[AST_CHANNEL_NAME];
1869         char forced_clid_name[AST_MAX_EXTENSION];
1870         char stored_clid_name[AST_MAX_EXTENSION];
1871         int force_forwards_only;        /*!< TRUE if force CallerID on call forward only. Legacy behaviour.*/
1872         /*!
1873          * \brief Forced CallerID party information to send.
1874          * \note This will not have any malloced strings so do not free it.
1875          */
1876         struct ast_party_id forced_clid;
1877         /*!
1878          * \brief Stored CallerID information if needed.
1879          *
1880          * \note If OPT_ORIGINAL_CLID set then this is the o option
1881          * CallerID.  Otherwise it is the dialplan extension and hint
1882          * name.
1883          *
1884          * \note This will not have any malloced strings so do not free it.
1885          */
1886         struct ast_party_id stored_clid;
1887         /*!
1888          * \brief CallerID party information to store.
1889          * \note This will not have any malloced strings so do not free it.
1890          */
1891         struct ast_party_caller caller;
1892
1893         /* Reset all DIAL variables back to blank, to prevent confusion (in case we don't reset all of them). */
1894         pbx_builtin_setvar_helper(chan, "DIALSTATUS", "");
1895         pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", "");
1896         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", "");
1897         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", "");
1898         pbx_builtin_setvar_helper(chan, "DIALEDTIME", "");
1899
1900         if (ast_strlen_zero(data)) {
1901                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1902                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1903                 return -1;
1904         }
1905
1906         parse = ast_strdupa(data);
1907
1908         AST_STANDARD_APP_ARGS(args, parse);
1909
1910         if (!ast_strlen_zero(args.options) &&
1911                 ast_app_parse_options64(dial_exec_options, &opts, opt_args, args.options)) {
1912                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1913                 goto done;
1914         }
1915
1916         if (ast_strlen_zero(args.peers)) {
1917                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1918                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1919                 goto done;
1920         }
1921
1922         if (ast_cc_call_init(chan, &ignore_cc)) {
1923                 goto done;
1924         }
1925
1926         if (ast_test_flag64(&opts, OPT_SCREEN_NOINTRO) && !ast_strlen_zero(opt_args[OPT_ARG_SCREEN_NOINTRO])) {
1927                 delprivintro = atoi(opt_args[OPT_ARG_SCREEN_NOINTRO]);
1928
1929                 if (delprivintro < 0 || delprivintro > 1) {
1930                         ast_log(LOG_WARNING, "Unknown argument %d specified to n option, ignoring\n", delprivintro);
1931                         delprivintro = 0;
1932                 }
1933         }
1934
1935         if (!ast_test_flag64(&opts, OPT_RINGBACK)) {
1936                 opt_args[OPT_ARG_RINGBACK] = NULL;
1937         }
1938
1939         if (ast_test_flag64(&opts, OPT_OPERMODE)) {
1940                 opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
1941                 ast_verb(3, "Setting operator services mode to %d.\n", opermode);
1942         }
1943
1944         if (ast_test_flag64(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
1945                 calldurationlimit.tv_sec = atoi(opt_args[OPT_ARG_DURATION_STOP]);
1946                 if (!calldurationlimit.tv_sec) {
1947                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
1948                         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1949                         goto done;
1950                 }
1951                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n", calldurationlimit.tv_sec + calldurationlimit.tv_usec / 1000000.0);
1952         }
1953
1954         if (ast_test_flag64(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
1955                 dtmf_progress = opt_args[OPT_ARG_SENDDTMF];
1956                 dtmfcalled = strsep(&dtmf_progress, ":");
1957                 dtmfcalling = strsep(&dtmf_progress, ":");
1958         }
1959
1960         if (ast_test_flag64(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
1961                 if (ast_bridge_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
1962                         goto done;
1963         }
1964
1965         /* Setup the forced CallerID information to send if used. */
1966         ast_party_id_init(&forced_clid);
1967         force_forwards_only = 0;
1968         if (ast_test_flag64(&opts, OPT_FORCECLID)) {
1969                 if (ast_strlen_zero(opt_args[OPT_ARG_FORCECLID])) {
1970                         ast_channel_lock(chan);
1971                         forced_clid.number.str = ast_strdupa(S_OR(chan->macroexten, chan->exten));
1972                         ast_channel_unlock(chan);
1973                         forced_clid_name[0] = '\0';
1974                         forced_clid.name.str = (char *) get_cid_name(forced_clid_name,
1975                                 sizeof(forced_clid_name), chan);
1976                         force_forwards_only = 1;
1977                 } else {
1978                         /* Note: The opt_args[OPT_ARG_FORCECLID] string value is altered here. */
1979                         ast_callerid_parse(opt_args[OPT_ARG_FORCECLID], &forced_clid.name.str,
1980                                 &forced_clid.number.str);
1981                 }
1982                 if (!ast_strlen_zero(forced_clid.name.str)) {
1983                         forced_clid.name.valid = 1;
1984                 }
1985                 if (!ast_strlen_zero(forced_clid.number.str)) {
1986                         forced_clid.number.valid = 1;
1987                 }
1988         }
1989         if (ast_test_flag64(&opts, OPT_FORCE_CID_TAG)
1990                 && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_TAG])) {
1991                 forced_clid.tag = opt_args[OPT_ARG_FORCE_CID_TAG];
1992         }
1993         forced_clid.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
1994         if (ast_test_flag64(&opts, OPT_FORCE_CID_PRES)
1995                 && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_PRES])) {
1996                 int pres;
1997
1998                 pres = ast_parse_caller_presentation(opt_args[OPT_ARG_FORCE_CID_PRES]);
1999                 if (0 <= pres) {
2000                         forced_clid.number.presentation = pres;
2001                 }
2002         }
2003
2004         /* Setup the stored CallerID information if needed. */
2005         ast_party_id_init(&stored_clid);
2006         if (ast_test_flag64(&opts, OPT_ORIGINAL_CLID)) {
2007                 if (ast_strlen_zero(opt_args[OPT_ARG_ORIGINAL_CLID])) {
2008                         ast_channel_lock(chan);
2009                         ast_party_id_set_init(&stored_clid, &chan->caller.id);
2010                         if (!ast_strlen_zero(chan->caller.id.name.str)) {
2011                                 stored_clid.name.str = ast_strdupa(chan->caller.id.name.str);
2012                         }
2013                         if (!ast_strlen_zero(chan->caller.id.number.str)) {
2014                                 stored_clid.number.str = ast_strdupa(chan->caller.id.number.str);
2015                         }
2016                         if (!ast_strlen_zero(chan->caller.id.subaddress.str)) {
2017                                 stored_clid.subaddress.str = ast_strdupa(chan->caller.id.subaddress.str);
2018                         }
2019                         if (!ast_strlen_zero(chan->caller.id.tag)) {
2020                                 stored_clid.tag = ast_strdupa(chan->caller.id.tag);
2021                         }
2022                         ast_channel_unlock(chan);
2023                 } else {
2024                         /* Note: The opt_args[OPT_ARG_ORIGINAL_CLID] string value is altered here. */
2025                         ast_callerid_parse(opt_args[OPT_ARG_ORIGINAL_CLID], &stored_clid.name.str,
2026                                 &stored_clid.number.str);
2027                         if (!ast_strlen_zero(stored_clid.name.str)) {
2028                                 stored_clid.name.valid = 1;
2029                         }
2030                         if (!ast_strlen_zero(stored_clid.number.str)) {
2031                                 stored_clid.number.valid = 1;
2032                         }
2033                 }
2034         } else {
2035                 /*
2036                  * In case the new channel has no preset CallerID number by the
2037                  * channel driver, setup the dialplan extension and hint name.
2038                  */
2039                 stored_clid_name[0] = '\0';
2040                 stored_clid.name.str = (char *) get_cid_name(stored_clid_name,
2041                         sizeof(stored_clid_name), chan);
2042                 if (ast_strlen_zero(stored_clid.name.str)) {
2043                         stored_clid.name.str = NULL;
2044                 } else {
2045                         stored_clid.name.valid = 1;
2046                 }
2047                 ast_channel_lock(chan);
2048                 stored_clid.number.str = ast_strdupa(S_OR(chan->macroexten, chan->exten));
2049                 stored_clid.number.valid = 1;
2050                 ast_channel_unlock(chan);
2051         }
2052
2053         if (ast_test_flag64(&opts, OPT_RESETCDR) && chan->cdr)
2054                 ast_cdr_reset(chan->cdr, NULL);
2055         if (ast_test_flag64(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
2056                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(chan->exten);
2057
2058         if (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) {
2059                 res = setup_privacy_args(&pa, &opts, opt_args, chan);
2060                 if (res <= 0)
2061                         goto out;
2062                 res = -1; /* reset default */
2063         }
2064
2065         if (ast_test_flag64(&opts, OPT_DTMF_EXIT) || ast_test_flag64(&opts, OPT_CALLER_HANGUP)) {
2066                 __ast_answer(chan, 0, 0);
2067         }
2068
2069         if (continue_exec)
2070                 *continue_exec = 0;
2071
2072         /* If a channel group has been specified, get it for use when we create peer channels */
2073
2074         ast_channel_lock(chan);
2075         if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
2076                 outbound_group = ast_strdupa(outbound_group);   
2077                 pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
2078         } else if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP"))) {
2079                 outbound_group = ast_strdupa(outbound_group);
2080         }
2081         ast_channel_unlock(chan);       
2082         ast_copy_flags64(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING | OPT_IGNORE_CONNECTEDLINE |
2083                          OPT_CANCEL_TIMEOUT | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB | OPT_FORCECLID);
2084
2085         /* loop through the list of dial destinations */
2086         rest = args.peers;
2087         while ((cur = strsep(&rest, "&")) ) {
2088                 struct chanlist *tmp;
2089                 struct ast_channel *tc; /* channel for this destination */
2090                 /* Get a technology/[device:]number pair */
2091                 char *number = cur;
2092                 char *interface = ast_strdupa(number);
2093                 char *tech = strsep(&number, "/");
2094                 /* find if we already dialed this interface */
2095                 struct ast_dialed_interface *di;
2096                 AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
2097                 num_dialed++;
2098                 if (ast_strlen_zero(number)) {
2099                         ast_log(LOG_WARNING, "Dial argument takes format (technology/[device:]number1)\n");
2100                         goto out;
2101                 }
2102                 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
2103                         goto out;
2104                 if (opts.flags) {
2105                         ast_copy_flags64(tmp, &opts,
2106                                 OPT_CANCEL_ELSEWHERE |
2107                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
2108                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
2109                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
2110                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
2111                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
2112                                 OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID);
2113                         ast_set2_flag64(tmp, args.url, DIAL_NOFORWARDHTML);
2114                 }
2115                 ast_copy_string(numsubst, number, sizeof(numsubst));
2116                 /* Request the peer */
2117
2118                 ast_channel_lock(chan);
2119                 datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL);
2120                 /*
2121                  * Seed the chanlist's connected line information with previously
2122                  * acquired connected line info from the incoming channel.  The
2123                  * previously acquired connected line info could have been set
2124                  * through the CONNECTED_LINE dialplan function.
2125                  */
2126                 ast_party_connected_line_copy(&tmp->connected, &chan->connected);
2127                 ast_channel_unlock(chan);
2128
2129                 if (datastore)
2130                         dialed_interfaces = datastore->data;
2131                 else {
2132                         if (!(datastore = ast_datastore_alloc(&dialed_interface_info, NULL))) {
2133                                 ast_log(LOG_WARNING, "Unable to create channel datastore for dialed interfaces. Aborting!\n");
2134                                 chanlist_free(tmp);
2135                                 goto out;
2136                         }
2137
2138                         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
2139
2140                         if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
2141                                 ast_datastore_free(datastore);
2142                                 chanlist_free(tmp);
2143                                 goto out;
2144                         }
2145
2146                         datastore->data = dialed_interfaces;
2147                         AST_LIST_HEAD_INIT(dialed_interfaces);
2148
2149                         ast_channel_lock(chan);
2150                         ast_channel_datastore_add(chan, datastore);
2151                         ast_channel_unlock(chan);
2152                 }
2153
2154                 AST_LIST_LOCK(dialed_interfaces);
2155                 AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
2156                         if (!strcasecmp(di->interface, interface)) {
2157                                 ast_log(LOG_WARNING, "Skipping dialing interface '%s' again since it has already been dialed\n",
2158                                         di->interface);
2159                                 break;
2160                         }
2161                 }
2162                 AST_LIST_UNLOCK(dialed_interfaces);
2163
2164                 if (di) {
2165                         fulldial++;
2166                         chanlist_free(tmp);
2167                         continue;
2168                 }
2169
2170                 /* It is always ok to dial a Local interface.  We only keep track of
2171                  * which "real" interfaces have been dialed.  The Local channel will
2172                  * inherit this list so that if it ends up dialing a real interface,
2173                  * it won't call one that has already been called. */
2174                 if (strcasecmp(tech, "Local")) {
2175                         if (!(di = ast_calloc(1, sizeof(*di) + strlen(interface)))) {
2176                                 AST_LIST_UNLOCK(dialed_interfaces);
2177                                 chanlist_free(tmp);
2178                                 goto out;
2179                         }
2180                         strcpy(di->interface, interface);
2181
2182                         AST_LIST_LOCK(dialed_interfaces);
2183                         AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
2184                         AST_LIST_UNLOCK(dialed_interfaces);
2185                 }
2186
2187                 tc = ast_request(tech, chan->nativeformats, chan, numsubst, &cause);
2188                 if (!tc) {
2189                         /* If we can't, just go on to the next call */
2190                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
2191                                 tech, cause, ast_cause2str(cause));
2192                         handle_cause(cause, &num);
2193                         if (!rest) /* we are on the last destination */
2194                                 chan->hangupcause = cause;
2195                         chanlist_free(tmp);
2196                         if (!ignore_cc && (cause == AST_CAUSE_BUSY || cause == AST_CAUSE_CONGESTION)) {
2197                                 if (!ast_cc_callback(chan, tech, numsubst, ast_cc_busy_interface)) {
2198                                         ast_cc_extension_monitor_add_dialstring(chan, interface, "");
2199                                 }
2200                         }
2201                         continue;
2202                 }
2203                 ast_channel_get_device_name(tc, device_name, sizeof(device_name));
2204                 if (!ignore_cc) {
2205                         ast_cc_extension_monitor_add_dialstring(chan, interface, device_name);
2206                 }
2207                 pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", numsubst);
2208
2209                 ast_channel_lock(tc);
2210                 while (ast_channel_trylock(chan)) {
2211                         CHANNEL_DEADLOCK_AVOIDANCE(tc);
2212                 }
2213                 /* Setup outgoing SDP to match incoming one */
2214                 if (!outgoing && !rest && CAN_EARLY_BRIDGE(peerflags, chan, tc)) {
2215                         ast_rtp_instance_early_bridge_make_compatible(tc, chan);
2216                 }
2217                 
2218                 /* Inherit specially named variables from parent channel */
2219                 ast_channel_inherit_variables(chan, tc);
2220                 ast_channel_datastore_inherit(chan, tc);
2221
2222                 tc->appl = "AppDial";
2223                 tc->data = "(Outgoing Line)";
2224                 memset(&tc->whentohangup, 0, sizeof(tc->whentohangup));
2225
2226                 /* Determine CallerID to store in outgoing channel. */
2227                 ast_party_caller_set_init(&caller, &tc->caller);
2228                 if (ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
2229                         caller.id = stored_clid;
2230                         ast_channel_set_caller_event(tc, &caller, NULL);
2231                         ast_set_flag64(tmp, DIAL_CALLERID_ABSENT);
2232                 } else if (ast_strlen_zero(S_COR(tc->caller.id.number.valid,
2233                         tc->caller.id.number.str, NULL))) {
2234                         /*
2235                          * The new channel has no preset CallerID number by the channel
2236                          * driver.  Use the dialplan extension and hint name.
2237                          */
2238                         caller.id = stored_clid;
2239                         if (!caller.id.name.valid
2240                                 && !ast_strlen_zero(S_COR(chan->connected.id.name.valid,
2241                                         chan->connected.id.name.str, NULL))) {
2242                                 /*
2243                                  * No hint name available.  We have a connected name supplied by
2244                                  * the dialplan we can use instead.
2245                                  */
2246                                 caller.id.name.valid = 1;
2247                                 caller.id.name = chan->connected.id.name;
2248                         }
2249                         ast_channel_set_caller_event(tc, &caller, NULL);
2250                         ast_set_flag64(tmp, DIAL_CALLERID_ABSENT);
2251                 } else if (ast_strlen_zero(S_COR(tc->caller.id.name.valid, tc->caller.id.name.str,
2252                         NULL))) {
2253                         /* The new channel has no preset CallerID name by the channel driver. */
2254                         if (!ast_strlen_zero(S_COR(chan->connected.id.name.valid,
2255                                 chan->connected.id.name.str, NULL))) {
2256                                 /*
2257                                  * We have a connected name supplied by the dialplan we can
2258                                  * use instead.
2259                                  */
2260                                 caller.id.name.valid = 1;
2261                                 caller.id.name = chan->connected.id.name;
2262                                 ast_channel_set_caller_event(tc, &caller, NULL);
2263                         }
2264                 }
2265
2266                 /* Determine CallerID for outgoing channel to send. */
2267                 if (ast_test_flag64(peerflags, OPT_FORCECLID) && !force_forwards_only) {
2268                         struct ast_party_connected_line connected;
2269
2270                         ast_party_connected_line_set_init(&connected, &tc->connected);
2271                         connected.id = forced_clid;
2272                         ast_channel_set_connected_line(tc, &connected, NULL);
2273                 } else {
2274                         ast_connected_line_copy_from_caller(&tc->connected, &chan->caller);
2275                 }
2276
2277                 ast_party_redirecting_copy(&tc->redirecting, &chan->redirecting);
2278
2279                 tc->dialed.transit_network_select = chan->dialed.transit_network_select;
2280
2281                 if (!ast_strlen_zero(chan->accountcode)) {
2282                         ast_string_field_set(tc, peeraccount, chan->accountcode);
2283                 }
2284                 if (ast_strlen_zero(tc->musicclass))
2285                         ast_string_field_set(tc, musicclass, chan->musicclass);
2286
2287                 /* Pass ADSI CPE and transfer capability */
2288                 tc->adsicpe = chan->adsicpe;
2289                 tc->transfercapability = chan->transfercapability;
2290
2291                 /* If we have an outbound group, set this peer channel to it */
2292                 if (outbound_group)
2293                         ast_app_group_set_channel(tc, outbound_group);
2294                 /* If the calling channel has the ANSWERED_ELSEWHERE flag set, inherit it. This is to support local channels */
2295                 if (ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE))
2296                         ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
2297
2298                 /* Check if we're forced by configuration */
2299                 if (ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE))
2300                          ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
2301
2302
2303                 /* Inherit context and extension */
2304                 ast_string_field_set(tc, dialcontext, ast_strlen_zero(chan->macrocontext) ? chan->context : chan->macrocontext);
2305                 if (!ast_strlen_zero(chan->macroexten))
2306                         ast_copy_string(tc->exten, chan->macroexten, sizeof(tc->exten));
2307                 else
2308                         ast_copy_string(tc->exten, chan->exten, sizeof(tc->exten));
2309
2310                 ast_channel_unlock(tc);
2311                 res = ast_call(tc, numsubst, 0); /* Place the call, but don't wait on the answer */
2312
2313                 /* Save the info in cdr's that we called them */
2314                 if (chan->cdr)
2315                         ast_cdr_setdestchan(chan->cdr, tc->name);
2316
2317                 /* check the results of ast_call */
2318                 if (res) {
2319                         /* Again, keep going even if there's an error */
2320                         ast_debug(1, "ast call on peer returned %d\n", res);
2321                         ast_verb(3, "Couldn't call %s/%s\n", tech, numsubst);
2322                         if (tc->hangupcause) {
2323                                 chan->hangupcause = tc->hangupcause;
2324                         }
2325                         ast_channel_unlock(chan);
2326                         ast_cc_call_failed(chan, tc, interface);
2327                         ast_hangup(tc);
2328                         tc = NULL;
2329                         chanlist_free(tmp);
2330                         continue;
2331                 } else {
2332                         senddialevent(chan, tc, numsubst);
2333                         ast_verb(3, "Called %s/%s\n", tech, numsubst);
2334                         ast_channel_unlock(chan);
2335                 }
2336                 /* Put them in the list of outgoing thingies...  We're ready now.
2337                    XXX If we're forcibly removed, these outgoing calls won't get
2338                    hung up XXX */
2339                 ast_set_flag64(tmp, DIAL_STILLGOING);
2340                 tmp->chan = tc;
2341                 tmp->next = outgoing;
2342                 outgoing = tmp;
2343                 /* If this line is up, don't try anybody else */
2344                 if (outgoing->chan->_state == AST_STATE_UP)
2345                         break;
2346         }
2347         
2348         if (ast_strlen_zero(args.timeout)) {
2349                 to = -1;
2350         } else {
2351                 to = atoi(args.timeout);
2352                 if (to > 0)
2353                         to *= 1000;
2354                 else {
2355                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'. Setting timeout to infinite\n", args.timeout);
2356                         to = -1;
2357                 }
2358         }
2359
2360         if (!outgoing) {
2361                 strcpy(pa.status, "CHANUNAVAIL");
2362                 if (fulldial == num_dialed) {
2363                         res = -1;
2364                         goto out;
2365                 }
2366         } else {
2367                 /* Our status will at least be NOANSWER */
2368                 strcpy(pa.status, "NOANSWER");
2369                 if (ast_test_flag64(outgoing, OPT_MUSICBACK)) {
2370                         moh = 1;
2371                         if (!ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
2372                                 char *original_moh = ast_strdupa(chan->musicclass);
2373                                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
2374                                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
2375                                 ast_string_field_set(chan, musicclass, original_moh);
2376                         } else {
2377                                 ast_moh_start(chan, NULL, NULL);
2378                         }
2379                         ast_indicate(chan, AST_CONTROL_PROGRESS);
2380                 } else if (ast_test_flag64(outgoing, OPT_RINGBACK)) {
2381                         if (!ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
2382                                 if (dial_handle_playtones(chan, opt_args[OPT_ARG_RINGBACK])){
2383                                         ast_indicate(chan, AST_CONTROL_RINGING);
2384                                         sentringing++;
2385                                 } else {
2386                                         ast_indicate(chan, AST_CONTROL_PROGRESS);
2387                                 }
2388                         } else {
2389                                 ast_indicate(chan, AST_CONTROL_RINGING);
2390                                 sentringing++;
2391                         }
2392                 }
2393         }
2394
2395         peer = wait_for_answer(chan, outgoing, &to, peerflags, opt_args, &pa, &num, &result,
2396                 dtmf_progress, ignore_cc, &forced_clid, &stored_clid);
2397
2398         /* The ast_channel_datastore_remove() function could fail here if the
2399          * datastore was moved to another channel during a masquerade. If this is
2400          * the case, don't free the datastore here because later, when the channel
2401          * to which the datastore was moved hangs up, it will attempt to free this
2402          * datastore again, causing a crash
2403          */
2404         ast_channel_lock(chan);
2405         if (!ast_channel_datastore_remove(chan, datastore)) {
2406                 ast_datastore_free(datastore);
2407         }
2408         ast_channel_unlock(chan);
2409         if (!peer) {
2410                 if (result) {
2411                         res = result;
2412                 } else if (to) { /* Musta gotten hung up */
2413                         res = -1;
2414                 } else { /* Nobody answered, next please? */
2415                         res = 0;
2416                 }
2417
2418                 /* SIP, in particular, sends back this error code to indicate an
2419                  * overlap dialled number needs more digits. */
2420                 if (chan->hangupcause == AST_CAUSE_INVALID_NUMBER_FORMAT) {
2421                         res = AST_PBX_INCOMPLETE;
2422                 }
2423
2424                 /* almost done, although the 'else' block is 400 lines */
2425         } else {
2426                 const char *number;
2427
2428                 if (ast_test_flag64(&opts, OPT_CALLER_ANSWER))
2429                         ast_answer(chan);
2430
2431                 strcpy(pa.status, "ANSWER");
2432                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2433                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
2434                    we will always return with -1 so that it is hung up properly after the
2435                    conversation.  */
2436                 hanguptree(outgoing, peer, 1);
2437                 outgoing = NULL;
2438                 /* If appropriate, log that we have a destination channel and set the answer time */
2439                 if (chan->cdr) {
2440                         ast_cdr_setdestchan(chan->cdr, peer->name);
2441                         ast_cdr_setanswer(chan->cdr, peer->cdr->answer);
2442                 }
2443                 if (peer->name)
2444                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
2445                 
2446                 ast_channel_lock(peer);
2447                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER"); 
2448                 if (!number)
2449                         number = numsubst;
2450                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
2451                 ast_channel_unlock(peer);
2452
2453                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
2454                         ast_debug(1, "app_dial: sendurl=%s.\n", args.url);
2455                         ast_channel_sendurl( peer, args.url );
2456                 }
2457                 if ( (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) && pa.privdb_val == AST_PRIVACY_UNKNOWN) {
2458                         if (do_privacy(chan, peer, &opts, opt_args, &pa)) {
2459                                 res = 0;
2460                                 goto out;
2461                         }
2462                 }
2463                 if (!ast_test_flag64(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
2464                         res = 0;
2465                 } else {
2466                         int digit = 0;
2467                         struct ast_channel *chans[2];
2468                         struct ast_channel *active_chan;
2469
2470                         chans[0] = chan;
2471                         chans[1] = peer;
2472
2473                         /* we need to stream the announcment while monitoring the caller for a hangup */
2474
2475                         /* stream the file */
2476                         res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
2477                         if (res) {
2478                                 res = 0;
2479                                 ast_log(LOG_ERROR, "error streaming file '%s' to callee\n", opt_args[OPT_ARG_ANNOUNCE]);
2480                         }
2481
2482                         ast_set_flag(peer, AST_FLAG_END_DTMF_ONLY);
2483                         while (peer->stream) {
2484                                 int ms;
2485
2486                                 ms = ast_sched_wait(peer->sched);
2487
2488                                 if (ms < 0 && !peer->timingfunc) {
2489                                         ast_stopstream(peer);
2490                                         break;
2491                                 }
2492                                 if (ms < 0)
2493                                         ms = 1000;
2494
2495                                 active_chan = ast_waitfor_n(chans, 2, &ms);
2496                                 if (active_chan) {
2497                                         struct ast_frame *fr = ast_read(active_chan);
2498                                         if (!fr) {
2499                                                 ast_hangup(peer);
2500                                                 res = -1;
2501                                                 goto done;
2502                                         }
2503                                         switch(fr->frametype) {
2504                                                 case AST_FRAME_DTMF_END:
2505                                                         digit = fr->subclass.integer;
2506                                                         if (active_chan == peer && strchr(AST_DIGIT_ANY, res)) {
2507                                                                 ast_stopstream(peer);
2508                                                                 res = ast_senddigit(chan, digit, 0);
2509                                                         }
2510                                                         break;
2511                                                 case AST_FRAME_CONTROL:
2512                                                         switch (fr->subclass.integer) {
2513                                                                 case AST_CONTROL_HANGUP:
2514                                                                         ast_frfree(fr);
2515                                                                         ast_hangup(peer);
2516                                                                         res = -1;
2517                                                                         goto done;
2518                                                                 default:
2519                                                                         break;
2520                                                         }
2521                                                         break;
2522                                                 default:
2523                                                         /* Ignore all others */
2524                                                         break;
2525                                         }
2526                                         ast_frfree(fr);
2527                                 }
2528                                 ast_sched_runq(peer->sched);
2529                         }
2530                         ast_clear_flag(peer, AST_FLAG_END_DTMF_ONLY);
2531                 }
2532
2533                 if (chan && peer && ast_test_flag64(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
2534                         /* chan and peer are going into the PBX, they both
2535                          * should probably get CDR records. */
2536                         ast_clear_flag(chan->cdr, AST_CDR_FLAG_DIALED);
2537                         ast_clear_flag(peer->cdr, AST_CDR_FLAG_DIALED);
2538
2539                         replace_macro_delimiter(opt_args[OPT_ARG_GOTO]);
2540                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
2541                         /* peer goes to the same context and extension as chan, so just copy info from chan*/
2542                         ast_copy_string(peer->context, chan->context, sizeof(peer->context));
2543                         ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
2544                         peer->priority = chan->priority + 2;
2545                         ast_pbx_start(peer);
2546                         hanguptree(outgoing, NULL, ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE) ? 1 : 0);
2547                         if (continue_exec)
2548                                 *continue_exec = 1;
2549                         res = 0;
2550                         goto done;
2551                 }