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