Option to send DTMF when receiving PROGRESS status
[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
564 static void hanguptree(struct chanlist *outgoing, struct ast_channel *exception, int answered_elsewhere)
565 {
566         /* Hang up a tree of stuff */
567         struct chanlist *oo;
568         while (outgoing) {
569                 /* Hangup any existing lines we have open */
570                 if (outgoing->chan && (outgoing->chan != exception)) {
571                         if (answered_elsewhere) {
572                                 /* The flag is used for local channel inheritance and stuff */
573                                 ast_set_flag(outgoing->chan, AST_FLAG_ANSWERED_ELSEWHERE);
574                                 /* This is for the channel drivers */
575                                 outgoing->chan->hangupcause = AST_CAUSE_ANSWERED_ELSEWHERE;
576                         }
577                         ast_hangup(outgoing->chan);
578                 }
579                 oo = outgoing;
580                 outgoing = outgoing->next;
581                 ast_free(oo);
582         }
583 }
584
585 #define AST_MAX_WATCHERS 256
586
587 /*
588  * argument to handle_cause() and other functions.
589  */
590 struct cause_args {
591         struct ast_channel *chan;
592         int busy;
593         int congestion;
594         int nochan;
595 };
596
597 static void handle_cause(int cause, struct cause_args *num)
598 {
599         struct ast_cdr *cdr = num->chan->cdr;
600
601         switch(cause) {
602         case AST_CAUSE_BUSY:
603                 if (cdr)
604                         ast_cdr_busy(cdr);
605                 num->busy++;
606                 break;
607
608         case AST_CAUSE_CONGESTION:
609                 if (cdr)
610                         ast_cdr_failed(cdr);
611                 num->congestion++;
612                 break;
613
614         case AST_CAUSE_NO_ROUTE_DESTINATION:
615         case AST_CAUSE_UNREGISTERED:
616                 if (cdr)
617                         ast_cdr_failed(cdr);
618                 num->nochan++;
619                 break;
620
621         case AST_CAUSE_NORMAL_CLEARING:
622                 break;
623
624         default:
625                 num->nochan++;
626                 break;
627         }
628 }
629
630 /* free the buffer if allocated, and set the pointer to the second arg */
631 #define S_REPLACE(s, new_val)           \
632         do {                            \
633                 if (s)                  \
634                         ast_free(s);    \
635                 s = (new_val);          \
636         } while (0)
637
638 static int onedigit_goto(struct ast_channel *chan, const char *context, char exten, int pri)
639 {
640         char rexten[2] = { exten, '\0' };
641
642         if (context) {
643                 if (!ast_goto_if_exists(chan, context, rexten, pri))
644                         return 1;
645         } else {
646                 if (!ast_goto_if_exists(chan, chan->context, rexten, pri))
647                         return 1;
648                 else if (!ast_strlen_zero(chan->macrocontext)) {
649                         if (!ast_goto_if_exists(chan, chan->macrocontext, rexten, pri))
650                                 return 1;
651                 }
652         }
653         return 0;
654 }
655
656
657 static const char *get_cid_name(char *name, int namelen, struct ast_channel *chan)
658 {
659         const char *context = S_OR(chan->macrocontext, chan->context);
660         const char *exten = S_OR(chan->macroexten, chan->exten);
661
662         return ast_get_hint(NULL, 0, name, namelen, chan, context, exten) ? name : "";
663 }
664
665 static void senddialevent(struct ast_channel *src, struct ast_channel *dst, const char *dialstring)
666 {
667         manager_event(EVENT_FLAG_CALL, "Dial",
668                 "SubEvent: Begin\r\n"
669                 "Channel: %s\r\n"
670                 "Destination: %s\r\n"
671                 "CallerIDNum: %s\r\n"
672                 "CallerIDName: %s\r\n"
673                 "UniqueID: %s\r\n"
674                 "DestUniqueID: %s\r\n"
675                 "Dialstring: %s\r\n",
676                 src->name, dst->name, S_OR(src->cid.cid_num, "<unknown>"),
677                 S_OR(src->cid.cid_name, "<unknown>"), src->uniqueid,
678                 dst->uniqueid, dialstring ? dialstring : "");
679 }
680
681 static void senddialendevent(const struct ast_channel *src, const char *dialstatus)
682 {
683         manager_event(EVENT_FLAG_CALL, "Dial",
684                 "SubEvent: End\r\n"
685                 "Channel: %s\r\n"
686                 "UniqueID: %s\r\n"
687                 "DialStatus: %s\r\n",
688                 src->name, src->uniqueid, dialstatus);
689 }
690
691 /*!
692  * helper function for wait_for_answer()
693  *
694  * XXX this code is highly suspicious, as it essentially overwrites
695  * the outgoing channel without properly deleting it.
696  */
697 static void do_forward(struct chanlist *o,
698         struct cause_args *num, struct ast_flags64 *peerflags, int single)
699 {
700         char tmpchan[256];
701         struct ast_channel *original = o->chan;
702         struct ast_channel *c = o->chan; /* the winner */
703         struct ast_channel *in = num->chan; /* the input channel */
704         char *stuff;
705         char *tech;
706         int cause;
707
708         ast_copy_string(tmpchan, c->call_forward, sizeof(tmpchan));
709         if ((stuff = strchr(tmpchan, '/'))) {
710                 *stuff++ = '\0';
711                 tech = tmpchan;
712         } else {
713                 const char *forward_context;
714                 ast_channel_lock(c);
715                 forward_context = pbx_builtin_getvar_helper(c, "FORWARD_CONTEXT");
716                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", c->call_forward, forward_context ? forward_context : c->context);
717                 ast_channel_unlock(c);
718                 stuff = tmpchan;
719                 tech = "Local";
720         }
721         /* Before processing channel, go ahead and check for forwarding */
722         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, c->name);
723         /* If we have been told to ignore forwards, just set this channel to null and continue processing extensions normally */
724         if (ast_test_flag64(peerflags, OPT_IGNORE_FORWARDING)) {
725                 ast_verb(3, "Forwarding %s to '%s/%s' prevented.\n", in->name, tech, stuff);
726                 c = o->chan = NULL;
727                 cause = AST_CAUSE_BUSY;
728         } else {
729                 /* Setup parameters */
730                 c = o->chan = ast_request(tech, in->nativeformats, stuff, &cause);
731                 if (c) {
732                         if (single)
733                                 ast_channel_make_compatible(o->chan, in);
734                         ast_channel_inherit_variables(in, o->chan);
735                         ast_channel_datastore_inherit(in, o->chan);
736                 } else
737                         ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s' (cause = %d)\n", tech, stuff, cause);
738         }
739         if (!c) {
740                 ast_clear_flag64(o, DIAL_STILLGOING);
741                 handle_cause(cause, num);
742                 ast_hangup(original);
743         } else {
744                 char *new_cid_num, *new_cid_name;
745                 struct ast_channel *src;
746
747                 ast_rtp_make_compatible(c, in, single);
748                 if (ast_test_flag64(o, OPT_FORCECLID)) {
749                         new_cid_num = ast_strdup(S_OR(in->macroexten, in->exten));
750                         new_cid_name = NULL; /* XXX no name ? */
751                         src = c; /* XXX possible bug in previous code, which used 'winner' ? it may have changed */
752                 } else {
753                         new_cid_num = ast_strdup(in->cid.cid_num);
754                         new_cid_name = ast_strdup(in->cid.cid_name);
755                         src = in;
756                 }
757                 ast_string_field_set(c, accountcode, src->accountcode);
758                 c->cdrflags = src->cdrflags;
759                 S_REPLACE(c->cid.cid_num, new_cid_num);
760                 S_REPLACE(c->cid.cid_name, new_cid_name);
761
762                 if (in->cid.cid_ani) { /* XXX or maybe unconditional ? */
763                         S_REPLACE(c->cid.cid_ani, ast_strdup(in->cid.cid_ani));
764                 }
765                 S_REPLACE(c->cid.cid_rdnis, ast_strdup(S_OR(in->macroexten, in->exten)));
766                 if (ast_call(c, tmpchan, 0)) {
767                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
768                         ast_clear_flag64(o, DIAL_STILLGOING);
769                         ast_hangup(original);
770                         ast_hangup(c);
771                         c = o->chan = NULL;
772                         num->nochan++;
773                 } else {
774                         senddialevent(in, c, stuff);
775                         /* After calling, set callerid to extension */
776                         if (!ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
777                                 char cidname[AST_MAX_EXTENSION] = "";
778                                 ast_set_callerid(c, S_OR(in->macroexten, in->exten), get_cid_name(cidname, sizeof(cidname), in), NULL);
779                         }
780                         /* Hangup the original channel now, in case we needed it */
781                         ast_hangup(original);
782                 }
783                 if (single) {
784                         ast_indicate(in, -1);
785                 }
786         }
787 }
788
789 /* argument used for some functions. */
790 struct privacy_args {
791         int sentringing;
792         int privdb_val;
793         char privcid[256];
794         char privintro[1024];
795         char status[256];
796 };
797
798 static struct ast_channel *wait_for_answer(struct ast_channel *in,
799         struct chanlist *outgoing, int *to, struct ast_flags64 *peerflags,
800         struct privacy_args *pa,
801         const struct cause_args *num_in, int *result, char *dtmf_progress)
802 {
803         struct cause_args num = *num_in;
804         int prestart = num.busy + num.congestion + num.nochan;
805         int orig = *to;
806         struct ast_channel *peer = NULL;
807         /* single is set if only one destination is enabled */
808         int single = outgoing && !outgoing->next && !ast_test_flag64(outgoing, OPT_MUSICBACK | OPT_RINGBACK);
809 #ifdef HAVE_EPOLL
810         struct chanlist *epollo;
811 #endif
812
813         if (single) {
814                 /* Turn off hold music, etc */
815                 ast_deactivate_generator(in);
816                 /* If we are calling a single channel, make them compatible for in-band tone purpose */
817                 ast_channel_make_compatible(outgoing->chan, in);
818         }
819
820 #ifdef HAVE_EPOLL
821         for (epollo = outgoing; epollo; epollo = epollo->next)
822                 ast_poll_channel_add(in, epollo->chan);
823 #endif
824
825         while (*to && !peer) {
826                 struct chanlist *o;
827                 int pos = 0; /* how many channels do we handle */
828                 int numlines = prestart;
829                 struct ast_channel *winner;
830                 struct ast_channel *watchers[AST_MAX_WATCHERS];
831
832                 watchers[pos++] = in;
833                 for (o = outgoing; o; o = o->next) {
834                         /* Keep track of important channels */
835                         if (ast_test_flag64(o, DIAL_STILLGOING) && o->chan)
836                                 watchers[pos++] = o->chan;
837                         numlines++;
838                 }
839                 if (pos == 1) { /* only the input channel is available */
840                         if (numlines == (num.busy + num.congestion + num.nochan)) {
841                                 ast_verb(2, "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
842                                 if (num.busy)
843                                         strcpy(pa->status, "BUSY");
844                                 else if (num.congestion)
845                                         strcpy(pa->status, "CONGESTION");
846                                 else if (num.nochan)
847                                         strcpy(pa->status, "CHANUNAVAIL");
848                         } else {
849                                 ast_verb(3, "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
850                         }
851                         *to = 0;
852                         return NULL;
853                 }
854                 winner = ast_waitfor_n(watchers, pos, to);
855                 for (o = outgoing; o; o = o->next) {
856                         struct ast_frame *f;
857                         struct ast_channel *c = o->chan;
858
859                         if (c == NULL)
860                                 continue;
861                         if (ast_test_flag64(o, DIAL_STILLGOING) && c->_state == AST_STATE_UP) {
862                                 if (!peer) {
863                                         ast_verb(3, "%s answered %s\n", c->name, in->name);
864                                         peer = c;
865                                         ast_copy_flags64(peerflags, o,
866                                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
867                                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
868                                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
869                                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
870                                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
871                                                 DIAL_NOFORWARDHTML);
872                                         ast_string_field_set(c, dialcontext, "");
873                                         ast_copy_string(c->exten, "", sizeof(c->exten));
874                                 }
875                                 continue;
876                         }
877                         if (c != winner)
878                                 continue;
879                         /* here, o->chan == c == winner */
880                         if (!ast_strlen_zero(c->call_forward)) {
881                                 do_forward(o, &num, peerflags, single);
882                                 continue;
883                         }
884                         f = ast_read(winner);
885                         if (!f) {
886                                 in->hangupcause = c->hangupcause;
887 #ifdef HAVE_EPOLL
888                                 ast_poll_channel_del(in, c);
889 #endif
890                                 ast_hangup(c);
891                                 c = o->chan = NULL;
892                                 ast_clear_flag64(o, DIAL_STILLGOING);
893                                 handle_cause(in->hangupcause, &num);
894                                 continue;
895                         }
896                         if (f->frametype == AST_FRAME_CONTROL) {
897                                 switch(f->subclass) {
898                                 case AST_CONTROL_ANSWER:
899                                         /* This is our guy if someone answered. */
900                                         if (!peer) {
901                                                 ast_verb(3, "%s answered %s\n", c->name, in->name);
902                                                 peer = c;
903                                                 if (peer->cdr) {
904                                                         peer->cdr->answer = ast_tvnow();
905                                                         peer->cdr->disposition = AST_CDR_ANSWERED;
906                                                 }
907                                                 ast_copy_flags64(peerflags, o,
908                                                         OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
909                                                         OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
910                                                         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
911                                                         OPT_CALLEE_PARK | OPT_CALLER_PARK |
912                                                         OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
913                                                         DIAL_NOFORWARDHTML);
914                                                 ast_string_field_set(c, dialcontext, "");
915                                                 ast_copy_string(c->exten, "", sizeof(c->exten));
916                                                 if (CAN_EARLY_BRIDGE(peerflags, in, peer))
917                                                         /* Setup early bridge if appropriate */
918                                                         ast_channel_early_bridge(in, peer);
919                                         }
920                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
921                                         in->hangupcause = AST_CAUSE_NORMAL_CLEARING;
922                                         c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
923                                         break;
924                                 case AST_CONTROL_BUSY:
925                                         ast_verb(3, "%s is busy\n", c->name);
926                                         in->hangupcause = c->hangupcause;
927                                         ast_hangup(c);
928                                         c = o->chan = NULL;
929                                         ast_clear_flag64(o, DIAL_STILLGOING);
930                                         handle_cause(AST_CAUSE_BUSY, &num);
931                                         break;
932                                 case AST_CONTROL_CONGESTION:
933                                         ast_verb(3, "%s is circuit-busy\n", c->name);
934                                         in->hangupcause = c->hangupcause;
935                                         ast_hangup(c);
936                                         c = o->chan = NULL;
937                                         ast_clear_flag64(o, DIAL_STILLGOING);
938                                         handle_cause(AST_CAUSE_CONGESTION, &num);
939                                         break;
940                                 case AST_CONTROL_RINGING:
941                                         ast_verb(3, "%s is ringing\n", c->name);
942                                         /* Setup early media if appropriate */
943                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
944                                                 ast_channel_early_bridge(in, c);
945                                         if (!(pa->sentringing) && !ast_test_flag64(outgoing, OPT_MUSICBACK)) {
946                                                 ast_indicate(in, AST_CONTROL_RINGING);
947                                                 pa->sentringing++;
948                                         }
949                                         break;
950                                 case AST_CONTROL_PROGRESS:
951                                         ast_verb(3, "%s is making progress passing it to %s\n", c->name, in->name);
952                                         /* Setup early media if appropriate */
953                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
954                                                 ast_channel_early_bridge(in, c);
955                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
956                                                 ast_indicate(in, AST_CONTROL_PROGRESS);
957                                                 if(!ast_strlen_zero(dtmf_progress)) {
958                                                         ast_verb(3, "Sending DTMF '%s' to the called party as result of receiving a PROGRESS message.\n", dtmf_progress);
959                                                         ast_dtmf_stream(c, in, dtmf_progress, 250, 0);
960                                                 }
961                                         break;
962                                 case AST_CONTROL_VIDUPDATE:
963                                         ast_verb(3, "%s requested a video update, passing it to %s\n", c->name, in->name);
964                                         ast_indicate(in, AST_CONTROL_VIDUPDATE);
965                                         break;
966                                 case AST_CONTROL_SRCUPDATE:
967                                         ast_verb(3, "%s requested a source update, passing it to %s\n", c->name, in->name);
968                                         ast_indicate(in, AST_CONTROL_SRCUPDATE);
969                                         break;
970                                 case AST_CONTROL_PROCEEDING:
971                                         ast_verb(3, "%s is proceeding passing it to %s\n", c->name, in->name);
972                                         if (single && CAN_EARLY_BRIDGE(peerflags, in, c))
973                                                 ast_channel_early_bridge(in, c);
974                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
975                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
976                                         break;
977                                 case AST_CONTROL_HOLD:
978                                         ast_verb(3, "Call on %s placed on hold\n", c->name);
979                                         ast_indicate(in, AST_CONTROL_HOLD);
980                                         break;
981                                 case AST_CONTROL_UNHOLD:
982                                         ast_verb(3, "Call on %s left from hold\n", c->name);
983                                         ast_indicate(in, AST_CONTROL_UNHOLD);
984                                         break;
985                                 case AST_CONTROL_OFFHOOK:
986                                 case AST_CONTROL_FLASH:
987                                         /* Ignore going off hook and flash */
988                                         break;
989                                 case -1:
990                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK | OPT_MUSICBACK)) {
991                                                 ast_verb(3, "%s stopped sounds\n", c->name);
992                                                 ast_indicate(in, -1);
993                                                 pa->sentringing = 0;
994                                         }
995                                         break;
996                                 default:
997                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass);
998                                 }
999                         } else if (single) {
1000                                 switch (f->frametype) {
1001                                         case AST_FRAME_VOICE:
1002                                         case AST_FRAME_IMAGE:
1003                                         case AST_FRAME_TEXT:
1004                                                 if (ast_write(in, f)) {
1005                                                         ast_log(LOG_WARNING, "Unable to write frame\n");
1006                                                 }
1007                                                 break;
1008                                         case AST_FRAME_HTML:
1009                                                 if (!ast_test_flag64(outgoing, DIAL_NOFORWARDHTML) && ast_channel_sendhtml(in, f->subclass, f->data.ptr, f->datalen) == -1) {
1010                                                         ast_log(LOG_WARNING, "Unable to send URL\n");
1011                                                 }
1012                                                 break;
1013                                         default:
1014                                                 break;
1015                                 }
1016                         }
1017                         ast_frfree(f);
1018                 } /* end for */
1019                 if (winner == in) {
1020                         struct ast_frame *f = ast_read(in);
1021 #if 0
1022                         if (f && (f->frametype != AST_FRAME_VOICE))
1023                                 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1024                         else if (!f || (f->frametype != AST_FRAME_VOICE))
1025                                 printf("Hangup received on %s\n", in->name);
1026 #endif
1027                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
1028                                 /* Got hung up */
1029                                 *to = -1;
1030                                 strcpy(pa->status, "CANCEL");
1031                                 ast_cdr_noanswer(in->cdr);
1032                                 if (f) {
1033                                         if (f->data.uint32) {
1034                                                 in->hangupcause = f->data.uint32;
1035                                         }
1036                                         ast_frfree(f);
1037                                 }
1038                                 return NULL;
1039                         }
1040
1041                         /* now f is guaranteed non-NULL */
1042                         if (f->frametype == AST_FRAME_DTMF) {
1043                                 if (ast_test_flag64(peerflags, OPT_DTMF_EXIT)) {
1044                                         const char *context;
1045                                         ast_channel_lock(in);
1046                                         context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
1047                                         if (onedigit_goto(in, context, (char) f->subclass, 1)) {
1048                                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass);
1049                                                 *to = 0;
1050                                                 ast_cdr_noanswer(in->cdr);
1051                                                 *result = f->subclass;
1052                                                 strcpy(pa->status, "CANCEL");
1053                                                 ast_frfree(f);
1054                                                 ast_channel_unlock(in);
1055                                                 return NULL;
1056                                         }
1057                                         ast_channel_unlock(in);
1058                                 }
1059
1060                                 if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP) &&
1061                                                 (f->subclass == '*')) { /* hmm it it not guaranteed to be '*' anymore. */
1062                                         ast_verb(3, "User hit %c to disconnect call.\n", f->subclass);
1063                                         *to = 0;
1064                                         strcpy(pa->status, "CANCEL");
1065                                         ast_cdr_noanswer(in->cdr);
1066                                         ast_frfree(f);
1067                                         return NULL;
1068                                 }
1069                         }
1070
1071                         /* Forward HTML stuff */
1072                         if (single && (f->frametype == AST_FRAME_HTML) && !ast_test_flag64(outgoing, DIAL_NOFORWARDHTML))
1073                                 if (ast_channel_sendhtml(outgoing->chan, f->subclass, f->data.ptr, f->datalen) == -1)
1074                                         ast_log(LOG_WARNING, "Unable to send URL\n");
1075
1076                         if (single && ((f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_DTMF_BEGIN) || (f->frametype == AST_FRAME_DTMF_END)))  {
1077                                 if (ast_write(outgoing->chan, f))
1078                                         ast_log(LOG_WARNING, "Unable to forward voice or dtmf\n");
1079                         }
1080                         if (single && (f->frametype == AST_FRAME_CONTROL) &&
1081                                 ((f->subclass == AST_CONTROL_HOLD) ||
1082                                 (f->subclass == AST_CONTROL_UNHOLD) ||
1083                                 (f->subclass == AST_CONTROL_VIDUPDATE) ||
1084                                  (f->subclass == AST_CONTROL_SRCUPDATE))) {
1085                                 ast_verb(3, "%s requested special control %d, passing it to %s\n", in->name, f->subclass, outgoing->chan->name);
1086                                 ast_indicate_data(outgoing->chan, f->subclass, f->data.ptr, f->datalen);
1087                         }
1088                         ast_frfree(f);
1089                 }
1090                 if (!*to)
1091                         ast_verb(3, "Nobody picked up in %d ms\n", orig);
1092                 if (!*to || ast_check_hangup(in))
1093                         ast_cdr_noanswer(in->cdr);
1094         }
1095
1096 #ifdef HAVE_EPOLL
1097         for (epollo = outgoing; epollo; epollo = epollo->next) {
1098                 if (epollo->chan)
1099                         ast_poll_channel_del(in, epollo->chan);
1100         }
1101 #endif
1102
1103         return peer;
1104 }
1105
1106 static void replace_macro_delimiter(char *s)
1107 {
1108         for (; *s; s++)
1109                 if (*s == '^')
1110                         *s = ',';
1111 }
1112
1113 /* returns true if there is a valid privacy reply */
1114 static int valid_priv_reply(struct ast_flags64 *opts, int res)
1115 {
1116         if (res < '1')
1117                 return 0;
1118         if (ast_test_flag64(opts, OPT_PRIVACY) && res <= '5')
1119                 return 1;
1120         if (ast_test_flag64(opts, OPT_SCREENING) && res <= '4')
1121                 return 1;
1122         return 0;
1123 }
1124
1125 static int do_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
1126         char *parse, struct timeval *calldurationlimit)
1127 {
1128         char *stringp = ast_strdupa(parse);
1129         char *limit_str, *warning_str, *warnfreq_str;
1130         const char *var;
1131         int play_to_caller = 0, play_to_callee = 0;
1132         int delta;
1133
1134         limit_str = strsep(&stringp, ":");
1135         warning_str = strsep(&stringp, ":");
1136         warnfreq_str = strsep(&stringp, ":");
1137
1138         config->timelimit = atol(limit_str);
1139         if (warning_str)
1140                 config->play_warning = atol(warning_str);
1141         if (warnfreq_str)
1142                 config->warning_freq = atol(warnfreq_str);
1143
1144         if (!config->timelimit) {
1145                 ast_log(LOG_WARNING, "Dial does not accept L(%s), hanging up.\n", limit_str);
1146                 config->timelimit = config->play_warning = config->warning_freq = 0;
1147                 config->warning_sound = NULL;
1148                 return -1; /* error */
1149         } else if ( (delta = config->play_warning - config->timelimit) > 0) {
1150                 int w = config->warning_freq;
1151
1152                 /* If the first warning is requested _after_ the entire call would end,
1153                    and no warning frequency is requested, then turn off the warning. If
1154                    a warning frequency is requested, reduce the 'first warning' time by
1155                    that frequency until it falls within the call's total time limit.
1156                    Graphically:
1157                                   timelim->|    delta        |<-playwarning
1158                         0__________________|_________________|
1159                                          | w  |    |    |    |
1160
1161                    so the number of intervals to cut is 1+(delta-1)/w
1162                 */
1163
1164                 if (w == 0) {
1165                         config->play_warning = 0;
1166                 } else {
1167                         config->play_warning -= w * ( 1 + (delta-1)/w );
1168                         if (config->play_warning < 1)
1169                                 config->play_warning = config->warning_freq = 0;
1170                 }
1171         }
1172         
1173         ast_channel_lock(chan);
1174
1175         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
1176
1177         play_to_caller = var ? ast_true(var) : 1;
1178
1179         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
1180         play_to_callee = var ? ast_true(var) : 0;
1181
1182         if (!play_to_caller && !play_to_callee)
1183                 play_to_caller = 1;
1184
1185         var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
1186         config->warning_sound = !ast_strlen_zero(var) ? ast_strdup(var) : ast_strdup("timeleft");
1187
1188         /* The code looking at config wants a NULL, not just "", to decide
1189          * that the message should not be played, so we replace "" with NULL.
1190          * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
1191          * not found.
1192          */
1193
1194         var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
1195         config->end_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
1196
1197         var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
1198         config->start_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
1199
1200         ast_channel_unlock(chan);
1201
1202         /* undo effect of S(x) in case they are both used */
1203         calldurationlimit->tv_sec = 0;
1204         calldurationlimit->tv_usec = 0;
1205
1206         /* more efficient to do it like S(x) does since no advanced opts */
1207         if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
1208                 calldurationlimit->tv_sec = config->timelimit / 1000;
1209                 calldurationlimit->tv_usec = (config->timelimit % 1000) * 1000;
1210                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n",
1211                         calldurationlimit->tv_sec + calldurationlimit->tv_usec / 1000000.0);
1212                 config->timelimit = play_to_caller = play_to_callee =
1213                 config->play_warning = config->warning_freq = 0;
1214         } else {
1215                 ast_verb(3, "Limit Data for this call:\n");
1216                 ast_verb(4, "timelimit      = %ld\n", config->timelimit);
1217                 ast_verb(4, "play_warning   = %ld\n", config->play_warning);
1218                 ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
1219                 ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
1220                 ast_verb(4, "warning_freq   = %ld\n", config->warning_freq);
1221                 ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
1222                 ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
1223                 ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
1224         }
1225         if (play_to_caller)
1226                 ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
1227         if (play_to_callee)
1228                 ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
1229         return 0;
1230 }
1231
1232 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
1233         struct ast_flags64 *opts, char **opt_args, struct privacy_args *pa)
1234 {
1235
1236         int res2;
1237         int loopcount = 0;
1238
1239         /* Get the user's intro, store it in priv-callerintros/$CID,
1240            unless it is already there-- this should be done before the
1241            call is actually dialed  */
1242
1243         /* all ring indications and moh for the caller has been halted as soon as the
1244            target extension was picked up. We are going to have to kill some
1245            time and make the caller believe the peer hasn't picked up yet */
1246
1247         if (ast_test_flag64(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1248                 char *original_moh = ast_strdupa(chan->musicclass);
1249                 ast_indicate(chan, -1);
1250                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
1251                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1252                 ast_string_field_set(chan, musicclass, original_moh);
1253         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1254                 ast_indicate(chan, AST_CONTROL_RINGING);
1255                 pa->sentringing++;
1256         }
1257
1258         /* Start autoservice on the other chan ?? */
1259         res2 = ast_autoservice_start(chan);
1260         /* Now Stream the File */
1261         for (loopcount = 0; loopcount < 3; loopcount++) {
1262                 if (res2 && loopcount == 0) /* error in ast_autoservice_start() */
1263                         break;
1264                 if (!res2) /* on timeout, play the message again */
1265                         res2 = ast_play_and_wait(peer, "priv-callpending");
1266                 if (!valid_priv_reply(opts, res2))
1267                         res2 = 0;
1268                 /* priv-callpending script:
1269                    "I have a caller waiting, who introduces themselves as:"
1270                 */
1271                 if (!res2)
1272                         res2 = ast_play_and_wait(peer, pa->privintro);
1273                 if (!valid_priv_reply(opts, res2))
1274                         res2 = 0;
1275                 /* now get input from the called party, as to their choice */
1276                 if (!res2) {
1277                         /* XXX can we have both, or they are mutually exclusive ? */
1278                         if (ast_test_flag64(opts, OPT_PRIVACY))
1279                                 res2 = ast_play_and_wait(peer, "priv-callee-options");
1280                         if (ast_test_flag64(opts, OPT_SCREENING))
1281                                 res2 = ast_play_and_wait(peer, "screen-callee-options");
1282                 }
1283                 /*! \page DialPrivacy Dial Privacy scripts
1284                 \par priv-callee-options script:
1285                         "Dial 1 if you wish this caller to reach you directly in the future,
1286                                 and immediately connect to their incoming call
1287                          Dial 2 if you wish to send this caller to voicemail now and
1288                                 forevermore.
1289                          Dial 3 to send this caller to the torture menus, now and forevermore.
1290                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1291                          Dial 5 to allow this caller to come straight thru to you in the future,
1292                                 but right now, just this once, send them to voicemail."
1293                 \par screen-callee-options script:
1294                         "Dial 1 if you wish to immediately connect to the incoming call
1295                          Dial 2 if you wish to send this caller to voicemail.
1296                          Dial 3 to send this caller to the torture menus.
1297                          Dial 4 to send this caller to a simple "go away" menu.
1298                 */
1299                 if (valid_priv_reply(opts, res2))
1300                         break;
1301                 /* invalid option */
1302                 res2 = ast_play_and_wait(peer, "vm-sorry");
1303         }
1304
1305         if (ast_test_flag64(opts, OPT_MUSICBACK)) {
1306                 ast_moh_stop(chan);
1307         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1308                 ast_indicate(chan, -1);
1309                 pa->sentringing = 0;
1310         }
1311         ast_autoservice_stop(chan);
1312         if (ast_test_flag64(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
1313                 /* map keypresses to various things, the index is res2 - '1' */
1314                 static const char *_val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
1315                 static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
1316                 int i = res2 - '1';
1317                 ast_verb(3, "--Set privacy database entry %s/%s to %s\n",
1318                         opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
1319                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
1320         }
1321         switch (res2) {
1322         case '1':
1323                 break;
1324         case '2':
1325                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1326                 break;
1327         case '3':
1328                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1329                 break;
1330         case '4':
1331                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1332                 break;
1333         case '5':
1334                 /* XXX should we set status to DENY ? */
1335                 if (ast_test_flag64(opts, OPT_PRIVACY))
1336                         break;
1337                 /* if not privacy, then 5 is the same as "default" case */
1338         default: /* bad input or -1 if failure to start autoservice */
1339                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1340                 /* well, there seems basically two choices. Just patch the caller thru immediately,
1341                           or,... put 'em thru to voicemail. */
1342                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1343                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1344                 /* XXX should we set status to DENY ? */
1345                 /* XXX what about the privacy flags ? */
1346                 break;
1347         }
1348
1349         if (res2 == '1') { /* the only case where we actually connect */
1350                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll
1351                    just clog things up, and it's not useful information, not being tied to a CID */
1352                 if (strncmp(pa->privcid, "NOCALLERID", 10) == 0 || ast_test_flag64(opts, OPT_SCREEN_NOINTRO)) {
1353                         ast_filedelete(pa->privintro, NULL);
1354                         if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1355                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1356                         else
1357                                 ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1358                 }
1359                 return 0; /* the good exit path */
1360         } else {
1361                 ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1362                 return -1;
1363         }
1364 }
1365
1366 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
1367 static int setup_privacy_args(struct privacy_args *pa,
1368         struct ast_flags64 *opts, char *opt_args[], struct ast_channel *chan)
1369 {
1370         char callerid[60];
1371         int res;
1372         char *l;
1373         int silencethreshold;
1374
1375         if (!ast_strlen_zero(chan->cid.cid_num)) {
1376                 l = ast_strdupa(chan->cid.cid_num);
1377                 ast_shrink_phone_number(l);
1378                 if (ast_test_flag64(opts, OPT_PRIVACY) ) {
1379                         ast_verb(3, "Privacy DB is '%s', clid is '%s'\n", opt_args[OPT_ARG_PRIVACY], l);
1380                         pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
1381                 } else {
1382                         ast_verb(3, "Privacy Screening, clid is '%s'\n", l);
1383                         pa->privdb_val = AST_PRIVACY_UNKNOWN;
1384                 }
1385         } else {
1386                 char *tnam, *tn2;
1387
1388                 tnam = ast_strdupa(chan->name);
1389                 /* clean the channel name so slashes don't try to end up in disk file name */
1390                 for (tn2 = tnam; *tn2; tn2++) {
1391                         if (*tn2 == '/')  /* any other chars to be afraid of? */
1392                                 *tn2 = '=';
1393                 }
1394                 ast_verb(3, "Privacy-- callerid is empty\n");
1395
1396                 snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
1397                 l = callerid;
1398                 pa->privdb_val = AST_PRIVACY_UNKNOWN;
1399         }
1400
1401         ast_copy_string(pa->privcid, l, sizeof(pa->privcid));
1402
1403         if (strncmp(pa->privcid, "NOCALLERID", 10) != 0 && ast_test_flag64(opts, OPT_SCREEN_NOCLID)) {
1404                 /* if callerid is set and OPT_SCREEN_NOCLID is set also */
1405                 ast_verb(3, "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
1406                 pa->privdb_val = AST_PRIVACY_ALLOW;
1407         } else if (ast_test_flag64(opts, OPT_SCREEN_NOCLID) && strncmp(pa->privcid, "NOCALLERID", 10) == 0) {
1408                 ast_verb(3, "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
1409         }
1410         
1411         if (pa->privdb_val == AST_PRIVACY_DENY) {
1412                 ast_verb(3, "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
1413                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1414                 return 0;
1415         } else if (pa->privdb_val == AST_PRIVACY_KILL) {
1416                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1417                 return 0; /* Is this right? */
1418         } else if (pa->privdb_val == AST_PRIVACY_TORTURE) {
1419                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1420                 return 0; /* is this right??? */
1421         } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN) {
1422                 /* Get the user's intro, store it in priv-callerintros/$CID,
1423                    unless it is already there-- this should be done before the
1424                    call is actually dialed  */
1425
1426                 /* make sure the priv-callerintros dir actually exists */
1427                 snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
1428                 if ((res = ast_mkdir(pa->privintro, 0755))) {
1429                         ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(res));
1430                         return -1;
1431                 }
1432
1433                 snprintf(pa->privintro, sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
1434                 if (ast_fileexists(pa->privintro, NULL, NULL ) > 0 && strncmp(pa->privcid, "NOCALLERID", 10) != 0) {
1435                         /* the DELUX version of this code would allow this caller the
1436                            option to hear and retape their previously recorded intro.
1437                         */
1438                 } else {
1439                         int duration; /* for feedback from play_and_wait */
1440                         /* the file doesn't exist yet. Let the caller submit his
1441                            vocal intro for posterity */
1442                         /* priv-recordintro script:
1443
1444                            "At the tone, please say your name:"
1445
1446                         */
1447                         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1448                         ast_answer(chan);
1449                         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 */
1450                                                                         /* don't think we'll need a lock removed, we took care of
1451                                                                            conflicts by naming the pa.privintro file */
1452                         if (res == -1) {
1453                                 /* Delete the file regardless since they hung up during recording */
1454                                 ast_filedelete(pa->privintro, NULL);
1455                                 if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1456                                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1457                                 else
1458                                         ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1459                                 return -1;
1460                         }
1461                         if (!ast_streamfile(chan, "vm-dialout", chan->language) )
1462                                 ast_waitstream(chan, "");
1463                 }
1464         }
1465         return 1; /* success */
1466 }
1467
1468 static void end_bridge_callback(void *data)
1469 {
1470         char buf[80];
1471         time_t end;
1472         struct ast_channel *chan = data;
1473
1474         if (!chan->cdr) {
1475                 return;
1476         }
1477
1478         time(&end);
1479
1480         ast_channel_lock(chan);
1481         if (chan->cdr->answer.tv_sec) {
1482                 snprintf(buf, sizeof(buf), "%ld", end - chan->cdr->answer.tv_sec);
1483                 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", buf);
1484         }
1485
1486         if (chan->cdr->start.tv_sec) {
1487                 snprintf(buf, sizeof(buf), "%ld", end - chan->cdr->start.tv_sec);
1488                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", buf);
1489         }
1490         ast_channel_unlock(chan);
1491 }
1492
1493 static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator) {
1494         bconfig->end_bridge_callback_data = originator;
1495 }
1496
1497 static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags64 *peerflags, int *continue_exec)
1498 {
1499         int res = -1; /* default: error */
1500         char *rest, *cur; /* scan the list of destinations */
1501         struct chanlist *outgoing = NULL; /* list of destinations */
1502         struct ast_channel *peer;
1503         int to; /* timeout */
1504         struct cause_args num = { chan, 0, 0, 0 };
1505         int cause;
1506         char numsubst[256];
1507         char cidname[AST_MAX_EXTENSION] = "";
1508
1509         struct ast_bridge_config config = { { 0, } };
1510         struct timeval calldurationlimit = { 0, };
1511         char *dtmfcalled = NULL, *dtmfcalling = NULL, *dtmf_progress=NULL;
1512         struct privacy_args pa = {
1513                 .sentringing = 0,
1514                 .privdb_val = 0,
1515                 .status = "INVALIDARGS",
1516         };
1517         int sentringing = 0, moh = 0;
1518         const char *outbound_group = NULL;
1519         int result = 0;
1520         char *parse;
1521         int opermode = 0;
1522         AST_DECLARE_APP_ARGS(args,
1523                 AST_APP_ARG(peers);
1524                 AST_APP_ARG(timeout);
1525                 AST_APP_ARG(options);
1526                 AST_APP_ARG(url);
1527         );
1528         struct ast_flags64 opts = { 0, };
1529         char *opt_args[OPT_ARG_ARRAY_SIZE];
1530         struct ast_datastore *datastore = NULL;
1531         int fulldial = 0, num_dialed = 0;
1532
1533         /* Reset all DIAL variables back to blank, to prevent confusion (in case we don't reset all of them). */
1534         pbx_builtin_setvar_helper(chan, "DIALSTATUS", "");
1535         pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", "");
1536         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", "");
1537         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", "");
1538         pbx_builtin_setvar_helper(chan, "DIALEDTIME", "");
1539
1540         if (ast_strlen_zero(data)) {
1541                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1542                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1543                 return -1;
1544         }
1545
1546         parse = ast_strdupa(data);
1547
1548         AST_STANDARD_APP_ARGS(args, parse);
1549
1550         if (!ast_strlen_zero(args.options) &&
1551                 ast_app_parse_options64(dial_exec_options, &opts, opt_args, args.options)) {
1552                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1553                 goto done;
1554         }
1555
1556         if (ast_strlen_zero(args.peers)) {
1557                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1558                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1559                 goto done;
1560         }
1561
1562         if (ast_test_flag64(&opts, OPT_OPERMODE)) {
1563                 opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
1564                 ast_verb(3, "Setting operator services mode to %d.\n", opermode);
1565         }
1566
1567         if (ast_test_flag64(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
1568                 calldurationlimit.tv_sec = atoi(opt_args[OPT_ARG_DURATION_STOP]);
1569                 if (!calldurationlimit.tv_sec) {
1570                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
1571                         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1572                         goto done;
1573                 }
1574                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n", calldurationlimit.tv_sec + calldurationlimit.tv_usec / 1000000.0);
1575         }
1576
1577         if (ast_test_flag64(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
1578                 dtmf_progress = opt_args[OPT_ARG_SENDDTMF];
1579                 dtmfcalled = strsep(&dtmf_progress, ":");
1580                 dtmfcalling = strsep(&dtmf_progress, ":");
1581         }
1582
1583         if (ast_test_flag64(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
1584                 if (do_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
1585                         goto done;
1586         }
1587
1588         if (ast_test_flag64(&opts, OPT_RESETCDR) && chan->cdr)
1589                 ast_cdr_reset(chan->cdr, NULL);
1590         if (ast_test_flag64(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
1591                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(chan->exten);
1592
1593         if (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) {
1594                 res = setup_privacy_args(&pa, &opts, opt_args, chan);
1595                 if (res <= 0)
1596                         goto out;
1597                 res = -1; /* reset default */
1598         }
1599
1600         if (ast_test_flag64(&opts, OPT_DTMF_EXIT)) {
1601                 __ast_answer(chan, 0, 0);
1602         }
1603
1604         if (continue_exec)
1605                 *continue_exec = 0;
1606
1607         /* If a channel group has been specified, get it for use when we create peer channels */
1608
1609         ast_channel_lock(chan);
1610         if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
1611                 outbound_group = ast_strdupa(outbound_group);   
1612                 pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
1613         } else if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP"))) {
1614                 outbound_group = ast_strdupa(outbound_group);
1615         }
1616         ast_channel_unlock(chan);       
1617         ast_copy_flags64(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING);
1618
1619         /* loop through the list of dial destinations */
1620         rest = args.peers;
1621         while ((cur = strsep(&rest, "&")) ) {
1622                 struct chanlist *tmp;
1623                 struct ast_channel *tc; /* channel for this destination */
1624                 /* Get a technology/[device:]number pair */
1625                 char *number = cur;
1626                 char *interface = ast_strdupa(number);
1627                 char *tech = strsep(&number, "/");
1628                 /* find if we already dialed this interface */
1629                 struct ast_dialed_interface *di;
1630                 AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
1631                 num_dialed++;
1632                 if (!number) {
1633                         ast_log(LOG_WARNING, "Dial argument takes format (technology/[device:]number1)\n");
1634                         goto out;
1635                 }
1636                 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1637                         goto out;
1638                 if (opts.flags) {
1639                         ast_copy_flags64(tmp, &opts,
1640                                 OPT_CANCEL_ELSEWHERE |
1641                                 OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1642                                 OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1643                                 OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1644                                 OPT_CALLEE_PARK | OPT_CALLER_PARK |
1645                                 OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1646                                 OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID);
1647                         ast_set2_flag64(tmp, args.url, DIAL_NOFORWARDHTML);
1648                 }
1649                 ast_copy_string(numsubst, number, sizeof(numsubst));
1650                 /* Request the peer */
1651
1652                 ast_channel_lock(chan);
1653                 datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL);
1654                 ast_channel_unlock(chan);
1655
1656                 if (datastore)
1657                         dialed_interfaces = datastore->data;
1658                 else {
1659                         if (!(datastore = ast_datastore_alloc(&dialed_interface_info, NULL))) {
1660                                 ast_log(LOG_WARNING, "Unable to create channel datastore for dialed interfaces. Aborting!\n");
1661                                 ast_free(tmp);
1662                                 goto out;
1663                         }
1664
1665                         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
1666
1667                         if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
1668                                 ast_free(tmp);
1669                                 goto out;
1670                         }
1671
1672                         datastore->data = dialed_interfaces;
1673                         AST_LIST_HEAD_INIT(dialed_interfaces);
1674
1675                         ast_channel_lock(chan);
1676                         ast_channel_datastore_add(chan, datastore);
1677                         ast_channel_unlock(chan);
1678                 }
1679
1680                 AST_LIST_LOCK(dialed_interfaces);
1681                 AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
1682                         if (!strcasecmp(di->interface, interface)) {
1683                                 ast_log(LOG_WARNING, "Skipping dialing interface '%s' again since it has already been dialed\n",
1684                                         di->interface);
1685                                 break;
1686                         }
1687                 }
1688                 AST_LIST_UNLOCK(dialed_interfaces);
1689
1690                 if (di) {
1691                         fulldial++;
1692                         ast_free(tmp);
1693                         continue;
1694                 }
1695
1696                 /* It is always ok to dial a Local interface.  We only keep track of
1697                  * which "real" interfaces have been dialed.  The Local channel will
1698                  * inherit this list so that if it ends up dialing a real interface,
1699                  * it won't call one that has already been called. */
1700                 if (strcasecmp(tech, "Local")) {
1701                         if (!(di = ast_calloc(1, sizeof(*di) + strlen(interface)))) {
1702                                 AST_LIST_UNLOCK(dialed_interfaces);
1703                                 ast_free(tmp);
1704                                 goto out;
1705                         }
1706                         strcpy(di->interface, interface);
1707
1708                         AST_LIST_LOCK(dialed_interfaces);
1709                         AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
1710                         AST_LIST_UNLOCK(dialed_interfaces);
1711                 }
1712
1713                 tc = ast_request(tech, chan->nativeformats, numsubst, &cause);
1714                 if (!tc) {
1715                         /* If we can't, just go on to the next call */
1716                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
1717                                 tech, cause, ast_cause2str(cause));
1718                         handle_cause(cause, &num);
1719                         if (!rest) /* we are on the last destination */
1720                                 chan->hangupcause = cause;
1721                         ast_free(tmp);
1722                         continue;
1723                 }
1724                 pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", numsubst);
1725
1726                 /* Setup outgoing SDP to match incoming one */
1727                 ast_rtp_make_compatible(tc, chan, !outgoing && !rest);
1728                 
1729                 /* Inherit specially named variables from parent channel */
1730                 ast_channel_inherit_variables(chan, tc);
1731                 ast_channel_datastore_inherit(chan, tc);
1732
1733                 tc->appl = "AppDial";
1734                 tc->data = "(Outgoing Line)";
1735                 memset(&tc->whentohangup, 0, sizeof(tc->whentohangup));
1736
1737                 S_REPLACE(tc->cid.cid_num, ast_strdup(chan->cid.cid_num));
1738                 S_REPLACE(tc->cid.cid_name, ast_strdup(chan->cid.cid_name));
1739                 S_REPLACE(tc->cid.cid_ani, ast_strdup(chan->cid.cid_ani));
1740                 S_REPLACE(tc->cid.cid_rdnis, ast_strdup(chan->cid.cid_rdnis));
1741                 
1742                 ast_string_field_set(tc, accountcode, chan->accountcode);
1743                 tc->cdrflags = chan->cdrflags;
1744                 if (ast_strlen_zero(tc->musicclass))
1745                         ast_string_field_set(tc, musicclass, chan->musicclass);
1746                 /* Pass callingpres, type of number, tns, ADSI CPE, transfer capability */
1747                 tc->cid.cid_pres = chan->cid.cid_pres;
1748                 tc->cid.cid_ton = chan->cid.cid_ton;
1749                 tc->cid.cid_tns = chan->cid.cid_tns;
1750                 tc->cid.cid_ani2 = chan->cid.cid_ani2;
1751                 tc->adsicpe = chan->adsicpe;
1752                 tc->transfercapability = chan->transfercapability;
1753
1754                 /* If we have an outbound group, set this peer channel to it */
1755                 if (outbound_group)
1756                         ast_app_group_set_channel(tc, outbound_group);
1757                 /* If the calling channel has the ANSWERED_ELSEWHERE flag set, inherit it. This is to support local channels */
1758                 if (ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE))
1759                         ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
1760
1761                 /* Check if we're forced by configuration */
1762                 if (ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE))
1763                          ast_set_flag(tc, AST_FLAG_ANSWERED_ELSEWHERE);
1764
1765
1766                 /* Inherit context and extension */
1767                 ast_string_field_set(tc, dialcontext, ast_strlen_zero(chan->macrocontext) ? chan->context : chan->macrocontext);
1768                 if (!ast_strlen_zero(chan->macroexten))
1769                         ast_copy_string(tc->exten, chan->macroexten, sizeof(tc->exten));
1770                 else
1771                         ast_copy_string(tc->exten, chan->exten, sizeof(tc->exten));
1772
1773                 res = ast_call(tc, numsubst, 0); /* Place the call, but don't wait on the answer */
1774
1775                 /* Save the info in cdr's that we called them */
1776                 if (chan->cdr)
1777                         ast_cdr_setdestchan(chan->cdr, tc->name);
1778
1779                 /* check the results of ast_call */
1780                 if (res) {
1781                         /* Again, keep going even if there's an error */
1782                         ast_debug(1, "ast call on peer returned %d\n", res);
1783                         ast_verb(3, "Couldn't call %s\n", numsubst);
1784                         if (tc->hangupcause) {
1785                                 chan->hangupcause = tc->hangupcause;
1786                         }
1787                         ast_hangup(tc);
1788                         tc = NULL;
1789                         ast_free(tmp);
1790                         continue;
1791                 } else {
1792                         senddialevent(chan, tc, numsubst);
1793                         ast_verb(3, "Called %s\n", numsubst);
1794                         if (!ast_test_flag64(peerflags, OPT_ORIGINAL_CLID))
1795                                 ast_set_callerid(tc, S_OR(chan->macroexten, chan->exten), get_cid_name(cidname, sizeof(cidname), chan), NULL);
1796                 }
1797                 /* Put them in the list of outgoing thingies...  We're ready now.
1798                    XXX If we're forcibly removed, these outgoing calls won't get
1799                    hung up XXX */
1800                 ast_set_flag64(tmp, DIAL_STILLGOING);
1801                 tmp->chan = tc;
1802                 tmp->next = outgoing;
1803                 outgoing = tmp;
1804                 /* If this line is up, don't try anybody else */
1805                 if (outgoing->chan->_state == AST_STATE_UP)
1806                         break;
1807         }
1808         
1809         if (ast_strlen_zero(args.timeout)) {
1810                 to = -1;
1811         } else {
1812                 to = atoi(args.timeout);
1813                 if (to > 0)
1814                         to *= 1000;
1815                 else {
1816                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'. Setting timeout to infinite\n", args.timeout);
1817                         to = -1;
1818                 }
1819         }
1820
1821         if (!outgoing) {
1822                 strcpy(pa.status, "CHANUNAVAIL");
1823                 if (fulldial == num_dialed) {
1824                         res = -1;
1825                         goto out;
1826                 }
1827         } else {
1828                 /* Our status will at least be NOANSWER */
1829                 strcpy(pa.status, "NOANSWER");
1830                 if (ast_test_flag64(outgoing, OPT_MUSICBACK)) {
1831                         moh = 1;
1832                         if (!ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1833                                 char *original_moh = ast_strdupa(chan->musicclass);
1834                                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
1835                                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1836                                 ast_string_field_set(chan, musicclass, original_moh);
1837                         } else {
1838                                 ast_moh_start(chan, NULL, NULL);
1839                         }
1840                         ast_indicate(chan, AST_CONTROL_PROGRESS);
1841                 } else if (ast_test_flag64(outgoing, OPT_RINGBACK)) {
1842                         ast_indicate(chan, AST_CONTROL_RINGING);
1843                         sentringing++;
1844                 }
1845         }
1846
1847         peer = wait_for_answer(chan, outgoing, &to, peerflags, &pa, &num, &result, dtmf_progress);
1848
1849         /* The ast_channel_datastore_remove() function could fail here if the
1850          * datastore was moved to another channel during a masquerade. If this is
1851          * the case, don't free the datastore here because later, when the channel
1852          * to which the datastore was moved hangs up, it will attempt to free this
1853          * datastore again, causing a crash
1854          */
1855         if (!ast_channel_datastore_remove(chan, datastore))
1856                 ast_datastore_free(datastore);
1857         if (!peer) {
1858                 if (result) {
1859                         res = result;
1860                 } else if (to) { /* Musta gotten hung up */
1861                         res = -1;
1862                 } else { /* Nobody answered, next please? */
1863                         res = 0;
1864                 }
1865
1866                 /* SIP, in particular, sends back this error code to indicate an
1867                  * overlap dialled number needs more digits. */
1868                 if (chan->hangupcause == AST_CAUSE_INVALID_NUMBER_FORMAT) {
1869                         res = AST_PBX_INCOMPLETE;
1870                 }
1871
1872                 /* almost done, although the 'else' block is 400 lines */
1873         } else {
1874                 const char *number;
1875
1876                 strcpy(pa.status, "ANSWER");
1877                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1878                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1879                    we will always return with -1 so that it is hung up properly after the
1880                    conversation.  */
1881                 hanguptree(outgoing, peer, 1);
1882                 outgoing = NULL;
1883                 /* If appropriate, log that we have a destination channel */
1884                 if (chan->cdr)
1885                         ast_cdr_setdestchan(chan->cdr, peer->name);
1886                 if (peer->name)
1887                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
1888                 
1889                 ast_channel_lock(peer);
1890                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER"); 
1891                 if (!number)
1892                         number = numsubst;
1893                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
1894                 ast_channel_unlock(peer);
1895
1896                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
1897                         ast_debug(1, "app_dial: sendurl=%s.\n", args.url);
1898                         ast_channel_sendurl( peer, args.url );
1899                 }
1900                 if ( (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) && pa.privdb_val == AST_PRIVACY_UNKNOWN) {
1901                         if (do_privacy(chan, peer, &opts, opt_args, &pa)) {
1902                                 res = 0;
1903                                 goto out;
1904                         }
1905                 }
1906                 if (!ast_test_flag64(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
1907                         res = 0;
1908                 } else {
1909                         int digit = 0;
1910                         /* Start autoservice on the other chan */
1911                         res = ast_autoservice_start(chan);
1912                         /* Now Stream the File */
1913                         if (!res)
1914                                 res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
1915                         if (!res) {
1916                                 digit = ast_waitstream(peer, AST_DIGIT_ANY);
1917                         }
1918                         /* Ok, done. stop autoservice */
1919                         res = ast_autoservice_stop(chan);
1920                         if (digit > 0 && !res)
1921                                 res = ast_senddigit(chan, digit, 0);
1922                         else
1923                                 res = digit;
1924
1925                 }
1926
1927                 if (chan && peer && ast_test_flag64(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
1928                         replace_macro_delimiter(opt_args[OPT_ARG_GOTO]);
1929                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
1930                         /* peer goes to the same context and extension as chan, so just copy info from chan*/
1931                         ast_copy_string(peer->context, chan->context, sizeof(peer->context));
1932                         ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
1933                         peer->priority = chan->priority + 2;
1934                         ast_pbx_start(peer);
1935                         hanguptree(outgoing, NULL, ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE) ? 1 : 0);
1936                         if (continue_exec)
1937                                 *continue_exec = 1;
1938                         res = 0;
1939                         goto done;
1940                 }
1941
1942                 if (ast_test_flag64(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
1943                         struct ast_app *theapp;
1944                         const char *macro_result;
1945
1946                         res = ast_autoservice_start(chan);
1947                         if (res) {
1948                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
1949                                 res = -1;
1950                         }
1951
1952                         theapp = pbx_findapp("Macro");
1953
1954                         if (theapp && !res) { /* XXX why check res here ? */
1955                                 /* Set peer->exten and peer->context so that MACRO_EXTEN and MACRO_CONTEXT get set */
1956                                 ast_copy_string(peer->context, chan->context, sizeof(peer->context));
1957                                 ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
1958
1959                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_MACRO]);
1960                                 res = pbx_exec(peer, theapp, opt_args[OPT_ARG_CALLEE_MACRO]);
1961                                 ast_debug(1, "Macro exited with status %d\n", res);
1962                                 res = 0;
1963                         } else {
1964                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
1965                                 res = -1;
1966                         }
1967
1968                         if (ast_autoservice_stop(chan) < 0) {
1969                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
1970                                 res = -1;
1971                         }
1972
1973                         ast_channel_lock(peer);
1974
1975                         if (!res && (macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
1976                                 char *macro_transfer_dest;
1977
1978                                 if (!strcasecmp(macro_result, "BUSY")) {
1979                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
1980                                         ast_set_flag64(peerflags, OPT_GO_ON);
1981                                         res = -1;
1982                                 } else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
1983                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
1984                                         ast_set_flag64(peerflags, OPT_GO_ON);
1985                                         res = -1;
1986                                 } else if (!strcasecmp(macro_result, "CONTINUE")) {
1987                                         /* hangup peer and keep chan alive assuming the macro has changed
1988                                            the context / exten / priority or perhaps
1989                                            the next priority in the current exten is desired.
1990                                         */
1991                                         ast_set_flag64(peerflags, OPT_GO_ON);
1992                                         res = -1;
1993                                 } else if (!strcasecmp(macro_result, "ABORT")) {
1994                                         /* Hangup both ends unless the caller has the g flag */
1995                                         res = -1;
1996                                 } else if (!strncasecmp(macro_result, "GOTO:", 5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
1997                                         res = -1;
1998                                         /* perform a transfer to a new extension */
1999                                         if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
2000                                                 replace_macro_delimiter(macro_transfer_dest);
2001                                                 if (!ast_parseable_goto(chan, macro_transfer_dest))
2002                                                         ast_set_flag64(peerflags, OPT_GO_ON);
2003                                         }
2004                                 }
2005                         }
2006
2007                         ast_channel_unlock(peer);
2008                 }
2009
2010                 if (ast_test_flag64(&opts, OPT_CALLEE_GOSUB) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GOSUB])) {
2011                         struct ast_app *theapp;
2012                         const char *gosub_result;
2013                         char *gosub_args, *gosub_argstart;
2014                         int res9 = -1;
2015
2016                         res9 = ast_autoservice_start(chan);
2017                         if (res9) {
2018                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2019                                 res9 = -1;
2020                         }
2021
2022                         theapp = pbx_findapp("Gosub");
2023
2024                         if (theapp && !res9) {
2025                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_GOSUB]);
2026
2027                                 /* Set where we came from */
2028                                 ast_copy_string(peer->context, "app_dial_gosub_virtual_context", sizeof(peer->context));
2029                                 ast_copy_string(peer->exten, "s", sizeof(peer->exten));
2030                                 peer->priority = 0;
2031
2032                                 gosub_argstart = strchr(opt_args[OPT_ARG_CALLEE_GOSUB], ',');
2033                                 if (gosub_argstart) {
2034                                         *gosub_argstart = 0;
2035                                         if (asprintf(&gosub_args, "%s,s,1(%s)", opt_args[OPT_ARG_CALLEE_GOSUB], gosub_argstart + 1) < 0) {
2036                                                 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
2037                                                 gosub_args = NULL;
2038                                         }
2039                                         *gosub_argstart = ',';
2040                                 } else {
2041                                         if (asprintf(&gosub_args, "%s,s,1", opt_args[OPT_ARG_CALLEE_GOSUB]) < 0) {
2042                                                 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
2043                                                 gosub_args = NULL;
2044                                         }
2045                                 }
2046
2047                                 if (gosub_args) {
2048                                         res9 = pbx_exec(peer, theapp, gosub_args);
2049                                         if (!res9) {
2050                                                 struct ast_pbx_args args;
2051                                                 /* A struct initializer fails to compile for this case ... */
2052                                                 memset(&args, 0, sizeof(args));
2053                                                 args.no_hangup_chan = 1;
2054                                                 ast_pbx_run_args(peer, &args);
2055                                         }
2056                                         ast_free(gosub_args);
2057                                         ast_debug(1, "Gosub exited with status %d\n", res9);
2058                                 } else {
2059                                         ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
2060                                 }
2061
2062                         } else if (!res9) {
2063                                 ast_log(LOG_ERROR, "Could not find application Gosub\n");
2064                                 res9 = -1;
2065                         }
2066
2067                         if (ast_autoservice_stop(chan) < 0) {
2068                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2069                                 res9 = -1;
2070                         }
2071                         
2072                         ast_channel_lock(peer);
2073
2074                         if (!res9 && (gosub_result = pbx_builtin_getvar_helper(peer, "GOSUB_RESULT"))) {
2075                                 char *gosub_transfer_dest;
2076
2077                                 if (!strcasecmp(gosub_result, "BUSY")) {
2078                                         ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
2079                                         ast_set_flag64(peerflags, OPT_GO_ON);
2080                                         res9 = -1;
2081                                 } else if (!strcasecmp(gosub_result, "CONGESTION") || !strcasecmp(gosub_result, "CHANUNAVAIL")) {
2082                                         ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
2083                                         ast_set_flag64(peerflags, OPT_GO_ON);
2084                                         res9 = -1;
2085                                 } else if (!strcasecmp(gosub_result, "CONTINUE")) {
2086                                         /* hangup peer and keep chan alive assuming the macro has changed
2087                                            the context / exten / priority or perhaps
2088                                            the next priority in the current exten is desired.
2089                                         */
2090                                         ast_set_flag64(peerflags, OPT_GO_ON);
2091                                         res9 = -1;
2092                                 } else if (!strcasecmp(gosub_result, "ABORT")) {
2093                                         /* Hangup both ends unless the caller has the g flag */
2094                                         res9 = -1;
2095                                 } else if (!strncasecmp(gosub_result, "GOTO:", 5) && (gosub_transfer_dest = ast_strdupa(gosub_result + 5))) {
2096                                         res9 = -1;
2097                                         /* perform a transfer to a new extension */
2098                                         if (strchr(gosub_transfer_dest, '^')) { /* context^exten^priority*/
2099                                                 replace_macro_delimiter(gosub_transfer_dest);
2100                                                 if (!ast_parseable_goto(chan, gosub_transfer_dest))
2101                                                         ast_set_flag64(peerflags, OPT_GO_ON);
2102                                         }
2103                                 }
2104                         }
2105
2106                         ast_channel_unlock(peer);       
2107                 }
2108
2109                 if (!res) {
2110                         if (!ast_tvzero(calldurationlimit)) {
2111                                 struct timeval whentohangup = calldurationlimit;
2112                                 peer->whentohangup = ast_tvadd(ast_tvnow(), whentohangup);
2113                         }
2114                         if (!ast_strlen_zero(dtmfcalled)) {
2115                                 ast_verb(3, "Sending DTMF '%s' to the called party.\n", dtmfcalled);
2116                                 res = ast_dtmf_stream(peer, chan, dtmfcalled, 250, 0);
2117                         }
2118                         if (!ast_strlen_zero(dtmfcalling)) {
2119                                 ast_verb(3, "Sending DTMF '%s' to the calling party.\n", dtmfcalling);
2120                                 res = ast_dtmf_stream(chan, peer, dtmfcalling, 250, 0);
2121                         }
2122                 }
2123
2124                 if (res) { /* some error */
2125                         res = -1;
2126                 } else {
2127                         if (ast_test_flag64(peerflags, OPT_CALLEE_TRANSFER))
2128                                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
2129                         if (ast_test_flag64(peerflags, OPT_CALLER_TRANSFER))
2130                                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
2131                         if (ast_test_flag64(peerflags, OPT_CALLEE_HANGUP))
2132                                 ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
2133                         if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP))
2134                                 ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
2135                         if (ast_test_flag64(peerflags, OPT_CALLEE_MONITOR))
2136                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
2137                         if (ast_test_flag64(peerflags, OPT_CALLER_MONITOR))
2138                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
2139                         if (ast_test_flag64(peerflags, OPT_CALLEE_PARK))
2140                                 ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
2141                         if (ast_test_flag64(peerflags, OPT_CALLER_PARK))
2142                                 ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
2143                         if (ast_test_flag64(peerflags, OPT_CALLEE_MIXMONITOR))
2144                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMIXMON);
2145                         if (ast_test_flag64(peerflags, OPT_CALLER_MIXMONITOR))
2146                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMIXMON);
2147                         if (ast_test_flag64(peerflags, OPT_GO_ON))
2148                                 ast_set_flag(&(config.features_caller), AST_FEATURE_NO_H_EXTEN);
2149
2150                         config.end_bridge_callback = end_bridge_callback;
2151                         config.end_bridge_callback_data = chan;
2152                         config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
2153                         
2154                         if (moh) {
2155                                 moh = 0;
2156                                 ast_moh_stop(chan);
2157                         } else if (sentringing) {
2158                                 sentringing = 0;
2159                                 ast_indicate(chan, -1);
2160                         }
2161                         /* Be sure no generators are left on it */
2162                         ast_deactivate_generator(chan);
2163                         /* Make sure channels are compatible */
2164                         res = ast_channel_make_compatible(chan, peer);
2165                         if (res < 0) {
2166                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
2167                                 ast_hangup(peer);
2168                                 res = -1;
2169                                 goto done;
2170                         }
2171                         if (opermode) {
2172                                 struct oprmode oprmode;
2173
2174                                 oprmode.peer = peer;
2175                                 oprmode.mode = opermode;
2176
2177                                 ast_channel_setoption(chan, AST_OPTION_OPRMODE, &oprmode, sizeof(oprmode), 0);
2178                         }
2179                         res = ast_bridge_call(chan, peer, &config);
2180                 }
2181
2182                 strcpy(peer->context, chan->context);
2183
2184                 if (ast_test_flag64(&opts, OPT_PEER_H) && ast_exists_extension(peer, peer->context, "h", 1, peer->cid.cid_num)) {
2185                         int autoloopflag;
2186                         int found;
2187                         int res9;
2188                         
2189                         strcpy(peer->exten, "h");
2190                         peer->priority = 1;
2191                         autoloopflag = ast_test_flag(peer, AST_FLAG_IN_AUTOLOOP); /* save value to restore at the end */
2192                         ast_set_flag(peer, AST_FLAG_IN_AUTOLOOP);
2193
2194                         while ((res9 = ast_spawn_extension(peer, peer->context, peer->exten, peer->priority, peer->cid.cid_num, &found, 1)) == 0)
2195                                 peer->priority++;
2196
2197                         if (found && res9) {
2198                                 /* Something bad happened, or a hangup has been requested. */
2199                                 ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
2200                                 ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
2201                         }
2202                         ast_set2_flag(peer, autoloopflag, AST_FLAG_IN_AUTOLOOP);  /* set it back the way it was */
2203                 }
2204                 if (!ast_check_hangup(peer) && ast_test_flag64(&opts, OPT_CALLEE_GO_ON) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GO_ON])) {          
2205                         replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_GO_ON]);
2206                         ast_parseable_goto(peer, opt_args[OPT_ARG_CALLEE_GO_ON]);
2207                         ast_pbx_start(peer);
2208                 } else {
2209                         if (!ast_check_hangup(chan))
2210                                 chan->hangupcause = peer->hangupcause;
2211                         ast_hangup(peer);
2212                 }
2213         }
2214 out:
2215         if (moh) {
2216                 moh = 0;
2217                 ast_moh_stop(chan);
2218         } else if (sentringing) {
2219                 sentringing = 0;
2220                 ast_indicate(chan, -1);
2221         }
2222         ast_channel_early_bridge(chan, NULL);
2223         hanguptree(outgoing, NULL, 0); /* In this case, there's no answer anywhere */
2224         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
2225         senddialendevent(chan, pa.status);
2226         ast_debug(1, "Exiting with DIALSTATUS=%s.\n", pa.status);
2227         
2228         if ((ast_test_flag64(peerflags, OPT_GO_ON)) && !ast_check_hangup(chan) && (res != AST_PBX_INCOMPLETE)) {
2229                 if (!ast_tvzero(calldurationlimit))
2230                         memset(&chan->whentohangup, 0, sizeof(chan->whentohangup));
2231                 res = 0;
2232         }
2233
2234 done:
2235         if (config.warning_sound) {
2236                 ast_free((char *)config.warning_sound);
2237         }
2238         if (config.end_sound) {
2239                 ast_free((char *)config.end_sound);
2240         }
2241         if (config.start_sound) {
2242                 ast_free((char *)config.start_sound);
2243         }
2244         return res;
2245 }
2246
2247 static int dial_exec(struct ast_channel *chan, void *data)
2248 {
2249         struct ast_flags64 peerflags;
2250
2251         memset(&peerflags, 0, sizeof(peerflags));
2252
2253         return dial_exec_full(chan, data, &peerflags, NULL);
2254 }
2255
2256 static int retrydial_exec(struct ast_channel *chan, void *data)
2257 {
2258         char *parse;
2259         const char *context = NULL;
2260         int sleepms = 0, loops = 0, res = -1;
2261         struct ast_flags64 peerflags = { 0, };
2262         AST_DECLARE_APP_ARGS(args,
2263                 AST_APP_ARG(announce);
2264                 AST_APP_ARG(sleep);
2265                 AST_APP_ARG(retries);
2266                 AST_APP_ARG(dialdata);
2267         );
2268
2269         if (ast_strlen_zero(data)) {
2270                 ast_log(LOG_WARNING, "RetryDial requires an argument!\n");
2271                 return -1;
2272         }
2273
2274         parse = ast_strdupa(data);
2275         AST_STANDARD_APP_ARGS(args, parse);
2276
2277         if (!ast_strlen_zero(args.sleep) && (sleepms = atoi(args.sleep)))
2278                 sleepms *= 1000;
2279
2280         if (!ast_strlen_zero(args.retries)) {
2281                 loops = atoi(args.retries);
2282         }
2283
2284         if (!args.dialdata) {
2285                 ast_log(LOG_ERROR, "%s requires a 4th argument (dialdata)\n", rapp);
2286                 goto done;
2287         }
2288
2289         if (sleepms < 1000)
2290                 sleepms = 10000;
2291
2292         if (!loops)
2293                 loops = -1; /* run forever */
2294
2295         ast_channel_lock(chan);
2296         context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
2297         context = !ast_strlen_zero(context) ? ast_strdupa(context) : NULL;
2298         ast_channel_unlock(chan);
2299
2300         res = 0;
2301         while (loops) {
2302                 int continue_exec;
2303
2304                 chan->data = "Retrying";
2305                 if (ast_test_flag(chan, AST_FLAG_MOH))
2306                         ast_moh_stop(chan);
2307
2308                 res = dial_exec_full(chan, args.dialdata, &peerflags, &continue_exec);
2309                 if (continue_exec)
2310                         break;
2311
2312                 if (res == 0) {
2313                         if (ast_test_flag64(&peerflags, OPT_DTMF_EXIT)) {
2314                                 if (!ast_strlen_zero(args.announce)) {
2315                                         if (ast_fileexists(args.announce, NULL, chan->language) > 0) {
2316                                                 if (!(res = ast_streamfile(chan, args.announce, chan->language)))
2317                                                         ast_waitstream(chan, AST_DIGIT_ANY);
2318                                         } else
2319                                                 ast_log(LOG_WARNING, "Announce file \"%s\" specified in Retrydial does not exist\n", args.announce);
2320                                 }
2321                                 if (!res && sleepms) {
2322                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
2323                                                 ast_moh_start(chan, NULL, NULL);
2324                                         res = ast_waitfordigit(chan, sleepms);
2325                                 }
2326                         } else {
2327                                 if (!ast_strlen_zero(args.announce)) {
2328                                         if (ast_fileexists(args.announce, NULL, chan->language) > 0) {
2329                                                 if (!(res = ast_streamfile(chan, args.announce, chan->language)))
2330                                                         res = ast_waitstream(chan, "");
2331                                         } else
2332                                                 ast_log(LOG_WARNING, "Announce file \"%s\" specified in Retrydial does not exist\n", args.announce);
2333                                 }
2334                                 if (sleepms) {
2335                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
2336                                                 ast_moh_start(chan, NULL, NULL);
2337                                         if (!res)
2338                                                 res = ast_waitfordigit(chan, sleepms);
2339                                 }
2340                         }
2341                 }
2342
2343                 if (res < 0 || res == AST_PBX_INCOMPLETE) {
2344                         break;
2345                 } else if (res > 0) { /* Trying to send the call elsewhere (1 digit ext) */
2346                         if (onedigit_goto(chan, context, (char) res, 1)) {
2347                                 res = 0;
2348                                 break;
2349                         }
2350                 }
2351                 loops--;
2352         }
2353         if (loops == 0)
2354                 res = 0;
2355         else if (res == 1)
2356                 res = 0;
2357
2358         if (ast_test_flag(chan, AST_FLAG_MOH))
2359                 ast_moh_stop(chan);
2360  done:
2361         return res;
2362 }
2363
2364 static int unload_module(void)
2365 {
2366         int res;
2367         struct ast_context *con;
2368
2369         res = ast_unregister_application(app);
2370         res |= ast_unregister_application(rapp);
2371
2372         if ((con = ast_context_find("app_dial_gosub_virtual_context"))) {
2373                 ast_context_remove_extension2(con, "s", 1, NULL, 0);
2374                 ast_context_destroy(con, "app_dial"); /* leave nothing behind */
2375         }
2376
2377         return res;
2378 }
2379
2380 static int load_module(void)
2381 {
2382         int res;
2383         struct ast_context *con;
2384
2385         con = ast_context_find_or_create(NULL, NULL, "app_dial_gosub_virtual_context", "app_dial");
2386         if (!con)
2387                 ast_log(LOG_ERROR, "Dial virtual context 'app_dial_gosub_virtual_context' does not exist and unable to create\n");
2388         else
2389                 ast_add_extension2(con, 1, "s", 1, NULL, NULL, "NoOp", ast_strdup(""), ast_free_ptr, "app_dial");
2390
2391         res = ast_register_application_xml(app, dial_exec);
2392         res |= ast_register_application_xml(rapp, retrydial_exec);
2393
2394         return res;
2395 }
2396
2397 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialing Application");