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