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