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