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