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