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