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