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