Merge "astobj2: Create function to copy weak proxied objects from container."
[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="ANSWEREDTIME">
569                                         <para>This is the amount of time for actual call.</para>
570                                 </variable>
571                                 <variable name="DIALEDPEERNAME">
572                                         <para>The name of the outbound channel that answered the call.</para>
573                                 </variable>
574                                 <variable name="DIALEDPEERNUMBER">
575                                         <para>The number that was dialed for the answered outbound channel.</para>
576                                 </variable>
577                                 <variable name="FORWARDERNAME">
578                                         <para>If a call forward occurred, the name of the forwarded channel.</para>
579                                 </variable>
580                                 <variable name="DIALSTATUS">
581                                         <para>This is the status of the call</para>
582                                         <value name="CHANUNAVAIL" />
583                                         <value name="CONGESTION" />
584                                         <value name="NOANSWER" />
585                                         <value name="BUSY" />
586                                         <value name="ANSWER" />
587                                         <value name="CANCEL" />
588                                         <value name="DONTCALL">
589                                                 For the Privacy and Screening Modes.
590                                                 Will be set if the called party chooses to send the calling party to the 'Go Away' script.
591                                         </value>
592                                         <value name="TORTURE">
593                                                 For the Privacy and Screening Modes.
594                                                 Will be set if the called party chooses to send the calling party to the 'torture' script.
595                                         </value>
596                                         <value name="INVALIDARGS" />
597                                 </variable>
598                         </variablelist>
599                 </description>
600                 <see-also>
601                         <ref type="application">RetryDial</ref>
602                         <ref type="application">SendDTMF</ref>
603                         <ref type="application">Gosub</ref>
604                         <ref type="application">Macro</ref>
605                 </see-also>
606         </application>
607         <application name="RetryDial" language="en_US">
608                 <synopsis>
609                         Place a call, retrying on failure allowing an optional exit extension.
610                 </synopsis>
611                 <syntax>
612                         <parameter name="announce" required="true">
613                                 <para>Filename of sound that will be played when no channel can be reached</para>
614                         </parameter>
615                         <parameter name="sleep" required="true">
616                                 <para>Number of seconds to wait after a dial attempt failed before a new attempt is made</para>
617                         </parameter>
618                         <parameter name="retries" required="true">
619                                 <para>Number of retries</para>
620                                 <para>When this is reached flow will continue at the next priority in the dialplan</para>
621                         </parameter>
622                         <parameter name="dialargs" required="true">
623                                 <para>Same format as arguments provided to the Dial application</para>
624                         </parameter>
625                 </syntax>
626                 <description>
627                         <para>This application will attempt to place a call using the normal Dial application.
628                         If no channel can be reached, the <replaceable>announce</replaceable> file will be played.
629                         Then, it will wait <replaceable>sleep</replaceable> number of seconds before retrying the call.
630                         After <replaceable>retries</replaceable> number of attempts, the calling channel will continue at the next priority in the dialplan.
631                         If the <replaceable>retries</replaceable> setting is set to 0, this application will retry endlessly.
632                         While waiting to retry a call, a 1 digit extension may be dialed. If that
633                         extension exists in either the context defined in <variable>EXITCONTEXT</variable> or the current
634                         one, The call will jump to that extension immediately.
635                         The <replaceable>dialargs</replaceable> are specified in the same format that arguments are provided
636                         to the Dial application.</para>
637                 </description>
638                 <see-also>
639                         <ref type="application">Dial</ref>
640                 </see-also>
641         </application>
642  ***/
643
644 static const char app[] = "Dial";
645 static const char rapp[] = "RetryDial";
646
647 enum {
648         OPT_ANNOUNCE =          (1 << 0),
649         OPT_RESETCDR =          (1 << 1),
650         OPT_DTMF_EXIT =         (1 << 2),
651         OPT_SENDDTMF =          (1 << 3),
652         OPT_FORCECLID =         (1 << 4),
653         OPT_GO_ON =             (1 << 5),
654         OPT_CALLEE_HANGUP =     (1 << 6),
655         OPT_CALLER_HANGUP =     (1 << 7),
656         OPT_ORIGINAL_CLID =     (1 << 8),
657         OPT_DURATION_LIMIT =    (1 << 9),
658         OPT_MUSICBACK =         (1 << 10),
659         OPT_CALLEE_MACRO =      (1 << 11),
660         OPT_SCREEN_NOINTRO =    (1 << 12),
661         OPT_SCREEN_NOCALLERID = (1 << 13),
662         OPT_IGNORE_CONNECTEDLINE = (1 << 14),
663         OPT_SCREENING =         (1 << 15),
664         OPT_PRIVACY =           (1 << 16),
665         OPT_RINGBACK =          (1 << 17),
666         OPT_DURATION_STOP =     (1 << 18),
667         OPT_CALLEE_TRANSFER =   (1 << 19),
668         OPT_CALLER_TRANSFER =   (1 << 20),
669         OPT_CALLEE_MONITOR =    (1 << 21),
670         OPT_CALLER_MONITOR =    (1 << 22),
671         OPT_GOTO =              (1 << 23),
672         OPT_OPERMODE =          (1 << 24),
673         OPT_CALLEE_PARK =       (1 << 25),
674         OPT_CALLER_PARK =       (1 << 26),
675         OPT_IGNORE_FORWARDING = (1 << 27),
676         OPT_CALLEE_GOSUB =      (1 << 28),
677         OPT_CALLEE_MIXMONITOR = (1 << 29),
678         OPT_CALLER_MIXMONITOR = (1 << 30),
679 };
680
681 /* flags are now 64 bits, so keep it up! */
682 #define DIAL_STILLGOING      (1LLU << 31)
683 #define DIAL_NOFORWARDHTML   (1LLU << 32)
684 #define DIAL_CALLERID_ABSENT (1LLU << 33) /* TRUE if caller id is not available for connected line. */
685 #define OPT_CANCEL_ELSEWHERE (1LLU << 34)
686 #define OPT_PEER_H           (1LLU << 35)
687 #define OPT_CALLEE_GO_ON     (1LLU << 36)
688 #define OPT_CANCEL_TIMEOUT   (1LLU << 37)
689 #define OPT_FORCE_CID_TAG    (1LLU << 38)
690 #define OPT_FORCE_CID_PRES   (1LLU << 39)
691 #define OPT_CALLER_ANSWER    (1LLU << 40)
692 #define OPT_PREDIAL_CALLEE   (1LLU << 41)
693 #define OPT_PREDIAL_CALLER   (1LLU << 42)
694 #define OPT_RING_WITH_EARLY_MEDIA (1LLU << 43)
695 #define OPT_HANGUPCAUSE      (1LLU << 44)
696
697 enum {
698         OPT_ARG_ANNOUNCE = 0,
699         OPT_ARG_SENDDTMF,
700         OPT_ARG_GOTO,
701         OPT_ARG_DURATION_LIMIT,
702         OPT_ARG_MUSICBACK,
703         OPT_ARG_CALLEE_MACRO,
704         OPT_ARG_RINGBACK,
705         OPT_ARG_CALLEE_GOSUB,
706         OPT_ARG_CALLEE_GO_ON,
707         OPT_ARG_PRIVACY,
708         OPT_ARG_DURATION_STOP,
709         OPT_ARG_OPERMODE,
710         OPT_ARG_SCREEN_NOINTRO,
711         OPT_ARG_ORIGINAL_CLID,
712         OPT_ARG_FORCECLID,
713         OPT_ARG_FORCE_CID_TAG,
714         OPT_ARG_FORCE_CID_PRES,
715         OPT_ARG_PREDIAL_CALLEE,
716         OPT_ARG_PREDIAL_CALLER,
717         OPT_ARG_HANGUPCAUSE,
718         /* note: this entry _MUST_ be the last one in the enum */
719         OPT_ARG_ARRAY_SIZE
720 };
721
722 AST_APP_OPTIONS(dial_exec_options, BEGIN_OPTIONS
723         AST_APP_OPTION_ARG('A', OPT_ANNOUNCE, OPT_ARG_ANNOUNCE),
724         AST_APP_OPTION('a', OPT_CALLER_ANSWER),
725         AST_APP_OPTION_ARG('b', OPT_PREDIAL_CALLEE, OPT_ARG_PREDIAL_CALLEE),
726         AST_APP_OPTION_ARG('B', OPT_PREDIAL_CALLER, OPT_ARG_PREDIAL_CALLER),
727         AST_APP_OPTION('C', OPT_RESETCDR),
728         AST_APP_OPTION('c', OPT_CANCEL_ELSEWHERE),
729         AST_APP_OPTION('d', OPT_DTMF_EXIT),
730         AST_APP_OPTION_ARG('D', OPT_SENDDTMF, OPT_ARG_SENDDTMF),
731         AST_APP_OPTION('e', OPT_PEER_H),
732         AST_APP_OPTION_ARG('f', OPT_FORCECLID, OPT_ARG_FORCECLID),
733         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
734         AST_APP_OPTION('g', OPT_GO_ON),
735         AST_APP_OPTION_ARG('G', OPT_GOTO, OPT_ARG_GOTO),
736         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
737         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
738         AST_APP_OPTION('i', OPT_IGNORE_FORWARDING),
739         AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
740         AST_APP_OPTION('k', OPT_CALLEE_PARK),
741         AST_APP_OPTION('K', OPT_CALLER_PARK),
742         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
743         AST_APP_OPTION_ARG('m', OPT_MUSICBACK, OPT_ARG_MUSICBACK),
744         AST_APP_OPTION_ARG('M', OPT_CALLEE_MACRO, OPT_ARG_CALLEE_MACRO),
745         AST_APP_OPTION_ARG('n', OPT_SCREEN_NOINTRO, OPT_ARG_SCREEN_NOINTRO),
746         AST_APP_OPTION('N', OPT_SCREEN_NOCALLERID),
747         AST_APP_OPTION_ARG('o', OPT_ORIGINAL_CLID, OPT_ARG_ORIGINAL_CLID),
748         AST_APP_OPTION_ARG('O', OPT_OPERMODE, OPT_ARG_OPERMODE),
749         AST_APP_OPTION('p', OPT_SCREENING),
750         AST_APP_OPTION_ARG('P', OPT_PRIVACY, OPT_ARG_PRIVACY),
751         AST_APP_OPTION_ARG('Q', OPT_HANGUPCAUSE, OPT_ARG_HANGUPCAUSE),
752         AST_APP_OPTION_ARG('r', OPT_RINGBACK, OPT_ARG_RINGBACK),
753         AST_APP_OPTION('R', OPT_RING_WITH_EARLY_MEDIA),
754         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
755         AST_APP_OPTION_ARG('s', OPT_FORCE_CID_TAG, OPT_ARG_FORCE_CID_TAG),
756         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
757         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
758         AST_APP_OPTION_ARG('u', OPT_FORCE_CID_PRES, OPT_ARG_FORCE_CID_PRES),
759         AST_APP_OPTION_ARG('U', OPT_CALLEE_GOSUB, OPT_ARG_CALLEE_GOSUB),
760         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
761         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
762         AST_APP_OPTION('x', OPT_CALLEE_MIXMONITOR),
763         AST_APP_OPTION('X', OPT_CALLER_MIXMONITOR),
764         AST_APP_OPTION('z', OPT_CANCEL_TIMEOUT),
765 END_OPTIONS );
766
767 #define CAN_EARLY_BRIDGE(flags,chan,peer) (!ast_test_flag64(flags, OPT_CALLEE_HANGUP | \
768         OPT_CALLER_HANGUP | OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER | \
769         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR | OPT_CALLEE_PARK |  \
770         OPT_CALLER_PARK | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB) && \
771         !ast_channel_audiohooks(chan) && !ast_channel_audiohooks(peer) && \
772         ast_framehook_list_is_empty(ast_channel_framehooks(chan)) && ast_framehook_list_is_empty(ast_channel_framehooks(peer)))
773
774 /*
775  * The list of active channels
776  */
777 struct chanlist {
778         AST_LIST_ENTRY(chanlist) node;
779         struct ast_channel *chan;
780         /*! Channel interface dialing string (is tech/number).  (Stored in stuff[]) */
781         const char *interface;
782         /*! Channel technology name.  (Stored in stuff[]) */
783         const char *tech;
784         /*! Channel device addressing.  (Stored in stuff[]) */
785         const char *number;
786         /*! Original channel name.  Must be freed.  Could be NULL if allocation failed. */
787         char *orig_chan_name;
788         uint64_t flags;
789         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
790         struct ast_party_connected_line connected;
791         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
792         unsigned int pending_connected_update:1;
793         struct ast_aoc_decoded *aoc_s_rate_list;
794         /*! The interface, tech, and number strings are stuffed here. */
795         char stuff[0];
796 };
797
798 AST_LIST_HEAD_NOLOCK(dial_head, chanlist);
799
800 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str **featurecode);
801
802 static void chanlist_free(struct chanlist *outgoing)
803 {
804         ast_party_connected_line_free(&outgoing->connected);
805         ast_aoc_destroy_decoded(outgoing->aoc_s_rate_list);
806         ast_free(outgoing->orig_chan_name);
807         ast_free(outgoing);
808 }
809
810 static void hanguptree(struct dial_head *out_chans, struct ast_channel *exception, int hangupcause)
811 {
812         /* Hang up a tree of stuff */
813         struct chanlist *outgoing;
814
815         while ((outgoing = AST_LIST_REMOVE_HEAD(out_chans, node))) {
816                 /* Hangup any existing lines we have open */
817                 if (outgoing->chan && (outgoing->chan != exception)) {
818                         if (hangupcause >= 0) {
819                                 /* This is for the channel drivers */
820                                 ast_channel_hangupcause_set(outgoing->chan, hangupcause);
821                         }
822                         ast_hangup(outgoing->chan);
823                 }
824                 chanlist_free(outgoing);
825         }
826 }
827
828 #define AST_MAX_WATCHERS 256
829
830 /*
831  * argument to handle_cause() and other functions.
832  */
833 struct cause_args {
834         struct ast_channel *chan;
835         int busy;
836         int congestion;
837         int nochan;
838 };
839
840 static void handle_cause(int cause, struct cause_args *num)
841 {
842         switch(cause) {
843         case AST_CAUSE_BUSY:
844                 num->busy++;
845                 break;
846         case AST_CAUSE_CONGESTION:
847                 num->congestion++;
848                 break;
849         case AST_CAUSE_NO_ROUTE_DESTINATION:
850         case AST_CAUSE_UNREGISTERED:
851                 num->nochan++;
852                 break;
853         case AST_CAUSE_NO_ANSWER:
854         case AST_CAUSE_NORMAL_CLEARING:
855                 break;
856         default:
857                 num->nochan++;
858                 break;
859         }
860 }
861
862 static int onedigit_goto(struct ast_channel *chan, const char *context, char exten, int pri)
863 {
864         char rexten[2] = { exten, '\0' };
865
866         if (context) {
867                 if (!ast_goto_if_exists(chan, context, rexten, pri))
868                         return 1;
869         } else {
870                 if (!ast_goto_if_exists(chan, ast_channel_context(chan), rexten, pri))
871                         return 1;
872                 else if (!ast_strlen_zero(ast_channel_macrocontext(chan))) {
873                         if (!ast_goto_if_exists(chan, ast_channel_macrocontext(chan), rexten, pri))
874                                 return 1;
875                 }
876         }
877         return 0;
878 }
879
880 /* do not call with chan lock held */
881 static const char *get_cid_name(char *name, int namelen, struct ast_channel *chan)
882 {
883         const char *context;
884         const char *exten;
885
886         ast_channel_lock(chan);
887         context = ast_strdupa(S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan)));
888         exten = ast_strdupa(S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan)));
889         ast_channel_unlock(chan);
890
891         return ast_get_hint(NULL, 0, name, namelen, chan, context, exten) ? name : "";
892 }
893
894 /*!
895  * helper function for wait_for_answer()
896  *
897  * \param o Outgoing call channel list.
898  * \param num Incoming call channel cause accumulation
899  * \param peerflags Dial option flags
900  * \param single TRUE if there is only one outgoing call.
901  * \param caller_entertained TRUE if the caller is being entertained by MOH or ringback.
902  * \param to Remaining call timeout time.
903  * \param forced_clid OPT_FORCECLID caller id to send
904  * \param stored_clid Caller id representing the called party if needed
905  *
906  * XXX this code is highly suspicious, as it essentially overwrites
907  * the outgoing channel without properly deleting it.
908  *
909  * \todo eventually this function should be intergrated into and replaced by ast_call_forward()
910  */
911 static void do_forward(struct chanlist *o, struct cause_args *num,
912         struct ast_flags64 *peerflags, int single, int caller_entertained, int *to,
913         struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
914 {
915         char tmpchan[256];
916         char forwarder[AST_CHANNEL_NAME];
917         struct ast_channel *original = o->chan;
918         struct ast_channel *c = o->chan; /* the winner */
919         struct ast_channel *in = num->chan; /* the input channel */
920         char *stuff;
921         char *tech;
922         int cause;
923         struct ast_party_caller caller;
924
925         ast_copy_string(forwarder, ast_channel_name(c), sizeof(forwarder));
926         ast_copy_string(tmpchan, ast_channel_call_forward(c), sizeof(tmpchan));
927         if ((stuff = strchr(tmpchan, '/'))) {
928                 *stuff++ = '\0';
929                 tech = tmpchan;
930         } else {
931                 const char *forward_context;
932                 ast_channel_lock(c);
933                 forward_context = pbx_builtin_getvar_helper(c, "FORWARD_CONTEXT");
934                 if (ast_strlen_zero(forward_context)) {
935                         forward_context = NULL;
936                 }
937                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", ast_channel_call_forward(c), forward_context ? forward_context : ast_channel_context(c));
938                 ast_channel_unlock(c);
939                 stuff = tmpchan;
940                 tech = "Local";
941         }
942         if (!strcasecmp(tech, "Local")) {
943                 /*
944                  * Drop the connected line update block for local channels since
945                  * this is going to run dialplan and the user can change his
946                  * mind about what connected line information he wants to send.
947                  */
948                 ast_clear_flag64(o, OPT_IGNORE_CONNECTEDLINE);
949         }
950
951         /* Before processing channel, go ahead and check for forwarding */
952         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", ast_channel_name(in), tech, stuff, ast_channel_name(c));
953         /* If we have been told to ignore forwards, just set this channel to null and continue processing extensions normally */
954         if (ast_test_flag64(peerflags, OPT_IGNORE_FORWARDING)) {
955                 ast_verb(3, "Forwarding %s to '%s/%s' prevented.\n", ast_channel_name(in), tech, stuff);
956                 ast_channel_publish_dial_forward(in, original, NULL, NULL, "CANCEL",
957                         ast_channel_call_forward(original));
958                 c = o->chan = NULL;
959                 cause = AST_CAUSE_BUSY;
960         } else {
961                 struct ast_stream_topology *topology;
962
963                 ast_channel_lock(in);
964                 topology = ast_stream_topology_clone(ast_channel_get_stream_topology(in));
965                 ast_channel_unlock(in);
966
967                 /* Setup parameters */
968                 c = o->chan = ast_request_with_stream_topology(tech, topology, NULL, in, stuff, &cause);
969
970                 ast_stream_topology_free(topology);
971
972                 if (c) {
973                         if (single && !caller_entertained) {
974                                 ast_channel_make_compatible(in, o->chan);
975                         }
976                         ast_channel_lock_both(in, o->chan);
977                         ast_channel_inherit_variables(in, o->chan);
978                         ast_channel_datastore_inherit(in, o->chan);
979                         pbx_builtin_setvar_helper(o->chan, "FORWARDERNAME", forwarder);
980                         ast_max_forwards_decrement(o->chan);
981                         ast_channel_unlock(in);
982                         ast_channel_unlock(o->chan);
983                         /* When a call is forwarded, we don't want to track new interfaces
984                          * dialed for CC purposes. Setting the done flag will ensure that
985                          * any Dial operations that happen later won't record CC interfaces.
986                          */
987                         ast_ignore_cc(o->chan);
988                         ast_log(LOG_NOTICE, "Not accepting call completion offers from call-forward recipient %s\n", ast_channel_name(o->chan));
989                 } else
990                         ast_log(LOG_NOTICE,
991                                 "Forwarding failed to create channel to dial '%s/%s' (cause = %d)\n",
992                                 tech, stuff, cause);
993         }
994         if (!c) {
995                 ast_channel_publish_dial(in, original, stuff, "BUSY");
996                 ast_clear_flag64(o, DIAL_STILLGOING);
997                 handle_cause(cause, num);
998                 ast_hangup(original);
999         } else {
1000                 ast_channel_lock_both(c, original);
1001                 ast_party_redirecting_copy(ast_channel_redirecting(c),
1002                         ast_channel_redirecting(original));
1003                 ast_channel_unlock(c);
1004                 ast_channel_unlock(original);
1005
1006                 ast_channel_lock_both(c, in);
1007
1008                 if (single && !caller_entertained && CAN_EARLY_BRIDGE(peerflags, c, in)) {
1009                         ast_rtp_instance_early_bridge_make_compatible(c, in);
1010                 }
1011
1012                 if (!ast_channel_redirecting(c)->from.number.valid
1013                         || ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
1014                         /*
1015                          * The call was not previously redirected so it is
1016                          * now redirected from this number.
1017                          */
1018                         ast_party_number_free(&ast_channel_redirecting(c)->from.number);
1019                         ast_party_number_init(&ast_channel_redirecting(c)->from.number);
1020                         ast_channel_redirecting(c)->from.number.valid = 1;
1021                         ast_channel_redirecting(c)->from.number.str =
1022                                 ast_strdup(S_OR(ast_channel_macroexten(in), ast_channel_exten(in)));
1023                 }
1024
1025                 ast_channel_dialed(c)->transit_network_select = ast_channel_dialed(in)->transit_network_select;
1026
1027                 /* Determine CallerID to store in outgoing channel. */
1028                 ast_party_caller_set_init(&caller, ast_channel_caller(c));
1029                 if (ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
1030                         caller.id = *stored_clid;
1031                         ast_channel_set_caller_event(c, &caller, NULL);
1032                         ast_set_flag64(o, DIAL_CALLERID_ABSENT);
1033                 } else if (ast_strlen_zero(S_COR(ast_channel_caller(c)->id.number.valid,
1034                         ast_channel_caller(c)->id.number.str, NULL))) {
1035                         /*
1036                          * The new channel has no preset CallerID number by the channel
1037                          * driver.  Use the dialplan extension and hint name.
1038                          */
1039                         caller.id = *stored_clid;
1040                         ast_channel_set_caller_event(c, &caller, NULL);
1041                         ast_set_flag64(o, DIAL_CALLERID_ABSENT);
1042                 } else {
1043                         ast_clear_flag64(o, DIAL_CALLERID_ABSENT);
1044                 }
1045
1046                 /* Determine CallerID for outgoing channel to send. */
1047                 if (ast_test_flag64(o, OPT_FORCECLID)) {
1048                         struct ast_party_connected_line connected;
1049
1050                         ast_party_connected_line_init(&connected);
1051                         connected.id = *forced_clid;
1052                         ast_party_connected_line_copy(ast_channel_connected(c), &connected);
1053                 } else {
1054                         ast_connected_line_copy_from_caller(ast_channel_connected(c), ast_channel_caller(in));
1055                 }
1056
1057                 ast_channel_req_accountcodes(c, in, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
1058
1059                 ast_channel_appl_set(c, "AppDial");
1060                 ast_channel_data_set(c, "(Outgoing Line)");
1061                 ast_channel_publish_snapshot(c);
1062
1063                 ast_channel_unlock(in);
1064                 if (single && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1065                         struct ast_party_redirecting redirecting;
1066
1067                         /*
1068                          * Redirecting updates to the caller make sense only on single
1069                          * calls.
1070                          *
1071                          * We must unlock c before calling
1072                          * ast_channel_redirecting_macro, because we put c into
1073                          * autoservice there.  That is pretty much a guaranteed
1074                          * deadlock.  This is why the handling of c's lock may seem a
1075                          * bit unusual here.
1076                          */
1077                         ast_party_redirecting_init(&redirecting);
1078                         ast_party_redirecting_copy(&redirecting, ast_channel_redirecting(c));
1079                         ast_channel_unlock(c);
1080                         if (ast_channel_redirecting_sub(c, in, &redirecting, 0) &&
1081                                 ast_channel_redirecting_macro(c, in, &redirecting, 1, 0)) {
1082                                 ast_channel_update_redirecting(in, &redirecting, NULL);
1083                         }
1084                         ast_party_redirecting_free(&redirecting);
1085                 } else {
1086                         ast_channel_unlock(c);
1087                 }
1088
1089                 if (ast_test_flag64(peerflags, OPT_CANCEL_TIMEOUT)) {
1090                         *to = -1;
1091                 }
1092
1093                 if (ast_call(c, stuff, 0)) {
1094                         ast_log(LOG_NOTICE, "Forwarding failed to dial '%s/%s'\n",
1095                                 tech, stuff);
1096                         ast_channel_publish_dial(in, original, stuff, "CONGESTION");
1097                         ast_clear_flag64(o, DIAL_STILLGOING);
1098                         ast_hangup(original);
1099                         ast_hangup(c);
1100                         c = o->chan = NULL;
1101                         num->nochan++;
1102                 } else {
1103                         ast_channel_publish_dial_forward(in, original, c, NULL, "CANCEL",
1104                                 ast_channel_call_forward(original));
1105
1106                         ast_channel_publish_dial(in, c, stuff, NULL);
1107
1108                         /* Hangup the original channel now, in case we needed it */
1109                         ast_hangup(original);
1110                 }
1111                 if (single && !caller_entertained) {
1112                         ast_indicate(in, -1);
1113                 }
1114         }
1115 }
1116
1117 /* argument used for some functions. */
1118 struct privacy_args {
1119         int sentringing;
1120         int privdb_val;
1121         char privcid[256];
1122         char privintro[1024];
1123         char status[256];
1124 };
1125
1126 static void publish_dial_end_event(struct ast_channel *in, struct dial_head *out_chans, struct ast_channel *exception, const char *status)
1127 {
1128         struct chanlist *outgoing;
1129         AST_LIST_TRAVERSE(out_chans, outgoing, node) {
1130                 if (!outgoing->chan || outgoing->chan == exception) {
1131                         continue;
1132                 }
1133                 ast_channel_publish_dial(in, outgoing->chan, NULL, status);
1134         }
1135 }
1136
1137 /*!
1138  * \internal
1139  * \brief Update connected line on chan from peer.
1140  * \since 13.6.0
1141  *
1142  * \param chan Channel to get connected line updated.
1143  * \param peer Channel providing connected line information.
1144  * \param is_caller Non-zero if chan is the calling channel.
1145  *
1146  * \return Nothing
1147  */
1148 static void update_connected_line_from_peer(struct ast_channel *chan, struct ast_channel *peer, int is_caller)
1149 {
1150         struct ast_party_connected_line connected_caller;
1151
1152         ast_party_connected_line_init(&connected_caller);
1153
1154         ast_channel_lock(peer);
1155         ast_connected_line_copy_from_caller(&connected_caller, ast_channel_caller(peer));
1156         ast_channel_unlock(peer);
1157         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1158         if (ast_channel_connected_line_sub(peer, chan, &connected_caller, 0)
1159                 && ast_channel_connected_line_macro(peer, chan, &connected_caller, is_caller, 0)) {
1160                 ast_channel_update_connected_line(chan, &connected_caller, NULL);
1161         }
1162         ast_party_connected_line_free(&connected_caller);
1163 }
1164
1165 static struct ast_channel *wait_for_answer(struct ast_channel *in,
1166         struct dial_head *out_chans, int *to, struct ast_flags64 *peerflags,
1167         char *opt_args[],
1168         struct privacy_args *pa,
1169         const struct cause_args *num_in, int *result, char *dtmf_progress,
1170         const int ignore_cc,
1171         struct ast_party_id *forced_clid, struct ast_party_id *stored_clid)
1172 {
1173         struct cause_args num = *num_in;
1174         int prestart = num.busy + num.congestion + num.nochan;
1175         int orig = *to;
1176         struct ast_channel *peer = NULL;
1177         struct chanlist *outgoing = AST_LIST_FIRST(out_chans);
1178         /* single is set if only one destination is enabled */
1179         int single = outgoing && !AST_LIST_NEXT(outgoing, node);
1180         int caller_entertained = outgoing
1181                 && ast_test_flag64(outgoing, OPT_MUSICBACK | OPT_RINGBACK);
1182         struct ast_str *featurecode = ast_str_alloca(AST_FEATURE_MAX_LEN + 1);
1183         int cc_recall_core_id;
1184         int is_cc_recall;
1185         int cc_frame_received = 0;
1186         int num_ringing = 0;
1187         struct timeval start = ast_tvnow();
1188
1189         if (single) {
1190                 /* Turn off hold music, etc */
1191                 if (!caller_entertained) {
1192                         ast_deactivate_generator(in);
1193                         /* If we are calling a single channel, and not providing ringback or music, */
1194                         /* then, make them compatible for in-band tone purpose */
1195                         if (ast_channel_make_compatible(in, outgoing->chan) < 0) {
1196                                 /* If these channels can not be made compatible,
1197                                  * there is no point in continuing.  The bridge
1198                                  * will just fail if it gets that far.
1199                                  */
1200                                 *to = -1;
1201                                 strcpy(pa->status, "CONGESTION");
1202                                 ast_channel_publish_dial(in, outgoing->chan, NULL, pa->status);
1203                                 return NULL;
1204                         }
1205                 }
1206
1207                 if (!ast_test_flag64(outgoing, OPT_IGNORE_CONNECTEDLINE)
1208                         && !ast_test_flag64(outgoing, DIAL_CALLERID_ABSENT)) {
1209                         update_connected_line_from_peer(in, outgoing->chan, 1);
1210                 }
1211         }
1212
1213         is_cc_recall = ast_cc_is_recall(in, &cc_recall_core_id, NULL);
1214
1215         while ((*to = ast_remaining_ms(start, orig)) && !peer) {
1216                 struct chanlist *o;
1217                 int pos = 0; /* how many channels do we handle */
1218                 int numlines = prestart;
1219                 struct ast_channel *winner;
1220                 struct ast_channel *watchers[AST_MAX_WATCHERS];
1221
1222                 watchers[pos++] = in;
1223                 AST_LIST_TRAVERSE(out_chans, o, node) {
1224                         /* Keep track of important channels */
1225                         if (ast_test_flag64(o, DIAL_STILLGOING) && o->chan)
1226                                 watchers[pos++] = o->chan;
1227                         numlines++;
1228                 }
1229                 if (pos == 1) { /* only the input channel is available */
1230                         if (numlines == (num.busy + num.congestion + num.nochan)) {
1231                                 ast_verb(2, "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
1232                                 if (num.busy)
1233                                         strcpy(pa->status, "BUSY");
1234                                 else if (num.congestion)
1235                                         strcpy(pa->status, "CONGESTION");
1236                                 else if (num.nochan)
1237                                         strcpy(pa->status, "CHANUNAVAIL");
1238                         } else {
1239                                 ast_verb(3, "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
1240                         }
1241                         *to = 0;
1242                         if (is_cc_recall) {
1243                                 ast_cc_failed(cc_recall_core_id, "Everyone is busy/congested for the recall. How sad");
1244                         }
1245                         return NULL;
1246                 }
1247                 winner = ast_waitfor_n(watchers, pos, to);
1248                 AST_LIST_TRAVERSE(out_chans, o, node) {
1249                         struct ast_frame *f;
1250                         struct ast_channel *c = o->chan;
1251
1252                         if (c == NULL)
1253                                 continue;
1254                         if (ast_test_flag64(o, DIAL_STILLGOING) && ast_channel_state(c) == AST_STATE_UP) {
1255                                 if (!peer) {
1256                                         ast_verb(3, "%s answered %s\n", ast_channel_name(c), ast_channel_name(in));
1257                                         if (o->orig_chan_name
1258                                                 && strcmp(o->orig_chan_name, ast_channel_name(c))) {
1259                                                 /*
1260                                                  * The channel name changed so we must generate COLP update.
1261                                                  * Likely because a call pickup channel masqueraded in.
1262                                                  */
1263                                                 update_connected_line_from_peer(in, c, 1);
1264                                         } else if (!single && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1265                                                 if (o->pending_connected_update) {
1266                                                         if (ast_channel_connected_line_sub(c, in, &o->connected, 0) &&
1267                                                                 ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
1268                                                                 ast_channel_update_connected_line(in, &o->connected, NULL);
1269                                                         }
1270                                                 } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1271                                                         update_connected_line_from_peer(in, c, 1);
1272                                                 }
1273                                         }
1274                                         if (o->aoc_s_rate_list) {
1275                                                 size_t encoded_size;
1276                                                 struct ast_aoc_encoded *encoded;
1277                                                 if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
1278                                                         ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
1279                                                         ast_aoc_destroy_encoded(encoded);
1280                                                 }
1281                                         }
1282                                         peer = c;
1283                                         publish_dial_end_event(in, out_chans, peer, "CANCEL");
1284                                         ast_copy_flags64(peerflags, o,
1285                                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1286                                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1287                                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1288                                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
1289                                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1290                                                 DIAL_NOFORWARDHTML);
1291                                         ast_channel_dialcontext_set(c, "");
1292                                         ast_channel_exten_set(c, "");
1293                                 }
1294                                 continue;
1295                         }
1296                         if (c != winner)
1297                                 continue;
1298                         /* here, o->chan == c == winner */
1299                         if (!ast_strlen_zero(ast_channel_call_forward(c))) {
1300                                 pa->sentringing = 0;
1301                                 if (!ignore_cc && (f = ast_read(c))) {
1302                                         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_CC) {
1303                                                 /* This channel is forwarding the call, and is capable of CC, so
1304                                                  * be sure to add the new device interface to the list
1305                                                  */
1306                                                 ast_handle_cc_control_frame(in, c, f->data.ptr);
1307                                         }
1308                                         ast_frfree(f);
1309                                 }
1310
1311                                 if (o->pending_connected_update) {
1312                                         /*
1313                                          * Re-seed the chanlist's connected line information with
1314                                          * previously acquired connected line info from the incoming
1315                                          * channel.  The previously acquired connected line info could
1316                                          * have been set through the CONNECTED_LINE dialplan function.
1317                                          */
1318                                         o->pending_connected_update = 0;
1319                                         ast_channel_lock(in);
1320                                         ast_party_connected_line_copy(&o->connected, ast_channel_connected(in));
1321                                         ast_channel_unlock(in);
1322                                 }
1323
1324                                 do_forward(o, &num, peerflags, single, caller_entertained, &orig,
1325                                         forced_clid, stored_clid);
1326
1327                                 if (o->chan) {
1328                                         ast_free(o->orig_chan_name);
1329                                         o->orig_chan_name = ast_strdup(ast_channel_name(o->chan));
1330                                         if (single
1331                                                 && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)
1332                                                 && !ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1333                                                 update_connected_line_from_peer(in, o->chan, 1);
1334                                         }
1335                                 }
1336                                 continue;
1337                         }
1338                         f = ast_read(winner);
1339                         if (!f) {
1340                                 ast_channel_hangupcause_set(in, ast_channel_hangupcause(c));
1341                                 ast_channel_publish_dial(in, c, NULL, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(c)));
1342                                 ast_hangup(c);
1343                                 c = o->chan = NULL;
1344                                 ast_clear_flag64(o, DIAL_STILLGOING);
1345                                 handle_cause(ast_channel_hangupcause(in), &num);
1346                                 continue;
1347                         }
1348                         switch (f->frametype) {
1349                         case AST_FRAME_CONTROL:
1350                                 switch (f->subclass.integer) {
1351                                 case AST_CONTROL_ANSWER:
1352                                         /* This is our guy if someone answered. */
1353                                         if (!peer) {
1354                                                 ast_verb(3, "%s answered %s\n", ast_channel_name(c), ast_channel_name(in));
1355                                                 if (o->orig_chan_name
1356                                                         && strcmp(o->orig_chan_name, ast_channel_name(c))) {
1357                                                         /*
1358                                                          * The channel name changed so we must generate COLP update.
1359                                                          * Likely because a call pickup channel masqueraded in.
1360                                                          */
1361                                                         update_connected_line_from_peer(in, c, 1);
1362                                                 } else if (!single && !ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1363                                                         if (o->pending_connected_update) {
1364                                                                 if (ast_channel_connected_line_sub(c, in, &o->connected, 0) &&
1365                                                                         ast_channel_connected_line_macro(c, in, &o->connected, 1, 0)) {
1366                                                                         ast_channel_update_connected_line(in, &o->connected, NULL);
1367                                                                 }
1368                                                         } else if (!ast_test_flag64(o, DIAL_CALLERID_ABSENT)) {
1369                                                                 update_connected_line_from_peer(in, c, 1);
1370                                                         }
1371                                                 }
1372                                                 if (o->aoc_s_rate_list) {
1373                                                         size_t encoded_size;
1374                                                         struct ast_aoc_encoded *encoded;
1375                                                         if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
1376                                                                 ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
1377                                                                 ast_aoc_destroy_encoded(encoded);
1378                                                         }
1379                                                 }
1380                                                 peer = c;
1381                                                 /* Inform everyone else that they've been canceled.
1382                                                  * The dial end event for the peer will be sent out after
1383                                                  * other Dial options have been handled.
1384                                                  */
1385                                                 publish_dial_end_event(in, out_chans, peer, "CANCEL");
1386                                                 ast_copy_flags64(peerflags, o,
1387                                                         OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1388                                                         OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1389                                                         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1390                                                         OPT_CALLEE_PARK | OPT_CALLER_PARK |
1391                                                         OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1392                                                         DIAL_NOFORWARDHTML);
1393                                                 ast_channel_dialcontext_set(c, "");
1394                                                 ast_channel_exten_set(c, "");
1395                                                 if (CAN_EARLY_BRIDGE(peerflags, in, peer)) {
1396                                                         /* Setup early bridge if appropriate */
1397                                                         ast_channel_early_bridge(in, peer);
1398                                                 }
1399                                         }
1400                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
1401                                         ast_channel_hangupcause_set(in, AST_CAUSE_NORMAL_CLEARING);
1402                                         ast_channel_hangupcause_set(c, AST_CAUSE_NORMAL_CLEARING);
1403                                         break;
1404                                 case AST_CONTROL_BUSY:
1405                                         ast_verb(3, "%s is busy\n", ast_channel_name(c));
1406                                         ast_channel_hangupcause_set(in, ast_channel_hangupcause(c));
1407                                         ast_channel_publish_dial(in, c, NULL, "BUSY");
1408                                         ast_hangup(c);
1409                                         c = o->chan = NULL;
1410                                         ast_clear_flag64(o, DIAL_STILLGOING);
1411                                         handle_cause(AST_CAUSE_BUSY, &num);
1412                                         break;
1413                                 case AST_CONTROL_CONGESTION:
1414                                         ast_verb(3, "%s is circuit-busy\n", ast_channel_name(c));
1415                                         ast_channel_hangupcause_set(in, ast_channel_hangupcause(c));
1416                                         ast_channel_publish_dial(in, c, NULL, "CONGESTION");
1417                                         ast_hangup(c);
1418                                         c = o->chan = NULL;
1419                                         ast_clear_flag64(o, DIAL_STILLGOING);
1420                                         handle_cause(AST_CAUSE_CONGESTION, &num);
1421                                         break;
1422                                 case AST_CONTROL_RINGING:
1423                                         /* This is a tricky area to get right when using a native
1424                                          * CC agent. The reason is that we do the best we can to send only a
1425                                          * single ringing notification to the caller.
1426                                          *
1427                                          * Call completion complicates the logic used here. CCNR is typically
1428                                          * offered during a ringing message. Let's say that party A calls
1429                                          * parties B, C, and D. B and C do not support CC requests, but D
1430                                          * does. If we were to receive a ringing notification from B before
1431                                          * the others, then we would end up sending a ringing message to
1432                                          * A with no CCNR offer present.
1433                                          *
1434                                          * The approach that we have taken is that if we receive a ringing
1435                                          * response from a party and no CCNR offer is present, we need to
1436                                          * wait. Specifically, we need to wait until either a) a called party
1437                                          * offers CCNR in its ringing response or b) all called parties have
1438                                          * responded in some way to our call and none offers CCNR.
1439                                          *
1440                                          * The drawback to this is that if one of the parties has a delayed
1441                                          * response or, god forbid, one just plain doesn't respond to our
1442                                          * outgoing call, then this will result in a significant delay between
1443                                          * when the caller places the call and hears ringback.
1444                                          *
1445                                          * Note also that if CC is disabled for this call, then it is perfectly
1446                                          * fine for ringing frames to get sent through.
1447                                          */
1448                                         ++num_ringing;
1449                                         if (ignore_cc || cc_frame_received || num_ringing == numlines) {
1450                                                 ast_verb(3, "%s is ringing\n", ast_channel_name(c));
1451                                                 /* Setup early media if appropriate */
1452                                                 if (single && !caller_entertained
1453                                                         && CAN_EARLY_BRIDGE(peerflags, in, c)) {
1454                                                         ast_channel_early_bridge(in, c);
1455                                                 }
1456                                                 if (!(pa->sentringing) && !ast_test_flag64(outgoing, OPT_MUSICBACK) && ast_strlen_zero(opt_args[OPT_ARG_RINGBACK])) {
1457                                                         ast_indicate(in, AST_CONTROL_RINGING);
1458                                                         pa->sentringing++;
1459                                                 }
1460                                         }
1461                                         ast_channel_publish_dial(in, c, NULL, "RINGING");
1462                                         break;
1463                                 case AST_CONTROL_PROGRESS:
1464                                         ast_verb(3, "%s is making progress passing it to %s\n", ast_channel_name(c), ast_channel_name(in));
1465                                         /* Setup early media if appropriate */
1466                                         if (single && !caller_entertained
1467                                                 && CAN_EARLY_BRIDGE(peerflags, in, c)) {
1468                                                 ast_channel_early_bridge(in, c);
1469                                         }
1470                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK)) {
1471                                                 if (single || (!single && !pa->sentringing)) {
1472                                                         ast_indicate(in, AST_CONTROL_PROGRESS);
1473                                                 }
1474                                         }
1475                                         if (!ast_strlen_zero(dtmf_progress)) {
1476                                                 ast_verb(3,
1477                                                         "Sending DTMF '%s' to the called party as result of receiving a PROGRESS message.\n",
1478                                                         dtmf_progress);
1479                                                 ast_dtmf_stream(c, in, dtmf_progress, 250, 0);
1480                                         }
1481                                         ast_channel_publish_dial(in, c, NULL, "PROGRESS");
1482                                         break;
1483                                 case AST_CONTROL_VIDUPDATE:
1484                                 case AST_CONTROL_SRCUPDATE:
1485                                 case AST_CONTROL_SRCCHANGE:
1486                                         if (!single || caller_entertained) {
1487                                                 break;
1488                                         }
1489                                         ast_verb(3, "%s requested media update control %d, passing it to %s\n",
1490                                                 ast_channel_name(c), f->subclass.integer, ast_channel_name(in));
1491                                         ast_indicate(in, f->subclass.integer);
1492                                         break;
1493                                 case AST_CONTROL_CONNECTED_LINE:
1494                                         if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1495                                                 ast_verb(3, "Connected line update to %s prevented.\n", ast_channel_name(in));
1496                                                 break;
1497                                         }
1498                                         if (!single) {
1499                                                 struct ast_party_connected_line connected;
1500
1501                                                 ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n",
1502                                                         ast_channel_name(c), ast_channel_name(in));
1503                                                 ast_party_connected_line_set_init(&connected, &o->connected);
1504                                                 ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
1505                                                 ast_party_connected_line_set(&o->connected, &connected, NULL);
1506                                                 ast_party_connected_line_free(&connected);
1507                                                 o->pending_connected_update = 1;
1508                                                 break;
1509                                         }
1510                                         if (ast_channel_connected_line_sub(c, in, f, 1) &&
1511                                                 ast_channel_connected_line_macro(c, in, f, 1, 1)) {
1512                                                 ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
1513                                         }
1514                                         break;
1515                                 case AST_CONTROL_AOC:
1516                                         {
1517                                                 struct ast_aoc_decoded *decoded = ast_aoc_decode(f->data.ptr, f->datalen, o->chan);
1518                                                 if (decoded && (ast_aoc_get_msg_type(decoded) == AST_AOC_S)) {
1519                                                         ast_aoc_destroy_decoded(o->aoc_s_rate_list);
1520                                                         o->aoc_s_rate_list = decoded;
1521                                                 } else {
1522                                                         ast_aoc_destroy_decoded(decoded);
1523                                                 }
1524                                         }
1525                                         break;
1526                                 case AST_CONTROL_REDIRECTING:
1527                                         if (!single) {
1528                                                 /*
1529                                                  * Redirecting updates to the caller make sense only on single
1530                                                  * calls.
1531                                                  */
1532                                                 break;
1533                                         }
1534                                         if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1535                                                 ast_verb(3, "Redirecting update to %s prevented.\n", ast_channel_name(in));
1536                                                 break;
1537                                         }
1538                                         ast_verb(3, "%s redirecting info has changed, passing it to %s\n",
1539                                                 ast_channel_name(c), ast_channel_name(in));
1540                                         if (ast_channel_redirecting_sub(c, in, f, 1) &&
1541                                                 ast_channel_redirecting_macro(c, in, f, 1, 1)) {
1542                                                 ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
1543                                         }
1544                                         pa->sentringing = 0;
1545                                         break;
1546                                 case AST_CONTROL_PROCEEDING:
1547                                         ast_verb(3, "%s is proceeding passing it to %s\n", ast_channel_name(c), ast_channel_name(in));
1548                                         if (single && !caller_entertained
1549                                                 && CAN_EARLY_BRIDGE(peerflags, in, c)) {
1550                                                 ast_channel_early_bridge(in, c);
1551                                         }
1552                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
1553                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
1554                                         ast_channel_publish_dial(in, c, NULL, "PROCEEDING");
1555                                         break;
1556                                 case AST_CONTROL_HOLD:
1557                                         /* XXX this should be saved like AST_CONTROL_CONNECTED_LINE for !single || caller_entertained */
1558                                         ast_verb(3, "Call on %s placed on hold\n", ast_channel_name(c));
1559                                         ast_indicate_data(in, AST_CONTROL_HOLD, f->data.ptr, f->datalen);
1560                                         break;
1561                                 case AST_CONTROL_UNHOLD:
1562                                         /* XXX this should be saved like AST_CONTROL_CONNECTED_LINE for !single || caller_entertained */
1563                                         ast_verb(3, "Call on %s left from hold\n", ast_channel_name(c));
1564                                         ast_indicate(in, AST_CONTROL_UNHOLD);
1565                                         break;
1566                                 case AST_CONTROL_OFFHOOK:
1567                                 case AST_CONTROL_FLASH:
1568                                         /* Ignore going off hook and flash */
1569                                         break;
1570                                 case AST_CONTROL_CC:
1571                                         if (!ignore_cc) {
1572                                                 ast_handle_cc_control_frame(in, c, f->data.ptr);
1573                                                 cc_frame_received = 1;
1574                                         }
1575                                         break;
1576                                 case AST_CONTROL_PVT_CAUSE_CODE:
1577                                         ast_indicate_data(in, AST_CONTROL_PVT_CAUSE_CODE, f->data.ptr, f->datalen);
1578                                         break;
1579                                 case -1:
1580                                         if (single && !caller_entertained) {
1581                                                 ast_verb(3, "%s stopped sounds\n", ast_channel_name(c));
1582                                                 ast_indicate(in, -1);
1583                                                 pa->sentringing = 0;
1584                                         }
1585                                         break;
1586                                 default:
1587                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
1588                                         break;
1589                                 }
1590                                 break;
1591                         case AST_FRAME_VIDEO:
1592                         case AST_FRAME_VOICE:
1593                         case AST_FRAME_IMAGE:
1594                                 if (caller_entertained) {
1595                                         break;
1596                                 }
1597                                 /* Fall through */
1598                         case AST_FRAME_TEXT:
1599                                 if (single && ast_write(in, f)) {
1600                                         ast_log(LOG_WARNING, "Unable to write frametype: %u\n",
1601                                                 f->frametype);
1602                                 }
1603                                 break;
1604                         case AST_FRAME_HTML:
1605                                 if (single && !ast_test_flag64(outgoing, DIAL_NOFORWARDHTML)
1606                                         && ast_channel_sendhtml(in, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
1607                                         ast_log(LOG_WARNING, "Unable to send URL\n");
1608                                 }
1609                                 break;
1610                         default:
1611                                 break;
1612                         }
1613                         ast_frfree(f);
1614                 } /* end for */
1615                 if (winner == in) {
1616                         struct ast_frame *f = ast_read(in);
1617 #if 0
1618                         if (f && (f->frametype != AST_FRAME_VOICE))
1619                                 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1620                         else if (!f || (f->frametype != AST_FRAME_VOICE))
1621                                 printf("Hangup received on %s\n", in->name);
1622 #endif
1623                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
1624                                 /* Got hung up */
1625                                 *to = -1;
1626                                 strcpy(pa->status, "CANCEL");
1627                                 publish_dial_end_event(in, out_chans, NULL, pa->status);
1628                                 if (f) {
1629                                         if (f->data.uint32) {
1630                                                 ast_channel_hangupcause_set(in, f->data.uint32);
1631                                         }
1632                                         ast_frfree(f);
1633                                 }
1634                                 if (is_cc_recall) {
1635                                         ast_cc_completed(in, "CC completed, although the caller hung up (cancelled)");
1636                                 }
1637                                 return NULL;
1638                         }
1639
1640                         /* now f is guaranteed non-NULL */
1641                         if (f->frametype == AST_FRAME_DTMF) {
1642                                 if (ast_test_flag64(peerflags, OPT_DTMF_EXIT)) {
1643                                         const char *context;
1644                                         ast_channel_lock(in);
1645                                         context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
1646                                         if (onedigit_goto(in, context, (char) f->subclass.integer, 1)) {
1647                                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
1648                                                 *to = 0;
1649                                                 *result = f->subclass.integer;
1650                                                 strcpy(pa->status, "CANCEL");
1651                                                 publish_dial_end_event(in, out_chans, NULL, pa->status);
1652                                                 ast_frfree(f);
1653                                                 ast_channel_unlock(in);
1654                                                 if (is_cc_recall) {
1655                                                         ast_cc_completed(in, "CC completed, but the caller used DTMF to exit");
1656                                                 }
1657                                                 return NULL;
1658                                         }
1659                                         ast_channel_unlock(in);
1660                                 }
1661
1662                                 if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP) &&
1663                                         detect_disconnect(in, f->subclass.integer, &featurecode)) {
1664                                         ast_verb(3, "User requested call disconnect.\n");
1665                                         *to = 0;
1666                                         strcpy(pa->status, "CANCEL");
1667                                         publish_dial_end_event(in, out_chans, NULL, pa->status);
1668                                         ast_frfree(f);
1669                                         if (is_cc_recall) {
1670                                                 ast_cc_completed(in, "CC completed, but the caller hung up with DTMF");
1671                                         }
1672                                         return NULL;
1673                                 }
1674                         }
1675
1676                         /* Send the frame from the in channel to all outgoing channels. */
1677                         AST_LIST_TRAVERSE(out_chans, o, node) {
1678                                 if (!o->chan || !ast_test_flag64(o, DIAL_STILLGOING)) {
1679                                         /* This outgoing channel has died so don't send the frame to it. */
1680                                         continue;
1681                                 }
1682                                 switch (f->frametype) {
1683                                 case AST_FRAME_HTML:
1684                                         /* Forward HTML stuff */
1685                                         if (!ast_test_flag64(o, DIAL_NOFORWARDHTML)
1686                                                 && ast_channel_sendhtml(o->chan, f->subclass.integer, f->data.ptr, f->datalen) == -1) {
1687                                                 ast_log(LOG_WARNING, "Unable to send URL\n");
1688                                         }
1689                                         break;
1690                                 case AST_FRAME_VIDEO:
1691                                 case AST_FRAME_VOICE:
1692                                 case AST_FRAME_IMAGE:
1693                                         if (!single || caller_entertained) {
1694                                                 /*
1695                                                  * We are calling multiple parties or caller is being
1696                                                  * entertained and has thus not been made compatible.
1697                                                  * No need to check any other called parties.
1698                                                  */
1699                                                 goto skip_frame;
1700                                         }
1701                                         /* Fall through */
1702                                 case AST_FRAME_TEXT:
1703                                 case AST_FRAME_DTMF_BEGIN:
1704                                 case AST_FRAME_DTMF_END:
1705                                         if (ast_write(o->chan, f)) {
1706                                                 ast_log(LOG_WARNING, "Unable to forward frametype: %u\n",
1707                                                         f->frametype);
1708                                         }
1709                                         break;
1710                                 case AST_FRAME_CONTROL:
1711                                         switch (f->subclass.integer) {
1712                                         case AST_CONTROL_HOLD:
1713                                                 ast_verb(3, "Call on %s placed on hold\n", ast_channel_name(o->chan));
1714                                                 ast_indicate_data(o->chan, AST_CONTROL_HOLD, f->data.ptr, f->datalen);
1715                                                 break;
1716                                         case AST_CONTROL_UNHOLD:
1717                                                 ast_verb(3, "Call on %s left from hold\n", ast_channel_name(o->chan));
1718                                                 ast_indicate(o->chan, AST_CONTROL_UNHOLD);
1719                                                 break;
1720                                         case AST_CONTROL_VIDUPDATE:
1721                                         case AST_CONTROL_SRCUPDATE:
1722                                         case AST_CONTROL_SRCCHANGE:
1723                                                 if (!single || caller_entertained) {
1724                                                         /*
1725                                                          * We are calling multiple parties or caller is being
1726                                                          * entertained and has thus not been made compatible.
1727                                                          * No need to check any other called parties.
1728                                                          */
1729                                                         goto skip_frame;
1730                                                 }
1731                                                 ast_verb(3, "%s requested media update control %d, passing it to %s\n",
1732                                                         ast_channel_name(in), f->subclass.integer, ast_channel_name(o->chan));
1733                                                 ast_indicate(o->chan, f->subclass.integer);
1734                                                 break;
1735                                         case AST_CONTROL_CONNECTED_LINE:
1736                                                 if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1737                                                         ast_verb(3, "Connected line update to %s prevented.\n", ast_channel_name(o->chan));
1738                                                         break;
1739                                                 }
1740                                                 if (ast_channel_connected_line_sub(in, o->chan, f, 1) &&
1741                                                         ast_channel_connected_line_macro(in, o->chan, f, 0, 1)) {
1742                                                         ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
1743                                                 }
1744                                                 break;
1745                                         case AST_CONTROL_REDIRECTING:
1746                                                 if (ast_test_flag64(o, OPT_IGNORE_CONNECTEDLINE)) {
1747                                                         ast_verb(3, "Redirecting update to %s prevented.\n", ast_channel_name(o->chan));
1748                                                         break;
1749                                                 }
1750                                                 if (ast_channel_redirecting_sub(in, o->chan, f, 1) &&
1751                                                         ast_channel_redirecting_macro(in, o->chan, f, 0, 1)) {
1752                                                         ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
1753                                                 }
1754                                                 break;
1755                                         default:
1756                                                 /* We are not going to do anything with this frame. */
1757                                                 goto skip_frame;
1758                                         }
1759                                         break;
1760                                 default:
1761                                         /* We are not going to do anything with this frame. */
1762                                         goto skip_frame;
1763                                 }
1764                         }
1765 skip_frame:;
1766                         ast_frfree(f);
1767                 }
1768         }
1769
1770         if (!*to || ast_check_hangup(in)) {
1771                 ast_verb(3, "Nobody picked up in %d ms\n", orig);
1772                 publish_dial_end_event(in, out_chans, NULL, "NOANSWER");
1773         }
1774
1775         if (is_cc_recall) {
1776                 ast_cc_completed(in, "Recall completed!");
1777         }
1778         return peer;
1779 }
1780
1781 static int detect_disconnect(struct ast_channel *chan, char code, struct ast_str **featurecode)
1782 {
1783         char disconnect_code[AST_FEATURE_MAX_LEN];
1784         int res;
1785
1786         ast_str_append(featurecode, 1, "%c", code);
1787
1788         res = ast_get_builtin_feature(chan, "disconnect", disconnect_code, sizeof(disconnect_code));
1789         if (res) {
1790                 ast_str_reset(*featurecode);
1791                 return 0;
1792         }
1793
1794         if (strlen(disconnect_code) > ast_str_strlen(*featurecode)) {
1795                 /* Could be a partial match, anyway */
1796                 if (strncmp(disconnect_code, ast_str_buffer(*featurecode), ast_str_strlen(*featurecode))) {
1797                         ast_str_reset(*featurecode);
1798                 }
1799                 return 0;
1800         }
1801
1802         if (strcmp(disconnect_code, ast_str_buffer(*featurecode))) {
1803                 ast_str_reset(*featurecode);
1804                 return 0;
1805         }
1806
1807         return 1;
1808 }
1809
1810 /* returns true if there is a valid privacy reply */
1811 static int valid_priv_reply(struct ast_flags64 *opts, int res)
1812 {
1813         if (res < '1')
1814                 return 0;
1815         if (ast_test_flag64(opts, OPT_PRIVACY) && res <= '5')
1816                 return 1;
1817         if (ast_test_flag64(opts, OPT_SCREENING) && res <= '4')
1818                 return 1;
1819         return 0;
1820 }
1821
1822 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
1823         struct ast_flags64 *opts, char **opt_args, struct privacy_args *pa)
1824 {
1825
1826         int res2;
1827         int loopcount = 0;
1828
1829         /* Get the user's intro, store it in priv-callerintros/$CID,
1830            unless it is already there-- this should be done before the
1831            call is actually dialed  */
1832
1833         /* all ring indications and moh for the caller has been halted as soon as the
1834            target extension was picked up. We are going to have to kill some
1835            time and make the caller believe the peer hasn't picked up yet */
1836
1837         if (ast_test_flag64(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1838                 char *original_moh = ast_strdupa(ast_channel_musicclass(chan));
1839                 ast_indicate(chan, -1);
1840                 ast_channel_musicclass_set(chan, opt_args[OPT_ARG_MUSICBACK]);
1841                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1842                 ast_channel_musicclass_set(chan, original_moh);
1843         } else if (ast_test_flag64(opts, OPT_RINGBACK) || ast_test_flag64(opts, OPT_RING_WITH_EARLY_MEDIA)) {
1844                 ast_indicate(chan, AST_CONTROL_RINGING);
1845                 pa->sentringing++;
1846         }
1847
1848         /* Start autoservice on the other chan ?? */
1849         res2 = ast_autoservice_start(chan);
1850         /* Now Stream the File */
1851         for (loopcount = 0; loopcount < 3; loopcount++) {
1852                 if (res2 && loopcount == 0) /* error in ast_autoservice_start() */
1853                         break;
1854                 if (!res2) /* on timeout, play the message again */
1855                         res2 = ast_play_and_wait(peer, "priv-callpending");
1856                 if (!valid_priv_reply(opts, res2))
1857                         res2 = 0;
1858                 /* priv-callpending script:
1859                    "I have a caller waiting, who introduces themselves as:"
1860                 */
1861                 if (!res2)
1862                         res2 = ast_play_and_wait(peer, pa->privintro);
1863                 if (!valid_priv_reply(opts, res2))
1864                         res2 = 0;
1865                 /* now get input from the called party, as to their choice */
1866                 if (!res2) {
1867                         /* XXX can we have both, or they are mutually exclusive ? */
1868                         if (ast_test_flag64(opts, OPT_PRIVACY))
1869                                 res2 = ast_play_and_wait(peer, "priv-callee-options");
1870                         if (ast_test_flag64(opts, OPT_SCREENING))
1871                                 res2 = ast_play_and_wait(peer, "screen-callee-options");
1872                 }
1873
1874                 /*! \page DialPrivacy Dial Privacy scripts
1875                  * \par priv-callee-options script:
1876                  * \li Dial 1 if you wish this caller to reach you directly in the future,
1877                  *      and immediately connect to their incoming call.
1878                  * \li Dial 2 if you wish to send this caller to voicemail now and forevermore.
1879                  * \li Dial 3 to send this caller to the torture menus, now and forevermore.
1880                  * \li Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1881                  * \li Dial 5 to allow this caller to come straight thru to you in the future,
1882                  *      but right now, just this once, send them to voicemail.
1883                  *
1884                  * \par screen-callee-options script:
1885                  * \li Dial 1 if you wish to immediately connect to the incoming call
1886                  * \li Dial 2 if you wish to send this caller to voicemail.
1887                  * \li Dial 3 to send this caller to the torture menus.
1888                  * \li Dial 4 to send this caller to a simple "go away" menu.
1889                  */
1890                 if (valid_priv_reply(opts, res2))
1891                         break;
1892                 /* invalid option */
1893                 res2 = ast_play_and_wait(peer, "vm-sorry");
1894         }
1895
1896         if (ast_test_flag64(opts, OPT_MUSICBACK)) {
1897                 ast_moh_stop(chan);
1898         } else if (ast_test_flag64(opts, OPT_RINGBACK) || ast_test_flag64(opts, OPT_RING_WITH_EARLY_MEDIA)) {
1899                 ast_indicate(chan, -1);
1900                 pa->sentringing = 0;
1901         }
1902         ast_autoservice_stop(chan);
1903         if (ast_test_flag64(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
1904                 /* map keypresses to various things, the index is res2 - '1' */
1905                 static const char * const _val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
1906                 static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
1907                 int i = res2 - '1';
1908                 ast_verb(3, "--Set privacy database entry %s/%s to %s\n",
1909                         opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
1910                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
1911         }
1912         switch (res2) {
1913         case '1':
1914                 break;
1915         case '2':
1916                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1917                 break;
1918         case '3':
1919                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1920                 break;
1921         case '4':
1922                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1923                 break;
1924         case '5':
1925                 if (ast_test_flag64(opts, OPT_PRIVACY)) {
1926                         ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1927                         break;
1928                 }
1929                 /* if not privacy, then 5 is the same as "default" case */
1930         default: /* bad input or -1 if failure to start autoservice */
1931                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1932                 /* well, there seems basically two choices. Just patch the caller thru immediately,
1933                           or,... put 'em thru to voicemail. */
1934                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1935                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1936                 /* XXX should we set status to DENY ? */
1937                 /* XXX what about the privacy flags ? */
1938                 break;
1939         }
1940
1941         if (res2 == '1') { /* the only case where we actually connect */
1942                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll
1943                    just clog things up, and it's not useful information, not being tied to a CID */
1944                 if (strncmp(pa->privcid, "NOCALLERID", 10) == 0 || ast_test_flag64(opts, OPT_SCREEN_NOINTRO)) {
1945                         ast_filedelete(pa->privintro, NULL);
1946                         if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1947                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1948                         else
1949                                 ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1950                 }
1951                 return 0; /* the good exit path */
1952         } else {
1953                 return -1;
1954         }
1955 }
1956
1957 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
1958 static int setup_privacy_args(struct privacy_args *pa,
1959         struct ast_flags64 *opts, char *opt_args[], struct ast_channel *chan)
1960 {
1961         char callerid[60];
1962         int res;
1963         char *l;
1964
1965         if (ast_channel_caller(chan)->id.number.valid
1966                 && !ast_strlen_zero(ast_channel_caller(chan)->id.number.str)) {
1967                 l = ast_strdupa(ast_channel_caller(chan)->id.number.str);
1968                 ast_shrink_phone_number(l);
1969                 if (ast_test_flag64(opts, OPT_PRIVACY) ) {
1970                         ast_verb(3, "Privacy DB is '%s', clid is '%s'\n", opt_args[OPT_ARG_PRIVACY], l);
1971                         pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
1972                 } else {
1973                         ast_verb(3, "Privacy Screening, clid is '%s'\n", l);
1974                         pa->privdb_val = AST_PRIVACY_UNKNOWN;
1975                 }
1976         } else {
1977                 char *tnam, *tn2;
1978
1979                 tnam = ast_strdupa(ast_channel_name(chan));
1980                 /* clean the channel name so slashes don't try to end up in disk file name */
1981                 for (tn2 = tnam; *tn2; tn2++) {
1982                         if (*tn2 == '/')  /* any other chars to be afraid of? */
1983                                 *tn2 = '=';
1984                 }
1985                 ast_verb(3, "Privacy-- callerid is empty\n");
1986
1987                 snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", ast_channel_exten(chan), tnam);
1988                 l = callerid;
1989                 pa->privdb_val = AST_PRIVACY_UNKNOWN;
1990         }
1991
1992         ast_copy_string(pa->privcid, l, sizeof(pa->privcid));
1993
1994         if (strncmp(pa->privcid, "NOCALLERID", 10) != 0 && ast_test_flag64(opts, OPT_SCREEN_NOCALLERID)) {
1995                 /* if callerid is set and OPT_SCREEN_NOCALLERID is set also */
1996                 ast_verb(3, "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
1997                 pa->privdb_val = AST_PRIVACY_ALLOW;
1998         } else if (ast_test_flag64(opts, OPT_SCREEN_NOCALLERID) && strncmp(pa->privcid, "NOCALLERID", 10) == 0) {
1999                 ast_verb(3, "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
2000         }
2001
2002         if (pa->privdb_val == AST_PRIVACY_DENY) {
2003                 ast_verb(3, "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
2004                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
2005                 return 0;
2006         } else if (pa->privdb_val == AST_PRIVACY_KILL) {
2007                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
2008                 return 0; /* Is this right? */
2009         } else if (pa->privdb_val == AST_PRIVACY_TORTURE) {
2010                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
2011                 return 0; /* is this right??? */
2012         } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN) {
2013                 /* Get the user's intro, store it in priv-callerintros/$CID,
2014                    unless it is already there-- this should be done before the
2015                    call is actually dialed  */
2016
2017                 /* make sure the priv-callerintros dir actually exists */
2018                 snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
2019                 if ((res = ast_mkdir(pa->privintro, 0755))) {
2020                         ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(res));
2021                         return -1;
2022                 }
2023
2024                 snprintf(pa->privintro, sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
2025                 if (ast_fileexists(pa->privintro, NULL, NULL ) > 0 && strncmp(pa->privcid, "NOCALLERID", 10) != 0) {
2026                         /* the DELUX version of this code would allow this caller the
2027                            option to hear and retape their previously recorded intro.
2028                         */
2029                 } else {
2030                         int duration; /* for feedback from play_and_wait */
2031                         /* the file doesn't exist yet. Let the caller submit his
2032                            vocal intro for posterity */
2033                         /* priv-recordintro script:
2034
2035                            "At the tone, please say your name:"
2036
2037                         */
2038                         int silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
2039                         ast_answer(chan);
2040                         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 */
2041                                                                         /* don't think we'll need a lock removed, we took care of
2042                                                                            conflicts by naming the pa.privintro file */
2043                         if (res == -1) {
2044                                 /* Delete the file regardless since they hung up during recording */
2045                                 ast_filedelete(pa->privintro, NULL);
2046                                 if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
2047                                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
2048                                 else
2049                                         ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
2050                                 return -1;
2051                         }
2052                         if (!ast_streamfile(chan, "vm-dialout", ast_channel_language(chan)) )
2053                                 ast_waitstream(chan, "");
2054                 }
2055         }
2056         return 1; /* success */
2057 }
2058
2059 static void end_bridge_callback(void *data)
2060 {
2061         char buf[80];
2062         time_t end;
2063         struct ast_channel *chan = data;
2064
2065         time(&end);
2066
2067         ast_channel_lock(chan);
2068         ast_channel_stage_snapshot(chan);
2069         snprintf(buf, sizeof(buf), "%d", ast_channel_get_up_time(chan));
2070         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", buf);
2071         snprintf(buf, sizeof(buf), "%d", ast_channel_get_duration(chan));
2072         pbx_builtin_setvar_helper(chan, "DIALEDTIME", buf);
2073         ast_channel_stage_snapshot_done(chan);
2074         ast_channel_unlock(chan);
2075 }
2076
2077 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator) {
2078         bconfig->end_bridge_callback_data = originator;
2079 }
2080
2081 static int dial_handle_playtones(struct ast_channel *chan, const char *data)
2082 {
2083         struct ast_tone_zone_sound *ts = NULL;
2084         int res;
2085         const char *str = data;
2086
2087         if (ast_strlen_zero(str)) {
2088                 ast_debug(1,"Nothing to play\n");
2089                 return -1;
2090         }
2091
2092         ts = ast_get_indication_tone(ast_channel_zone(chan), str);
2093
2094         if (ts && ts->data[0]) {
2095                 res = ast_playtones_start(chan, 0, ts->data, 0);
2096         } else {
2097                 res = -1;
2098         }
2099
2100         if (ts) {
2101                 ts = ast_tone_zone_sound_unref(ts);
2102         }
2103
2104         if (res) {
2105                 ast_log(LOG_WARNING, "Unable to start playtone \'%s\'\n", str);
2106         }
2107
2108         return res;
2109 }
2110
2111 /*!
2112  * \internal
2113  * \brief Setup the after bridge goto location on the peer.
2114  * \since 12.0.0
2115  *
2116  * \param chan Calling channel for bridge.
2117  * \param peer Peer channel for bridge.
2118  * \param opts Dialing option flags.
2119  * \param opt_args Dialing option argument strings.
2120  *
2121  * \return Nothing
2122  */
2123 static void setup_peer_after_bridge_goto(struct ast_channel *chan, struct ast_channel *peer, struct ast_flags64 *opts, char *opt_args[])
2124 {
2125         const char *context;
2126         const char *extension;
2127         int priority;
2128
2129         if (ast_test_flag64(opts, OPT_PEER_H)) {
2130                 ast_channel_lock(chan);
2131                 context = ast_strdupa(ast_channel_context(chan));
2132                 ast_channel_unlock(chan);
2133                 ast_bridge_set_after_h(peer, context);
2134         } else if (ast_test_flag64(opts, OPT_CALLEE_GO_ON)) {
2135                 ast_channel_lock(chan);
2136                 context = ast_strdupa(ast_channel_context(chan));
2137                 extension = ast_strdupa(ast_channel_exten(chan));
2138                 priority = ast_channel_priority(chan);
2139                 ast_channel_unlock(chan);
2140                 ast_bridge_set_after_go_on(peer, context, extension, priority,
2141                         opt_args[OPT_ARG_CALLEE_GO_ON]);
2142         }
2143 }
2144
2145 static int dial_exec_full(struct ast_channel *chan, const char *data, struct ast_flags64 *peerflags, int *continue_exec)
2146 {
2147         int res = -1; /* default: error */
2148         char *rest, *cur; /* scan the list of destinations */
2149         struct dial_head out_chans = AST_LIST_HEAD_NOLOCK_INIT_VALUE; /* list of destinations */
2150         struct chanlist *outgoing;
2151         struct chanlist *tmp;
2152         struct ast_channel *peer;
2153         int to; /* timeout */
2154         struct cause_args num = { chan, 0, 0, 0 };
2155         int cause;
2156
2157         struct ast_bridge_config config = { { 0, } };
2158         struct timeval calldurationlimit = { 0, };
2159         char *dtmfcalled = NULL, *dtmfcalling = NULL, *dtmf_progress=NULL;
2160         struct privacy_args pa = {
2161                 .sentringing = 0,
2162                 .privdb_val = 0,
2163                 .status = "INVALIDARGS",
2164         };
2165         int sentringing = 0, moh = 0;
2166         const char *outbound_group = NULL;
2167         int result = 0;
2168         char *parse;
2169         int opermode = 0;
2170         int delprivintro = 0;
2171         AST_DECLARE_APP_ARGS(args,
2172                 AST_APP_ARG(peers);
2173                 AST_APP_ARG(timeout);
2174                 AST_APP_ARG(options);
2175                 AST_APP_ARG(url);
2176         );
2177         struct ast_flags64 opts = { 0, };
2178         char *opt_args[OPT_ARG_ARRAY_SIZE];
2179         int fulldial = 0, num_dialed = 0;
2180         int ignore_cc = 0;
2181         char device_name[AST_CHANNEL_NAME];
2182         char forced_clid_name[AST_MAX_EXTENSION];
2183         char stored_clid_name[AST_MAX_EXTENSION];
2184         int force_forwards_only;        /*!< TRUE if force CallerID on call forward only. Legacy behaviour.*/
2185         /*!
2186          * \brief Forced CallerID party information to send.
2187          * \note This will not have any malloced strings so do not free it.
2188          */
2189         struct ast_party_id forced_clid;
2190         /*!
2191          * \brief Stored CallerID information if needed.
2192          *
2193          * \note If OPT_ORIGINAL_CLID set then this is the o option
2194          * CallerID.  Otherwise it is the dialplan extension and hint
2195          * name.
2196          *
2197          * \note This will not have any malloced strings so do not free it.
2198          */
2199         struct ast_party_id stored_clid;
2200         /*!
2201          * \brief CallerID party information to store.
2202          * \note This will not have any malloced strings so do not free it.
2203          */
2204         struct ast_party_caller caller;
2205         int max_forwards;
2206
2207         /* Reset all DIAL variables back to blank, to prevent confusion (in case we don't reset all of them). */
2208         ast_channel_lock(chan);
2209         ast_channel_stage_snapshot(chan);
2210         pbx_builtin_setvar_helper(chan, "DIALSTATUS", "");
2211         pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", "");
2212         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", "");
2213         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", "");
2214         pbx_builtin_setvar_helper(chan, "DIALEDTIME", "");
2215         ast_channel_stage_snapshot_done(chan);
2216         max_forwards = ast_max_forwards_get(chan);
2217         ast_channel_unlock(chan);
2218
2219         if (max_forwards <= 0) {
2220                 ast_log(LOG_WARNING, "Cannot place outbound call from channel '%s'. Max forwards exceeded\n",
2221                                 ast_channel_name(chan));
2222                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", "BUSY");
2223                 return -1;
2224         }
2225
2226         if (ast_strlen_zero(data)) {
2227                 ast_log(LOG_WARNING, "Dial requires an argument (technology/resource)\n");
2228                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2229                 return -1;
2230         }
2231
2232         if (ast_check_hangup_locked(chan)) {
2233                 /*
2234                  * Caller hung up before we could dial.  If dial is executed
2235                  * within an AGI then the AGI has likely eaten all queued
2236                  * frames before executing the dial in DeadAGI mode.  With
2237                  * the caller hung up and no pending frames from the caller's
2238                  * read queue, dial would not know that the call has hung up
2239                  * until a called channel answers.  It is rather annoying to
2240                  * whoever just answered the non-existent call.
2241                  *
2242                  * Dial should not continue execution in DeadAGI mode, hangup
2243                  * handlers, or the h exten.
2244                  */
2245                 ast_verb(3, "Caller hung up before dial.\n");
2246                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", "CANCEL");
2247                 return -1;
2248         }
2249
2250         parse = ast_strdupa(data);
2251
2252         AST_STANDARD_APP_ARGS(args, parse);
2253
2254         if (!ast_strlen_zero(args.options) &&
2255                 ast_app_parse_options64(dial_exec_options, &opts, opt_args, args.options)) {
2256                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2257                 goto done;
2258         }
2259
2260         if (ast_strlen_zero(args.peers)) {
2261                 ast_log(LOG_WARNING, "Dial requires an argument (technology/resource)\n");
2262                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2263                 goto done;
2264         }
2265
2266         if (ast_cc_call_init(chan, &ignore_cc)) {
2267                 goto done;
2268         }
2269
2270         if (ast_test_flag64(&opts, OPT_SCREEN_NOINTRO) && !ast_strlen_zero(opt_args[OPT_ARG_SCREEN_NOINTRO])) {
2271                 delprivintro = atoi(opt_args[OPT_ARG_SCREEN_NOINTRO]);
2272
2273                 if (delprivintro < 0 || delprivintro > 1) {
2274                         ast_log(LOG_WARNING, "Unknown argument %d specified to n option, ignoring\n", delprivintro);
2275                         delprivintro = 0;
2276                 }
2277         }
2278
2279         if (!ast_test_flag64(&opts, OPT_RINGBACK)) {
2280                 opt_args[OPT_ARG_RINGBACK] = NULL;
2281         }
2282
2283         if (ast_test_flag64(&opts, OPT_OPERMODE)) {
2284                 opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
2285                 ast_verb(3, "Setting operator services mode to %d.\n", opermode);
2286         }
2287
2288         if (ast_test_flag64(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
2289                 calldurationlimit.tv_sec = atoi(opt_args[OPT_ARG_DURATION_STOP]);
2290                 if (!calldurationlimit.tv_sec) {
2291                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
2292                         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2293                         goto done;
2294                 }
2295                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n", calldurationlimit.tv_sec + calldurationlimit.tv_usec / 1000000.0);
2296         }
2297
2298         if (ast_test_flag64(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
2299                 dtmf_progress = opt_args[OPT_ARG_SENDDTMF];
2300                 dtmfcalled = strsep(&dtmf_progress, ":");
2301                 dtmfcalling = strsep(&dtmf_progress, ":");
2302         }
2303
2304         if (ast_test_flag64(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
2305                 if (ast_bridge_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
2306                         goto done;
2307         }
2308
2309         /* Setup the forced CallerID information to send if used. */
2310         ast_party_id_init(&forced_clid);
2311         force_forwards_only = 0;
2312         if (ast_test_flag64(&opts, OPT_FORCECLID)) {
2313                 if (ast_strlen_zero(opt_args[OPT_ARG_FORCECLID])) {
2314                         ast_channel_lock(chan);
2315                         forced_clid.number.str = ast_strdupa(S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan)));
2316                         ast_channel_unlock(chan);
2317                         forced_clid_name[0] = '\0';
2318                         forced_clid.name.str = (char *) get_cid_name(forced_clid_name,
2319                                 sizeof(forced_clid_name), chan);
2320                         force_forwards_only = 1;
2321                 } else {
2322                         /* Note: The opt_args[OPT_ARG_FORCECLID] string value is altered here. */
2323                         ast_callerid_parse(opt_args[OPT_ARG_FORCECLID], &forced_clid.name.str,
2324                                 &forced_clid.number.str);
2325                 }
2326                 if (!ast_strlen_zero(forced_clid.name.str)) {
2327                         forced_clid.name.valid = 1;
2328                 }
2329                 if (!ast_strlen_zero(forced_clid.number.str)) {
2330                         forced_clid.number.valid = 1;
2331                 }
2332         }
2333         if (ast_test_flag64(&opts, OPT_FORCE_CID_TAG)
2334                 && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_TAG])) {
2335                 forced_clid.tag = opt_args[OPT_ARG_FORCE_CID_TAG];
2336         }
2337         forced_clid.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
2338         if (ast_test_flag64(&opts, OPT_FORCE_CID_PRES)
2339                 && !ast_strlen_zero(opt_args[OPT_ARG_FORCE_CID_PRES])) {
2340                 int pres;
2341
2342                 pres = ast_parse_caller_presentation(opt_args[OPT_ARG_FORCE_CID_PRES]);
2343                 if (0 <= pres) {
2344                         forced_clid.number.presentation = pres;
2345                 }
2346         }
2347
2348         /* Setup the stored CallerID information if needed. */
2349         ast_party_id_init(&stored_clid);
2350         if (ast_test_flag64(&opts, OPT_ORIGINAL_CLID)) {
2351                 if (ast_strlen_zero(opt_args[OPT_ARG_ORIGINAL_CLID])) {
2352                         ast_channel_lock(chan);
2353                         ast_party_id_set_init(&stored_clid, &ast_channel_caller(chan)->id);
2354                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.name.str)) {
2355                                 stored_clid.name.str = ast_strdupa(ast_channel_caller(chan)->id.name.str);
2356                         }
2357                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.number.str)) {
2358                                 stored_clid.number.str = ast_strdupa(ast_channel_caller(chan)->id.number.str);
2359                         }
2360                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.subaddress.str)) {
2361                                 stored_clid.subaddress.str = ast_strdupa(ast_channel_caller(chan)->id.subaddress.str);
2362                         }
2363                         if (!ast_strlen_zero(ast_channel_caller(chan)->id.tag)) {
2364                                 stored_clid.tag = ast_strdupa(ast_channel_caller(chan)->id.tag);
2365                         }
2366                         ast_channel_unlock(chan);
2367                 } else {
2368                         /* Note: The opt_args[OPT_ARG_ORIGINAL_CLID] string value is altered here. */
2369                         ast_callerid_parse(opt_args[OPT_ARG_ORIGINAL_CLID], &stored_clid.name.str,
2370                                 &stored_clid.number.str);
2371                         if (!ast_strlen_zero(stored_clid.name.str)) {
2372                                 stored_clid.name.valid = 1;
2373                         }
2374                         if (!ast_strlen_zero(stored_clid.number.str)) {
2375                                 stored_clid.number.valid = 1;
2376                         }
2377                 }
2378         } else {
2379                 /*
2380                  * In case the new channel has no preset CallerID number by the
2381                  * channel driver, setup the dialplan extension and hint name.
2382                  */
2383                 stored_clid_name[0] = '\0';
2384                 stored_clid.name.str = (char *) get_cid_name(stored_clid_name,
2385                         sizeof(stored_clid_name), chan);
2386                 if (ast_strlen_zero(stored_clid.name.str)) {
2387                         stored_clid.name.str = NULL;
2388                 } else {
2389                         stored_clid.name.valid = 1;
2390                 }
2391                 ast_channel_lock(chan);
2392                 stored_clid.number.str = ast_strdupa(S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan)));
2393                 stored_clid.number.valid = 1;
2394                 ast_channel_unlock(chan);
2395         }
2396
2397         if (ast_test_flag64(&opts, OPT_RESETCDR)) {
2398                 ast_cdr_reset(ast_channel_name(chan), 0);
2399         }
2400         if (ast_test_flag64(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
2401                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(ast_channel_exten(chan));
2402
2403         if (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) {
2404                 res = setup_privacy_args(&pa, &opts, opt_args, chan);
2405                 if (res <= 0)
2406                         goto out;
2407                 res = -1; /* reset default */
2408         }
2409
2410         if (continue_exec)
2411                 *continue_exec = 0;
2412
2413         /* If a channel group has been specified, get it for use when we create peer channels */
2414
2415         ast_channel_lock(chan);
2416         if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
2417                 outbound_group = ast_strdupa(outbound_group);
2418                 pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
2419         } else if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP"))) {
2420                 outbound_group = ast_strdupa(outbound_group);
2421         }
2422         ast_channel_unlock(chan);
2423
2424         /* Set per dial instance flags.  These flags are also passed back to RetryDial. */
2425         ast_copy_flags64(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID
2426                 | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING | OPT_CANCEL_TIMEOUT
2427                 | OPT_ANNOUNCE | OPT_CALLEE_MACRO | OPT_CALLEE_GOSUB | OPT_FORCECLID);
2428
2429         /* PREDIAL: Run gosub on the caller's channel */
2430         if (ast_test_flag64(&opts, OPT_PREDIAL_CALLER)
2431                 && !ast_strlen_zero(opt_args[OPT_ARG_PREDIAL_CALLER])) {
2432                 ast_replace_subargument_delimiter(opt_args[OPT_ARG_PREDIAL_CALLER]);
2433                 ast_app_exec_sub(NULL, chan, opt_args[OPT_ARG_PREDIAL_CALLER], 0);
2434         }
2435
2436         /* loop through the list of dial destinations */
2437         rest = args.peers;
2438         while ((cur = strsep(&rest, "&")) ) {
2439                 struct ast_channel *tc; /* channel for this destination */
2440                 /* Get a technology/resource pair */
2441                 char *number = cur;
2442                 char *tech = strsep(&number, "/");
2443                 size_t tech_len;
2444                 size_t number_len;
2445                 struct ast_stream_topology *topology;
2446
2447                 num_dialed++;
2448                 if (ast_strlen_zero(number)) {
2449                         ast_log(LOG_WARNING, "Dial argument takes format (technology/resource)\n");
2450                         goto out;
2451                 }
2452
2453                 tech_len = strlen(tech) + 1;
2454                 number_len = strlen(number) + 1;
2455                 tmp = ast_calloc(1, sizeof(*tmp) + (2 * tech_len) + number_len);
2456                 if (!tmp) {
2457                         goto out;
2458                 }
2459
2460                 /* Save tech, number, and interface. */
2461                 cur = tmp->stuff;
2462                 strcpy(cur, tech);
2463                 tmp->tech = cur;
2464                 cur += tech_len;
2465                 strcpy(cur, tech);
2466                 cur[tech_len - 1] = '/';
2467                 tmp->interface = cur;
2468                 cur += tech_len;
2469                 strcpy(cur, number);
2470                 tmp->number = cur;
2471
2472                 if (opts.flags) {
2473                         /* Set per outgoing call leg options. */
2474                         ast_copy_flags64(tmp, &opts,
2475                                 OPT_CANCEL_ELSEWHERE |
2476                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
2477                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
2478                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
2479                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
2480                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
2481                                 OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID | OPT_IGNORE_CONNECTEDLINE |
2482                                 OPT_RING_WITH_EARLY_MEDIA);
2483                         ast_set2_flag64(tmp, args.url, DIAL_NOFORWARDHTML);
2484                 }
2485
2486                 /* Request the peer */
2487
2488                 ast_channel_lock(chan);
2489                 /*
2490                  * Seed the chanlist's connected line information with previously
2491                  * acquired connected line info from the incoming channel.  The
2492                  * previously acquired connected line info could have been set
2493                  * through the CONNECTED_LINE dialplan function.
2494                  */
2495                 ast_party_connected_line_copy(&tmp->connected, ast_channel_connected(chan));
2496
2497                 topology = ast_stream_topology_clone(ast_channel_get_stream_topology(chan));
2498
2499                 ast_channel_unlock(chan);
2500
2501                 tc = ast_request_with_stream_topology(tmp->tech, topology, NULL, chan, tmp->number, &cause);
2502
2503                 ast_stream_topology_free(topology);
2504
2505                 if (!tc) {
2506                         /* If we can't, just go on to the next call */
2507                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
2508                                 tmp->tech, cause, ast_cause2str(cause));
2509                         handle_cause(cause, &num);
2510                         if (!rest) {
2511                                 /* we are on the last destination */
2512                                 ast_channel_hangupcause_set(chan, cause);
2513                         }
2514                         if (!ignore_cc && (cause == AST_CAUSE_BUSY || cause == AST_CAUSE_CONGESTION)) {
2515                                 if (!ast_cc_callback(chan, tmp->tech, tmp->number, ast_cc_busy_interface)) {