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