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