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