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