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