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