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