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