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