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