Merge "res_pjsip_mwi: potential double unref, and potential unwanted double link"
[asterisk/asterisk.git] / apps / app_dial.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, 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         <support_level>core</support_level>
30  ***/
31
32
33 #include "asterisk.h"
34
35 #include <sys/time.h>
36 #include <signal.h>
37 #include <sys/stat.h>
38 #include <netinet/in.h>
39
40 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
41 #include "asterisk/lock.h"
42 #include "asterisk/file.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/module.h"
46 #include "asterisk/translate.h"
47 #include "asterisk/say.h"
48 #include "asterisk/config.h"
49 #include "asterisk/features.h"
50 #include "asterisk/musiconhold.h"
51 #include "asterisk/callerid.h"
52 #include "asterisk/utils.h"
53 #include "asterisk/app.h"
54 #include "asterisk/causes.h"
55 #include "asterisk/rtp_engine.h"
56 #include "asterisk/manager.h"
57 #include "asterisk/privacy.h"
58 #include "asterisk/stringfields.h"
59 #include "asterisk/dsp.h"
60 #include "asterisk/aoc.h"
61 #include "asterisk/ccss.h"
62 #include "asterisk/indications.h"
63 #include "asterisk/framehook.h"
64 #include "asterisk/dial.h"
65 #include "asterisk/stasis_channels.h"
66 #include "asterisk/bridge_after.h"
67 #include "asterisk/features_config.h"
68 #include "asterisk/max_forwards.h"
69 #include "asterisk/stream.h"
70
71 /*** DOCUMENTATION
72         <application name="Dial" language="en_US">
73                 <synopsis>
74                         Attempt to connect to another device or endpoint and bridge the call.
75                 </synopsis>
76                 <syntax>
77                         <parameter name="Technology/Resource" required="true" argsep="&amp;">
78                                 <argument name="Technology/Resource" required="true">
79                                         <para>Specification of the device(s) to dial.  These must be in the format of
80                                         <literal>Technology/Resource</literal>, where <replaceable>Technology</replaceable>
81                                         represents a particular channel driver, and <replaceable>Resource</replaceable>
82                                         represents a resource available to that particular channel driver.</para>
83                                 </argument>
84                                 <argument name="Technology2/Resource2" required="false" multiple="true">
85                                         <para>Optional extra devices to dial in parallel</para>
86                                         <para>If you need more than one enter them as
87                                         Technology2/Resource2&amp;Technology3/Resource3&amp;.....</para>
88                                 </argument>
89                         </parameter>
90                         <parameter name="timeout" required="false">
91                                 <para>Specifies the number of seconds we attempt to dial the specified devices.</para>
92                                 <para>If not specified, this defaults to 136 years.</para>
93                         </parameter>
94                         <parameter name="options" required="false">
95                                 <optionlist>
96                                 <option name="A">
97                                         <argument name="x" required="true">
98                                                 <para>The file to play to the called party</para>
99                                         </argument>
100                                         <para>Play an announcement to the called party, where <replaceable>x</replaceable> is the prompt to be played</para>
101                                 </option>
102                                 <option name="a">
103                                         <para>Immediately answer the calling channel when the called channel answers in
104                                         all cases. Normally, the calling channel is answered when the called channel
105                                         answers, but when options such as <literal>A()</literal> and
106                                         <literal>M()</literal> are used, the calling channel is
107                                         not answered until all actions on the called channel (such as playing an
108                                         announcement) are completed.  This option can be used to answer the calling
109                                         channel before doing anything on the called channel. You will rarely need to use
110                                         this option, the default behavior is adequate in most cases.</para>
111                                 </option>
112                                 <option name="b" argsep="^">
113                                         <para>Before initiating an outgoing call, <literal>Gosub</literal> to the specified
114                                         location using the newly created channel.  The <literal>Gosub</literal> will be
115                                         executed for each destination channel.</para>
116                                         <argument name="context" required="false" />
117                                         <argument name="exten" required="false" />
118                                         <argument name="priority" required="true" hasparams="optional" argsep="^">
119                                                 <argument name="arg1" multiple="true" required="true" />
120                                                 <argument name="argN" />
121                                         </argument>
122                                 </option>
123                                 <option name="B" argsep="^">
124                                         <para>Before initiating the outgoing call(s), <literal>Gosub</literal> to the
125                                         specified location using the current channel.</para>
126                                         <argument name="context" required="false" />
127                                         <argument name="exten" required="false" />
128                                         <argument name="priority" required="true" hasparams="optional" argsep="^">
129                                                 <argument name="arg1" multiple="true" required="true" />
130                                                 <argument name="argN" />
131                                         </argument>
132                                 </option>
133                                 <option name="C">
134                                         <para>Reset the call detail record (CDR) for this call.</para>
135                                 </option>
136                                 <option name="c">
137                                         <para>If the Dial() application cancels this call, always set
138                                         <variable>HANGUPCAUSE</variable> to 'answered elsewhere'</para>
139                                 </option>
140                                 <option name="d">
141                                         <para>Allow the calling user to dial a 1 digit extension while waiting for
142                                         a call to be answered. Exit to that extension if it exists in the
143                                         current context, or the context defined in the <variable>EXITCONTEXT</variable> variable,
144                                         if it exists.</para>
145                                         <para>NOTE: Many SIP and ISDN phones cannot send DTMF digits until the call is
146                                         connected.  If you wish to use this option with these phones, you
147                                         can use the <literal>Answer</literal> application before dialing.</para>
148                                 </option>
149                                 <option name="D" argsep=":">
150                                         <argument name="called" />
151                                         <argument name="calling" />
152                                         <argument name="progress" />
153                                         <para>Send the specified DTMF strings <emphasis>after</emphasis> the called
154                                         party has answered, but before the call gets bridged.  The
155                                         <replaceable>called</replaceable> DTMF string is sent to the called party, and the
156                                         <replaceable>calling</replaceable> DTMF string is sent to the calling party.  Both arguments
157                                         can be used alone.  If <replaceable>progress</replaceable> is specified, its DTMF is sent
158                                         to the called party immediately after receiving a <literal>PROGRESS</literal> message.</para>
159                                         <para>See <literal>SendDTMF</literal> for valid digits.</para>
160                                 </option>
161                                 <option name="e">
162                                         <para>Execute the <literal>h</literal> extension for peer after the call ends</para>
163                                 </option>
164                                 <option name="f">
165                                         <argument name="x" required="false" />
166                                         <para>If <replaceable>x</replaceable> is not provided, force the CallerID sent on a call-forward or
167                                         deflection to the dialplan extension of this <literal>Dial()</literal> using a dialplan <literal>hint</literal>.
168                                         For example, some PSTNs do not allow CallerID to be set to anything
169                                         other than the numbers assigned to you.
170                                         If <replaceable>x</replaceable> is provided, force the CallerID sent to <replaceable>x</replaceable>.</para>
171                                 </option>
172                                 <option name="F" argsep="^">
173                                         <argument name="context" required="false" />
174                                         <argument name="exten" required="false" />
175                                         <argument name="priority" required="true" />
176                                         <para>When the caller hangs up, transfer the <emphasis>called</emphasis> party
177                                         to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
178                                         <para>NOTE: Any channel variables you want the called channel to inherit from the caller channel must be
179                                         prefixed with one or two underbars ('_').</para>
180                                 </option>
181                                 <option name="F">
182                                         <para>When the caller hangs up, transfer the <emphasis>called</emphasis> party to the next priority of the current extension
183                                         and <emphasis>start</emphasis> execution at that location.</para>
184                                         <para>NOTE: Any channel variables you want the called channel to inherit from the caller channel must be
185                                         prefixed with one or two underbars ('_').</para>
186                                         <para>NOTE: Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
187                                 </option>
188                                 <option name="g">
189                                         <para>Proceed with dialplan execution at the next priority in the current extension if the
190                                         destination channel hangs up.</para>
191                                 </option>
192                                 <option name="G" argsep="^">
193                                         <argument name="context" required="false" />
194                                         <argument name="exten" required="false" />
195                                         <argument name="priority" required="true" />
196                                         <para>If the call is answered, transfer the calling party to
197                                         the specified <replaceable>priority</replaceable> and the called party to the specified
198                                         <replaceable>priority</replaceable> plus one.</para>
199                                         <para>NOTE: You cannot use any additional action post answer options in conjunction with this option.</para>
200                                 </option>
201                                 <option name="h">
202                                         <para>Allow the called party to hang up by sending the DTMF sequence
203                                         defined for disconnect in <filename>features.conf</filename>.</para>
204                                 </option>
205                                 <option name="H">
206                                         <para>Allow the calling party to hang up by sending the DTMF sequence
207                                         defined for disconnect in <filename>features.conf</filename>.</para>
208                                         <para>NOTE: Many SIP and ISDN phones cannot send DTMF digits until the call is
209                                         connected.  If you wish to allow DTMF disconnect before the dialed
210                                         party answers with these phones, you can use the <literal>Answer</literal>
211                                         application before dialing.</para>
212                                 </option>
213                                 <option name="i">
214                                         <para>Asterisk will ignore any forwarding requests it may receive on this dial attempt.</para>
215                                 </option>
216                                 <option name="I">
217                                         <para>Asterisk will ignore any connected line update requests or any redirecting party
218                                         update requests it may receive on this dial attempt.</para>
219                                 </option>
220                                 <option name="k">
221                                         <para>Allow the called party to enable parking of the call by sending
222                                         the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
223                                 </option>
224                                 <option name="K">
225                                         <para>Allow the calling party to enable parking of the call by sending
226                                         the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
227                                 </option>
228                                 <option name="L" argsep=":">
229                                         <argument name="x" required="true">
230                                                 <para>Maximum call time, in milliseconds</para>
231                                         </argument>
232                                         <argument name="y">
233                                                 <para>Warning time, in milliseconds</para>
234                                         </argument>
235                                         <argument name="z">
236                                                 <para>Repeat time, in milliseconds</para>
237                                         </argument>
238                                         <para>Limit the call to <replaceable>x</replaceable> milliseconds. Play a warning when <replaceable>y</replaceable> milliseconds are
239                                         left. Repeat the warning every <replaceable>z</replaceable> milliseconds until time expires.</para>
240                                         <para>This option is affected by the following variables:</para>
241                                         <variablelist>
242                                                 <variable name="LIMIT_PLAYAUDIO_CALLER">
243                                                         <value name="yes" default="true" />
244                                                         <value name="no" />
245                                                         <para>If set, this variable causes Asterisk to play the prompts to the caller.</para>
246                                                 </variable>
247                                                 <variable name="LIMIT_PLAYAUDIO_CALLEE">
248                                                         <value name="yes" />
249                                                         <value name="no" default="true"/>
250                                                         <para>If set, this variable causes Asterisk to play the prompts to the callee.</para>
251                                                 </variable>
252                                                 <variable name="LIMIT_TIMEOUT_FILE">
253                                                         <value name="filename"/>
254                                                         <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play when the timeout is reached.
255                                                         If not set, the time remaining will be announced.</para>
256                                                 </variable>
257                                                 <variable name="LIMIT_CONNECT_FILE">
258                                                         <value name="filename"/>
259                                                         <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play when the call begins.
260                                                         If not set, the time remaining will be announced.</para>
261                                                 </variable>
262                                                 <variable name="LIMIT_WARNING_FILE">
263                                                         <value name="filename"/>
264                                                         <para>If specified, <replaceable>filename</replaceable> specifies the sound prompt to play as
265                                                         a warning when time <replaceable>x</replaceable> is reached. If not set, the time remaining will be announced.</para>
266                                                 </variable>
267                                         </variablelist>
268                                 </option>
269                                 <option name="m">
270                                         <argument name="class" required="false"/>
271                                         <para>Provide hold music to the calling party until a requested
272                                         channel answers. A specific music on hold <replaceable>class</replaceable>
273                                         (as defined in <filename>musiconhold.conf</filename>) can be specified.</para>
274                                 </option>
275                                 <option name="M" argsep="^">
276                                         <argument name="macro" required="true">
277                                                 <para>Name of the macro that should be executed.</para>
278                                         </argument>
279                                         <argument name="arg" multiple="true">
280                                                 <para>Macro arguments</para>
281                                         </argument>
282                                         <para>Execute the specified <replaceable>macro</replaceable> for the <emphasis>called</emphasis> channel
283                                         before connecting to the calling channel. Arguments can be specified to the Macro
284                                         using <literal>^</literal> as a delimiter. The macro can set the variable
285                                         <variable>MACRO_RESULT</variable> to specify the following actions after the macro is
286                                         finished executing:</para>
287                                         <variablelist>
288                                                 <variable name="MACRO_RESULT">
289                                                         <para>If set, this action will be taken after the macro finished executing.</para>
290                                                         <value name="ABORT">
291                                                                 Hangup both legs of the call
292                                                         </value>
293                                                         <value name="CONGESTION">
294                                                                 Behave as if line congestion was encountered
295                                                         </value>
296                                                         <value name="BUSY">
297                                                                 Behave as if a busy signal was encountered
298                                                         </value>
299                                                         <value name="CONTINUE">
300                                                                 Hangup the called party and allow the calling party to continue dialplan execution at the next priority
301                                                         </value>
302                                                         <value name="GOTO:[[&lt;context&gt;^]&lt;exten&gt;^]&lt;priority&gt;">
303                                                                 Transfer the call to the specified destination.
304                                                         </value>
305                                                 </variable>
306                                         </variablelist>
307                                         <para>NOTE: You cannot use any additional action post answer options in conjunction
308                                         with this option. Also, pbx services are run on the peer (called) channel,
309                                         so you will not be able to set timeouts via the <literal>TIMEOUT()</literal> function in this macro.</para>
310                                         <para>WARNING: Be aware of the limitations that macros have, specifically with regards to use of
311                                         the <literal>WaitExten</literal> application. For more information, see the documentation for
312                                         <literal>Macro()</literal>.</para>
313                                         <para>NOTE: Macros are deprecated, GoSub should be used instead,
314                                         see the <literal>U</literal> option.</para>
315                                 </option>
316                                 <option name="n">
317                                         <argument name="delete">
318                                                 <para>With <replaceable>delete</replaceable> either not specified or set to <literal>0</literal>,
319                                                 the recorded introduction will not be deleted if the caller hangs up while the remote party has not
320                                                 yet answered.</para>
321                                                 <para>With <replaceable>delete</replaceable> set to <literal>1</literal>, the introduction will
322                                                 always be deleted.</para>
323                                         </argument>
324                                         <para>This option is a modifier for the call screening/privacy mode. (See the
325                                         <literal>p</literal> and <literal>P</literal> options.) It specifies
326                                         that no introductions are to be saved in the <directory>priv-callerintros</directory>
327                                         directory.</para>
328                                 </option>
329                                 <option name="N">
330                                         <para>This option is a modifier for the call screening/privacy mode. It specifies
331                                         that if CallerID is present, do not screen the call.</para>
332                                 </option>
333                                 <option name="o">
334                                         <argument name="x" required="false" />
335                                         <para>If <replaceable>x</replaceable> is not provided, specify that the CallerID that was present on the
336                                         <emphasis>calling</emphasis> channel be stored as the CallerID on the <emphasis>called</emphasis> channel.
337                                         This was the behavior of Asterisk 1.0 and earlier.
338                                         If <replaceable>x</replaceable> is provided, specify the CallerID stored on the <emphasis>called</emphasis> channel.
339                                         Note that <literal>o(${CALLERID(all)})</literal> is similar to option <literal>o</literal> without the parameter.</para>
340                                 </option>
341                                 <option name="O">
342                                         <argument name="mode">
343                                                 <para>With <replaceable>mode</replaceable> either not specified or set to <literal>1</literal>,
344                                                 the originator hanging up will cause the phone to ring back immediately.</para>
345                                                 <para>With <replaceable>mode</replaceable> set to <literal>2</literal>, when the operator
346                                                 flashes the trunk, it will ring their phone back.</para>
347                                         </argument>
348                                         <para>Enables <emphasis>operator services</emphasis> mode.  This option only
349                                         works when bridging a DAHDI channel to another DAHDI channel
350                                         only. if specified on non-DAHDI interfaces, it will be ignored.
351                                         When the destination answers (presumably an operator services
352                                         station), the originator no longer has control of their line.
353                                         They may hang up, but the switch will not release their line
354                                         until the destination party (the operator) hangs up.</para>
355                                 </option>
356                                 <option name="p">
357                                         <para>This option enables screening mode. This is basically Privacy mode
358                                         without memory.</para>
359                                 </option>
360                                 <option name="P">
361                                         <argument name="x" />
362                                         <para>Enable privacy mode. Use <replaceable>x</replaceable> as the family/key in the AstDB database if
363                                         it is provided. The current extension is used if a database family/key is not specified.</para>
364                                 </option>
365                                 <option name="Q">
366                                         <argument name="cause" required="true"/>
367                                         <para>Specify the Q.850/Q.931 <replaceable>cause</replaceable> to send on
368                                         unanswered channels when another channel answers the call.
369                                         As with <literal>Hangup()</literal>, <replaceable>cause</replaceable>
370                                         can be a numeric cause code or a name such as
371                                                 <literal>NO_ANSWER</literal>,
372                                                 <literal>USER_BUSY</literal>,
373                                                 <literal>CALL_REJECTED</literal> or
374                                                 <literal>ANSWERED_ELSEWHERE</literal> (the default if Q isn't specified).
375                                                 You can also specify <literal>0</literal> or <literal>NONE</literal>
376                                                 to send no cause.  See the <filename>causes.h</filename> file for the
377                                                 full list of valid causes and names.
378                                                 </para>
379                                         <para>NOTE: chan_sip does not support setting the cause on a CANCEL to anything
380                                         other than ANSWERED_ELSEWHERE.</para>
381                                 </option>
382                                 <option name="r">
383                                         <para>Default: Indicate ringing to the calling party, even if the called party isn't actually ringing. Pass no audio to the calling
384                                         party until the called channel has answered.</para>
385                                         <argument name="tone" required="false">
386                                                 <para>Indicate progress to calling party. Send audio 'tone' from the <filename>indications.conf</filename> tonezone currently in use.</para>
387                                         </argument>
388                                 </option>
389                                 <option name="R">
390                                         <para>Default: Indicate ringing to the calling party, even if the called party isn't actually ringing.
391                                         Allow interruption of the ringback if early media is received on the channel.</para>
392                                 </option>
393                                 <option name="S">
394                                         <argument name="x" required="true" />
395                                         <para>Hang up the call <replaceable>x</replaceable> seconds <emphasis>after</emphasis> the called party has
396                                         answered the call.</para>
397                                 </option>
398                                 <option name="s">
399                                         <argument name="x" required="true" />
400                                         <para>Force the outgoing CallerID tag parameter to be set to the string <replaceable>x</replaceable>.</para>
401                                         <para>Works with the <literal>f</literal> option.</para>
402                                 </option>
403                                 <option name="t">
404                                         <para>Allow the called party to transfer the calling party by sending the
405                                         DTMF sequence defined in <filename>features.conf</filename>. This setting does not perform policy enforcement on
406                                         transfers initiated by other methods.</para>
407                                 </option>
408                                 <option name="T">
409                                         <para>Allow the calling party to transfer the called party by sending the
410                                         DTMF sequence defined in <filename>features.conf</filename>. This setting does not perform policy enforcement on
411                                         transfers initiated by other methods.</para>
412                                 </option>
413                                 <option name="U" argsep="^">
414                                         <argument name="x" required="true">
415                                                 <para>Name of the subroutine context to execute via <literal>Gosub</literal>.
416                                                 The subroutine execution starts in the named context at the s exten and priority 1.</para>
417                                         </argument>
418                                         <argument name="arg" multiple="true" required="false">
419                                                 <para>Arguments for the <literal>Gosub</literal> routine</para>
420                                         </argument>
421                                         <para>Execute via <literal>Gosub</literal> the routine <replaceable>x</replaceable> for the <emphasis>called</emphasis> channel before connecting
422                                         to the calling channel. Arguments can be specified to the <literal>Gosub</literal>
423                                         using <literal>^</literal> as a delimiter. The <literal>Gosub</literal> routine can set the variable
424                                         <variable>GOSUB_RESULT</variable> to specify the following actions after the <literal>Gosub</literal> returns.</para>
425                                         <variablelist>
426                                                 <variable name="GOSUB_RESULT">
427                                                         <value name="ABORT">
428                                                                 Hangup both legs of the call.
429                                                         </value>
430                                                         <value name="CONGESTION">
431                                                                 Behave as if line congestion was encountered.
432                                                         </value>
433                                                         <value name="BUSY">
434                                                                 Behave as if a busy signal was encountered.
435                                                         </value>
436                                                         <value name="CONTINUE">
437                                                                 Hangup the called party and allow the calling party
438                                                                 to continue dialplan execution at the next priority.
439                                                         </value>
440                                                         <value name="GOTO:[[&lt;context&gt;^]&lt;exten&gt;^]&lt;priority&gt;">
441                                                                 Transfer the call to the specified destination.
442                                                         </value>
443                                                 </variable>
444                                         </variablelist>
445                                         <para>NOTE: You cannot use any additional action post answer options in conjunction
446                                         with this option. Also, pbx services are run on the <emphasis>called</emphasis> channel,
447                                         so you will not be able to set timeouts via the <literal>TIMEOUT()</literal> function in this routine.</para>
448                                 </option>
449                                 <option name="u">
450                                         <argument name = "x" required="true">
451                                                 <para>Force the outgoing callerid presentation indicator parameter to be set
452                                                 to one of the values passed in <replaceable>x</replaceable>:
453                                                 <literal>allowed_not_screened</literal>
454                                                 <literal>allowed_passed_screen</literal>
455                                                 <literal>allowed_failed_screen</literal>
456                                                 <literal>allowed</literal>
457                                                 <literal>prohib_not_screened</literal>
458                                                 <literal>prohib_passed_screen</literal>
459                                                 <literal>prohib_failed_screen</literal>
460                                                 <literal>prohib</literal>
461                                                 <literal>unavailable</literal></para>
462                                         </argument>
463                                         <para>Works with the <literal>f</literal> option.</para>
464                                 </option>
465                                 <option name="w">
466                                         <para>Allow the called party to enable recording of the call by sending
467                                         the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
468                                 </option>
469                                 <option name="W">
470                                         <para>Allow the calling party to enable recording of the call by sending
471                                         the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
472                                 </option>
473                                 <option name="x">
474                                         <para>Allow the called party to enable recording of the call by sending
475                                         the DTMF sequence defined for one-touch automixmonitor in <filename>features.conf</filename>.</para>
476                                 </option>
477                                 <option name="X">
478                                         <para>Allow the calling party to enable recording of the call by sending
479                                         the DTMF sequence defined for one-touch automixmonitor in <filename>features.conf</filename>.</para>
480                                 </option>
481                                 <option name="z">
482                                         <para>On a call forward, cancel any dial timeout which has been set for this call.</para>
483                                 </option>
484                                 </optionlist>
485                         </parameter>
486                         <parameter name="URL">
487                                 <para>The optional URL will be sent to the called party if the channel driver supports it.</para>
488                         </parameter>
489                 </syntax>
490                 <description>
491                         <para>This application will place calls to one or more specified channels. As soon
492                         as one of the requested channels answers, the originating channel will be
493                         answered, if it has not already been answered. These two channels will then
494                         be active in a bridged call. All other channels that were requested will then
495                         be hung up.</para>
496
497                         <para>Unless there is a timeout specified, the Dial application will wait
498                         indefinitely until one of the called channels answers, the user hangs up, or
499                         if all of the called channels are busy or unavailable. Dialplan execution will
500                         continue if no requested channels can be called, or if the timeout expires.
501                         This application will report normal termination if the originating channel
502                         hangs up, or if the call is bridged and either of the parties in the bridge
503                         ends the call.</para>
504                         <para>If the <variable>OUTBOUND_GROUP</variable> variable is set, all peer channels created by this
505                         application will be put into that group (as in <literal>Set(GROUP()=...</literal>).
506                         If the <variable>OUTBOUND_GROUP_ONCE</variable> variable is set, all peer channels created by this
507                         application will be put into that group (as in <literal>Set(GROUP()=...</literal>). Unlike <variable>OUTBOUND_GROUP</variable>,
508                         however, the variable will be unset after use.</para>
509
510                         <example title="Dial with 30 second timeout">
511                          same => n,Dial(PJSIP/alice,30)
512                         </example>
513                         <example title="Parallel dial with 45 second timeout">
514                          same => n,Dial(PJSIP/alice&amp;PJIP/bob,45)
515                         </example>
516                         <example title="Dial with 'g' continuation option">
517                          same => n,Dial(PJSIP/alice,,g)
518                          same => n,Log(NOTICE, Alice call result: ${DIALSTATUS})
519                         </example>
520                         <example title="Dial with transfer/recording features for calling party">
521                          same => n,Dial(PJSIP/alice,,TX)
522                         </example>
523                         <example title="Dial with call length limit">
524                          same => n,Dial(PJSIP/alice,,L(60000:30000:10000))
525                         </example>
526                         <example title="Dial alice and bob and send NO_ANSWER to bob instead of ANSWERED_ELSEWHERE when alice answers">
527                          same => n,Dial(PJSIP/alice&amp;PJSIP/bob,,Q(NO_ANSWER))
528                         </example>
529                         <example title="Dial with pre-dial subroutines">
530                         [default]
531
532                         exten => callee_channel,1,NoOp(ARG1=${ARG1} ARG2=${ARG2})
533                          same => n,Log(NOTICE, I'm called on channel ${CHANNEL} prior to it starting the dial attempt)
534                          same => n,Return()
535
536                         exten => called_channel,1,NoOp(ARG1=${ARG1} ARG2=${ARG2})
537                          same => n,Log(NOTICE, I'm called on outbound channel ${CHANNEL} prior to it being used to dial someone)
538                          same => n,Return()
539
540                         exten => _X.,1,NoOp()
541                          same => n,Dial(PJSIP/alice,,b(default^called_channel^1(my_gosub_arg1^my_gosub_arg2))B(default^callee_channel^1(my_gosub_arg1^my_gosub_arg2)))
542                          same => n,Hangup()
543                         </example>
544                         <example title="Dial with post-answer subroutine executed on outbound channel">
545                         [my_gosub_routine]
546
547                         exten => s,1,NoOp(ARG1=${ARG1} ARG2=${ARG2})
548                          same => n,Playback(hello)
549                          same => n,Return()
550
551                         [default]
552
553                         exten => _X.,1,NoOp()
554                          same => n,Dial(PJSIP/alice,,U(my_gosub_routine^my_gosub_arg1^my_gosub_arg2))
555                          same => n,Hangup()
556                         </example>
557                         <example title="Dial into ConfBridge using 'G' option">
558                          same => n,Dial(PJSIP/alice,,G(jump_to_here))
559                          same => n(jump_to_here),Goto(confbridge)
560                          same => n,Goto(confbridge)
561                          same => n(confbridge),ConfBridge(${EXTEN})
562                         </example>
563                         <para>This application sets the following channel variables:</para>
564                         <variablelist>
565                                 <variable name="DIALEDTIME">
566                                         <para>This is the time from dialing a channel until when it is disconnected.</para>
567                                 </variable>
568                                 <variable name="DIALEDTIME_MS">
569                                         <para>This is the milliseconds version of the DIALEDTIME variable.</para>
570                                 </variable>
571                                 <variable name="ANSWEREDTIME">
572                                         <para>This is the amount of time for actual call.</para>
573                                 </variable>
574                                 <variable name="ANSWEREDTIME_MS">
575                                         <para>This is the milliseconds version of the ANSWEREDTIME variable.</para>
576                                 </variable>
577                                 <variable name="RINGTIME">
578                                         <para>This is the time from creating the channel to the first RINGING event received. Empty if there was no ring.</para>
579                                 </variable>
580                                 <variable name="RINGTIME_MS">
581                                         <para>This is the milliseconds version of the RINGTIME variable.</para>
582                                 </variable>
583                                 <variable name="PROGRESSTIME">
584                                         <para>This is the time from creating the channel to the first PROGRESS event received. Empty if there was no such event.</para>
585                                 </variable>
586                                 <variable name="PROGRESSTIME_MS">
587                                         <para>This is the milliseconds version of the PROGRESSTIME variable.</para>
588                                 </variable>
589                                 <variable name="DIALEDPEERNAME">
590                                         <para>The name of the outbound channel that answered the call.</para>
591                                 </variable>
592                                 <variable name="DIALEDPEERNUMBER">
593                                         <para>The number that was dialed for the answered outbound channel.</para>
594                                 </variable>
595                                 <variable name="FORWARDERNAME">
596                                         <para>If a call forward occurred, the name of the forwarded channel.</para>
597                                 </variable>
598                                 <variable name="DIALSTATUS">
599                                         <para>This is the status of the call</para>
600                                         <value name="CHANUNAVAIL" />
601                                         <value name="CONGESTION" />
602                                         <value name="NOANSWER" />
603                                         <value name="BUSY" />
604                                         <value name="ANSWER" />
605                                         <value name="CANCEL" />
606                                         <value name="DONTCALL">
607                                                 For the Privacy and Screening Modes.
608                                                 Will be set if the called party chooses to send the calling party to the 'Go Away' script.
609                                         </value>
610                                         <value name="TORTURE">
611                                                 For the Privacy and Screening Modes.
612                                                 Will be set if the called party chooses to send the calling party to the 'torture' script.
613                                         </value>
614                                         <value name="INVALIDARGS" />
615                                 </variable>
616                         </variablelist>
617                 </description>
618                 <see-also>
619                         <ref type="application">RetryDial</ref>
620                         <ref type="application">SendDTMF</ref>
621                         <ref type="application">Gosub</ref>
622                         <ref type="application">Macro</ref>
623                 </see-also>
624         </application>
625         <application name="RetryDial" language="en_US">
626                 <synopsis>
627                         Place a call, retrying on failure allowing an optional exit extension.
628                 </synopsis>
629                 <syntax>
630                         <parameter name="announce" required="true">
631                                 <para>Filename of sound that will be played when no channel can be reached</para>
632                         </parameter>
633                         <parameter name="sleep" required="true">
634                                 <para>Number of seconds to wait after a dial attempt failed before a new attempt is made</para>
635                         </parameter>
636                         <parameter name="retries" required="true">
637                                 <para>Number of retries</para>
638                                 <para>When this is reached flow will continue at the next priority in the dialplan</para>
639                         </parameter>
640                         <parameter name="dialargs" required="true">
641                                 <para>Same format as arguments provided to the Dial application</para>
642                         </parameter>
643                 </syntax>
644                 <description>
645                         <para>This application will attempt to place a call using the normal Dial application.
646                         If no channel can be reached, the <replaceable>announce</replaceable> file will be played.
647                         Then, it will wait <replaceable>sleep</replaceable> number of seconds before retrying the call.
648                         After <replaceable>retries</replaceable> number of attempts, the calling channel will continue at the next priority in the dialplan.
649                         If the <replaceable>retries</replaceable> setting is set to 0, this application will retry endlessly.
650                         While waiting to retry a call, a 1 digit extension may be dialed. If that
651                         extension exists in either the context defined in <variable>EXITCONTEXT</variable> or the current
652                         one, The call will jump to that extension immediately.
653                         The <replaceable>dialargs</replaceable> are specified in the same format that arguments are provided
654                         to the Dial application.</para>
655                 </description>
656                 <see-also>
657                         <ref type="application">Dial</ref>
658                 </see-also>
659         </application>
660  ***/
661
662 static const char app[] = "Dial";
663 static const char rapp[] = "RetryDial";
664
665 enum {
666         OPT_ANNOUNCE =          (1 << 0),
667         OPT_RESETCDR =          (1 << 1),
668         OPT_DTMF_EXIT =         (1 << 2),
669         OPT_SENDDTMF =          (1 << 3),
670         OPT_FORCECLID =         (1 << 4),
671         OPT_GO_ON =             (1 << 5),
672         OPT_CALLEE_HANGUP =     (1 << 6),
673         OPT_CALLER_HANGUP =     (1 << 7),
674         OPT_ORIGINAL_CLID =     (1 << 8),
675         OPT_DURATION_LIMIT =    (1 << 9),
676         OPT_MUSICBACK =         (1 << 10),
677         OPT_CALLEE_MACRO =      (1 << 11),
678         OPT_SCREEN_NOINTRO =    (1 << 12),
679         OPT_SCREEN_NOCALLERID = (1 << 13),
680         OPT_IGNORE_CONNECTEDLINE = (1 << 14),
681         OPT_SCREENING =         (1 << 15),
682         OPT_PRIVACY =           (1 << 16),
683         OPT_RINGBACK =          (1 << 17),
684         OPT_DURATION_STOP =     (1 << 18),
685         OPT_CALLEE_TRANSFER =   (1 << 19),
686         OPT_CALLER_TRANSFER =   (1 << 20),
687         OPT_CALLEE_MONITOR =    (1 << 21),
688         OPT_CALLER_MONITOR =    (1 << 22),
689         OPT_GOTO =              (1 << 23),
690         OPT_OPERMODE =          (1 << 24),
691         OPT_CALLEE_PARK =       (1 << 25),
692         OPT_CALLER_PARK =       (1 << 26),
693         OPT_IGNORE_FORWARDING = (1 << 27),
694         OPT_CALLEE_GOSUB =      (1 << 28),
695         OPT_CALLEE_MIXMONITOR = (1 << 29),
696         OPT_CALLER_MIXMONITOR = (1 << 30),
697 };
698
699 /* flags are now 64 bits, so keep it up! */
700 #define DIAL_STILLGOING      (1LLU << 31)
701 #define DIAL_NOFORWARDHTML   (1LLU << 32)
702 #define DIAL_CALLERID_ABSENT (1LLU << 33) /* TRUE if caller id is not available for connected line. */
703 #define OPT_CANCEL_ELSEWHERE (1LLU << 34)
704 #define OPT_PEER_H           (1LLU << 35)
705 #define OPT_CALLEE_GO_ON     (1LLU << 36)
706 #define OPT_CANCEL_TIMEOUT   (1LLU << 37)
707 #define OPT_FORCE_CID_TAG    (1LLU << 38)
708 #define OPT_FORCE_CID_PRES   (1LLU << 39)
709 #define OPT_CALLER_ANSWER    (1LLU << 40)
710 #define OPT_PREDIAL_CALLEE   (1LLU << 41)
711 #define OPT_PREDIAL_CALLER   (1LLU << 42)
712 #define OPT_RING_WITH_EARLY_MEDIA (1LLU << 43)
713 #define OPT_HANGUPCAUSE      (1LLU << 44)
714
715 enum {
716         OPT_ARG_ANNOUNCE = 0,
717         OPT_ARG_SENDDTMF,
718         OPT_ARG_GOTO,
719         OPT_ARG_DURATION_LIMIT,
720         OPT_ARG_MUSICBACK,
721         OPT_ARG_CALLEE_MACRO,
722         OPT_ARG_RINGBACK,
723         OPT_ARG_CALLEE_GOSUB,
724         OPT_ARG_CALLEE_GO_ON,
725         OPT_ARG_PRIVACY,
726         OPT_ARG_DURATION_STOP,
727         OPT_ARG_OPERMODE,
728         OPT_ARG_SCREEN_NOINTRO,
729         OPT_ARG_ORIGINAL_CLID,
730         OPT_ARG_FORCECLID,
731         OPT_ARG_FORCE_CID_TAG,
732         OPT_ARG_FORCE_CID_PRES,
733         OPT_ARG_PREDIAL_CALLEE,
734         OPT_ARG_PREDIAL_CALLER,
735         OPT_ARG_HANGUPCAUSE,
736         /* note: this entry _MUST_ be the last one in the enum */
737         OPT_ARG_ARRAY_SIZE
738 };
739
740 AST_APP_OPTIONS(dial_exec_options, BEGIN_OPTIONS
741         AST_APP_OPTION_ARG('A', OPT_ANNOUNCE, OPT_ARG_ANNOUNCE),
742         AST_APP_OPTION('a', OPT_CALLER_ANSWER),
743         AST_APP_OPTION_ARG('b', OPT_PREDIAL_CALLEE, OPT_ARG_PREDIAL_CALLEE),
744         AST_APP_OPTION_ARG('B', OPT_PREDIAL_CALLER, OPT_ARG_PREDIAL_CALLER),
745         AST_APP_OPTION('C', OPT_RESETCDR),
746         AST_APP_OPTION('c', OPT_CANCEL_ELSEWHERE),
747         AST_APP_OPTION('d', OPT_DTMF_EXIT),
748         AST_APP_OPTION_ARG('D', OPT_SENDDTMF, OPT_ARG_SENDDTMF),
749         AST_APP_OPTION('e', OPT_PEER_H),
750         AST_APP_OPTION_ARG('f', OPT_FORCECLID, OPT_ARG_FORCECLID),
751         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
752         AST_APP_OPTION('g', OPT_GO_ON),
753         AST_APP_OPTION_ARG('G', OPT_GOTO, OPT_ARG_GOTO),
754         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
755         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
756         AST_APP_OPTION('i', OPT_IGNORE_FORWARDING),
757         AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
758         AST_APP_OPTION('k', OPT_CALLEE_PARK),
759         AST_APP_OPTION('K', OPT_CALLER_PARK),
760         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
761         AST_APP_OPTION_ARG('m', OPT_MUSICBACK, OPT_ARG_MUSICBACK),
762         AST_APP_OPTION_ARG('M', OPT_CALLEE_MACRO, OPT_ARG_CALLEE_MACRO),
763         AST_APP_OPTION_ARG('n', OPT_SCREEN_NOINTRO, OPT_ARG_SCREEN_NOINTRO),
764         AST_APP_OPTION('N', OPT_SCREEN_NOCALLERID),
765         AST_APP_OPTION_ARG('o', OPT_ORIGINAL_CLID, OPT_ARG_ORIGINAL_CLID),
766         AST_APP_OPTION_ARG('O', OPT_OPERMODE, OPT_ARG_OPERMODE),
767         AST_APP_OPTION('p', OPT_SCREENING),
768         AST_APP_OPTION_ARG('P', OPT_PRIVACY, OPT_ARG_PRIVACY),
769         AST_APP_OPTION_ARG('Q', OPT_HANGUPCAUSE, OPT_ARG_HANGUPCAUSE),
770         AST_APP_OPTION_ARG('r', OPT_RINGBACK, OPT_ARG_RINGBACK),
771         AST_APP_OPTION('R', OPT_RING_WITH_EARLY_MEDIA),
772         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
773         AST_APP_OPTION_ARG('s', OPT_FORCE_CID_TAG, OPT_ARG_FORCE_CID_TAG),
774         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
775         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
776         AST_APP_OPTION_ARG('u', OPT_FORCE_CID_PRES, OPT_ARG_FORCE_CID_PRES),
777         AST_APP_OPTION_ARG('U', OPT_CALLEE_GOSUB, OPT_ARG_CALLEE_GOSUB),
778         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
779         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
780         AST_APP_OPTION('x', OPT_CALLEE_MIXMONITOR),
781         AST_APP_OPTION('X', OPT_CALLER_MIXMONITOR),
782         AST_APP_OPTION('z', OPT_CANCEL_TIMEOUT),
783 END_OPTIONS );
784
785 #define CAN_EARLY_BRIDGE(flags,chan,peer) (!ast_test_flag64(flags, OPT_CALLEE_HANGUP | \
786         OPT_CALLER_HANGUP | OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER | \
787         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR | OPT_CALLEE_PARK |  \
788         OPT_CALLER_PARK | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB) && \
789         !ast_channel_audiohooks(chan) && !ast_channel_audiohooks(peer) && \
790         ast_framehook_list_is_empty(ast_channel_framehooks(chan)) && ast_framehook_list_is_empty(ast_channel_framehooks(peer)))
791
792 /*
793  * The list of active channels
794  */
795 struct chanlist {
796         AST_LIST_ENTRY(chanlist) node;
797         struct ast_channel *chan;
798         /*! Channel interface dialing string (is tech/number).  (Stored in stuff[]) */
799         const char *interface;
800         /*! Channel technology name.  (Stored in stuff[]) */
801         const char *tech;
802         /*! Channel device addressing.  (Stored in stuff[]) */
803         const char *number;
804         /*! Original channel name.  Must be freed.  Could be NULL if allocation failed. */
805         char *orig_chan_name;
806         uint64_t flags;
807         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
808         struct ast_party_connected_line connected;
809         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
810         unsigned int pending_connected_update:1;
811         struct ast_aoc_decoded *aoc_s_rate_list;
812         /*! The interface, tech, and number strings are stuffed here. */
813         char stuff[0];
814 };
815
816 AST_LIST_HEAD_NOLOCK(dial_head, chanlist);
817
818 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str **featurecode);
819
820 static void chanlist_free(struct chanlist *outgoing)
821 {
822         ast_party_connected_line_free(&outgoing->connected);
823         ast_aoc_destroy_decoded(outgoing->aoc_s_rate_list);
824         ast_free(outgoing->orig_chan_name);
825         ast_free(outgoing);
826 }
827
828 static void hanguptree(struct dial_head *out_chans, struct ast_channel *exception, int hangupcause)
829 {
830         /* Hang up a tree of stuff */
831         struct chanlist *outgoing;
832
833         while ((outgoing = AST_LIST_REMOVE_HEAD(out_chans, node))) {
834                 /* Hangup any existing lines we have open */
835                 if (outgoing->chan && (outgoing->chan != exception)) {
836                         if (hangupcause >= 0) {
837                                 /* This is for the channel drivers */
838                                 ast_channel_hangupcause_set(outgoing->chan, hangupcause);
839                         }
840                         ast_hangup(outgoing->chan);
841                 }
842                 chanlist_free(outgoing);
843         }
844 }
845
846 #define AST_MAX_WATCHERS 256
847
848 /*
849  * argument to handle_cause() and other functions.
850  */
851 struct cause_args {
852         struct ast_channel *chan;
853         int busy;
854         int congestion;
855         int nochan;
856 };
857
858 static void handle_cause(int cause, struct cause_args *num)
859 {
860         switch(cause) {
861         case AST_CAUSE_BUSY:
862                 num->busy++;
863                 break;
864         case AST_CAUSE_CONGESTION:
865                 num->congestion++;
866                 break;
867         case AST_CAUSE_NO_ROUTE_DESTINATION:
868         case AST_CAUSE_UNREGISTERED:
869                 num->nochan++;
870                 break;
871         case AST_CAUSE_NO_ANSWER:
872         case AST_CAUSE_NORMAL_CLEARING:
873                 break;
874         default:
875                 num->nochan++;
876                 break;
877         }
878 }
879
880 static int onedigit_goto(struct ast_channel *chan, const char *context, char exten, int pri)
881 {
882         char rexten[2] = { exten, '\0' };
883
884         if (context) {
885                 if (!ast_goto_if_exists(chan, context, rexten, pri))
886                         return 1;
887         } else {
888                 if (!ast_goto_if_exists(chan, ast_channel_context(chan), rexten, pri))
889                         return 1;
890                 else if (!ast_strlen_zero(ast_channel_macrocontext(chan))) {
891                         if (!ast_goto_if_exists(chan, ast_channel_macrocontext(chan), rexten, pri))
892                                 return 1;
893                 }
894         }
895         return 0;
896 }
897
898 /* do not call with chan lock held */
899 static const char *get_cid_name(char *name, int namelen, struct ast_channel *chan)
900 {
901         const char *context;
902         const char *exten;
903
904         ast_channel_lock(chan);
905         context = ast_strdupa(S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan)));
906         exten = ast_strdupa(S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan)));
907         ast_channel_unlock(chan);
908
909         return ast_get_hint(NULL, 0, name, namelen, chan, context, exten) ? name : "";
910 }
911
912 /*!
913  * helper function for wait_for_answer()
914  *
915  * \param o Outgoing call channel list.
916  * \param num Incoming call channel cause accumulation
917  * \param peerflags Dial option flags
918  * \param single TRUE if there is only one outgoing call.
919  * \param caller_entertained TRUE if the caller is being entertained by MOH or ringback.
920  * \param to Remaining call timeout time.
921  * \param forced_clid OPT_FORCECLID caller id to send
922  * \param stored_clid Caller id representing the called party if needed
923  *
924  * XXX this code is highly suspicious, as it essentially overwrites
925  * the outgoing channel without properly deleting it.
926  *
927  * \todo eventually this function should be intergrated into and replaced by ast_call_forward()
928  */
929 static void do_forward(struct chanlist *o, struct cause_args *num,
930         struct ast_flags64 *peerflags, int single, int caller_entertained, int *to,
931         struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
932 {
933         char tmpchan[256];
934         char forwarder[AST_CHANNEL_NAME];
935         struct ast_channel *original = o->chan;
936         struct ast_channel *c = o->chan; /* the winner */
937         struct ast_channel *in = num->chan; /* the input channel */
938         char *stuff;
939         char *tech;
940         int cause;
941         struct ast_party_caller caller;
942
943         ast_copy_string(forwarder, ast_channel_name(c), sizeof(forwarder));
944         ast_copy_string(tmpchan, ast_channel_call_forward(c), sizeof(tmpchan));
945         if ((stuff = strchr(tmpchan, '/'))) {
946                 *stuff++ = '\0';
947                 tech = tmpchan;
948         } else {
949                 const char *forward_context;
950                 ast_channel_lock(c);
951                 forward_context = pbx_builtin_getvar_helper(c, "FORWARD_CONTEXT");
952                 if (ast_strlen_zero(forward_context)) {
953                         forward_context = NULL;
954                 }
955                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", ast_channel_call_forward(c), forward_context ? forward_context : ast_channel_context(c));
956                 ast_channel_unlock(c);
957                 stuff = tmpchan;
958                 tech = "Local";
959         }
960         if (!strcasecmp(tech, "Local")) {
961                 /*
962                  * Drop the connected line update block for local channels since
963                  * this is going to run dialplan and the user can change his
964                  * mind about what connected line information he wants to send.
965                  */
966                 ast_clear_flag64(o, OPT_IGNORE_CONNECTEDLINE);
967         }
968
969         /* Before processing channel, go ahead and check for forwarding */
970         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", ast_channel_name(in), tech, stuff, ast_channel_name(c));
971         /* If we have been told to ignore forwards, just set this channel to null and continue processing extensions normally */
972         if (ast_test_flag64(peerflags, OPT_IGNORE_FORWARDING)) {
973                 ast_verb(3, "Forwarding %s to '%s/%s' prevented.\n", ast_channel_name(in), tech, stuff);
974                 ast_channel_publish_dial_forward(in, original, NULL, NULL, "CANCEL",
975                         ast_channel_call_forward(original));
976                 c = o->chan = NULL;
977                 cause = AST_CAUSE_BUSY;
978         } else {
979                 struct ast_stream_topology *topology;
980
981                 ast_channel_lock(in);
982                 topology = ast_stream_topology_clone(ast_channel_get_stream_topology(in));
983                 ast_channel_unlock(in);
984
985                 /* Setup parameters */
986                 c = o->chan = ast_request_with_stream_topology(tech, topology, NULL, in, stuff, &cause);
987
988                 ast_stream_topology_free(topology);
989
990                 if (c) {
991                         if (single && !caller_entertained) {
992                                 ast_channel_make_compatible(in, o->chan);
993                         }
994                         ast_channel_lock_both(in, o->chan);
995                         ast_channel_inherit_variables(in, o->chan);
996                         ast_channel_datastore_inherit(in, o->chan);
997                         pbx_builtin_setvar_helper(o->chan, "FORWARDERNAME", forwarder);
998                         ast_max_forwards_decrement(o->chan);
999                         ast_channel_unlock(in);
1000                         ast_channel_unlock(o->chan);
1001                         /* When a call is forwarded, we don't want to track new interfaces
1002                          * dialed for CC purposes. Setting the done flag will ensure that
1003                          * any Dial operations that happen later won't record CC interfaces.
1004                          */
1005                         ast_ignore_cc(o->chan);
1006                         ast_log(LOG_NOTICE, "Not accepting call completion offers from call-forward recipient %s\n", ast_channel_name(o->chan));
1007                 } else
1008                         ast_log(LOG_NOTICE,
1009                                 "Forwarding failed to create channel to dial '%s/%s' (cause = %d)\n",
1010                                 tech, stuff, cause);
1011         }
1012         if (!c) {
1013                 ast_channel_publish_dial(in, original, stuff, "BUSY");
1014                 ast_clear_flag64(o, DIAL_STILLGOING);
1015                 handle_cause(cause, num);
1016                 ast_hangup(original);
1017         } else {
1018                 ast_channel_lock_both(c, original);
1019                 ast_party_redirecting_copy(ast_channel_redirecting(c),
1020                         ast_channel_redirecting(original));
1021                 ast_channel_unlock(c);
1022                 ast_channel_unlock(original);
1023
1024                 ast_channel_lock_both(c, in);
1025
1026                 if (single && !caller_entertained && CAN_EARLY_BRIDGE(peerflags, c, in)) {
1027                         ast_rtp_instance_early_bridge_make_compatible(c, in);
1028                 }
1029
1030                 if (!ast_channel_redirecting(c)->from.number.valid
1031                         || ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
1032                         /*
1033                          * The call was not previously redirected so it is
1034                          * now redirected from this number.
1035                          */
1036                         ast_party_number_free(&ast_channel_redirecting(c)->from.number);
1037                         ast_party_number_init(&ast_channel_redirecting(c)->from.number);
1038                         ast_channel_redirecting(c)->from.number.valid = 1;
1039                         ast_channel_redirecting(c)->from.number.str =
1040                                 ast_strdup(S_OR(ast_channel_macroexten(in), ast_channel_exten(in)));
1041                 }
1042
1043                 ast_channel_dialed(c)->transit_network_select = ast_channel_dialed(in)->transit_network_select;
1044
1045                 /* Determine CallerID to store in outgoing channel. */
1046                 ast_party_caller_set_init(&caller, ast_channel_caller(c));
1047                 if (ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
1048                         caller.id = *stored_clid;
1049                         ast_channel_set_caller_event(c, &caller, NULL);
1050                         ast_set_flag64(o, DIAL_CALLERID_ABSENT);
1051                 } else if (ast_strlen_zero(S_COR(ast_channel_caller(c)->id.number.valid,
1052                         ast_channel_caller(c)->id.number.str, NULL))) {
1053                         /*
1054                          * The new channel has no preset CallerID number by the channel
1055                          * driver.  Use the dialplan extension and hint name.
1056                          */
1057                         caller.id = *stored_clid;
1058                         ast_channel_set_caller_event(c, &caller, NULL);
1059                         ast_set_flag64(o, DIAL_CALLERID_ABSENT);
1060                 } else {
1061                         ast_clear_flag64(o, DIAL_CALLERID_ABSENT);
1062                 }
1063
1064                 /* Determine CallerID for outgoing channel to send. */
1065                 if (ast_test_flag64(o, OPT_FORCECLID)) {
1066                         struct ast_party_connected_line connected;
1067
1068                         ast_party_connected_line_init(&connected);
1069                         connected.id = *forced_clid;
1070                         ast_party_connected_line_copy(ast_channel_connected(c), &connected);
1071                 } else {
1072                         ast_connected_line_copy_from_caller(ast_channel_connected(c), ast_channel_caller(in));
1073                 }
1074
1075                 ast_channel_req_accountcodes(c, in, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
1076
1077                 ast_channel_appl_set(c, "AppDial");
1078                 ast_channel_data_set(c, "(Outgoing Line)");
1079                 ast_channel_publish_snapshot(c);
1080
1081                 ast_channel_unlock(in);
1082                 if (single && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1083                         struct ast_party_redirecting redirecting;
1084
1085                         /*
1086                          * Redirecting updates to the caller make sense only on single
1087                          * calls.
1088                          *
1089                          * We must unlock c before calling
1090                          * ast_channel_redirecting_macro, because we put c into
1091                          * autoservice there.  That is pretty much a guaranteed
1092                          * deadlock.  This is why the handling of c's lock may seem a
1093                          * bit unusual here.
1094                          */
1095                         ast_party_redirecting_init(&redirecting);
1096                         ast_party_redirecting_copy(&redirecting, ast_channel_redirecting(c));
1097                         ast_channel_unlock(c);
1098                         if (ast_channel_redirecting_sub(c, in, &redirecting, 0) &&
1099                                 ast_channel_redirecting_macro(c, in, &redirecting, 1, 0)) {
1100                                 ast_channel_update_redirecting(in, &redirecting, NULL);
1101                         }
1102                         ast_party_redirecting_free(&redirecting);
1103                 } else {
1104                         ast_channel_unlock(c);
1105                 }
1106
1107                 if (ast_test_flag64(peerflags, OPT_CANCEL_TIMEOUT)) {
1108                         *to = -1;
1109                 }
1110
1111                 if (ast_call(c, stuff, 0)) {
1112                         ast_log(LOG_NOTICE, "Forwarding failed to dial '%s/%s'\n",
1113                                 tech, stuff);
1114                         ast_channel_publish_dial(in, original, stuff, "CONGESTION");
1115                         ast_clear_flag64(o, DIAL_STILLGOING);
1116                         ast_hangup(original);
1117                         ast_hangup(c);
1118                         c = o->chan = NULL;
1119                         num->nochan++;
1120                 } else {
1121                         ast_channel_publish_dial_forward(in, original, c, NULL, "CANCEL",
1122                                 ast_channel_call_forward(original));
1123
1124                         ast_channel_publish_dial(in, c, stuff, NULL);
1125
1126                         /* Hangup the original channel now, in case we needed it */
1127                         ast_hangup(original);
1128                 }
1129                 if (single && !caller_entertained) {
1130                         ast_indicate(in, -1);
1131                 }
1132         }
1133 }
1134
1135 /* argument used for some functions. */
1136 struct privacy_args {
1137         int sentringing;
1138         int privdb_val;
1139         char privcid[256];
1140         char privintro[1024];
1141         char status[256];
1142 };
1143
1144 static void publish_dial_end_event(struct ast_channel *in, struct dial_head *out_chans, struct ast_channel *exception, const char *status)
1145 {
1146         struct chanlist *outgoing;
1147         AST_LIST_TRAVERSE(out_chans, outgoing, node) {
1148                 if (!outgoing->chan || outgoing->chan == exception) {
1149                         continue;
1150                 }
1151                 ast_channel_publish_dial(in, outgoing->chan, NULL, status);
1152         }
1153 }
1154
1155 /*!
1156  * \internal
1157  * \brief Update connected line on chan from peer.
1158  * \since 13.6.0
1159  *
1160  * \param chan Channel to get connected line updated.
1161  * \param peer Channel providing connected line information.
1162  * \param is_caller Non-zero if chan is the calling channel.
1163  *
1164  * \return Nothing
1165  */
1166 static void update_connected_line_from_peer(struct ast_channel *chan, struct ast_channel *peer, int is_caller)
1167 {
1168         struct ast_party_connected_line connected_caller;
1169
1170         ast_party_connected_line_init(&connected_caller);
1171
1172         ast_channel_lock(peer);
1173         ast_connected_line_copy_from_caller(&connected_caller, ast_channel_caller(peer));
1174         ast_channel_unlock(peer);
1175         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1176         if (ast_channel_connected_line_sub(peer, chan, &connected_caller, 0)
1177                 && ast_channel_connected_line_macro(peer, chan, &connected_caller, is_caller, 0)) {
1178                 ast_channel_update_connected_line(chan, &connected_caller, NULL);
1179         }
1180         ast_party_connected_line_free(&connected_caller);
1181 }
1182
1183 /*!
1184  * \internal
1185  * \pre chan is locked
1186  */
1187 static void set_duration_var(struct ast_channel *chan, const char *var_base, int64_t duration)
1188 {
1189         char buf[32];
1190         char full_var_name[128];
1191
1192         snprintf(buf, sizeof(buf), "%" PRId64, duration / 1000);
1193         pbx_builtin_setvar_helper(chan, var_base, buf);
1194
1195         snprintf(full_var_name, sizeof(full_var_name), "%s_MS", var_base);
1196         snprintf(buf, sizeof(buf), "%" PRId64, duration);
1197         pbx_builtin_setvar_helper(chan, full_var_name, buf);
1198 }
1199
1200 static struct ast_channel *wait_for_answer(struct ast_channel *in,
1201         struct dial_head *out_chans, int *to, struct ast_flags64 *peerflags,
1202         char *opt_args[],
1203         struct privacy_args *pa,
1204         const struct cause_args *num_in, int *result, char *dtmf_progress,
1205         const int ignore_cc,
1206         struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
1207 {
1208         struct cause_args num = *num_in;
1209         int prestart = num.busy + num.congestion + num.nochan;
1210         int orig = *to;
1211         struct ast_channel *peer = NULL;
1212         struct chanlist *outgoing = AST_LIST_FIRST(out_chans);
1213         /* single is set if only one destination is enabled */
1214         int single = outgoing && !AST_LIST_NEXT(outgoing, node);
1215         int caller_entertained = outgoing
1216                 && ast_test_flag64(outgoing, OPT_MUSICBACK | OPT_RINGBACK);
1217         struct ast_str *featurecode = ast_str_alloca(AST_FEATURE_MAX_LEN + 1);
1218         int cc_recall_core_id;
1219         int is_cc_recall;
1220         int cc_frame_received = 0;
1221         int num_ringing = 0;
1222         int sent_ring = 0;
1223         int sent_progress = 0;
1224         struct timeval start = ast_tvnow();
1225
1226         if (single) {
1227                 /* Turn off hold music, etc */
1228                 if (!caller_entertained) {
1229                         ast_deactivate_generator(in);
1230                         /* If we are calling a single channel, and not providing ringback or music, */
1231                         /* then, make them compatible for in-band tone purpose */
1232                         if (ast_channel_make_compatible(in, outgoing->chan) < 0) {
1233                                 /* If these channels can not be made compatible,
1234                                  * there is no point in continuing.  The bridge
1235                                  * will just fail if it gets that far.
1236                                  */
1237                                 *to = -1;
1238                                 strcpy(pa->status, "CONGESTION");
1239                                 ast_channel_publish_dial(in, outgoing->chan, NULL, pa->status);
1240                                 return NULL;
1241                         }
1242                 }
1243
1244                 if (!ast_test_flag64(outgoing, OPT_IGNORE_CONNECTEDLINE)
1245                         && !ast_test_flag64(outgoing, DIAL_CALLERID_ABSENT)) {
1246                         update_connected_line_from_peer(in, outgoing->chan, 1);
1247                 }
1248         }
1249
1250         is_cc_recall = ast_cc_is_recall(in, &cc_recall_core_id, NULL);
1251
1252         while ((*to = ast_remaining_ms(start, orig)) && !peer) {
1253                 struct chanlist *o;
1254                 int pos = 0; /* how many channels do we handle */
1255                 int numlines = prestart;
1256                 struct ast_channel *winner;
1257                 struct ast_channel *watchers[AST_MAX_WATCHERS];
1258
1259                 watchers[pos++] = in;
1260                 AST_LIST_TRAVERSE(out_chans, o, node) {
1261                         /* Keep track of important channels */
1262                         if (ast_test_flag64(o, DIAL_STILLGOING) && o->chan)
1263                                 watchers[pos++] = o->chan;
1264                         numlines++;
1265                 }
1266                 if (pos == 1) { /* only the input channel is available */
1267                         if (numlines == (num.busy + num.congestion + num.nochan)) {
1268                                 ast_verb(2, "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
1269                                 if (num.busy)
1270                                         strcpy(pa->status, "BUSY");
1271                                 else if (num.congestion)
1272                                         strcpy(pa->status, "CONGESTION");
1273                                 else if (num.nochan)
1274                                         strcpy(pa->status, "CHANUNAVAIL");
1275                         } else {
1276                                 ast_verb(3, "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
1277                         }
1278                         *to = 0;
1279                         if (is_cc_recall) {
1280                                 ast_cc_failed(cc_recall_core_id, "Everyone is busy/congested for the recall. How sad");
1281                         }
1282                         return NULL;
1283                 }
1284                 winner = ast_waitfor_n(watchers, pos, to);
1285                 AST_LIST_TRAVERSE(out_chans, o, node) {
1286                         struct ast_frame *f;
1287                         struct ast_channel *c = o->chan;
1288
1289                         if (c == NULL)
1290                                 continue;
1291                         if (ast_test_flag64(o, DIAL_STILLGOING) && ast_channel_state(c) == AST_STATE_UP) {
1292                                 if (!peer) {
1293                                         ast_verb(3, "%s answered %s\n", ast_channel_name(c), ast_channel_name(in));
1294                                         if (o->orig_chan_name
1295                                                 && strcmp(o->orig_chan_name, ast_channel_name(c))) {
1296                                                 /*
1297                                                  * The channel name changed so we must generate COLP update.
1298                                                  * Likely because a call pickup channel masqueraded in.
1299                                                  */
1300                                                 update_connected_line_from_peer(in, c, 1);
1301                                         } else if (!single && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1302                                                 if (o->pending_connected_update) {
1303                                                         if (ast_channel_connected_line_sub(c, in, &o->connected, 0) &&
1304                                                                 ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
1305                                                                 ast_channel_update_connected_line(in, &o->connected, NULL);
1306                                                         }
1307                                                 } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1308                                                         update_connected_line_from_peer(in, c, 1);
1309                                                 }
1310                                         }
1311                                         if (o->aoc_s_rate_list) {
1312                                                 size_t encoded_size;
1313                                                 struct ast_aoc_encoded *encoded;
1314                                                 if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
1315                                                         ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
1316                                                         ast_aoc_destroy_encoded(encoded);
1317                                                 }
1318                                         }
1319                                         peer = c;
1320                                         publish_dial_end_event(in, out_chans, peer, "CANCEL");
1321                                         ast_copy_flags64(peerflags, o,
1322                                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1323                                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1324                                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1325                                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
1326                                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1327                                                 DIAL_NOFORWARDHTML);
1328                                         ast_channel_dialcontext_set(c, "");
1329                                         ast_channel_exten_set(c, "");
1330                                 }
1331                                 continue;
1332                         }
1333                         if (c != winner)
1334                                 continue;
1335                         /* here, o->chan == c == winner */
1336                         if (!ast_strlen_zero(ast_channel_call_forward(c))) {
1337                                 pa->sentringing = 0;
1338                                 if (!ignore_cc && (f = ast_read(c))) {
1339                                         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_CC) {
1340                                                 /* This channel is forwarding the call, and is capable of CC, so
1341                                                  * be sure to add the new device interface to the list
1342                                                  */
1343                                                 ast_handle_cc_control_frame(in, c, f->data.ptr);
1344                                         }
1345                                         ast_frfree(f);
1346                                 }
1347
1348                                 if (o->pending_connected_update) {
1349                                         /*
1350                                          * Re-seed the chanlist's connected line information with
1351                                          * previously acquired connected line info from the incoming
1352                                          * channel.  The previously acquired connected line info could
1353                                          * have been set through the CONNECTED_LINE dialplan function.
1354                                          */
1355                                         o->pending_connected_update = 0;
1356                                         ast_channel_lock(in);
1357                                         ast_party_connected_line_copy(&o->connected, ast_channel_connected(in));
1358                                         ast_channel_unlock(in);
1359                                 }
1360
1361                                 do_forward(o, &num, peerflags, single, caller_entertained, &orig,
1362                                         forced_clid, stored_clid);
1363
1364                                 if (o->chan) {
1365                                         ast_free(o->orig_chan_name);
1366                                         o->orig_chan_name = ast_strdup(ast_channel_name(o->chan));
1367                                         if (single
1368                                                 && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)
1369                                                 && !ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1370                                                 update_connected_line_from_peer(in, o->chan, 1);
1371                                         }
1372                                 }
1373                                 continue;
1374                         }
1375                         f = ast_read(winner);
1376                         if (!f) {
1377                                 ast_channel_hangupcause_set(in, ast_channel_hangupcause(c));
1378                                 ast_channel_publish_dial(in, c, NULL, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(c)));
1379                                 ast_hangup(c);
1380                                 c = o->chan = NULL;
1381                                 ast_clear_flag64(o, DIAL_STILLGOING);
1382                                 handle_cause(ast_channel_hangupcause(in), &num);
1383                                 continue;
1384                         }
1385                         switch (f->frametype) {
1386                         case AST_FRAME_CONTROL:
1387                                 switch (f->subclass.integer) {
1388                                 case AST_CONTROL_ANSWER:
1389                                         /* This is our guy if someone answered. */
1390                                         if (!peer) {
1391                                                 ast_verb(3, "%s answered %s\n", ast_channel_name(c), ast_channel_name(in));
1392                                                 if (o->orig_chan_name
1393                                                         && strcmp(o->orig_chan_name, ast_channel_name(c))) {
1394                                                         /*
1395                                                          * The channel name changed so we must generate COLP update.
1396                                                          * Likely because a call pickup channel masqueraded in.
1397                                                          */
1398                                                         update_connected_line_from_peer(in, c, 1);
1399                                                 } else if (!single && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1400                                                         if (o->pending_connected_update) {
1401                                                                 if (ast_channel_connected_line_sub(c, in, &o->connected, 0) &&
1402                                                                         ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
1403                                                                         ast_channel_update_connected_line(in, &o->connected, NULL);
1404                                                                 }
1405                                                         } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1406                                                                 update_connected_line_from_peer(in, c, 1);
1407                                                         }
1408                                                 }
1409                                                 if (o->aoc_s_rate_list) {
1410                                                         size_t encoded_size;
1411                                                         struct ast_aoc_encoded *encoded;
1412                                                         if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
1413                                                                 ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
1414                                                                 ast_aoc_destroy_encoded(encoded);
1415                                                         }
1416                                                 }
1417                                                 peer = c;
1418                                                 /* Inform everyone else that they've been canceled.
1419                                                  * The dial end event for the peer will be sent out after
1420                                                  * other Dial options have been handled.
1421                                                  */
1422                                                 publish_dial_end_event(in, out_chans, peer, "CANCEL");
1423                                                 ast_copy_flags64(peerflags, o,
1424                                                         OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1425                                                         OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1426                                                         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1427                                                         OPT_CALLEE_PARK | OPT_CALLER_PARK |
1428                                                         OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1429                                                         DIAL_NOFORWARDHTML);
1430                                                 ast_channel_dialcontext_set(c, "");
1431                                                 ast_channel_exten_set(c, "");
1432                                                 if (CAN_EARLY_BRIDGE(peerflags, in, peer)) {
1433                                                         /* Setup early bridge if appropriate */
1434                                                         ast_channel_early_bridge(in, peer);
1435                                                 }
1436                                         }
1437                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
1438                                         ast_channel_hangupcause_set(in, AST_CAUSE_NORMAL_CLEARING);
1439                                         ast_channel_hangupcause_set(c, AST_CAUSE_NORMAL_CLEARING);
1440                                         break;
1441                                 case AST_CONTROL_BUSY:
1442                                         ast_verb(3, "%s is busy\n", ast_channel_name(c));
1443                                         ast_channel_hangupcause_set(in, ast_channel_hangupcause(c));
1444                                         ast_channel_publish_dial(in, c, NULL, "BUSY");
1445                                         ast_hangup(c);
1446                                         c = o->chan = NULL;
1447                                         ast_clear_flag64(o, DIAL_STILLGOING);
1448                                         handle_cause(AST_CAUSE_BUSY, &num);
1449                                         break;
1450                                 case AST_CONTROL_CONGESTION:
1451                                         ast_verb(3, "%s is circuit-busy\n", ast_channel_name(c));
1452                                         ast_channel_hangupcause_set(in, ast_channel_hangupcause(c));
1453                                         ast_channel_publish_dial(in, c, NULL, "CONGESTION");
1454                                         ast_hangup(c);
1455                                         c = o->chan = NULL;
1456                                         ast_clear_flag64(o, DIAL_STILLGOING);
1457                                         handle_cause(AST_CAUSE_CONGESTION, &num);
1458                                         break;
1459                                 case AST_CONTROL_RINGING:
1460                                         /* This is a tricky area to get right when using a native
1461                                          * CC agent. The reason is that we do the best we can to send only a
1462                                          * single ringing notification to the caller.
1463                                          *
1464                                          * Call completion complicates the logic used here. CCNR is typically
1465                                          * offered during a ringing message. Let's say that party A calls
1466                                          * parties B, C, and D. B and C do not support CC requests, but D
1467                                          * does. If we were to receive a ringing notification from B before
1468                                          * the others, then we would end up sending a ringing message to
1469                                          * A with no CCNR offer present.
1470                                          *
1471                                          * The approach that we have taken is that if we receive a ringing
1472                                          * response from a party and no CCNR offer is present, we need to
1473                                          * wait. Specifically, we need to wait until either a) a called party
1474                                          * offers CCNR in its ringing response or b) all called parties have
1475                                          * responded in some way to our call and none offers CCNR.
1476                                          *
1477                                          * The drawback to this is that if one of the parties has a delayed
1478                                          * response or, god forbid, one just plain doesn't respond to our
1479                                          * outgoing call, then this will result in a significant delay between
1480                                          * when the caller places the call and hears ringback.
1481                                          *
1482                                          * Note also that if CC is disabled for this call, then it is perfectly
1483                                          * fine for ringing frames to get sent through.
1484                                          */
1485                                         ++num_ringing;
1486                                         if (ignore_cc || cc_frame_received || num_ringing == numlines) {
1487                                                 ast_verb(3, "%s is ringing\n", ast_channel_name(c));
1488                                                 /* Setup early media if appropriate */
1489                                                 if (single && !caller_entertained
1490                                                         && CAN_EARLY_BRIDGE(peerflags, in, c)) {
1491                                                         ast_channel_early_bridge(in, c);
1492                                                 }
1493                                                 if (!(pa->sentringing) && !ast_test_flag64(outgoing, OPT_MUSICBACK) && ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
1494                                                         ast_indicate(in, AST_CONTROL_RINGING);
1495                                                         pa->sentringing++;
1496                                                 }
1497                                                 if (!sent_ring) {
1498                                                         struct timeval now, then;
1499                                                         int64_t diff;
1500
1501                                                         now = ast_tvnow();
1502
1503                                                         ast_channel_lock(in);
1504                                                         ast_channel_stage_snapshot(in);
1505
1506                                                         then = ast_channel_creationtime(c);
1507                                                         diff = ast_tvzero(then) ? 0 : ast_tvdiff_ms(now, then);
1508                                                         set_duration_var(in, "RINGTIME", diff);
1509
1510                                                         ast_channel_stage_snapshot_done(in);
1511                                                         ast_channel_unlock(in);
1512                                                         sent_ring = 1;
1513                                                 }
1514                                         }
1515                                         ast_channel_publish_dial(in, c, NULL, "RINGING");
1516                                         break;
1517                                 case AST_CONTROL_PROGRESS:
1518                                         ast_verb(3, "%s is making progress passing it to %s\n", ast_channel_name(c), ast_channel_name(in));
1519                                         /* Setup early media if appropriate */
1520                                         if (single && !caller_entertained
1521                                                 && CAN_EARLY_BRIDGE(peerflags, in, c)) {
1522                                                 ast_channel_early_bridge(in, c);
1523                                         }
1524                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK)) {
1525                                                 if (single || (!single && !pa->sentringing)) {
1526                                                         ast_indicate(in, AST_CONTROL_PROGRESS);
1527                                                 }
1528                                         }
1529                                         if (!sent_progress) {
1530                                                 struct timeval now, then;
1531                                                 int64_t diff;
1532
1533                                                 now = ast_tvnow();
1534
1535                                                 ast_channel_lock(in);
1536                                                 ast_channel_stage_snapshot(in);
1537
1538                                                 then = ast_channel_creationtime(c);
1539                                                 diff = ast_tvzero(then) ? 0 : ast_tvdiff_ms(now, then);
1540                                                 set_duration_var(in, "PROGRESSTIME", diff);
1541
1542                                                 ast_channel_stage_snapshot_done(in);
1543                                                 ast_channel_unlock(in);
1544                                                 sent_progress = 1;
1545                                         }
1546                                         if (!ast_strlen_zero(dtmf_progress)) {
1547                                                 ast_verb(3,
1548                                                         "Sending DTMF '%s' to the called party as result of receiving a PROGRESS message.\n",
1549                                                         dtmf_progress);
1550                                                 ast_dtmf_stream(c, in, dtmf_progress, 250, 0);
1551                                         }
1552                                         ast_channel_publish_dial(in, c, NULL, "PROGRESS");
1553                                         break;
1554                                 case AST_CONTROL_VIDUPDATE:
1555                                 case AST_CONTROL_SRCUPDATE:
1556                                 case AST_CONTROL_SRCCHANGE:
1557                                         if (!single || caller_entertained) {
1558                                                 break;
1559                                         }
1560                                         ast_verb(3, "%s requested media update control %d, passing it to %s\n",
1561                                                 ast_channel_name(c), f->subclass.integer, ast_channel_name(in));
1562                                         ast_indicate(in, f->subclass.integer);
1563                                         break;
1564                                 case AST_CONTROL_CONNECTED_LINE:
1565                                         if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1566                                                 ast_verb(3, "Connected line update to %s prevented.\n", ast_channel_name(in));
1567                                                 break;
1568                                         }
1569                                         if (!single) {
1570                                                 struct ast_party_connected_line connected;
1571
1572                                                 ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n",
1573                                                         ast_channel_name(c), ast_channel_name(in));
1574                                                 ast_party_connected_line_set_init(&connected, &o->connected);
1575                                                 ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
1576                                                 ast_party_connected_line_set(&o->connected, &connected, NULL);
1577                                                 ast_party_connected_line_free(&connected);
1578                                                 o->pending_connected_update = 1;
1579                                                 break;
1580                                         }
1581                                         if (ast_channel_connected_line_sub(c, in, f, 1) &&
1582                                                 ast_channel_connected_line_macro(c, in, f, 1, 1)) {
1583                                                 ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
1584                                         }
1585                                         break;
1586                                 case AST_CONTROL_AOC:
1587                                         {
1588                                                 struct ast_aoc_decoded *decoded = ast_aoc_decode(f->data.ptr, f->datalen, o->chan);
1589                                                 if (decoded && (ast_aoc_get_msg_type(decoded) == AST_AOC_S)) {
1590                                                         ast_aoc_destroy_decoded(o->aoc_s_rate_list);
1591                                                         o->aoc_s_rate_list = decoded;
1592                                                 } else {
1593                                                         ast_aoc_destroy_decoded(decoded);
1594                                                 }
1595                                         }
1596                                         break;
1597                                 case AST_CONTROL_REDIRECTING:
1598                                         if (!single) {
1599                                                 /*
1600                                                  * Redirecting updates to the caller make sense only on single
1601                                                  * calls.
1602                                                  */
1603                                                 break;
1604                                         }
1605                                         if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1606                                                 ast_verb(3, "Redirecting update to %s prevented.\n", ast_channel_name(in));
1607                                                 break;
1608                                         }
1609                                         ast_verb(3, "%s redirecting info has changed, passing it to %s\n",
1610                                                 ast_channel_name(c), ast_channel_name(in));
1611                                         if (ast_channel_redirecting_sub(c, in, f, 1) &&
1612                                                 ast_channel_redirecting_macro(c, in, f, 1, 1)) {
1613                                                 ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
1614                                         }
1615                                         pa->sentringing = 0;
1616                                         break;
1617                                 case AST_CONTROL_PROCEEDING:
1618                                         ast_verb(3, "%s is proceeding passing it to %s\n", ast_channel_name(c), ast_channel_name(in));
1619                                         if (single && !caller_entertained
1620                                                 && CAN_EARLY_BRIDGE(peerflags, in, c)) {
1621                                                 ast_channel_early_bridge(in, c);
1622                                         }
1623                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
1624                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
1625                                         ast_channel_publish_dial(in, c, NULL, "PROCEEDING");
1626                                         break;
1627                                 case AST_CONTROL_HOLD:
1628                                         /* XXX this should be saved like AST_CONTROL_CONNECTED_LINE for !single || caller_entertained */
1629                                         ast_verb(3, "Call on %s placed on hold\n", ast_channel_name(c));
1630                                         ast_indicate_data(in, AST_CONTROL_HOLD, f->data.ptr, f->datalen);
1631                                         break;
1632                                 case AST_CONTROL_UNHOLD:
1633                                         /* XXX this should be saved like AST_CONTROL_CONNECTED_LINE for !single || caller_entertained */
1634                                         ast_verb(3, "Call on %s left from hold\n", ast_channel_name(c));
1635                                         ast_indicate(in, AST_CONTROL_UNHOLD);
1636                                         break;
1637                                 case AST_CONTROL_OFFHOOK:
1638                                 case AST_CONTROL_FLASH:
1639                                         /* Ignore going off hook and flash */
1640                                         break;
1641                                 case AST_CONTROL_CC:
1642                                         if (!ignore_cc) {
1643                                                 ast_handle_cc_control_frame(in, c, f->data.ptr);
1644                                                 cc_frame_received = 1;
1645                                         }
1646                                         break;
1647                                 case AST_CONTROL_PVT_CAUSE_CODE:
1648                                         ast_indicate_data(in, AST_CONTROL_PVT_CAUSE_CODE, f->data.ptr, f->datalen);
1649                                         break;
1650                                 case -1:
1651                                         if (single && !caller_entertained) {
1652                                                 ast_verb(3, "%s stopped sounds\n", ast_channel_name(c));
1653                                                 ast_indicate(in, -1);
1654                                                 pa->sentringing = 0;
1655                                         }
1656                                         break;
1657                                 default:
1658                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
1659                                         break;
1660                                 }
1661                                 break;
1662                         case AST_FRAME_VIDEO:
1663                         case AST_FRAME_VOICE:
1664                         case AST_FRAME_IMAGE:
1665                                 if (caller_entertained) {
1666                                         break;
1667                                 }
1668                                 /* Fall through */
1669                         case AST_FRAME_TEXT:
1670                                 if (single && ast_write(in, f)) {
1671                                         ast_log(LOG_WARNING, "Unable to write frametype: %u\n",
1672                                                 f->frametype);
1673                                 }
1674                                 break;
1675                         case AST_FRAME_HTML:
1676                                 if (single && !ast_test_flag64(outgoing, DIAL_NOFORWARDHTML)
1677                                         && ast_channel_sendhtml(in, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
1678                                         ast_log(LOG_WARNING, "Unable to send URL\n");
1679                                 }
1680                                 break;
1681                         default:
1682                                 break;
1683                         }
1684                         ast_frfree(f);
1685                 } /* end for */
1686                 if (winner == in) {
1687                         struct ast_frame *f = ast_read(in);
1688 #if 0
1689                         if (f && (f->frametype != AST_FRAME_VOICE))
1690                                 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1691                         else if (!f || (f->frametype != AST_FRAME_VOICE))
1692                                 printf("Hangup received on %s\n", in->name);
1693 #endif
1694                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
1695                                 /* Got hung up */
1696                                 *to = -1;
1697                                 strcpy(pa->status, "CANCEL");
1698                                 publish_dial_end_event(in, out_chans, NULL, pa->status);
1699                                 if (f) {
1700                                         if (f->data.uint32) {
1701                                                 ast_channel_hangupcause_set(in, f->data.uint32);
1702                                         }
1703                                         ast_frfree(f);
1704                                 }
1705                                 if (is_cc_recall) {
1706                                         ast_cc_completed(in, "CC completed, although the caller hung up (cancelled)");
1707                                 }
1708                                 return NULL;
1709                         }
1710
1711                         /* now f is guaranteed non-NULL */
1712                         if (f->frametype == AST_FRAME_DTMF) {
1713                                 if (ast_test_flag64(peerflags, OPT_DTMF_EXIT)) {
1714                                         const char *context;
1715                                         ast_channel_lock(in);
1716                                         context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
1717                                         if (onedigit_goto(in, context, (char) f->subclass.integer, 1)) {
1718                                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
1719                                                 *to = 0;
1720                                                 *result = f->subclass.integer;
1721                                                 strcpy(pa->status, "CANCEL");
1722                                                 publish_dial_end_event(in, out_chans, NULL, pa->status);
1723                                                 ast_frfree(f);
1724                                                 ast_channel_unlock(in);
1725                                                 if (is_cc_recall) {
1726                                                         ast_cc_completed(in, "CC completed, but the caller used DTMF to exit");
1727                                                 }
1728                                                 return NULL;
1729                                         }
1730                                         ast_channel_unlock(in);
1731                                 }
1732
1733                                 if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP) &&
1734                                         detect_disconnect(in, f->subclass.integer, &featurecode)) {
1735                                         ast_verb(3, "User requested call disconnect.\n");
1736                                         *to = 0;
1737                                         strcpy(pa->status, "CANCEL");
1738                                         publish_dial_end_event(in, out_chans, NULL, pa->status);
1739                                         ast_frfree(f);
1740                                         if (is_cc_recall) {
1741                                                 ast_cc_completed(in, "CC completed, but the caller hung up with DTMF");
1742                                         }
1743                                         return NULL;
1744                                 }
1745                         }
1746
1747                         /* Send the frame from the in channel to all outgoing channels. */
1748                         AST_LIST_TRAVERSE(out_chans, o, node) {
1749                                 if (!o->chan || !ast_test_flag64(o, DIAL_STILLGOING)) {
1750                                         /* This outgoing channel has died so don't send the frame to it. */
1751                                         continue;
1752                                 }
1753                                 switch (f->frametype) {
1754                                 case AST_FRAME_HTML:
1755                                         /* Forward HTML stuff */
1756                                         if (!ast_test_flag64(o, DIAL_NOFORWARDHTML)
1757                                                 && ast_channel_sendhtml(o->chan, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
1758                                                 ast_log(LOG_WARNING, "Unable to send URL\n");
1759                                         }
1760                                         break;
1761                                 case AST_FRAME_VIDEO:
1762                                 case AST_FRAME_VOICE:
1763                                 case AST_FRAME_IMAGE:
1764                                         if (!single || caller_entertained) {
1765                                                 /*
1766                                                  * We are calling multiple parties or caller is being
1767                                                  * entertained and has thus not been made compatible.
1768                                                  * No need to check any other called parties.
1769                                                  */
1770                                                 goto skip_frame;
1771                                         }
1772                                         /* Fall through */
1773                                 case AST_FRAME_TEXT:
1774                                 case AST_FRAME_DTMF_BEGIN:
1775                                 case AST_FRAME_DTMF_END:
1776                                         if (ast_write(o->chan, f)) {
1777                                                 ast_log(LOG_WARNING, "Unable to forward frametype: %u\n",
1778                                                         f->frametype);
1779                                         }
1780                                         break;
1781                                 case AST_FRAME_CONTROL:
1782                                         switch (f->subclass.integer) {
1783                                         case AST_CONTROL_HOLD:
1784                                                 ast_verb(3, "Call on %s placed on hold\n", ast_channel_name(o->chan));
1785                                                 ast_indicate_data(o->chan, AST_CONTROL_HOLD, f->data.ptr, f->datalen);
1786                                                 break;
1787                                         case AST_CONTROL_UNHOLD:
1788                                                 ast_verb(3, "Call on %s left from hold\n", ast_channel_name(o->chan));
1789                                                 ast_indicate(o->chan, AST_CONTROL_UNHOLD);
1790                                                 break;
1791                                         case AST_CONTROL_VIDUPDATE:
1792                                         case AST_CONTROL_SRCUPDATE:
1793                                         case AST_CONTROL_SRCCHANGE:
1794                                                 if (!single || caller_entertained) {
1795                                                         /*
1796                                                          * We are calling multiple parties or caller is being
1797                                                          * entertained and has thus not been made compatible.
1798                                                          * No need to check any other called parties.
1799                                                          */
1800                                                         goto skip_frame;
1801                                                 }
1802                                                 ast_verb(3, "%s requested media update control %d, passing it to %s\n",
1803                                                         ast_channel_name(in), f->subclass.integer, ast_channel_name(o->chan));
1804                                                 ast_indicate(o->chan, f->subclass.integer);
1805                                                 break;
1806                                         case AST_CONTROL_CONNECTED_LINE:
1807                                                 if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1808                                                         ast_verb(3, "Connected line update to %s prevented.\n", ast_channel_name(o->chan));
1809                                                         break;
1810                                                 }
1811                                                 if (ast_channel_connected_line_sub(in, o->chan, f, 1) &&
1812                                                         ast_channel_connected_line_macro(in, o->chan, f, 0, 1)) {
1813                                                         ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
1814                                                 }
1815                                                 break;
1816                                         case AST_CONTROL_REDIRECTING:
1817                                                 if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1818                                                         ast_verb(3, "Redirecting update to %s prevented.\n", ast_channel_name(o->chan));
1819                                                         break;
1820                                                 }
1821                                                 if (ast_channel_redirecting_sub(in, o->chan, f, 1) &&
1822                                                         ast_channel_redirecting_macro(in, o->chan, f, 0, 1)) {
1823                                                         ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
1824                                                 }
1825                                                 break;
1826                                         default:
1827                                                 /* We are not going to do anything with this frame. */
1828                                                 goto skip_frame;
1829                                         }
1830                                         break;
1831                                 default:
1832                                         /* We are not going to do anything with this frame. */
1833                                         goto skip_frame;
1834                                 }
1835                         }
1836 skip_frame:;
1837                         ast_frfree(f);
1838                 }
1839         }
1840
1841         if (!*to || ast_check_hangup(in)) {
1842                 ast_verb(3, "Nobody picked up in %d ms\n", orig);
1843                 publish_dial_end_event(in, out_chans, NULL, "NOANSWER");
1844         }
1845
1846         if (is_cc_recall) {
1847                 ast_cc_completed(in, "Recall completed!");
1848         }
1849         return peer;
1850 }
1851
1852 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str **featurecode)
1853 {
1854         char disconnect_code[AST_FEATURE_MAX_LEN];
1855         int res;
1856
1857         ast_str_append(featurecode, 1, "%c", code);
1858
1859         res = ast_get_builtin_feature(chan, "disconnect", disconnect_code, sizeof(disconnect_code));
1860         if (res) {
1861                 ast_str_reset(*featurecode);
1862                 return 0;
1863         }
1864
1865         if (strlen(disconnect_code) > ast_str_strlen(*featurecode)) {
1866                 /* Could be a partial match, anyway */
1867                 if (strncmp(disconnect_code, ast_str_buffer(*featurecode), ast_str_strlen(*featurecode))) {
1868                         ast_str_reset(*featurecode);
1869                 }
1870                 return 0;
1871         }
1872
1873         if (strcmp(disconnect_code, ast_str_buffer(*featurecode))) {
1874                 ast_str_reset(*featurecode);
1875                 return 0;
1876         }
1877
1878         return 1;
1879 }
1880
1881 /* returns true if there is a valid privacy reply */
1882 static int valid_priv_reply(struct ast_flags64 *opts, int res)
1883 {
1884         if (res < '1')
1885                 return 0;
1886         if (ast_test_flag64(opts, OPT_PRIVACY) && res <= '5')
1887                 return 1;
1888         if (ast_test_flag64(opts, OPT_SCREENING) && res <= '4')
1889                 return 1;
1890         return 0;
1891 }
1892
1893 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
1894         struct ast_flags64 *opts, char **opt_args, struct privacy_args *pa)
1895 {
1896
1897         int res2;
1898         int loopcount = 0;
1899
1900         /* Get the user's intro, store it in priv-callerintros/$CID,
1901            unless it is already there-- this should be done before the
1902            call is actually dialed  */
1903
1904         /* all ring indications and moh for the caller has been halted as soon as the
1905            target extension was picked up. We are going to have to kill some
1906            time and make the caller believe the peer hasn't picked up yet */
1907
1908         if (ast_test_flag64(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1909                 char *original_moh = ast_strdupa(ast_channel_musicclass(chan));
1910                 ast_indicate(chan, -1);
1911                 ast_channel_musicclass_set(chan, opt_args[OPT_ARG_MUSICBACK]);
1912                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1913                 ast_channel_musicclass_set(chan, original_moh);
1914         } else if (ast_test_flag64(opts, OPT_RINGBACK) || ast_test_flag64(opts, OPT_RING_WITH_EARLY_MEDIA)) {
1915                 ast_indicate(chan, AST_CONTROL_RINGING);
1916                 pa->sentringing++;
1917         }
1918
1919         /* Start autoservice on the other chan ?? */
1920         res2 = ast_autoservice_start(chan);
1921         /* Now Stream the File */
1922         for (loopcount = 0; loopcount < 3; loopcount++) {
1923                 if (res2 && loopcount == 0) /* error in ast_autoservice_start() */
1924                         break;
1925                 if (!res2) /* on timeout, play the message again */
1926                         res2 = ast_play_and_wait(peer, "priv-callpending");
1927                 if (!valid_priv_reply(opts, res2))
1928                         res2 = 0;
1929                 /* priv-callpending script:
1930                    "I have a caller waiting, who introduces themselves as:"
1931                 */
1932                 if (!res2)
1933                         res2 = ast_play_and_wait(peer, pa->privintro);
1934                 if (!valid_priv_reply(opts, res2))
1935                         res2 = 0;
1936                 /* now get input from the called party, as to their choice */
1937                 if (!res2) {
1938                         /* XXX can we have both, or they are mutually exclusive ? */
1939                         if (ast_test_flag64(opts, OPT_PRIVACY))
1940                                 res2 = ast_play_and_wait(peer, "priv-callee-options");
1941                         if (ast_test_flag64(opts, OPT_SCREENING))
1942                                 res2 = ast_play_and_wait(peer, "screen-callee-options");
1943                 }
1944
1945                 /*! \page DialPrivacy Dial Privacy scripts
1946                  * \par priv-callee-options script:
1947                  * \li Dial 1 if you wish this caller to reach you directly in the future,
1948                  *      and immediately connect to their incoming call.
1949                  * \li Dial 2 if you wish to send this caller to voicemail now and forevermore.
1950                  * \li Dial 3 to send this caller to the torture menus, now and forevermore.
1951                  * \li Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1952                  * \li Dial 5 to allow this caller to come straight thru to you in the future,
1953                  *      but right now, just this once, send them to voicemail.
1954                  *
1955                  * \par screen-callee-options script:
1956                  * \li Dial 1 if you wish to immediately connect to the incoming call
1957                  * \li Dial 2 if you wish to send this caller to voicemail.
1958                  * \li Dial 3 to send this caller to the torture menus.
1959                  * \li Dial 4 to send this caller to a simple "go away" menu.
1960                  */
1961                 if (valid_priv_reply(opts, res2))
1962                         break;
1963                 /* invalid option */
1964                 res2 = ast_play_and_wait(peer, "vm-sorry");
1965         }
1966
1967         if (ast_test_flag64(opts, OPT_MUSICBACK)) {
1968                 ast_moh_stop(chan);
1969         } else if (ast_test_flag64(opts, OPT_RINGBACK) || ast_test_flag64(opts, OPT_RING_WITH_EARLY_MEDIA)) {
1970                 ast_indicate(chan, -1);
1971                 pa->sentringing = 0;
1972         }
1973         ast_autoservice_stop(chan);
1974         if (ast_test_flag64(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
1975                 /* map keypresses to various things, the index is res2 - '1' */
1976                 static const char * const _val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
1977                 static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
1978                 int i = res2 - '1';
1979                 ast_verb(3, "--Set privacy database entry %s/%s to %s\n",
1980                         opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
1981                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
1982         }
1983         switch (res2) {
1984         case '1':
1985                 break;
1986         case '2':
1987                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1988                 break;
1989         case '3':
1990                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1991                 break;
1992         case '4':
1993                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1994                 break;
1995         case '5':
1996                 if (ast_test_flag64(opts, OPT_PRIVACY)) {
1997                         ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1998                         break;
1999                 }
2000                 /* if not privacy, then 5 is the same as "default" case */
2001         default: /* bad input or -1 if failure to start autoservice */
2002                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
2003                 /* well, there seems basically two choices. Just patch the caller thru immediately,
2004                           or,... put 'em thru to voicemail. */
2005                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
2006                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
2007                 /* XXX should we set status to DENY ? */
2008                 /* XXX what about the privacy flags ? */
2009                 break;
2010         }
2011
2012         if (res2 == '1') { /* the only case where we actually connect */
2013                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll
2014                    just clog things up, and it's not useful information, not being tied to a CID */
2015                 if (strncmp(pa->privcid, "NOCALLERID", 10) == 0 || ast_test_flag64(opts, OPT_SCREEN_NOINTRO)) {
2016                         ast_filedelete(pa->privintro, NULL);
2017                         if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
2018                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
2019                         else
2020                                 ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
2021                 }
2022                 return 0; /* the good exit path */
2023         } else {
2024                 return -1;
2025         }
2026 }
2027
2028 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
2029 static int setup_privacy_args(struct privacy_args *pa,
2030         struct ast_flags64 *opts, char *opt_args[], struct ast_channel *chan)
2031 {
2032         char callerid[60];
2033         int res;
2034         char *l;
2035
2036         if (ast_channel_caller(chan)->id.number.valid
2037                 && !ast_strlen_zero(ast_channel_caller(chan)->id.number.str)) {
2038                 l = ast_strdupa(ast_channel_caller(chan)->id.number.str);
2039                 ast_shrink_phone_number(l);
2040                 if (ast_test_flag64(opts, OPT_PRIVACY) ) {
2041                         ast_verb(3, "Privacy DB is '%s', clid is '%s'\n", opt_args[OPT_ARG_PRIVACY], l);
2042                         pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
2043                 } else {
2044                         ast_verb(3, "Privacy Screening, clid is '%s'\n", l);
2045                         pa->privdb_val = AST_PRIVACY_UNKNOWN;
2046                 }
2047         } else {
2048                 char *tnam, *tn2;
2049
2050                 tnam = ast_strdupa(ast_channel_name(chan));
2051                 /* clean the channel name so slashes don't try to end up in disk file name */
2052                 for (tn2 = tnam; *tn2; tn2++) {
2053                         if (*tn2 == '/')  /* any other chars to be afraid of? */
2054                                 *tn2 = '=';
2055                 }
2056                 ast_verb(3, "Privacy-- callerid is empty\n");
2057
2058                 snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", ast_channel_exten(chan), tnam);
2059                 l = callerid;
2060                 pa->privdb_val = AST_PRIVACY_UNKNOWN;
2061         }
2062
2063         ast_copy_string(pa->privcid, l, sizeof(pa->privcid));
2064
2065         if (strncmp(pa->privcid, "NOCALLERID", 10) != 0 && ast_test_flag64(opts, OPT_SCREEN_NOCALLERID)) {
2066                 /* if callerid is set and OPT_SCREEN_NOCALLERID is set also */
2067                 ast_verb(3, "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
2068                 pa->privdb_val = AST_PRIVACY_ALLOW;
2069         } else if (ast_test_flag64(opts, OPT_SCREEN_NOCALLERID) && strncmp(pa->privcid, "NOCALLERID", 10) == 0) {
2070                 ast_verb(3, "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
2071         }
2072
2073         if (pa->privdb_val == AST_PRIVACY_DENY) {
2074                 ast_verb(3, "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
2075                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
2076                 return 0;
2077         } else if (pa->privdb_val == AST_PRIVACY_KILL) {
2078                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
2079                 return 0; /* Is this right? */
2080         } else if (pa->privdb_val == AST_PRIVACY_TORTURE) {
2081                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
2082                 return 0; /* is this right??? */
2083         } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN) {
2084                 /* Get the user's intro, store it in priv-callerintros/$CID,
2085                    unless it is already there-- this should be done before the
2086                    call is actually dialed  */
2087
2088                 /* make sure the priv-callerintros dir actually exists */
2089                 snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
2090                 if ((res = ast_mkdir(pa->privintro, 0755))) {
2091                         ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(res));
2092                         return -1;
2093                 }
2094
2095                 snprintf(pa->privintro, sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
2096                 if (ast_fileexists(pa->privintro, NULL, NULL ) > 0 && strncmp(pa->privcid, "NOCALLERID", 10) != 0) {
2097                         /* the DELUX version of this code would allow this caller the
2098                            option to hear and retape their previously recorded intro.
2099                         */
2100                 } else {
2101                         int duration; /* for feedback from play_and_wait */
2102                         /* the file doesn't exist yet. Let the caller submit his
2103                            vocal intro for posterity */
2104                         /* priv-recordintro script:
2105
2106                            "At the tone, please say your name:"
2107
2108                         */
2109                         int silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
2110                         ast_answer(chan);
2111                         res = ast_play_and_record(chan, "priv-recordintro", pa->privintro, 4, "sln", &duration, NULL, silencethreshold, 2000, 0);  /* NOTE: I've reduced the total time to 4 sec */
2112                                                                         /* don't think we'll need a lock removed, we took care of
2113                                                                            conflicts by naming the pa.privintro file */
2114                         if (res == -1) {
2115                                 /* Delete the file regardless since they hung up during recording */
2116                                 ast_filedelete(pa->privintro, NULL);
2117                                 if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
2118                                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
2119                                 else
2120                                         ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
2121                                 return -1;
2122                         }
2123                         if (!ast_streamfile(chan, "vm-dialout", ast_channel_language(chan)) )
2124                                 ast_waitstream(chan, "");
2125                 }
2126         }
2127         return 1; /* success */
2128 }
2129
2130 static void end_bridge_callback(void *data)
2131 {
2132         struct ast_channel *chan = data;
2133
2134         ast_channel_lock(chan);
2135         ast_channel_stage_snapshot(chan);
2136         set_duration_var(chan, "ANSWEREDTIME", ast_channel_get_up_time_ms(chan));
2137         set_duration_var(chan, "DIALEDTIME", ast_channel_get_duration_ms(chan));
2138         ast_channel_stage_snapshot_done(chan);
2139         ast_channel_unlock(chan);
2140 }
2141
2142 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator) {
2143         bconfig->end_bridge_callback_data = originator;
2144 }
2145
2146 static int dial_handle_playtones(struct ast_channel *chan, const char *data)
2147 {
2148         struct ast_tone_zone_sound *ts = NULL;
2149         int res;
2150         const char *str = data;
2151
2152         if (ast_strlen_zero(str)) {
2153                 ast_debug(1,"Nothing to play\n");
2154                 return -1;
2155         }
2156
2157         ts = ast_get_indication_tone(ast_channel_zone(chan), str);
2158
2159         if (ts && ts->data[0]) {
2160                 res = ast_playtones_start(chan, 0, ts->data, 0);
2161         } else {
2162                 res = -1;
2163         }
2164
2165         if (ts) {
2166                 ts = ast_tone_zone_sound_unref(ts);
2167         }
2168
2169         if (res) {
2170                 ast_log(LOG_WARNING, "Unable to start playtone \'%s\'\n", str);
2171         }
2172
2173         return res;
2174 }
2175
2176 /*!
2177  * \internal
2178  * \brief Setup the after bridge goto location on the peer.
2179  * \since 12.0.0
2180  *
2181  * \param chan Calling channel for bridge.
2182  * \param peer Peer channel for bridge.
2183  * \param opts Dialing option flags.
2184  * \param opt_args Dialing option argument strings.
2185  *
2186  * \return Nothing
2187  */
2188 static void setup_peer_after_bridge_goto(struct ast_channel *chan, struct ast_channel *peer, struct ast_flags64 *opts, char *opt_args[])
2189 {
2190         const char *context;
2191         const char *extension;
2192         int priority;
2193
2194         if (ast_test_flag64(opts, OPT_PEER_H)) {
2195                 ast_channel_lock(chan);
2196                 context = ast_strdupa(ast_channel_context(chan));
2197                 ast_channel_unlock(chan);
2198                 ast_bridge_set_after_h(peer, context);
2199         } else if (ast_test_flag64(opts, OPT_CALLEE_GO_ON)) {
2200                 ast_channel_lock(chan);
2201                 context = ast_strdupa(ast_channel_context(chan));
2202                 extension = ast_strdupa(ast_channel_exten(chan));
2203                 priority = ast_channel_priority(chan);
2204                 ast_channel_unlock(chan);
2205                 ast_bridge_set_after_go_on(peer, context, extension, priority,
2206                         opt_args[OPT_ARG_CALLEE_GO_ON]);
2207         }
2208 }
2209
2210 static int dial_exec_full(struct ast_channel *chan, const char *data, struct ast_flags64 *peerflags, int *continue_exec)
2211 {
2212         int res = -1; /* default: error */
2213         char *rest, *cur; /* scan the list of destinations */
2214         struct dial_head out_chans = AST_LIST_HEAD_NOLOCK_INIT_VALUE; /* list of destinations */
2215         struct chanlist *outgoing;
2216         struct chanlist *tmp;
2217         struct ast_channel *peer;
2218         int to; /* timeout */
2219         struct cause_args num = { chan, 0, 0, 0 };
2220         int cause;
2221
2222         struct ast_bridge_config config = { { 0, } };
2223         struct timeval calldurationlimit = { 0, };
2224         char *dtmfcalled = NULL, *dtmfcalling = NULL, *dtmf_progress=NULL;
2225         struct privacy_args pa = {
2226                 .sentringing = 0,
2227                 .privdb_val = 0,
2228                 .status = "INVALIDARGS",
2229         };
2230         int sentringing = 0, moh = 0;
2231         const char *outbound_group = NULL;
2232         int result = 0;
2233         char *parse;
2234         int opermode = 0;
2235         int delprivintro = 0;
2236         AST_DECLARE_APP_ARGS(args,
2237                 AST_APP_ARG(peers);
2238                 AST_APP_ARG(timeout);
2239                 AST_APP_ARG(options);
2240                 AST_APP_ARG(url);
2241         );
2242         struct ast_flags64 opts = { 0, };
2243         char *opt_args[OPT_ARG_ARRAY_SIZE];
2244         int fulldial = 0, num_dialed = 0;
2245         int ignore_cc = 0;
2246         char device_name[AST_CHANNEL_NAME];
2247         char forced_clid_name[AST_MAX_EXTENSION];
2248         char stored_clid_name[AST_MAX_EXTENSION];
2249         int force_forwards_only;        /*!< TRUE if force CallerID on call forward only. Legacy behaviour.*/
2250         /*!
2251          * \brief Forced CallerID party information to send.
2252          * \note This will not have any malloced strings so do not free it.
2253          */
2254         struct ast_party_id forced_clid;
2255         /*!
2256          * \brief Stored CallerID information if needed.
2257          *
2258          * \note If OPT_ORIGINAL_CLID set then this is the o option
2259          * CallerID.  Otherwise it is the dialplan extension and hint
2260          * name.
2261          *
2262          * \note This will not have any malloced strings so do not free it.
2263          */
2264         struct ast_party_id stored_clid;
2265         /*!
2266          * \brief CallerID party information to store.
2267          * \note This will not have any malloced strings so do not free it.
2268          */
2269         struct ast_party_caller caller;
2270         int max_forwards;
2271
2272         /* Reset all DIAL variables back to blank, to prevent confusion (in case we don't reset all of them). */
2273         ast_channel_lock(chan);
2274         ast_channel_stage_snapshot(chan);
2275         pbx_builtin_setvar_helper(chan, "DIALSTATUS", "");
2276         pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", "");
2277         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", "");
2278         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", "");
2279         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME_MS", "");
2280         pbx_builtin_setvar_helper(chan, "DIALEDTIME", "");
2281         pbx_builtin_setvar_helper(chan, "DIALEDTIME_MS", "");
2282         pbx_builtin_setvar_helper(chan, "RINGTIME", "");
2283         pbx_builtin_setvar_helper(chan, "RINGTIME_MS", "");
2284         pbx_builtin_setvar_helper(chan, "PROGRESSTIME", "");
2285         pbx_builtin_setvar_helper(chan, "PROGRESSTIME_MS", "");
2286         ast_channel_stage_snapshot_done(chan);
2287         max_forwards = ast_max_forwards_get(chan);
2288         ast_channel_unlock(chan);
2289
2290         if (max_forwards <= 0) {
2291                 ast_log(LOG_WARNING, "Cannot place outbound call from channel '%s'. Max forwards exceeded\n",
2292                                 ast_channel_name(chan));
2293                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", "BUSY");
2294                 return -1;
2295         }
2296
2297         if (ast_strlen_zero(data)) {
2298                 ast_log(LOG_WARNING, "Dial requires an argument (technology/resource)\n");
2299                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2300                 return -1;
2301         }
2302
2303         if (ast_check_hangup_locked(chan)) {
2304                 /*
2305                  * Caller hung up before we could dial.  If dial is executed
2306                  * within an AGI then the AGI has likely eaten all queued
2307                  * frames before executing the dial in DeadAGI mode.  With
2308                  * the caller hung up and no pending frames from the caller's
2309                  * read queue, dial would not know that the call has hung up
2310                  * until a called channel answers.  It is rather annoying to
2311                  * whoever just answered the non-existent call.
2312                  *
2313                  * Dial should not continue execution in DeadAGI mode, hangup
2314                  * handlers, or the h exten.
2315                  */
2316                 ast_verb(3, "Caller hung up before dial.\n");
2317                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", "CANCEL");
2318                 return -1;
2319         }
2320
2321         parse = ast_strdupa(data);
2322
2323         AST_STANDARD_APP_ARGS(args, parse);
2324
2325         if (!ast_strlen_zero(args.options) &&
2326                 ast_app_parse_options64(dial_exec_options, &opts, opt_args, args.options)) {
2327                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2328                 goto done;
2329         }
2330
2331         if (ast_strlen_zero(args.peers)) {
2332                 ast_log(LOG_WARNING, "Dial requires an argument (technology/resource)\n");
2333                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2334                 goto done;
2335         }
2336
2337         if (ast_cc_call_init(chan, &ignore_cc)) {
2338                 goto done;
2339         }
2340
2341         if (ast_test_flag64(&opts, OPT_SCREEN_NOINTRO) && !ast_strlen_zero(opt_args[OPT_ARG_SCREEN_NOINTRO])) {
2342                 delprivintro = atoi(opt_args[OPT_ARG_SCREEN_NOINTRO]);
2343
2344                 if (delprivintro < 0 || delprivintro > 1) {
2345                         ast_log(LOG_WARNING, "Unknown argument %d specified to n option, ignoring\n", delprivintro);
2346                         delprivintro = 0;
2347                 }
2348         }
2349
2350         if (!ast_test_flag64(&opts, OPT_RINGBACK)) {
2351                 opt_args[OPT_ARG_RINGBACK] = NULL;
2352         }
2353
2354         if (ast_test_flag64(&opts, OPT_OPERMODE)) {
2355                 opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
2356                 ast_verb(3, "Setting operator services mode to %d.\n", opermode);
2357         }
2358
2359         if (ast_test_flag64(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
2360                 calldurationlimit.tv_sec = atoi(opt_args[OPT_ARG_DURATION_STOP]);
2361                 if (!calldurationlimit.tv_sec) {
2362                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
2363                         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2364                         goto done;
2365                 }
2366                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n", calldurationlimit.tv_sec + calldurationlimit.tv_usec / 1000000.0);
2367         }
2368
2369         if (ast_test_flag64(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
2370                 dtmf_progress = opt_args[OPT_ARG_SENDDTMF];
2371                 dtmfcalled = strsep(&dtmf_progress, ":");
2372                 dtmfcalling = strsep(&dtmf_progress, ":");
2373         }
2374
2375         if (ast_test_flag64(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
2376                 if (ast_bridge_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
2377                         goto done;
2378         }
2379
2380         /* Setup the forced CallerID information to send if used. */
2381         ast_party_id_init(&forced_clid);
2382         force_forwards_only = 0;
2383         if (ast_test_flag64(&opts, OPT_FORCECLID)) {
2384                 if (ast_strlen_zero(opt_args[OPT_ARG_FORCECLID])) {
2385                         ast_channel_lock(chan);
2386                         forced_clid.number.str = ast_strdupa(S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan)));
2387                         ast_channel_unlock(chan);
2388                         forced_clid_name[0] = '\0';
2389                         forced_clid.name.str = (char *) get_cid_name(forced_clid_name,
2390                                 sizeof(forced_clid_name), chan);
2391                         force_forwards_only = 1;
2392                 } else {
2393                         /* Note: The opt_args[OPT_ARG_FORCECLID] string value is altered here. */
2394                         ast_callerid_parse(opt_args[OPT_ARG_FORCECLID], &forced_clid.name.str,
2395                                 &forced_clid.number.str);
2396                 }
2397                 if (!ast_strlen_zero(forced_clid.name.str)) {
2398                         forced_clid.name.valid = 1;
2399                 }
2400                 if (!ast_strlen_zero(forced_clid.number.str)) {
2401                         forced_clid.number.valid = 1;
2402                 }
2403         }
2404         if (ast_test_flag64(&opts, OPT_FORCE_CID_TAG)
2405                 && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_TAG])) {
2406                 forced_clid.tag = opt_args[OPT_ARG_FORCE_CID_TAG];
2407         }
2408         forced_clid.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
2409         if (ast_test_flag64(&opts, OPT_FORCE_CID_PRES)
2410                 && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_PRES])) {
2411                 int pres;
2412
2413                 pres = ast_parse_caller_presentation(opt_args[OPT_ARG_FORCE_CID_PRES]);
2414                 if (0 <= pres) {
2415                         forced_clid.number.presentation = pres;
2416                 }
2417         }
2418
2419         /* Setup the stored CallerID information if needed. */
2420         ast_party_id_init(&stored_clid);
2421         if (ast_test_flag64(&opts, OPT_ORIGINAL_CLID)) {
2422                 if (ast_strlen_zero(opt_args[OPT_ARG_ORIGINAL_CLID])) {
2423                         ast_channel_lock(chan);
2424                         ast_party_id_set_init(&stored_clid, &ast_channel_caller(chan)->id);
2425                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.name.str)) {
2426                                 stored_clid.name.str = ast_strdupa(ast_channel_caller(chan)->id.name.str);
2427                         }
2428                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.number.str)) {
2429                                 stored_clid.number.str = ast_strdupa(ast_channel_caller(chan)->id.number.str);
2430                         }
2431                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.subaddress.str)) {
2432                                 stored_clid.subaddress.str = ast_strdupa(ast_channel_caller(chan)->id.subaddress.str);
2433                         }
2434                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.tag)) {
2435                                 stored_clid.tag = ast_strdupa(ast_channel_caller(chan)->id.tag);
2436                         }
2437                         ast_channel_unlock(chan);
2438                 } else {
2439                         /* Note: The opt_args[OPT_ARG_ORIGINAL_CLID] string value is altered here. */
2440                         ast_callerid_parse(opt_args[OPT_ARG_ORIGINAL_CLID], &stored_clid.name.str,
2441                                 &stored_clid.number.str);
2442                         if (!ast_strlen_zero(stored_clid.name.str)) {
2443                                 stored_clid.name.valid = 1;
2444                         }
2445                         if (!ast_strlen_zero(stored_clid.number.str)) {
2446                                 stored_clid.number.valid = 1;
2447                         }
2448                 }
2449         } else {
2450                 /*
2451                  * In case the new channel has no preset CallerID number by the
2452                  * channel driver, setup the dialplan extension and hint name.
2453                  */
2454                 stored_clid_name[0] = '\0';
2455                 stored_clid.name.str = (char *) get_cid_name(stored_clid_name,
2456                         sizeof(stored_clid_name), chan);
2457                 if (ast_strlen_zero(stored_clid.name.str)) {
2458                         stored_clid.name.str = NULL;
2459                 } else {
2460                         stored_clid.name.valid = 1;
2461                 }
2462                 ast_channel_lock(chan);
2463                 stored_clid.number.str = ast_strdupa(S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan)));
2464                 stored_clid.number.valid = 1;
2465                 ast_channel_unlock(chan);
2466         }
2467
2468         if (ast_test_flag64(&opts, OPT_RESETCDR)) {
2469                 ast_cdr_reset(ast_channel_name(chan), 0);
2470         }
2471         if (ast_test_flag64(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
2472                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(ast_channel_exten(chan));
2473
2474         if (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) {
2475                 res = setup_privacy_args(&pa, &opts, opt_args, chan);
2476                 if (res <= 0)
2477                         goto out;
2478                 res = -1; /* reset default */
2479         }
2480
2481         if (continue_exec)
2482                 *continue_exec = 0;
2483
2484         /* If a channel group has been specified, get it for use when we create peer channels */
2485
2486         ast_channel_lock(chan);
2487         if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
2488                 outbound_group = ast_strdupa(outbound_group);
2489                 pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
2490         } else if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP"))) {
2491                 outbound_group = ast_strdupa(outbound_group);
2492         }
2493         ast_channel_unlock(chan);
2494
2495         /* Set per dial instance flags.  These flags are also passed back to RetryDial. */
2496         ast_copy_flags64(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID
2497                 | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING | OPT_CANCEL_TIMEOUT
2498                 | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB | OPT_FORCECLID);
2499
2500         /* PREDIAL: Run gosub on the caller's channel */
2501         if (ast_test_flag64(&opts, OPT_PREDIAL_CALLER)
2502                 && !ast_strlen_zero(opt_args[OPT_ARG_PREDIAL_CALLER])) {
2503                 ast_replace_subargument_delimiter(opt_args[OPT_ARG_PREDIAL_CALLER]);
2504                 ast_app_exec_sub(NULL, chan, opt_args[OPT_ARG_PREDIAL_CALLER], 0);
2505         }
2506
2507         /* loop through the list of dial destinations */
2508         rest = args.peers;
2509         while ((cur = strsep(&rest, "&")) ) {
2510                 struct ast_channel *tc; /* channel for this destination */
2511                 /* Get a technology/resource pair */
2512                 char *number = cur;
2513                 char *tech = strsep(&number, "/");
2514                 size_t tech_len;
2515                 size_t number_len;
2516                 struct ast_stream_topology *topology;
2517
2518                 num_dialed++;
2519                 if (ast_strlen_zero(number)) {
2520                         ast_log(LOG_WARNING, "Dial argument takes format (technology/resource)\n");
2521                         goto out;
2522                 }
2523
2524                 tech_len = strlen(tech) + 1;
2525                 number_len = strlen(number) + 1;
2526                 tmp = ast_calloc(1, sizeof(*tmp) + (2 * tech_len) + number_len);
2527                 if (!tmp) {
2528                         goto out;
2529                 }
2530
2531                 /* Save tech, number, and interface. */
2532                 cur = tmp->stuff;
2533                 strcpy(cur, tech);
2534                 tmp->tech = cur;
2535                 cur += tech_len;
2536                 strcpy(cur, tech);
2537                 cur[tech_len - 1] = '/';
2538                 tmp->interface = cur;
2539                 cur += tech_len;
2540                 strcpy(cur, number);
2541                 tmp->number = cur;
2542
2543                 if (opts.flags) {
2544                         /* Set per outgoing call leg options. */
2545                         ast_copy_flags64(tmp, &opts,
2546                                 OPT_CANCEL_ELSEWHERE |
2547                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
2548                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
2549                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
2550                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
2551                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
2552                                 OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID | OPT_IGNORE_CONNECTEDLINE |
2553                                 OPT_RING_WITH_EARLY_MEDIA);
2554                         ast_set2_flag64(tmp, args.url, DIAL_NOFORWARDHTML);
2555                 }
2556
2557                 /* Request the peer */
2558
2559                 ast_channel_lock(chan);
2560                 /*
2561                  * Seed the chanlist's connected line information with previously
2562                  * acquired connected line info from the incoming channel.  The
2563                  * previously acquired connected line info could have been set
2564                  * through the CONNECTED_LINE dialplan function.
2565                  */
2566                 ast_party_connected_line_copy(&tmp->connected, ast_channel_connected(chan));
2567
2568                 topology = ast_stream_topology_clone(ast_channel_get_stream_topology(chan));
2569
2570                 ast_channel_unlock(chan);
2571
2572                 tc = ast_request_with_stream_topology(tmp->tech, topology, NULL, chan, tmp->number, &cause);
2573
2574                 ast_stream_topology_free(topology);
2575
2576                 if (!tc) {
2577                         /* If we can't, just go on to the next call */
2578                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
2579                                 tmp->tech, cause, ast_cause2str(cause));
2580                         handle_cause(cause, &num);
2581                         if (!rest) {
2582                                 /* we are on the last destination */
2583                                 ast_channel_hangupcause_set(chan, cause);
2584                         }
2585                         if (!ignore_cc && (cause == AST_CAUSE_BUSY || cause == AST_CAUSE_CONGESTION)) {
2586                                 if (!ast_cc_callback(chan, tmp->tech, tmp->number, ast_cc_busy_interface)) {
2587                                         ast_cc_extension_monitor_add_dialstring(chan, tmp->interface, "");
2588                                 }
2589                         }
2590                         chanlist_free(tmp);
2591                         continue;
2592                 }
2593
2594                 ast_channel_get_device_name(tc, device_name, sizeof(device_name));
2595                 if (!ignore_cc) {
2596                         ast_cc_extension_monitor_add_dialstring(chan, tmp->interface, device_name);
2597                 }
2598
2599                 ast_channel_lock_both(tc, chan);
2600                 ast_channel_stage_snapshot(tc);
2601
2602                 pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", tmp->number);
2603
2604                 /* Setup outgoing SDP to match incoming one */
2605                 if (!AST_LIST_FIRST(&out_chans) && !rest && CAN_EARLY_BRIDGE(peerflags, chan, tc)) {
2606                         /* We are on the only destination. */
2607                         ast_rtp_instance_early_bridge_make_compatible(tc, chan);
2608                 }
2609
2610                 /* Inherit specially named variables from parent channel */
2611                 ast_channel_inherit_variables(chan, tc);
2612                 ast_channel_datastore_inherit(chan, tc);
2613                 ast_max_forwards_decrement(tc);
2614
2615                 ast_channel_appl_set(tc, "AppDial");
2616                 ast_channel_data_set(tc, "(Outgoing Line)");
2617
2618                 memset(ast_channel_whentohangup(tc), 0, sizeof(*ast_channel_whentohangup(tc)));
2619
2620                 /* Determine CallerID to store in outgoing channel. */
2621                 ast_party_caller_set_init(&caller, ast_channel_caller(tc));
2622                 if (ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
2623                         caller.id = stored_clid;
2624                         ast_channel_set_caller_event(tc, &caller, NULL);
2625                         ast_set_flag64(tmp, DIAL_CALLERID_ABSENT);
2626                 } else if (ast_strlen_zero(S_COR(ast_channel_caller(tc)->id.number.valid,
2627                         ast_channel_caller(tc)->id.number.str, NULL))) {
2628                         /*
2629                          * The new channel has no preset CallerID number by the channel
2630                          * driver.  Use the dialplan extension and hint name.
2631                          */
2632                         caller.id = stored_clid;
2633                         if (!caller.id.name.valid
2634                                 && !ast_strlen_zero(S_COR(ast_channel_connected(chan)->id.name.valid,
2635                                         ast_channel_connected(chan)->id.name.str, NULL))) {
2636                                 /*
2637                                  * No hint name available.  We have a connected name supplied by
2638                                  * the dialplan we can use instead.
2639                                  */
2640                                 caller.id.name.valid = 1;
2641                                 caller.id.name = ast_channel_connected(chan)->id.name;
2642                         }
2643                         ast_channel_set_caller_event(tc, &caller, NULL);
2644                         ast_set_flag64(tmp, DIAL_CALLERID_ABSENT);
2645                 } else if (ast_strlen_zero(S_COR(ast_channel_caller(tc)->id.name.valid, ast_channel_caller(tc)->id.name.str,
2646                         NULL))) {
2647                         /* The new channel has no preset CallerID name by the channel driver. */
2648                         if (!ast_strlen_zero(S_COR(ast_channel_connected(chan)->id.name.valid,
2649                                 ast_channel_connected(chan)->id.name.str, NULL))) {
2650                                 /*
2651                                  * We have a connected name supplied by the dialplan we can
2652                                  * use instead.
2653                                  */
2654                                 caller.id.name.valid = 1;
2655                                 caller.id.name = ast_channel_connected(chan)->id.name;
2656                                 ast_channel_set_caller_event(tc, &caller, NULL);
2657                         }
2658                 }
2659
2660                 /* Determine CallerID for outgoing channel to send. */
2661                 if (ast_test_flag64(peerflags, OPT_FORCECLID) && !force_forwards_only) {
2662                         struct ast_party_connected_line connected;
2663
2664                         ast_party_connected_line_set_init(&connected, ast_channel_connected(tc));
2665                         connected.id = forced_clid;
2666                         ast_channel_set_connected_line(tc, &connected, NULL);
2667                 } else {
2668                         ast_connected_line_copy_from_caller(ast_channel_connected(tc), ast_channel_caller(chan));
2669                 }
2670
2671                 ast_party_redirecting_copy(ast_channel_redirecting(tc), ast_channel_redirecting(chan));
2672
2673                 ast_channel_dialed(tc)->transit_network_select = ast_channel_dialed(chan)->transit_network_select;
2674
2675                 ast_channel_req_accountcodes(tc, chan, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
2676                 if (ast_strlen_zero(ast_channel_musicclass(tc))) {
2677                         ast_channel_musicclass_set(tc, ast_channel_musicclass(chan));
2678                 }
2679
2680                 /* Pass ADSI CPE and transfer capability */
2681                 ast_channel_adsicpe_set(tc, ast_channel_adsicpe(chan));
2682                 ast_channel_transfercapability_set(tc, ast_channel_transfercapability(chan));
2683
2684                 /* If we have an outbound group, set this peer channel to it */
2685                 if (outbound_group)
2686                         ast_app_group_set_channel(tc, outbound_group);
2687                 /* If the calling channel has the ANSWERED_ELSEWHERE flag set, inherit it. This is to support local channels */
2688                 if (ast_channel_hangupcause(chan) == AST_CAUSE_ANSWERED_ELSEWHERE)
2689                         ast_channel_hangupcause_set(tc, AST_CAUSE_ANSWERED_ELSEWHERE);
2690
2691                 /* Check if we're forced by configuration */
2692                 if (ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE))
2693                          ast_channel_hangupcause_set(tc, AST_CAUSE_ANSWERED_ELSEWHERE);
2694
2695
2696                 /* Inherit context and extension */
2697                 ast_channel_dialcontext_set(tc, ast_strlen_zero(ast_channel_macrocontext(chan)) ? ast_channel_context(chan) : ast_channel_macrocontext(chan));
2698                 if (!ast_strlen_zero(ast_channel_macroexten(chan)))
2699                         ast_channel_exten_set(tc, ast_channel_macroexten(chan));
2700                 else
2701                         ast_channel_exten_set(tc, ast_channel_exten(chan));
2702
2703                 ast_channel_stage_snapshot_done(tc);
2704
2705                 /* Save the original channel name to detect call pickup masquerading in. */
2706                 tmp->orig_chan_name = ast_strdup(ast_channel_name(tc));
2707
2708                 ast_channel_unlock(tc);
2709                 ast_channel_unlock(chan);
2710
2711                 /* Put channel in the list of outgoing thingies. */
2712                 tmp->chan = tc;
2713                 AST_LIST_INSERT_TAIL(&out_chans, tmp, node);
2714         }
2715
2716         /*
2717          * PREDIAL: Run gosub on all of the callee channels
2718          *
2719          * We run the callee predial before ast_call() in case the user
2720          * wishes to do something on the newly created channels before
2721          * the channel does anything important.
2722          *
2723          * Inside the target gosub we will be able to do something with
2724          * the newly created channel name ie: now the calling channel
2725          * can know what channel will be used to call the destination
2726          * ex: now we will know that SIP/abc-123 is calling SIP/def-124
2727          */
2728         if (ast_test_flag64(&opts, OPT_PREDIAL_CALLEE)
2729                 && !ast_strlen_zero(opt_args[OPT_ARG_PREDIAL_CALLEE])
2730                 && !AST_LIST_EMPTY(&out_chans)) {
2731                 const char *predial_callee;
2732
2733                 ast_replace_subargument_delimiter(opt_args[OPT_ARG_PREDIAL_CALLEE]);
2734                 predial_callee = ast_app_expand_sub_args(chan, opt_args[OPT_ARG_PREDIAL_CALLEE]);
2735                 if (predial_callee) {
2736                         ast_autoservice_start(chan);
2737                         AST_LIST_TRAVERSE(&out_chans, tmp, node) {
2738                                 ast_pre_call(tmp->chan, predial_callee);
2739                         }
2740                         ast_autoservice_stop(chan);
2741                         ast_free((char *) predial_callee);
2742                 }
2743         }
2744
2745         /* Start all outgoing calls */
2746         AST_LIST_TRAVERSE_SAFE_BEGIN(&out_chans, tmp, node) {
2747                 res = ast_call(tmp->chan, tmp->number, 0); /* Place the call, but don't wait on the answer */
2748                 ast_channel_lock(chan);
2749
2750                 /* check the results of ast_call */
2751                 if (res) {
2752                         /* Again, keep going even if there's an error */
2753                         ast_debug(1, "ast call on peer returned %d\n", res);
2754                         ast_verb(3, "Couldn't call %s\n", tmp->interface);
2755                         if (ast_channel_hangupcause(tmp->chan)) {
2756                                 ast_channel_hangupcause_set(chan, ast_channel_hangupcause(tmp->chan));
2757                         }
2758                         ast_channel_unlock(chan);
2759                         ast_cc_call_failed(chan, tmp->chan, tmp->interface);
2760                         ast_hangup(tmp->chan);
2761                         tmp->chan = NULL;
2762                         AST_LIST_REMOVE_CURRENT(node);
2763                         chanlist_free(tmp);
2764                         continue;
2765                 }
2766
2767                 ast_channel_publish_dial(chan, tmp->chan, tmp->number, NULL);
2768                 ast_channel_unlock(chan);
2769
2770                 ast_verb(3, "Called %s\n", tmp->interface);
2771                 ast_set_flag64(tmp, DIAL_STILLGOING);
2772
2773                 /* If this line is up, don't try anybody else */
2774                 if (ast_channel_state(tmp->chan) == AST_STATE_UP) {
2775                         break;
2776                 }
2777         }
2778         AST_LIST_TRAVERSE_SAFE_END;
2779
2780         if (ast_strlen_zero(args.timeout)) {
2781                 to = -1;
2782         } else {
2783                 to = atoi(args.timeout);
2784                 if (to > 0)
2785                         to *= 1000;
2786                 else {
2787                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'. Setting timeout to infinite\n", args.timeout);
2788                         to = -1;
2789                 }
2790         }
2791
2792         outgoing = AST_LIST_FIRST(&out_chans);
2793         if (!outgoing) {
2794                 strcpy(pa.status, "CHANUNAVAIL");
2795                 if (fulldial == num_dialed) {
2796                         res = -1;
2797                         goto out;
2798                 }
2799         } else {
2800                 /* Our status will at least be NOANSWER */
2801                 strcpy(pa.status, "NOANSWER");
2802                 if (ast_test_flag64(outgoing, OPT_MUSICBACK)) {
2803                         moh = 1;
2804                         if (!ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
2805                                 char *original_moh = ast_strdupa(ast_channel_musicclass(chan));
2806                                 ast_channel_musicclass_set(chan, opt_args[OPT_ARG_MUSICBACK]);
2807                                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
2808                                 ast_channel_musicclass_set(chan, original_moh);
2809                         } else {
2810                                 ast_moh_start(chan, NULL, NULL);
2811                         }
2812                         ast_indicate(chan, AST_CONTROL_PROGRESS);
2813                 } else if (ast_test_flag64(outgoing, OPT_RINGBACK) || ast_test_flag64(outgoing, OPT_RING_WITH_EARLY_MEDIA)) {
2814                         if (!ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
2815                                 if (dial_handle_playtones(chan, opt_args[OPT_ARG_RINGBACK])){
2816                                         ast_indicate(chan, AST_CONTROL_RINGING);
2817                                         sentringing++;
2818                                 } else {
2819                                         ast_indicate(chan, AST_CONTROL_PROGRESS);
2820                                 }
2821                         } else {
2822                                 ast_indicate(chan, AST_CONTROL_RINGING);
2823                                 sentringing++;
2824                         }
2825                 }
2826         }
2827
2828         peer = wait_for_answer(chan, &out_chans, &to, peerflags, opt_args, &pa, &num, &result,
2829                 dtmf_progress, ignore_cc, &forced_clid, &stored_clid);
2830
2831         if (!peer) {
2832                 if (result) {
2833                         res = result;
2834                 } else if (to) { /* Musta gotten hung up */
2835                         res = -1;
2836                 } else { /* Nobody answered, next please? */
2837                         res = 0;
2838                 }
2839         } else {
2840                 const char *number;
2841                 const char *name;
2842                 int dial_end_raised = 0;
2843                 int cause = -1;
2844
2845                 if (ast_test_flag64(&opts, OPT_CALLER_ANSWER)) {
2846                         ast_answer(chan);
2847                 }
2848
2849                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
2850                    we will always return with -1 so that it is hung up properly after the
2851                    conversation.  */
2852
2853                 if (ast_test_flag64(&opts, OPT_HANGUPCAUSE)
2854                         && !ast_strlen_zero(opt_args[OPT_ARG_HANGUPCAUSE])) {
2855                         cause = ast_str2cause(opt_args[OPT_ARG_HANGUPCAUSE]);
2856                         if (cause <= 0) {
2857                                 if (!strcasecmp(opt_args[OPT_ARG_HANGUPCAUSE], "NONE")) {
2858                                         cause = 0;
2859                                 } else if (sscanf(opt_args[OPT_ARG_HANGUPCAUSE], "%30d", &cause) != 1
2860                                         || cause < 0) {
2861                                         ast_log(LOG_WARNING, "Invalid cause given to Dial(...Q(<cause>)): \"%s\"\n",
2862                                                 opt_args[OPT_ARG_HANGUPCAUSE]);
2863                                         cause = -1;
2864                                 }
2865                         }
2866                 }
2867                 hanguptree(&out_chans, peer, cause >= 0 ? cause : AST_CAUSE_ANSWERED_ELSEWHERE);
2868
2869                 /* If appropriate, log that we have a destination channel and set the answer time */
2870
2871                 ast_channel_lock(peer);
2872                 name = ast_strdupa(ast_channel_name(peer));
2873
2874                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER");
2875                 if (ast_strlen_zero(number)) {
2876                         number = NULL;
2877                 } else {
2878                         number = ast_strdupa(number);
2879                 }
2880                 ast_channel_unlock(peer);
2881
2882                 ast_channel_lock(chan);
2883                 ast_channel_stage_snapshot(chan);
2884
2885                 strcpy(pa.status, "ANSWER");
2886                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2887
2888                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", name);
2889                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
2890
2891                 ast_channel_stage_snapshot_done(chan);
2892                 ast_channel_unlock(chan);
2893
2894                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
2895                         ast_debug(1, "app_dial: sendurl=%s.\n", args.url);
2896                         ast_channel_sendurl( peer, args.url );
2897                 }
2898                 if ( (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) && pa.privdb_val == AST_PRIVACY_UNKNOWN) {
2899                         if (do_privacy(chan, peer, &opts, opt_args, &pa)) {
2900                                 ast_channel_publish_dial(chan, peer, NULL, pa.status);
2901                                 /* hang up on the callee -- he didn't want to talk anyway! */
2902                                 ast_autoservice_chan_hangup_peer(chan, peer);
2903                                 res = 0;
2904                                 goto out;
2905                         }
2906                 }
2907                 if (!ast_test_flag64(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
2908                         res = 0;
2909                 } else {
2910                         int digit = 0;
2911                         struct ast_channel *chans[2];
2912                         struct ast_channel *active_chan;
2913
2914                         chans[0] = chan;
2915                         chans[1] = peer;
2916
2917                         /* we need to stream the announcement to the called party when the OPT_ARG_ANNOUNCE (-A) is setted */
2918
2919                         /* stream the file */
2920                         res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], ast_channel_language(peer));
2921                         if (res) {
2922                                 res = 0;
2923                                 ast_log(LOG_ERROR, "error streaming file '%s' to callee\n", opt_args[OPT_ARG_ANNOUNCE]);
2924                         }
2925
2926                         ast_channel_set_flag(peer, AST_FLAG_END_DTMF_ONLY);
2927                         while (ast_channel_stream(peer)) {
2928                                 int ms;
2929
2930                                 ms = ast_sched_wait(ast_channel_sched(peer));
2931
2932                                 if (ms < 0 && !ast_channel_timingfunc(peer)) {
2933                                         ast_stopstream(peer);
2934                                         break;
2935                                 }
2936                                 if (ms < 0)
2937                                         ms = 1000;
2938
2939                                 active_chan = ast_waitfor_n(chans, 2, &ms);
2940                                 if (active_chan) {
2941                                         struct ast_channel *other_chan;
2942                                         struct ast_frame *fr = ast_read(active_chan);
2943
2944                                         if (!fr) {
2945                                                 ast_autoservice_chan_hangup_peer(chan, peer);
2946                                                 res = -1;
2947                                                 goto done;
2948                                         }
2949                                         switch (fr->frametype) {
2950                                         case AST_FRAME_DTMF_END:
2951                                                 digit = fr->subclass.integer;
2952                                                 if (active_chan == peer && strchr(AST_DIGIT_ANY, res)) {
2953                                                         ast_stopstream(peer);
2954                                                         res = ast_senddigit(chan, digit, 0);
2955                                                 }
2956                                                 break;
2957                                         case AST_FRAME_CONTROL:
2958                                                 switch (fr->subclass.integer) {
2959                                                 case AST_CONTROL_HANGUP:
2960                                                         ast_frfree(fr);
2961                                                         ast_autoservice_chan_hangup_peer(chan, peer);
2962                                                         res = -1;
2963                                                         goto done;
2964                                                 case AST_CONTROL_CONNECTED_LINE:
2965                                                         /* Pass COLP update to the other channel. */
2966                                                         if (active_chan == chan) {
2967                                                                 other_chan = peer;
2968                                                         } else {
2969                                                                 other_chan = chan;
2970                                                         }
2971                                                         if (ast_channel_connected_line_sub(active_chan, other_chan, fr, 1)
2972                                                                 && ast_channel_connected_line_macro(active_chan,
2973                                                                         other_chan, fr, other_chan == chan, 1)) {
2974                                                                 ast_indicate_data(other_chan, fr->subclass.integer,
2975                                                                         fr->data.ptr, fr->datalen);
2976                                                         }
2977                                                         break;
2978                                                 default:
2979                                                         break;
2980                                                 }
2981                                                 break;
2982                                         default:
2983                                                 /* Ignore all others */
2984                                                 break;
2985                                         }
2986                                         ast_frfree(fr);
2987                                 }
2988                                 ast_sched_runq(ast_channel_sched(peer));
2989                         }
2990                         ast_channel_clear_flag(peer, AST_FLAG_END_DTMF_ONLY);
2991                 }
2992
2993                 if (chan && peer && ast_test_flag64(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
2994                         /* chan and peer are going into the PBX; as such neither are considered
2995                          * outgoing channels any longer */
2996                         ast_channel_clear_flag(chan, AST_FLAG_OUTGOING);
2997
2998                         ast_replace_subargument_delimiter(opt_args[OPT_ARG_GOTO]);
2999                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
3000                         /* peer goes to the same context and extension as chan, so just copy info from chan*/
3001                         ast_channel_lock(peer);
3002                         ast_channel_stage_snapshot(peer);
3003                         ast_clear_flag(ast_channel_flags(peer), AST_FLAG_OUTGOING);
3004                         ast_channel_context_set(peer, ast_channel_context(chan));
3005                         ast_channel_exten_set(peer, ast_channel_exten(chan));
3006                         ast_channel_priority_set(peer, ast_channel_priority(chan) + 2);
3007                         ast_channel_stage_snapshot_done(peer);
3008                         ast_channel_unlock(peer);
3009                         if (ast_pbx_start(peer)) {
3010                                 ast_autoservice_chan_hangup_peer(chan, peer);
3011                         }
3012                         if (continue_exec)
3013                                 *continue_exec = 1;
3014                         res = 0;
3015                         ast_channel_publish_dial(chan, peer, NULL, "ANSWER");
3016                         goto done;
3017                 }
3018
3019                 if (ast_test_flag64(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
3020                         const char *macro_result_peer;
3021                         int macro_res;
3022
3023                         /* Set peer->exten and peer->context so that MACRO_EXTEN and MACRO_CONTEXT get set */
3024                         ast_channel_lock_both(chan, peer);
3025                         ast_channel_context_set(peer, ast_channel_context(chan));
3026                         ast_channel_exten_set(peer, ast_channel_exten(chan));
3027                         ast_channel_unlock(peer);
3028                         ast_channel_unlock(chan);
3029                         ast_replace_subargument_delimiter(opt_args[OPT_ARG_CALLEE_MACRO]);
3030                         macro_res = ast_app_exec_macro(chan, peer, opt_args[OPT_ARG_CALLEE_MACRO]);
3031
3032                         ast_channel_lock(peer);
3033
3034                         if (!macro_res && (macro_result_peer = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
3035                                 char *macro_result = ast_strdupa(macro_result_peer);
3036                                 char *macro_transfer_dest;
3037
3038                                 ast_channel_unlock(peer);
3039
3040                                 if (!strcasecmp(macro_result, "BUSY")) {
3041                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
3042                                         ast_set_flag64(peerflags, OPT_GO_ON);
3043                                         macro_res = -1;
3044                                 } else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
3045                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
3046                                         ast_set_flag64(peerflags, OPT_GO_ON);
3047                                         macro_res = -1;
3048                                 } else if (!strcasecmp(macro_result, "CONTINUE")) {
3049                                         /* hangup peer and keep chan alive assuming the macro has changed
3050                                            the context / exten / priority or perhaps
3051                                            the next priority in the current exten is desired.
3052                                         */
3053                                         ast_set_flag64(peerflags, OPT_GO_ON);
3054                                         macro_res = -1;
3055                                 } else if (!strcasecmp(macro_result, "ABORT")) {
3056                                         /* Hangup both ends unless the caller has the g flag */
3057                                         macro_res = -1;
3058                                 } else if (!strncasecmp(macro_result, "GOTO:", 5)) {
3059                                         macro_transfer_dest = macro_result + 5;
3060                                         macro_res = -1;
3061                                         /* perform a transfer to a new extension */
3062                                         if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
3063                                                 ast_replace_subargument_delimiter(macro_transfer_dest);
3064                                         }
3065                                         if (!ast_parseable_goto(chan, macro_transfer_dest)) {
3066                                                 ast_set_flag64(peerflags, OPT_GO_ON);
3067                                         }
3068                                 }
3069                                 if (macro_res && !dial_end_raised) {
3070                                         ast_channel_publish_dial(chan, peer, NULL, macro_result);
3071                                         dial_end_raised = 1;
3072                                 }
3073                         } else {
3074                                 ast_channel_unlock(peer);
3075                         }
3076                         res = macro_res;
3077                 }
3078
3079                 if (ast_test_flag64(&opts, OPT_CALLEE_GOSUB) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GOSUB])) {
3080                         const char *gosub_result_peer;
3081                         char *gosub_argstart;
3082                         char *gosub_args = NULL;
3083                         int gosub_res = -1;
3084
3085                         ast_replace_subargument_delimiter(opt_args[OPT_ARG_CALLEE_GOSUB]);
3086                         gosub_argstart = strchr(opt_args[OPT_ARG_CALLEE_GOSUB], ',');
3087                         if (gosub_argstart) {
3088                                 const char *what_is_s = "s";
3089                                 *gosub_argstart = 0;
3090                                 if (!ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "s", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL)) &&
3091                                          ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "~~s~~", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL))) {
3092                                         what_is_s = "~~s~~";
3093                                 }
3094                                 if (ast_asprintf(&gosub_args, "%s,%s,1(%s)", opt_args[OPT_ARG_CALLEE_GOSUB], what_is_s, gosub_argstart + 1) < 0) {
3095                                         gosub_args = NULL;
3096                                 }
3097                                 *gosub_argstart = ',';
3098                         } else {
3099                                 const char *what_is_s = "s";
3100                                 if (!ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "s", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL)) &&
3101                                          ast_exists_extension(peer, opt_args[OPT_ARG_CALLEE_GOSUB], "~~s~~", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL))) {
3102                                         what_is_s = "~~s~~";
3103                                 }
3104                                 if (ast_asprintf(&gosub_args, "%s,%s,1", opt_args[OPT_ARG_CALLEE_GOSUB], what_is_s) < 0) {
3105                                         gosub_args = NULL;
3106                                 }
3107                         }
3108                         if (gosub_args) {
3109                                 gosub_res = ast_app_exec_sub(chan, peer, gosub_args, 0);
3110                                 ast_free(gosub_args);
3111                         } else {
3112                                 ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
3113                         }
3114
3115                         ast_channel_lock_both(chan, peer);
3116
3117                         if (!gosub_res && (gosub_result_peer = pbx_builtin_getvar_helper(peer, "GOSUB_RESULT"))) {
3118                                 char *gosub_transfer_dest;
3119                                 char *gosub_result = ast_strdupa(gosub_result_peer);
3120                                 const char *gosub_retval = pbx_builtin_getvar_helper(peer, "GOSUB_RETVAL");