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