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