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