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