Get rid of any remaining ast_verbose calls in the code in favor of
[asterisk/asterisk.git] / apps / app_dial.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, 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.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
64 static char *app = "Dial";
65
66 static char *synopsis = "Place a call and connect to the current channel";
67
68 static char *descrip =
69 "  Dial(Technology/resource[&Tech2/resource2...][,timeout][,options][,URL]):\n"
70 "This application will place calls to one or more specified channels. As soon\n"
71 "as one of the requested channels answers, the originating channel will be\n"
72 "answered, if it has not already been answered. These two channels will then\n"
73 "be active in a bridged call. All other channels that were requested will then\n"
74 "be hung up.\n"
75 "  Unless there is a timeout specified, the Dial application will wait\n"
76 "indefinitely until one of the called channels answers, the user hangs up, or\n"
77 "if all of the called channels are busy or unavailable. Dialplan executing will\n"
78 "continue if no requested channels can be called, or if the timeout expires.\n\n"
79 "  This application sets the following channel variables upon completion:\n"
80 "    DIALEDTIME   - This is the time from dialing a channel until when it\n"
81 "                   is disconnected.\n" 
82 "    ANSWEREDTIME - This is the amount of time for actual call.\n"
83 "    DIALSTATUS   - This is the status of the call:\n"
84 "                   CHANUNAVAIL | CONGESTION | NOANSWER | BUSY | ANSWER | CANCEL\n" 
85 "                   DONTCALL | TORTURE | INVALIDARGS\n"
86 "  For the Privacy and Screening Modes, the DIALSTATUS variable will be set to\n"
87 "DONTCALL if the called party chooses to send the calling party to the 'Go Away'\n"
88 "script. The DIALSTATUS variable will be set to TORTURE if the called party\n"
89 "wants to send the caller to the 'torture' script.\n"
90 "  This application will report normal termination if the originating channel\n"
91 "hangs up, or if the call is bridged and either of the parties in the bridge\n"
92 "ends the call.\n"
93 "  The optional URL will be sent to the called party if the channel supports it.\n"
94 "  If the OUTBOUND_GROUP variable is set, all peer channels created by this\n"
95 "application will be put into that group (as in Set(GROUP()=...).\n"
96 "  If the OUTBOUND_GROUP_ONCE variable is set, all peer channels created by this\n"
97 "application will be put into that group (as in Set(GROUP()=...). Unlike OUTBOUND_GROUP,\n"
98 "however, the variable will be unset after use.\n\n"
99 "  Options:\n"
100 "    A(x) - Play an announcement to the called party, using 'x' as the file.\n"
101 "    C    - Reset the CDR for this call.\n"
102 "    c    - If DIAL cancels this call, always set the flag to tell the channel\n"
103 "           driver that the call is answered elsewhere.\n"
104 "    d    - Allow the calling user to dial a 1 digit extension while waiting for\n"
105 "           a call to be answered. Exit to that extension if it exists in the\n"
106 "           current context, or the context defined in the EXITCONTEXT variable,\n"
107 "           if it exists.\n"
108 "    D([called][:calling]) - Send the specified DTMF strings *after* the called\n"
109 "           party has answered, but before the call gets bridged. The 'called'\n"
110 "           DTMF string is sent to the called party, and the 'calling' DTMF\n"
111 "           string is sent to the calling party. Both parameters can be used\n"
112 "           alone.\n"
113 "    e    - execute the 'h' extension for peer after the call ends\n"
114 "    f    - Force the callerid of the *calling* channel to be set as the\n"
115 "           extension associated with the channel using a dialplan 'hint'.\n"
116 "           For example, some PSTNs do not allow CallerID to be set to anything\n"
117 "           other than the number assigned to the caller.\n"
118 "    g    - Proceed with dialplan execution at the current extension if the\n"
119 "           destination channel hangs up.\n"
120 "    G(context^exten^pri) - If the call is answered, transfer the calling party to\n"
121 "           the specified priority and the called party to the specified priority+1.\n"
122 "           Optionally, an extension, or extension and context may be specified. \n"
123 "           Otherwise, the current extension is used. You cannot use any additional\n"
124 "           action post answer options in conjunction with this option.\n" 
125 "    h    - Allow the called party to hang up by sending the '*' DTMF digit.\n"
126 "    H    - Allow the calling party to hang up by hitting the '*' DTMF digit.\n"
127 "    i    - Asterisk will ignore any forwarding requests it may receive on this\n"
128 "           dial attempt.\n"
129 "    k    - Allow the called party to enable parking of the call by sending\n"
130 "           the DTMF sequence defined for call parking in features.conf.\n"
131 "    K    - Allow the calling party to enable parking of the call by sending\n"
132 "           the DTMF sequence defined for call parking in features.conf.\n"
133 "    L(x[:y][:z]) - Limit the call to 'x' ms. Play a warning when 'y' ms are\n"
134 "           left. Repeat the warning every 'z' ms. The following special\n"
135 "           variables can be used with this option:\n"
136 "           * LIMIT_PLAYAUDIO_CALLER   yes|no (default yes)\n"
137 "                                      Play sounds to the caller.\n"
138 "           * LIMIT_PLAYAUDIO_CALLEE   yes|no\n"
139 "                                      Play sounds to the callee.\n"
140 "           * LIMIT_TIMEOUT_FILE       File to play when time is up.\n"
141 "           * LIMIT_CONNECT_FILE       File to play when call begins.\n"
142 "           * LIMIT_WARNING_FILE       File to play as warning if 'y' is defined.\n"
143 "                                      The default is to say the time remaining.\n"
144 "    m([class]) - Provide hold music to the calling party until a requested\n"
145 "           channel answers. A specific MusicOnHold class can be\n"
146 "           specified.\n"
147 "    M(x[^arg]) - Execute the Macro for the *called* channel before connecting\n"
148 "           to the calling channel. Arguments can be specified to the Macro\n"
149 "           using '^' as a delimeter. The Macro can set the variable\n"
150 "           MACRO_RESULT to specify the following actions after the Macro is\n" 
151 "           finished executing.\n"
152 "           * ABORT        Hangup both legs of the call.\n"
153 "           * CONGESTION   Behave as if line congestion was encountered.\n"
154 "           * BUSY         Behave as if a busy signal was encountered.\n"
155 "           * CONTINUE     Hangup the called party and allow the calling party\n"
156 "                          to continue dialplan execution at the next priority.\n"
157 "           * GOTO:<context>^<exten>^<priority> - Transfer the call to the\n"
158 "                          specified priority. Optionally, an extension, or\n"
159 "                          extension and priority can be specified.\n"
160 "           You cannot use any additional action post answer options in conjunction\n"
161 "           with this option. Also, pbx services are not run on the peer (called) channel,\n"
162 "           so you will not be able to set timeouts via the TIMEOUT() function in this macro.\n"
163 "    n    - This option is a modifier for the screen/privacy mode. It specifies\n"
164 "           that no introductions are to be saved in the priv-callerintros\n"
165 "           directory.\n"
166 "    N    - This option is a modifier for the screen/privacy mode. It specifies\n"
167 "           that if callerID is present, do not screen the call.\n"
168 "    o    - Specify that the CallerID that was present on the *calling* channel\n"
169 "           be set as the CallerID on the *called* channel. This was the\n"
170 "           behavior of Asterisk 1.0 and earlier.\n"
171 "    O([x]) - \"Operator Services\" mode (Zaptel channel to Zaptel channel\n"
172 "             only, if specified on non-Zaptel interface, it will be ignored).\n"
173 "             When the destination answers (presumably an operator services\n"
174 "             station), the originator no longer has control of their line.\n"
175 "             They may hang up, but the switch will not release their line\n"
176 "             until the destination party hangs up (the operator). Specified\n"
177 "             without an arg, or with 1 as an arg, the originator hanging up\n"
178 "             will cause the phone to ring back immediately. With a 2 specified,\n"
179 "             when the \"operator\" flashes the trunk, it will ring their phone\n"
180 "             back.\n"
181 "    p    - This option enables screening mode. This is basically Privacy mode\n"
182 "           without memory.\n"
183 "    P([x]) - Enable privacy mode. Use 'x' as the family/key in the database if\n"
184 "           it is provided. The current extension is used if a database\n"
185 "           family/key is not specified.\n"
186 "    r    - Indicate ringing to the calling party. Pass no audio to the calling\n"
187 "           party until the called channel has answered.\n"
188 "    S(x) - Hang up the call after 'x' seconds *after* the called party has\n"
189 "           answered the call.\n"       
190 "    t    - Allow the called party to transfer the calling party by sending the\n"
191 "           DTMF sequence defined in features.conf.\n"
192 "    T    - Allow the calling party to transfer the called party by sending the\n"
193 "           DTMF sequence defined in features.conf.\n"
194 "    U(x[^arg]) - Execute via Gosub the routine 'x' for the *called* channel before connecting\n"
195 "           to the calling channel. Arguments can be specified to the Gosub\n"
196 "           using '^' as a delimeter. The Gosub routine can set the variable\n"
197 "           GOSUB_RESULT to specify the following actions after the Gosub returns.\n" 
198 "           * ABORT        Hangup both legs of the call.\n"
199 "           * CONGESTION   Behave as if line congestion was encountered.\n"
200 "           * BUSY         Behave as if a busy signal was encountered.\n"
201 "           * CONTINUE     Hangup the called party and allow the calling party\n"
202 "                          to continue dialplan execution at the next priority.\n"
203 "           * GOTO:<context>^<exten>^<priority> - Transfer the call to the\n"
204 "                          specified priority. Optionally, an extension, or\n"
205 "                          extension and priority can be specified.\n"
206 "           You cannot use any additional action post answer options in conjunction\n"
207 "           with this option. Also, pbx services are not run on the peer (called) channel,\n"
208 "           so you will not be able to set timeouts via the TIMEOUT() function in this routine.\n"
209 "    w    - Allow the called party to enable recording of the call by sending\n"
210 "           the DTMF sequence defined for one-touch recording in features.conf.\n"
211 "    W    - Allow the calling party to enable recording of the call by sending\n"
212 "           the DTMF sequence defined for one-touch recording in features.conf.\n"
213 "    x    - Allow the called party to enable recording of the call by sending\n"
214 "           the DTMF sequence defined for one-touch automixmonitor in features.conf\n"
215 "    X    - Allow the calling party to enable recording of the call by sending\n"
216 "           the DTMF sequence defined for one-touch automixmonitor in features.conf\n";
217  
218 /* RetryDial App by Anthony Minessale II <anthmct@yahoo.com> Jan/2005 */
219 static char *rapp = "RetryDial";
220 static char *rsynopsis = "Place a call, retrying on failure allowing optional exit extension.";
221 static char *rdescrip =
222 "  RetryDial(announce,sleep,retries,dialargs): This application will attempt to\n"
223 "place a call using the normal Dial application. If no channel can be reached,\n"
224 "the 'announce' file will be played. Then, it will wait 'sleep' number of\n"
225 "seconds before retying the call. After 'retires' number of attempts, the\n"
226 "calling channel will continue at the next priority in the dialplan. If the\n"
227 "'retries' setting is set to 0, this application will retry endlessly.\n"
228 "  While waiting to retry a call, a 1 digit extension may be dialed. If that\n"
229 "extension exists in either the context defined in ${EXITCONTEXT} or the current\n"
230 "one, The call will jump to that extension immediately.\n"
231 "  The 'dialargs' are specified in the same format that arguments are provided\n"
232 "to the Dial application.\n";
233
234 enum {
235         OPT_ANNOUNCE =          (1 << 0),
236         OPT_RESETCDR =          (1 << 1),
237         OPT_DTMF_EXIT =         (1 << 2),
238         OPT_SENDDTMF =          (1 << 3),
239         OPT_FORCECLID =         (1 << 4),
240         OPT_GO_ON =             (1 << 5),
241         OPT_CALLEE_HANGUP =     (1 << 6),
242         OPT_CALLER_HANGUP =     (1 << 7),
243         OPT_DURATION_LIMIT =    (1 << 9),
244         OPT_MUSICBACK =         (1 << 10),
245         OPT_CALLEE_MACRO =      (1 << 11),
246         OPT_SCREEN_NOINTRO =    (1 << 12),
247         OPT_SCREEN_NOCLID =     (1 << 13),
248         OPT_ORIGINAL_CLID =     (1 << 14),
249         OPT_SCREENING =         (1 << 15),
250         OPT_PRIVACY =           (1 << 16),
251         OPT_RINGBACK =          (1 << 17),
252         OPT_DURATION_STOP =     (1 << 18),
253         OPT_CALLEE_TRANSFER =   (1 << 19),
254         OPT_CALLER_TRANSFER =   (1 << 20),
255         OPT_CALLEE_MONITOR =    (1 << 21),
256         OPT_CALLER_MONITOR =    (1 << 22),
257         OPT_GOTO =              (1 << 23),
258         OPT_OPERMODE =          (1 << 24),
259         OPT_CALLEE_PARK =       (1 << 25),
260         OPT_CALLER_PARK =       (1 << 26),
261         OPT_IGNORE_FORWARDING = (1 << 27),
262         OPT_CALLEE_GOSUB =      (1 << 28),
263         OPT_CALLEE_MIXMONITOR = (1 << 29),
264         OPT_CALLER_MIXMONITOR = (1 << 30),
265 };
266
267 #define DIAL_STILLGOING                 (1 << 31)
268 #define DIAL_NOFORWARDHTML              ((uint64_t)1 << 32) /* flags are now 64 bits, so keep it up! */
269 #define OPT_CANCEL_ELSEWHERE    ((uint64_t)1 << 33)
270 #define OPT_PEER_H                      ((uint64_t)1 << 34)
271
272 enum {
273         OPT_ARG_ANNOUNCE = 0,
274         OPT_ARG_SENDDTMF,
275         OPT_ARG_GOTO,
276         OPT_ARG_DURATION_LIMIT,
277         OPT_ARG_MUSICBACK,
278         OPT_ARG_CALLEE_MACRO,
279         OPT_ARG_CALLEE_GOSUB,
280         OPT_ARG_PRIVACY,
281         OPT_ARG_DURATION_STOP,
282         OPT_ARG_OPERMODE,
283         /* note: this entry _MUST_ be the last one in the enum */
284         OPT_ARG_ARRAY_SIZE,
285 };
286
287 AST_APP_OPTIONS(dial_exec_options, BEGIN_OPTIONS
288         AST_APP_OPTION_ARG('A', OPT_ANNOUNCE, OPT_ARG_ANNOUNCE),
289         AST_APP_OPTION('C', OPT_RESETCDR),
290         AST_APP_OPTION('c', OPT_CANCEL_ELSEWHERE),
291         AST_APP_OPTION('d', OPT_DTMF_EXIT),
292         AST_APP_OPTION_ARG('D', OPT_SENDDTMF, OPT_ARG_SENDDTMF),
293         AST_APP_OPTION('e', OPT_PEER_H),
294         AST_APP_OPTION('f', OPT_FORCECLID),
295         AST_APP_OPTION('g', OPT_GO_ON),
296         AST_APP_OPTION_ARG('G', OPT_GOTO, OPT_ARG_GOTO),
297         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
298         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
299         AST_APP_OPTION('i', OPT_IGNORE_FORWARDING),
300         AST_APP_OPTION('k', OPT_CALLEE_PARK),
301         AST_APP_OPTION('K', OPT_CALLER_PARK),
302         AST_APP_OPTION('k', OPT_CALLEE_PARK),
303         AST_APP_OPTION('K', OPT_CALLER_PARK),
304         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
305         AST_APP_OPTION_ARG('m', OPT_MUSICBACK, OPT_ARG_MUSICBACK),
306         AST_APP_OPTION_ARG('M', OPT_CALLEE_MACRO, OPT_ARG_CALLEE_MACRO),
307         AST_APP_OPTION('n', OPT_SCREEN_NOINTRO),
308         AST_APP_OPTION('N', OPT_SCREEN_NOCLID),
309         AST_APP_OPTION('o', OPT_ORIGINAL_CLID),
310         AST_APP_OPTION_ARG('O', OPT_OPERMODE, OPT_ARG_OPERMODE),
311         AST_APP_OPTION('p', OPT_SCREENING),
312         AST_APP_OPTION_ARG('P', OPT_PRIVACY, OPT_ARG_PRIVACY),
313         AST_APP_OPTION('r', OPT_RINGBACK),
314         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
315         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
316         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
317         AST_APP_OPTION_ARG('U', OPT_CALLEE_GOSUB, OPT_ARG_CALLEE_GOSUB),
318         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
319         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
320         AST_APP_OPTION('x', OPT_CALLEE_MIXMONITOR),
321         AST_APP_OPTION('X', OPT_CALLER_MIXMONITOR),
322 END_OPTIONS );
323
324 #define CAN_EARLY_BRIDGE(flags) (!ast_test_flag64(flags, OPT_CALLEE_HANGUP | \
325         OPT_CALLER_HANGUP | OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER | \
326         OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR | OPT_CALLEE_PARK | OPT_CALLER_PARK))
327
328 /*
329  * The list of active channels
330  */
331 struct chanlist {
332         struct chanlist *next;
333         struct ast_channel *chan;
334         uint64_t flags;
335 };
336
337
338 static void hanguptree(struct chanlist *outgoing, struct ast_channel *exception, int answered_elsewhere)
339 {
340         /* Hang up a tree of stuff */
341         struct chanlist *oo;
342         while (outgoing) {
343                 /* Hangup any existing lines we have open */
344                 if (outgoing->chan && (outgoing->chan != exception)) {
345                         if (answered_elsewhere)
346                                 ast_set_flag(outgoing->chan, AST_FLAG_ANSWERED_ELSEWHERE);
347                         ast_hangup(outgoing->chan);
348                 }
349                 oo = outgoing;
350                 outgoing = outgoing->next;
351                 ast_free(oo);
352         }
353 }
354
355 #define AST_MAX_WATCHERS 256
356
357 /*
358  * argument to handle_cause() and other functions.
359  */
360 struct cause_args {
361         struct ast_channel *chan;
362         int busy;
363         int congestion;
364         int nochan;
365 };
366
367 static void handle_cause(int cause, struct cause_args *num)
368 {
369         struct ast_cdr *cdr = num->chan->cdr;
370
371         switch(cause) {
372         case AST_CAUSE_BUSY:
373                 if (cdr)
374                         ast_cdr_busy(cdr);
375                 num->busy++;
376                 break;
377
378         case AST_CAUSE_CONGESTION:
379                 if (cdr)
380                         ast_cdr_failed(cdr);
381                 num->congestion++;
382                 break;
383
384         case AST_CAUSE_UNREGISTERED:
385                 if (cdr)
386                         ast_cdr_failed(cdr);
387                 num->nochan++;
388                 break;
389
390         case AST_CAUSE_NORMAL_CLEARING:
391                 break;
392
393         default:
394                 num->nochan++;
395                 break;
396         }
397 }
398
399 /* free the buffer if allocated, and set the pointer to the second arg */
400 #define S_REPLACE(s, new_val)           \
401         do {                            \
402                 if (s)                  \
403                         ast_free(s);    \
404                 s = (new_val);          \
405         } while (0)
406
407 static int onedigit_goto(struct ast_channel *chan, const char *context, char exten, int pri) 
408 {
409         char rexten[2] = { exten, '\0' };
410
411         if (context) {
412                 if (!ast_goto_if_exists(chan, context, rexten, pri))
413                         return 1;
414         } else {
415                 if (!ast_goto_if_exists(chan, chan->context, rexten, pri))
416                         return 1;
417                 else if (!ast_strlen_zero(chan->macrocontext)) {
418                         if (!ast_goto_if_exists(chan, chan->macrocontext, rexten, pri))
419                                 return 1;
420                 }
421         }
422         return 0;
423 }
424
425
426 static const char *get_cid_name(char *name, int namelen, struct ast_channel *chan)
427 {
428         const char *context = S_OR(chan->macrocontext, chan->context);
429         const char *exten = S_OR(chan->macroexten, chan->exten);
430
431         return ast_get_hint(NULL, 0, name, namelen, chan, context, exten) ? name : "";
432 }
433
434 static void senddialevent(struct ast_channel *src, struct ast_channel *dst, const char *dialstring)
435 {
436         manager_event(EVENT_FLAG_CALL, "Dial", 
437                            "SubEvent: Begin\r\n"
438                            "Channel: %s\r\n"
439                            "Destination: %s\r\n"
440                            "CallerIDNum: %s\r\n"
441                            "CallerIDName: %s\r\n"
442                            "UniqueID: %s\r\n"
443                            "DestUniqueID: %s\r\n"
444                            "Dialstring: %s\r\n",
445                            src->name, dst->name, S_OR(src->cid.cid_num, "<unknown>"),
446                            S_OR(src->cid.cid_name, "<unknown>"), src->uniqueid,
447                            dst->uniqueid, dialstring ? dialstring : "");
448 }
449
450 static void senddialendevent(const struct ast_channel *src, const char *dialstatus)
451 {
452         manager_event(EVENT_FLAG_CALL, "Dial",
453                                         "SubEvent: End\r\n"
454                                         "Channel: %s\r\n"
455                                         "UniqueID: %s\r\n"
456                                         "DialStatus: %s\r\n",
457                                         src->name, src->uniqueid, dialstatus);
458 }       
459
460 /*!
461  * helper function for wait_for_answer()
462  *
463  * XXX this code is highly suspicious, as it essentially overwrites
464  * the outgoing channel without properly deleting it.
465  */
466 static void do_forward(struct chanlist *o,
467         struct cause_args *num, struct ast_flags64 *peerflags, int single)
468 {
469         char tmpchan[256];
470         struct ast_channel *original = o->chan;
471         struct ast_channel *c = o->chan; /* the winner */
472         struct ast_channel *in = num->chan; /* the input channel */
473         char *stuff;
474         char *tech;
475         int cause;
476
477         ast_copy_string(tmpchan, c->call_forward, sizeof(tmpchan));
478         if ((stuff = strchr(tmpchan, '/'))) {
479                 *stuff++ = '\0';
480                 tech = tmpchan;
481         } else {
482                 const char *forward_context = pbx_builtin_getvar_helper(c, "FORWARD_CONTEXT");
483                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", c->call_forward, forward_context ? forward_context : c->context);
484                 stuff = tmpchan;
485                 tech = "Local";
486         }
487         /* Before processing channel, go ahead and check for forwarding */
488         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, c->name);
489         /* If we have been told to ignore forwards, just set this channel to null and continue processing extensions normally */
490         if (ast_test_flag64(peerflags, OPT_IGNORE_FORWARDING)) {
491                 ast_verb(3, "Forwarding %s to '%s/%s' prevented.\n", in->name, tech, stuff);
492                 c = o->chan = NULL;
493                 cause = AST_CAUSE_BUSY;
494         } else {
495                 /* Setup parameters */
496                 c = o->chan = ast_request(tech, in->nativeformats, stuff, &cause);
497                 if (c) {
498                         if (single)
499                                 ast_channel_make_compatible(o->chan, in);
500                         ast_channel_inherit_variables(in, o->chan);
501                         ast_channel_datastore_inherit(in, o->chan);
502                 } else
503                         ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s' (cause = %d)\n", tech, stuff, cause);
504         }
505         if (!c) {
506                 ast_clear_flag64(o, DIAL_STILLGOING);   
507                 handle_cause(cause, num);
508         } else {
509                 char *new_cid_num, *new_cid_name;
510                 struct ast_channel *src;
511
512                 ast_rtp_make_compatible(c, in, single);
513                 if (ast_test_flag64(o, OPT_FORCECLID)) {
514                         new_cid_num = ast_strdup(S_OR(in->macroexten, in->exten));
515                         new_cid_name = NULL; /* XXX no name ? */
516                         src = c;        /* XXX possible bug in previous code, which used 'winner' ? it may have changed */
517                 } else {
518                         new_cid_num = ast_strdup(in->cid.cid_num);
519                         new_cid_name = ast_strdup(in->cid.cid_name);
520                         src = in;
521                 }
522                 ast_string_field_set(c, accountcode, src->accountcode);
523                 c->cdrflags = src->cdrflags;
524                 S_REPLACE(c->cid.cid_num, new_cid_num);
525                 S_REPLACE(c->cid.cid_name, new_cid_name);
526
527                 if (in->cid.cid_ani) { /* XXX or maybe unconditional ? */
528                         S_REPLACE(c->cid.cid_ani, ast_strdup(in->cid.cid_ani));
529                 }
530                 S_REPLACE(c->cid.cid_rdnis, ast_strdup(S_OR(in->macroexten, in->exten)));
531                 if (ast_call(c, tmpchan, 0)) {
532                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
533                         ast_clear_flag64(o, DIAL_STILLGOING);   
534                         ast_hangup(original);
535                         c = o->chan = NULL;
536                         num->nochan++;
537                 } else {
538                         senddialevent(in, c, stuff);
539                         /* After calling, set callerid to extension */
540                         if (!ast_test_flag64(peerflags, OPT_ORIGINAL_CLID)) {
541                                 char cidname[AST_MAX_EXTENSION] = "";
542                                 ast_set_callerid(c, S_OR(in->macroexten, in->exten), get_cid_name(cidname, sizeof(cidname), in), NULL);
543                         }
544                         /* Hangup the original channel now, in case we needed it */
545                         ast_hangup(original);
546                 }
547         }
548 }
549
550 /* argument used for some functions. */
551 struct privacy_args {
552         int sentringing;
553         int privdb_val;
554         char privcid[256];
555         char privintro[1024];
556         char status[256];
557 };
558
559 static struct ast_channel *wait_for_answer(struct ast_channel *in,
560         struct chanlist *outgoing, int *to, struct ast_flags64 *peerflags,
561         struct privacy_args *pa,
562         const struct cause_args *num_in, int *result)
563 {
564         struct cause_args num = *num_in;
565         int prestart = num.busy + num.congestion + num.nochan;
566         int orig = *to;
567         struct ast_channel *peer = NULL;
568         /* single is set if only one destination is enabled */
569         int single = outgoing && !outgoing->next && !ast_test_flag64(outgoing, OPT_MUSICBACK | OPT_RINGBACK);
570 #ifdef HAVE_EPOLL
571         struct chanlist *epollo;
572 #endif
573         
574         if (single) {
575                 /* Turn off hold music, etc */
576                 ast_deactivate_generator(in);
577                 /* If we are calling a single channel, make them compatible for in-band tone purpose */
578                 ast_channel_make_compatible(outgoing->chan, in);
579         }
580
581 #ifdef HAVE_EPOLL
582         for (epollo = outgoing; epollo; epollo = epollo->next)
583                 ast_poll_channel_add(in, epollo->chan);
584 #endif  
585         
586         while (*to && !peer) {
587                 struct chanlist *o;
588                 int pos = 0;    /* how many channels do we handle */
589                 int numlines = prestart;
590                 struct ast_channel *winner;
591                 struct ast_channel *watchers[AST_MAX_WATCHERS];
592
593                 watchers[pos++] = in;
594                 for (o = outgoing; o; o = o->next) {
595                         /* Keep track of important channels */
596                         if (ast_test_flag64(o, DIAL_STILLGOING) && o->chan)
597                                 watchers[pos++] = o->chan;
598                         numlines++;
599                 }
600                 if (pos == 1) { /* only the input channel is available */
601                         if (numlines == (num.busy + num.congestion + num.nochan)) {
602                                 ast_verb(2, "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
603                                 if (num.busy)
604                                         strcpy(pa->status, "BUSY");     
605                                 else if (num.congestion)
606                                         strcpy(pa->status, "CONGESTION");
607                                 else if (num.nochan)
608                                         strcpy(pa->status, "CHANUNAVAIL");
609                         } else {
610                                 ast_verb(3, "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, num.busy, num.congestion, num.nochan);
611                         }
612                         *to = 0;
613                         return NULL;
614                 }
615                 winner = ast_waitfor_n(watchers, pos, to);
616                 for (o = outgoing; o; o = o->next) {
617                         struct ast_frame *f;
618                         struct ast_channel *c = o->chan;
619
620                         if (c == NULL)
621                                 continue;
622                         if (ast_test_flag64(o, DIAL_STILLGOING) && c->_state == AST_STATE_UP) {
623                                 if (!peer) {
624                                         ast_verb(3, "%s answered %s\n", c->name, in->name);
625                                         peer = c;
626                                         ast_copy_flags64(peerflags, o,
627                                                        OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
628                                                        OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
629                                                        OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
630                                                        OPT_CALLEE_PARK | OPT_CALLER_PARK |
631                                                        OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
632                                                        DIAL_NOFORWARDHTML);
633                                         ast_copy_string(c->dialcontext, "", sizeof(c->dialcontext));
634                                         ast_copy_string(c->exten, "", sizeof(c->exten));
635                                 }
636                                 continue;
637                         }
638                         if (c != winner)
639                                 continue;
640                         /* here, o->chan == c == winner */
641                         if (!ast_strlen_zero(c->call_forward)) {
642                                 do_forward(o, &num, peerflags, single);
643                                 continue;
644                         }
645                         f = ast_read(winner);
646                         if (!f) {
647                                 in->hangupcause = c->hangupcause;
648 #ifdef HAVE_EPOLL
649                                 ast_poll_channel_del(in, c);
650 #endif
651                                 ast_hangup(c);
652                                 c = o->chan = NULL;
653                                 ast_clear_flag64(o, DIAL_STILLGOING);
654                                 handle_cause(in->hangupcause, &num);
655                                 continue;
656                         }
657                         if (f->frametype == AST_FRAME_CONTROL) {
658                                 switch(f->subclass) {
659                                 case AST_CONTROL_ANSWER:
660                                         /* This is our guy if someone answered. */
661                                         if (!peer) {
662                                                 ast_verb(3, "%s answered %s\n", c->name, in->name);
663                                                 peer = c;
664                                                 ast_copy_flags64(peerflags, o,
665                                                                OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
666                                                                OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
667                                                                OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
668                                                                OPT_CALLEE_PARK | OPT_CALLER_PARK |
669                                                                OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
670                                                                DIAL_NOFORWARDHTML);
671                                                 ast_copy_string(c->dialcontext, "", sizeof(c->dialcontext));
672                                                 ast_copy_string(c->exten, "", sizeof(c->exten));
673                                                 if (CAN_EARLY_BRIDGE(peerflags))
674                                                         /* Setup early bridge if appropriate */
675                                                         ast_channel_early_bridge(in, peer);
676                                         }
677                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
678                                         in->hangupcause = AST_CAUSE_NORMAL_CLEARING;
679                                         c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
680                                         break;
681                                 case AST_CONTROL_BUSY:
682                                         ast_verb(3, "%s is busy\n", c->name);
683                                         in->hangupcause = c->hangupcause;
684                                         ast_hangup(c);
685                                         c = o->chan = NULL;
686                                         ast_clear_flag64(o, DIAL_STILLGOING);   
687                                         handle_cause(AST_CAUSE_BUSY, &num);
688                                         break;
689                                 case AST_CONTROL_CONGESTION:
690                                         ast_verb(3, "%s is circuit-busy\n", c->name);
691                                         in->hangupcause = c->hangupcause;
692                                         ast_hangup(c);
693                                         c = o->chan = NULL;
694                                         ast_clear_flag64(o, DIAL_STILLGOING);
695                                         handle_cause(AST_CAUSE_CONGESTION, &num);
696                                         break;
697                                 case AST_CONTROL_RINGING:
698                                         ast_verb(3, "%s is ringing\n", c->name);
699                                         /* Setup early media if appropriate */
700                                         if (single && CAN_EARLY_BRIDGE(peerflags))
701                                                 ast_channel_early_bridge(in, c);
702                                         if (!(pa->sentringing) && !ast_test_flag64(outgoing, OPT_MUSICBACK)) {
703                                                 ast_indicate(in, AST_CONTROL_RINGING);
704                                                 pa->sentringing++;
705                                         }
706                                         break;
707                                 case AST_CONTROL_PROGRESS:
708                                         ast_verb(3, "%s is making progress passing it to %s\n", c->name, in->name);
709                                         /* Setup early media if appropriate */
710                                         if (single && CAN_EARLY_BRIDGE(peerflags))
711                                                 ast_channel_early_bridge(in, c);
712                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
713                                                 ast_indicate(in, AST_CONTROL_PROGRESS);
714                                         break;
715                                 case AST_CONTROL_VIDUPDATE:
716                                         ast_verb(3, "%s requested a video update, passing it to %s\n", c->name, in->name);
717                                         ast_indicate(in, AST_CONTROL_VIDUPDATE);
718                                         break;
719                                 case AST_CONTROL_PROCEEDING:
720                                         ast_verb(3, "%s is proceeding passing it to %s\n", c->name, in->name);
721                                         if (single && CAN_EARLY_BRIDGE(peerflags))
722                                                 ast_channel_early_bridge(in, c);
723                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK))
724                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
725                                         break;
726                                 case AST_CONTROL_HOLD:
727                                         ast_verb(3, "Call on %s placed on hold\n", c->name);
728                                         ast_indicate(in, AST_CONTROL_HOLD);
729                                         break;
730                                 case AST_CONTROL_UNHOLD:
731                                         ast_verb(3, "Call on %s left from hold\n", c->name);
732                                         ast_indicate(in, AST_CONTROL_UNHOLD);
733                                         break;
734                                 case AST_CONTROL_OFFHOOK:
735                                 case AST_CONTROL_FLASH:
736                                         /* Ignore going off hook and flash */
737                                         break;
738                                 case -1:
739                                         if (!ast_test_flag64(outgoing, OPT_RINGBACK | OPT_MUSICBACK)) {
740                                                 ast_verb(3, "%s stopped sounds\n", c->name);
741                                                 ast_indicate(in, -1);
742                                                 pa->sentringing = 0;
743                                         }
744                                         break;
745                                 default:
746                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass);
747                                 }
748                         } else if (single) {
749                                 /* XXX are we sure the logic is correct ? or we should just switch on f->frametype ? */
750                                 if (f->frametype == AST_FRAME_VOICE && !ast_test_flag64(outgoing, OPT_RINGBACK|OPT_MUSICBACK)) {
751                                         if (ast_write(in, f)) 
752                                                 ast_log(LOG_WARNING, "Unable to forward voice frame\n");
753                                 } else if (f->frametype == AST_FRAME_IMAGE && !ast_test_flag64(outgoing, OPT_RINGBACK|OPT_MUSICBACK)) {
754                                         if (ast_write(in, f))
755                                                 ast_log(LOG_WARNING, "Unable to forward image\n");
756                                 } else if (f->frametype == AST_FRAME_TEXT && !ast_test_flag64(outgoing, OPT_RINGBACK|OPT_MUSICBACK)) {
757                                         if (ast_write(in, f))
758                                                 ast_log(LOG_WARNING, "Unable to send text\n");
759                                 } else if (f->frametype == AST_FRAME_HTML && !ast_test_flag64(outgoing, DIAL_NOFORWARDHTML)) {
760                                         if (ast_channel_sendhtml(in, f->subclass, f->data, f->datalen) == -1)
761                                                 ast_log(LOG_WARNING, "Unable to send URL\n");
762                                 }
763                         }
764                         ast_frfree(f);
765                 } /* end for */
766                 if (winner == in) {
767                         struct ast_frame *f = ast_read(in);
768 #if 0
769                         if (f && (f->frametype != AST_FRAME_VOICE))
770                                 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
771                         else if (!f || (f->frametype != AST_FRAME_VOICE))
772                                 printf("Hangup received on %s\n", in->name);
773 #endif
774                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
775                                 /* Got hung up */
776                                 *to = -1;
777                                 strcpy(pa->status, "CANCEL");
778                                 ast_cdr_noanswer(in->cdr);
779                                 if (f)
780                                         ast_frfree(f);
781                                 return NULL;
782                         }
783
784                         /* now f is guaranteed non-NULL */
785                         if (f->frametype == AST_FRAME_DTMF) {
786                                 if (ast_test_flag64(peerflags, OPT_DTMF_EXIT)) {
787                                         const char *context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
788                                         if (onedigit_goto(in, context, (char) f->subclass, 1)) {
789                                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass);
790                                                 *to = 0;
791                                                 ast_cdr_noanswer(in->cdr);
792                                                 *result = f->subclass;
793                                                 strcpy(pa->status, "CANCEL");
794                                                 ast_frfree(f);
795                                                 return NULL;
796                                         }
797                                 }
798
799                                 if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP) && 
800                                                   (f->subclass == '*')) { /* hmm it it not guaranteed to be '*' anymore. */
801                                         ast_verb(3, "User hit %c to disconnect call.\n", f->subclass);
802                                         *to = 0;
803                                         strcpy(pa->status, "CANCEL");
804                                         ast_cdr_noanswer(in->cdr);
805                                         ast_frfree(f);
806                                         return NULL;
807                                 }
808                         }
809
810                         /* Forward HTML stuff */
811                         if (single && (f->frametype == AST_FRAME_HTML) && !ast_test_flag64(outgoing, DIAL_NOFORWARDHTML)) 
812                                 if (ast_channel_sendhtml(outgoing->chan, f->subclass, f->data, f->datalen) == -1)
813                                         ast_log(LOG_WARNING, "Unable to send URL\n");
814                         
815
816                         if (single && ((f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_DTMF_BEGIN) || (f->frametype == AST_FRAME_DTMF_END)))  {
817                                 if (ast_write(outgoing->chan, f))
818                                         ast_log(LOG_WARNING, "Unable to forward voice or dtmf\n");
819                         }
820                         if (single && (f->frametype == AST_FRAME_CONTROL) && 
821                                 ((f->subclass == AST_CONTROL_HOLD) || 
822                                  (f->subclass == AST_CONTROL_UNHOLD) || 
823                                  (f->subclass == AST_CONTROL_VIDUPDATE))) {
824                                 ast_verb(3, "%s requested special control %d, passing it to %s\n", in->name, f->subclass, outgoing->chan->name);
825                                 ast_indicate_data(outgoing->chan, f->subclass, f->data, f->datalen);
826                         }
827                         ast_frfree(f);
828                 }
829                 if (!*to)
830                         ast_verb(3, "Nobody picked up in %d ms\n", orig);
831                 if (!*to || ast_check_hangup(in)) {
832                         ast_cdr_noanswer(in->cdr);
833                 }
834                 
835         }
836         if (peer && !ast_cdr_log_unanswered()) {
837                 /* suppress the CDR's that didn't win */
838                 struct chanlist *o;
839                 for (o = outgoing; o; o = o->next) {
840                         struct ast_channel *c = o->chan;
841                         if (c && c != peer && c->cdr) {
842                                 ast_set_flag(c->cdr, AST_CDR_FLAG_POST_DISABLED);
843                         }
844                 }
845         } else if (!peer && !ast_cdr_log_unanswered()) {
846                         /* suppress the CDR's that didn't win */
847                 struct chanlist *o;
848                 for (o = outgoing; o; o = o->next) {
849                         struct ast_channel *c = o->chan;
850                         if (c && c->cdr) {
851                                 ast_set_flag(c->cdr, AST_CDR_FLAG_POST_DISABLED);               
852                         }
853                 }
854         }
855         
856 #ifdef HAVE_EPOLL
857         for (epollo = outgoing; epollo; epollo = epollo->next) {
858                 if (epollo->chan)
859                         ast_poll_channel_del(in, epollo->chan);
860         }
861 #endif
862
863         return peer;
864 }
865
866 static void replace_macro_delimiter(char *s)
867 {
868         for (; *s; s++)
869                 if (*s == '^')
870                         *s = ',';
871 }
872
873
874 /* returns true if there is a valid privacy reply */
875 static int valid_priv_reply(struct ast_flags64 *opts, int res)
876 {
877         if (res < '1')
878                 return 0;
879         if (ast_test_flag64(opts, OPT_PRIVACY) && res <= '5')
880                 return 1;
881         if (ast_test_flag64(opts, OPT_SCREENING) && res <= '4')
882                 return 1;
883         return 0;
884 }
885
886 static int do_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
887         char *parse, unsigned int *calldurationlimit)
888 {
889         char *stringp = ast_strdupa(parse);
890         char *limit_str, *warning_str, *warnfreq_str;
891         const char *var;
892         int play_to_caller = 0, play_to_callee = 0;
893         int delta;
894
895         limit_str = strsep(&stringp, ":");
896         warning_str = strsep(&stringp, ":");
897         warnfreq_str = strsep(&stringp, ":");
898
899         config->timelimit = atol(limit_str);
900         if (warning_str)
901                 config->play_warning = atol(warning_str);
902         if (warnfreq_str)
903                 config->warning_freq = atol(warnfreq_str);
904
905         if (!config->timelimit) {
906                 ast_log(LOG_WARNING, "Dial does not accept L(%s), hanging up.\n", limit_str);
907                 config->timelimit = config->play_warning = config->warning_freq = 0;
908                 config->warning_sound = NULL;
909                 return -1;      /* error */
910         } else if ( (delta = config->play_warning - config->timelimit) > 0) {
911                 int w = config->warning_freq;
912
913                 /* If the first warning is requested _after_ the entire call would end,
914                    and no warning frequency is requested, then turn off the warning. If
915                    a warning frequency is requested, reduce the 'first warning' time by
916                    that frequency until it falls within the call's total time limit.
917                    Graphically:
918                                   timelim->|    delta        |<-playwarning
919                         0__________________|_________________|
920                                          | w  |    |    |    |
921
922                    so the number of intervals to cut is 1+(delta-1)/w
923                 */
924
925                 if (w == 0) {
926                         config->play_warning = 0;
927                 } else {
928                         config->play_warning -= w * ( 1 + (delta-1)/w );
929                         if (config->play_warning < 1)
930                                 config->play_warning = config->warning_freq = 0;
931                 }
932         }
933
934         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
935         play_to_caller = var ? ast_true(var) : 1;
936         
937         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
938         play_to_callee = var ? ast_true(var) : 0;
939         
940         if (!play_to_caller && !play_to_callee)
941                 play_to_caller = 1;
942         
943         var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
944         config->warning_sound = S_OR(var, "timeleft");
945
946         /* The code looking at config wants a NULL, not just "", to decide
947          * that the message should not be played, so we replace "" with NULL.
948          * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
949          * not found.
950          */
951         var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
952         config->end_sound = S_OR(var, NULL);
953         var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
954         config->start_sound = S_OR(var, NULL);
955
956         /* undo effect of S(x) in case they are both used */
957         *calldurationlimit = 0;
958         /* more efficient to do it like S(x) does since no advanced opts */
959         if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
960                 *calldurationlimit = config->timelimit / 1000;
961                 ast_verb(3, "Setting call duration limit to %d seconds.\n",
962                                 *calldurationlimit);
963                 config->timelimit = play_to_caller = play_to_callee =
964                 config->play_warning = config->warning_freq = 0;
965         } else {
966                 ast_verb(3, "Limit Data for this call:\n");
967                 ast_verb(4, "timelimit      = %ld\n", config->timelimit);
968                 ast_verb(4, "play_warning   = %ld\n", config->play_warning);
969                 ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
970                 ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
971                 ast_verb(4, "warning_freq   = %ld\n", config->warning_freq);
972                 ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
973                 ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
974                 ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
975         }
976         if (play_to_caller)
977                 ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
978         if (play_to_callee)
979                 ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
980         return 0;
981 }
982
983 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
984     struct ast_flags64 *opts, char **opt_args, struct privacy_args *pa)
985 {
986
987         int res2;
988         int loopcount = 0;
989
990         /* Get the user's intro, store it in priv-callerintros/$CID, 
991            unless it is already there-- this should be done before the 
992            call is actually dialed  */
993
994         /* all ring indications and moh for the caller has been halted as soon as the 
995            target extension was picked up. We are going to have to kill some
996            time and make the caller believe the peer hasn't picked up yet */
997
998         if (ast_test_flag64(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
999                 char *original_moh = ast_strdupa(chan->musicclass);
1000                 ast_indicate(chan, -1);
1001                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
1002                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1003                 ast_string_field_set(chan, musicclass, original_moh);
1004         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1005                 ast_indicate(chan, AST_CONTROL_RINGING);
1006                 pa->sentringing++;
1007         }
1008
1009         /* Start autoservice on the other chan ?? */
1010         res2 = ast_autoservice_start(chan);
1011         /* Now Stream the File */
1012         for (loopcount = 0; loopcount < 3; loopcount++) {
1013                 if (res2 && loopcount == 0)     /* error in ast_autoservice_start() */
1014                         break;
1015                 if (!res2)      /* on timeout, play the message again */
1016                         res2 = ast_play_and_wait(peer, "priv-callpending");
1017                 if (!valid_priv_reply(opts, res2))
1018                         res2 = 0;
1019                 /* priv-callpending script: 
1020                    "I have a caller waiting, who introduces themselves as:"
1021                 */
1022                 if (!res2)
1023                         res2 = ast_play_and_wait(peer, pa->privintro);
1024                 if (!valid_priv_reply(opts, res2))
1025                         res2 = 0;
1026                 /* now get input from the called party, as to their choice */
1027                 if (!res2) {
1028                         /* XXX can we have both, or they are mutually exclusive ? */
1029                         if (ast_test_flag64(opts, OPT_PRIVACY))
1030                                 res2 = ast_play_and_wait(peer, "priv-callee-options");
1031                         if (ast_test_flag64(opts, OPT_SCREENING))
1032                                 res2 = ast_play_and_wait(peer, "screen-callee-options");
1033                 }
1034                 /*! \page DialPrivacy Dial Privacy scripts
1035                 \par priv-callee-options script:
1036                         "Dial 1 if you wish this caller to reach you directly in the future,
1037                                 and immediately connect to their incoming call
1038                          Dial 2 if you wish to send this caller to voicemail now and 
1039                                 forevermore.
1040                          Dial 3 to send this caller to the torture menus, now and forevermore.
1041                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1042                          Dial 5 to allow this caller to come straight thru to you in the future,
1043                                 but right now, just this once, send them to voicemail."
1044                 \par screen-callee-options script:
1045                         "Dial 1 if you wish to immediately connect to the incoming call
1046                          Dial 2 if you wish to send this caller to voicemail.
1047                          Dial 3 to send this caller to the torture menus.
1048                          Dial 4 to send this caller to a simple "go away" menu.
1049                 */
1050                 if (valid_priv_reply(opts, res2))
1051                         break;
1052                 /* invalid option */
1053                 res2 = ast_play_and_wait(peer, "vm-sorry");
1054         }
1055
1056         if (ast_test_flag64(opts, OPT_MUSICBACK)) {
1057                 ast_moh_stop(chan);
1058         } else if (ast_test_flag64(opts, OPT_RINGBACK)) {
1059                 ast_indicate(chan, -1);
1060                 pa->sentringing = 0;
1061         }
1062         ast_autoservice_stop(chan);
1063         if (ast_test_flag64(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
1064                 /* map keypresses to various things, the index is res2 - '1' */
1065                 static const char *_val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
1066                 static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
1067                 int i = res2 - '1';
1068                 ast_verb(3, "--Set privacy database entry %s/%s to %s\n",
1069                                              opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
1070                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
1071         }
1072         switch (res2) {
1073         case '1':
1074                 break;
1075         case '2':
1076                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1077                 break;
1078         case '3':
1079                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1080                 break;
1081         case '4':
1082                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1083                 break;
1084         case '5':
1085                 /* XXX should we set status to DENY ? */
1086                 if (ast_test_flag64(opts, OPT_PRIVACY))
1087                         break;
1088                 /* if not privacy, then 5 is the same as "default" case */
1089         default:        /* bad input or -1 if failure to start autoservice */
1090                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1091                 /* well, there seems basically two choices. Just patch the caller thru immediately,
1092                           or,... put 'em thru to voicemail. */
1093                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1094                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1095                 /* XXX should we set status to DENY ? */
1096                 /* XXX what about the privacy flags ? */
1097                 break;
1098         }
1099
1100         if (res2 == '1') {      /* the only case where we actually connect */
1101                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll 
1102                    just clog things up, and it's not useful information, not being tied to a CID */
1103                 if (strncmp(pa->privcid, "NOCALLERID", 10) == 0 || ast_test_flag64(opts, OPT_SCREEN_NOINTRO)) {
1104                         ast_filedelete(pa->privintro, NULL);
1105                         if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1106                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1107                         else
1108                                 ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1109                 }
1110                 return 0;       /* the good exit path */
1111         } else {
1112                 ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1113                 return -1;
1114         }
1115 }
1116
1117 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
1118 static int setup_privacy_args(struct privacy_args *pa,
1119         struct ast_flags64 *opts, char *opt_args[], struct ast_channel *chan)
1120 {
1121         char callerid[60];
1122         int res;
1123         char *l;
1124
1125         if (!ast_strlen_zero(chan->cid.cid_num)) {
1126                 l = ast_strdupa(chan->cid.cid_num);
1127                 ast_shrink_phone_number(l);
1128                 if (ast_test_flag64(opts, OPT_PRIVACY) ) {
1129                         ast_verb(3, "Privacy DB is '%s', clid is '%s'\n", opt_args[OPT_ARG_PRIVACY], l);
1130                         pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
1131                 } else {
1132                         ast_verb(3, "Privacy Screening, clid is '%s'\n", l);
1133                         pa->privdb_val = AST_PRIVACY_UNKNOWN;
1134                 }
1135         } else {
1136                 char *tnam, *tn2;
1137
1138                 tnam = ast_strdupa(chan->name);
1139                 /* clean the channel name so slashes don't try to end up in disk file name */
1140                 for (tn2 = tnam; *tn2; tn2++) {
1141                         if (*tn2 == '/')  /* any other chars to be afraid of? */
1142                                 *tn2 = '=';
1143                 }
1144                 ast_verb(3, "Privacy-- callerid is empty\n");
1145
1146                 snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
1147                 l = callerid;
1148                 pa->privdb_val = AST_PRIVACY_UNKNOWN;
1149         }
1150         
1151         ast_copy_string(pa->privcid, l, sizeof(pa->privcid));
1152
1153         if (strncmp(pa->privcid, "NOCALLERID", 10) != 0 && ast_test_flag64(opts, OPT_SCREEN_NOCLID)) {
1154                 /* if callerid is set and OPT_SCREEN_NOCLID is set also */  
1155                 ast_verb(3, "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
1156                 pa->privdb_val = AST_PRIVACY_ALLOW;
1157         } else if (ast_test_flag64(opts, OPT_SCREEN_NOCLID) && strncmp(pa->privcid, "NOCALLERID", 10) == 0) {
1158                 ast_verb(3, "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
1159         }
1160         
1161         if (pa->privdb_val == AST_PRIVACY_DENY) {
1162                 ast_verb(3, "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
1163                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1164                 return 0;
1165         } else if (pa->privdb_val == AST_PRIVACY_KILL) {
1166                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1167                 return 0; /* Is this right? */
1168         } else if (pa->privdb_val == AST_PRIVACY_TORTURE) {
1169                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1170                 return 0; /* is this right??? */
1171         } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN) {
1172                 /* Get the user's intro, store it in priv-callerintros/$CID, 
1173                    unless it is already there-- this should be done before the 
1174                    call is actually dialed  */
1175
1176                 /* make sure the priv-callerintros dir actually exists */
1177                 snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
1178                 if ((res = ast_mkdir(pa->privintro, 0755))) {
1179                         ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(res));
1180                         return -1;
1181                 }
1182
1183                 snprintf(pa->privintro, sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
1184                 if (ast_fileexists(pa->privintro, NULL, NULL ) > 0 && strncmp(pa->privcid, "NOCALLERID", 10) != 0) {
1185                         /* the DELUX version of this code would allow this caller the
1186                            option to hear and retape their previously recorded intro.
1187                         */
1188                 } else {
1189                         int duration; /* for feedback from play_and_wait */
1190                         /* the file doesn't exist yet. Let the caller submit his
1191                            vocal intro for posterity */
1192                         /* priv-recordintro script:
1193
1194                            "At the tone, please say your name:"
1195
1196                         */
1197                         ast_answer(chan);
1198                         res = ast_play_and_record(chan, "priv-recordintro", pa->privintro, 4, "gsm", &duration, 128, 2000, 0);  /* NOTE: I've reduced the total time to 4 sec */
1199                                                                         /* don't think we'll need a lock removed, we took care of
1200                                                                            conflicts by naming the pa.privintro file */
1201                         if (res == -1) {
1202                                 /* Delete the file regardless since they hung up during recording */
1203                                 ast_filedelete(pa->privintro, NULL);
1204                                 if (ast_fileexists(pa->privintro, NULL, NULL) > 0)
1205                                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1206                                 else
1207                                         ast_verb(3, "Successfully deleted %s intro file\n", pa->privintro);
1208                                 return -1;
1209                         }
1210                         if (!ast_streamfile(chan, "vm-dialout", chan->language) )
1211                                 ast_waitstream(chan, "");
1212                 }
1213         }
1214         return 1;       /* success */
1215 }
1216
1217 static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags64 *peerflags, int *continue_exec)
1218 {
1219         int res = -1;   /* default: error */
1220         char *rest, *cur;       /* scan the list of destinations */
1221         struct chanlist *outgoing = NULL;       /* list of destinations */
1222         struct ast_channel *peer;
1223         int to; /* timeout */
1224         struct cause_args num = { chan, 0, 0, 0 };
1225         int cause;
1226         char numsubst[256];
1227         char cidname[AST_MAX_EXTENSION] = "";
1228
1229         struct ast_bridge_config config = { { 0, } };
1230         unsigned int calldurationlimit = 0;
1231         char *dtmfcalled = NULL, *dtmfcalling = NULL;
1232         struct privacy_args pa = {
1233                 .sentringing = 0,
1234                 .privdb_val = 0,
1235                 .status = "INVALIDARGS",
1236         };
1237         int sentringing = 0, moh = 0;
1238         const char *outbound_group = NULL;
1239         int result = 0;
1240         time_t start_time;
1241         char *parse;
1242         int opermode = 0;
1243         AST_DECLARE_APP_ARGS(args,
1244                              AST_APP_ARG(peers);
1245                              AST_APP_ARG(timeout);
1246                              AST_APP_ARG(options);
1247                              AST_APP_ARG(url);
1248         );
1249         struct ast_flags64 opts = { 0, };
1250         char *opt_args[OPT_ARG_ARRAY_SIZE];
1251         struct ast_datastore *datastore = NULL;
1252         int fulldial = 0, num_dialed = 0;
1253
1254         if (ast_strlen_zero(data)) {
1255                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1256                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1257                 return -1;
1258         }
1259
1260         parse = ast_strdupa(data);
1261         
1262         AST_STANDARD_APP_ARGS(args, parse);
1263
1264         if (!ast_strlen_zero(args.options) &&
1265                         ast_app_parse_options64(dial_exec_options, &opts, opt_args, args.options)) {
1266                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1267                 goto done;
1268         }
1269
1270         if (ast_strlen_zero(args.peers)) {
1271                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1272                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1273                 goto done;
1274         }
1275
1276         if (ast_test_flag64(&opts, OPT_OPERMODE)) {
1277                 opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
1278                 ast_verb(3, "Setting operator services mode to %d.\n", opermode);
1279         }
1280         
1281         if (ast_test_flag64(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
1282                 calldurationlimit = atoi(opt_args[OPT_ARG_DURATION_STOP]);
1283                 if (!calldurationlimit) {
1284                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
1285                         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1286                         goto done;
1287                 }
1288                 ast_verb(3, "Setting call duration limit to %d seconds.\n", calldurationlimit);
1289         }
1290
1291         if (ast_test_flag64(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
1292                 dtmfcalling = opt_args[OPT_ARG_SENDDTMF];
1293                 dtmfcalled = strsep(&dtmfcalling, ":");
1294         }
1295
1296         if (ast_test_flag64(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
1297                 if (do_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
1298                         goto done;
1299         }
1300
1301         if (ast_test_flag64(&opts, OPT_RESETCDR) && chan->cdr)
1302                 ast_cdr_reset(chan->cdr, NULL);
1303         if (ast_test_flag64(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
1304                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(chan->exten);
1305
1306         if (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) {
1307                 res = setup_privacy_args(&pa, &opts, opt_args, chan);
1308                 if (res <= 0)
1309                         goto out;
1310                 res = -1;       /* reset default */
1311         }
1312
1313         if (continue_exec)
1314                 *continue_exec = 0;
1315         
1316         /* If a channel group has been specified, get it for use when we create peer channels */
1317         if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
1318                 outbound_group = ast_strdupa(outbound_group);
1319                 pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
1320         } else {
1321                 outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP");
1322         }
1323             
1324         ast_copy_flags64(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING);
1325         /* loop through the list of dial destinations */
1326         rest = args.peers;
1327         while ((cur = strsep(&rest, "&")) ) {
1328                 struct chanlist *tmp;
1329                 struct ast_channel *tc; /* channel for this destination */
1330                 /* Get a technology/[device:]number pair */
1331                 char *number = cur;
1332                 char *interface = ast_strdupa(number);
1333                 char *tech = strsep(&number, "/");
1334                 /* find if we already dialed this interface */
1335                 struct ast_dialed_interface *di;
1336                 AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
1337                 num_dialed++;
1338                 if (!number) {
1339                         ast_log(LOG_WARNING, "Dial argument takes format (technology/[device:]number1)\n");
1340                         goto out;
1341                 }
1342                 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1343                         goto out;
1344                 if (opts.flags) {
1345                         ast_copy_flags64(tmp, &opts,
1346                                        OPT_CANCEL_ELSEWHERE |
1347                                        OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1348                                        OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1349                                        OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1350                                        OPT_CALLEE_PARK | OPT_CALLER_PARK |
1351                                        OPT_CALLEE_MIXMONITOR | OPT_CALLER_MIXMONITOR |
1352                                        OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID);
1353                         ast_set2_flag64(tmp, args.url, DIAL_NOFORWARDHTML);     
1354                 }
1355                 ast_copy_string(numsubst, number, sizeof(numsubst));
1356                 /* Request the peer */
1357
1358                 ast_channel_lock(chan);
1359                 datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL);
1360                 ast_channel_unlock(chan);
1361
1362                 if (datastore)
1363                         dialed_interfaces = datastore->data;
1364                 else {
1365                         if (!(datastore = ast_channel_datastore_alloc(&dialed_interface_info, NULL))) {
1366                                 ast_log(LOG_WARNING, "Unable to create channel datastore for dialed interfaces. Aborting!\n"); 
1367                                 ast_free(tmp);
1368                                 goto out;
1369                         }
1370
1371                         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
1372
1373                         if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
1374                                 ast_free(tmp);
1375                                 goto out;
1376                         }
1377
1378                         datastore->data = dialed_interfaces;
1379                         AST_LIST_HEAD_INIT(dialed_interfaces);
1380
1381                         ast_channel_lock(chan);
1382                         ast_channel_datastore_add(chan, datastore);
1383                         ast_channel_unlock(chan);
1384                 }
1385
1386                 AST_LIST_LOCK(dialed_interfaces);
1387                 AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
1388                         if (!strcasecmp(di->interface, interface)) {
1389                                 ast_log(LOG_WARNING, "Skipping dialing interface '%s' again since it has already been dialed\n", 
1390                                         di->interface);
1391                                 break;
1392                         }
1393                 }
1394                 AST_LIST_UNLOCK(dialed_interfaces);
1395
1396                 if (di) {
1397                         fulldial++;
1398                         ast_free(tmp);
1399                         continue;
1400                 }
1401
1402                 /* It is always ok to dial a Local interface.  We only keep track of
1403                  * which "real" interfaces have been dialed.  The Local channel will
1404                  * inherit this list so that if it ends up dialing a real interface,
1405                  * it won't call one that has already been called. */
1406                 if (strcasecmp(tech, "Local")) {
1407                         if (!(di = ast_calloc(1, sizeof(*di) + strlen(interface)))) {
1408                                 AST_LIST_UNLOCK(dialed_interfaces);
1409                                 ast_free(tmp);
1410                                 goto out;
1411                         }
1412                         strcpy(di->interface, interface);
1413
1414                         AST_LIST_LOCK(dialed_interfaces);
1415                         AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
1416                         AST_LIST_UNLOCK(dialed_interfaces);
1417                 }
1418
1419                 tc = ast_request(tech, chan->nativeformats, numsubst, &cause);
1420                 if (!tc) {
1421                         /* If we can't, just go on to the next call */
1422                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
1423                                     tech, cause, ast_cause2str(cause));
1424                         handle_cause(cause, &num);
1425                         if (!rest)      /* we are on the last destination */
1426                                 chan->hangupcause = cause;
1427                         ast_free(tmp);
1428                         continue;
1429                 }
1430                 pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", numsubst);
1431
1432                 /* Setup outgoing SDP to match incoming one */
1433                 ast_rtp_make_compatible(tc, chan, !outgoing && !rest);
1434                 
1435                 /* Inherit specially named variables from parent channel */
1436                 ast_channel_inherit_variables(chan, tc);
1437
1438                 tc->appl = "AppDial";
1439                 tc->data = "(Outgoing Line)";
1440                 tc->whentohangup = 0;
1441
1442                 S_REPLACE(tc->cid.cid_num, ast_strdup(chan->cid.cid_num));
1443                 S_REPLACE(tc->cid.cid_name, ast_strdup(chan->cid.cid_name));
1444                 S_REPLACE(tc->cid.cid_ani, ast_strdup(chan->cid.cid_ani));
1445                 S_REPLACE(tc->cid.cid_rdnis, ast_strdup(chan->cid.cid_rdnis));
1446                 
1447                 /* Copy language from incoming to outgoing */
1448                 ast_string_field_set(tc, language, chan->language);
1449                 ast_string_field_set(tc, accountcode, chan->accountcode);
1450                 tc->cdrflags = chan->cdrflags;
1451                 if (ast_strlen_zero(tc->musicclass))
1452                         ast_string_field_set(tc, musicclass, chan->musicclass);
1453                 /* Pass callingpres, type of number, tns, ADSI CPE, transfer capability */
1454                 tc->cid.cid_pres = chan->cid.cid_pres;
1455                 tc->cid.cid_ton = chan->cid.cid_ton;
1456                 tc->cid.cid_tns = chan->cid.cid_tns;
1457                 tc->cid.cid_ani2 = chan->cid.cid_ani2;
1458                 tc->adsicpe = chan->adsicpe;
1459                 tc->transfercapability = chan->transfercapability;
1460
1461                 /* If we have an outbound group, set this peer channel to it */
1462                 if (outbound_group)
1463                         ast_app_group_set_channel(tc, outbound_group);
1464
1465                 /* Inherit context and extension */
1466                 if (!ast_strlen_zero(chan->macrocontext))
1467                         ast_copy_string(tc->dialcontext, chan->macrocontext, sizeof(tc->dialcontext));
1468                 else
1469                         ast_copy_string(tc->dialcontext, chan->context, sizeof(tc->dialcontext));
1470                 if (!ast_strlen_zero(chan->macroexten))
1471                         ast_copy_string(tc->exten, chan->macroexten, sizeof(tc->exten));
1472                 else
1473                         ast_copy_string(tc->exten, chan->exten, sizeof(tc->exten));
1474
1475                 res = ast_call(tc, numsubst, 0);        /* Place the call, but don't wait on the answer */
1476
1477                 /* Save the info in cdr's that we called them */
1478                 if (chan->cdr)
1479                         ast_cdr_setdestchan(chan->cdr, tc->name);
1480
1481                 /* check the results of ast_call */
1482                 if (res) {
1483                         /* Again, keep going even if there's an error */
1484                         ast_debug(1, "ast call on peer returned %d\n", res);
1485                         ast_verb(3, "Couldn't call %s\n", numsubst);
1486                         ast_hangup(tc);
1487                         tc = NULL;
1488                         ast_free(tmp);
1489                         continue;
1490                 } else {
1491                         senddialevent(chan, tc, numsubst);
1492                         ast_verb(3, "Called %s\n", numsubst);
1493                         if (!ast_test_flag64(peerflags, OPT_ORIGINAL_CLID))
1494                                 ast_set_callerid(tc, S_OR(chan->macroexten, chan->exten), get_cid_name(cidname, sizeof(cidname), chan), NULL);
1495                 }
1496                 /* Put them in the list of outgoing thingies...  We're ready now. 
1497                    XXX If we're forcibly removed, these outgoing calls won't get
1498                    hung up XXX */
1499                 ast_set_flag64(tmp, DIAL_STILLGOING);   
1500                 tmp->chan = tc;
1501                 tmp->next = outgoing;
1502                 outgoing = tmp;
1503                 /* If this line is up, don't try anybody else */
1504                 if (outgoing->chan->_state == AST_STATE_UP)
1505                         break;
1506         }
1507         
1508         if (ast_strlen_zero(args.timeout)) {
1509                 to = -1;
1510         } else {
1511                 to = atoi(args.timeout);
1512                 if (to > 0)
1513                         to *= 1000;
1514                 else
1515                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'\n", args.timeout);
1516         }
1517
1518         if (!outgoing) {
1519                 strcpy(pa.status, "CHANUNAVAIL");
1520                 if (fulldial == num_dialed) {
1521                         res = -1;
1522                         goto out;
1523                 }
1524         } else {
1525                 /* Our status will at least be NOANSWER */
1526                 strcpy(pa.status, "NOANSWER");
1527                 if (ast_test_flag64(outgoing, OPT_MUSICBACK)) {
1528                         moh = 1;
1529                         if (!ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1530                                 char *original_moh = ast_strdupa(chan->musicclass);
1531                                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
1532                                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1533                                 ast_string_field_set(chan, musicclass, original_moh);
1534                         } else {
1535                                 ast_moh_start(chan, NULL, NULL);
1536                         }
1537                         ast_indicate(chan, AST_CONTROL_PROGRESS);
1538                 } else if (ast_test_flag64(outgoing, OPT_RINGBACK)) {
1539                         ast_indicate(chan, AST_CONTROL_RINGING);
1540                         sentringing++;
1541                 }
1542         }
1543
1544         time(&start_time);
1545         peer = wait_for_answer(chan, outgoing, &to, peerflags, &pa, &num, &result);
1546
1547         ast_channel_datastore_remove(chan, datastore);
1548         ast_channel_datastore_free(datastore);
1549         if (!peer) {
1550                 if (result) {
1551                         res = result;
1552                 } else if (to) { /* Musta gotten hung up */
1553                         res = -1;
1554                 } else { /* Nobody answered, next please? */
1555                         res = 0;
1556                 }
1557                 /* almost done, although the 'else' block is 400 lines */
1558         } else {
1559                 const char *number;
1560                 time_t end_time, answer_time = time(NULL);
1561                 char toast[80]; /* buffer to set variables */
1562
1563                 strcpy(pa.status, "ANSWER");
1564                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1565                    we will always return with -1 so that it is hung up properly after the 
1566                    conversation.  */
1567                 hanguptree(outgoing, peer, 1);
1568                 outgoing = NULL;
1569                 /* If appropriate, log that we have a destination channel */
1570                 if (chan->cdr)
1571                         ast_cdr_setdestchan(chan->cdr, peer->name);
1572                 if (peer->name)
1573                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
1574
1575                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER");
1576                 if (!number)
1577                         number = numsubst;
1578                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
1579                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
1580                         ast_debug(1, "app_dial: sendurl=%s.\n", args.url);
1581                         ast_channel_sendurl( peer, args.url );
1582                 }
1583                 if ( (ast_test_flag64(&opts, OPT_PRIVACY) || ast_test_flag64(&opts, OPT_SCREENING)) && pa.privdb_val == AST_PRIVACY_UNKNOWN) {
1584                         if (do_privacy(chan, peer, &opts, opt_args, &pa)) {
1585                                 res = 0;
1586                                 goto out;
1587                         }
1588                 }
1589                 if (!ast_test_flag64(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
1590                         res = 0;
1591                 } else {
1592                         int digit = 0;
1593                         /* Start autoservice on the other chan */
1594                         res = ast_autoservice_start(chan);
1595                         /* Now Stream the File */
1596                         if (!res)
1597                                 res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
1598                         if (!res) {
1599                                 digit = ast_waitstream(peer, AST_DIGIT_ANY); 
1600                         }
1601                         /* Ok, done. stop autoservice */
1602                         res = ast_autoservice_stop(chan);
1603                         if (digit > 0 && !res)
1604                                 res = ast_senddigit(chan, digit, 0); 
1605                         else
1606                                 res = digit;
1607
1608                 }
1609
1610                 if (chan && peer && ast_test_flag64(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
1611                         replace_macro_delimiter(opt_args[OPT_ARG_GOTO]);
1612                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
1613                         /* peer goes to the same context and extension as chan, so just copy info from chan*/
1614                         ast_copy_string(peer->context, chan->context, sizeof(peer->context));
1615                         ast_copy_string(peer->exten, chan->exten, sizeof(peer->exten));
1616                         peer->priority = chan->priority + 2;
1617                         ast_pbx_start(peer);
1618                         hanguptree(outgoing, NULL, ast_test_flag64(&opts, OPT_CANCEL_ELSEWHERE) ? 1 : 0);
1619                         if (continue_exec)
1620                                 *continue_exec = 1;
1621                         res = 0;
1622                         goto done;
1623                 }
1624
1625                 if (ast_test_flag64(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
1626                         struct ast_app *theapp;
1627                         const char *macro_result;
1628
1629                         res = ast_autoservice_start(chan);
1630                         if (res) {
1631                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
1632                                 res = -1;
1633                         }
1634
1635                         theapp = pbx_findapp("Macro");
1636
1637                         if (theapp && !res) {   /* XXX why check res here ? */
1638                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_MACRO]);
1639                                 res = pbx_exec(peer, theapp, opt_args[OPT_ARG_CALLEE_MACRO]);
1640                                 ast_debug(1, "Macro exited with status %d\n", res);
1641                                 res = 0;
1642                         } else {
1643                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
1644                                 res = -1;
1645                         }
1646
1647                         if (ast_autoservice_stop(chan) < 0) {
1648                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
1649                                 res = -1;
1650                         }
1651
1652                         if (!res && (macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
1653                                 char *macro_transfer_dest;
1654
1655                                 if (!strcasecmp(macro_result, "BUSY")) {
1656                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
1657                                         ast_set_flag64(peerflags, OPT_GO_ON);
1658                                         res = -1;
1659                                 } else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
1660                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
1661                                         ast_set_flag64(peerflags, OPT_GO_ON);   
1662                                         res = -1;
1663                                 } else if (!strcasecmp(macro_result, "CONTINUE")) {
1664                                         /* hangup peer and keep chan alive assuming the macro has changed 
1665                                            the context / exten / priority or perhaps 
1666                                            the next priority in the current exten is desired.
1667                                         */
1668                                         ast_set_flag64(peerflags, OPT_GO_ON);   
1669                                         res = -1;
1670                                 } else if (!strcasecmp(macro_result, "ABORT")) {
1671                                         /* Hangup both ends unless the caller has the g flag */
1672                                         res = -1;
1673                                 } else if (!strncasecmp(macro_result, "GOTO:", 5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
1674                                         res = -1;
1675                                         /* perform a transfer to a new extension */
1676                                         if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
1677                                                 replace_macro_delimiter(macro_transfer_dest);
1678                                                 if (!ast_parseable_goto(chan, macro_transfer_dest))
1679                                                         ast_set_flag64(peerflags, OPT_GO_ON);
1680                                         }
1681                                 }
1682                         }
1683                 }
1684
1685                 if (ast_test_flag64(&opts, OPT_CALLEE_GOSUB) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_GOSUB])) {
1686                         struct ast_app *theapp;
1687                         const char *gosub_result;
1688                         char *gosub_args, *gosub_argstart;
1689
1690                         res = ast_autoservice_start(chan);
1691                         if (res) {
1692                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
1693                                 res = -1;
1694                         }
1695
1696                         theapp = pbx_findapp("Gosub");
1697
1698                         if (theapp && !res) {   /* XXX why check res here ? */
1699                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_GOSUB]);
1700
1701                                 /* Set where we came from */
1702                                 ast_copy_string(peer->context, "app_dial_gosub_virtual_context", sizeof(peer->context));
1703                                 ast_copy_string(peer->exten, "s", sizeof(peer->exten));
1704                                 peer->priority = 0;
1705
1706                                 gosub_argstart = strchr(opt_args[OPT_ARG_CALLEE_GOSUB], '|');
1707                                 if (gosub_argstart) {
1708                                         *gosub_argstart = 0;
1709                                         asprintf(&gosub_args, "%s|s|1(%s)", opt_args[OPT_ARG_CALLEE_GOSUB], gosub_argstart + 1);
1710                                         *gosub_argstart = '|';
1711                                 } else {
1712                                         asprintf(&gosub_args, "%s|s|1", opt_args[OPT_ARG_CALLEE_GOSUB]);
1713                                 }
1714
1715                                 if (gosub_args) {
1716                                         res = pbx_exec(peer, theapp, gosub_args);
1717                                         ast_pbx_run(peer);
1718                                         ast_free(gosub_args);
1719                                         if (option_debug)
1720                                                 ast_log(LOG_DEBUG, "Gosub exited with status %d\n", res);
1721                                 } else
1722                                         ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
1723                                 
1724                                 res = 0;
1725                         } else {
1726                                 ast_log(LOG_ERROR, "Could not find application Gosub\n");
1727                                 res = -1;
1728                         }
1729
1730                         if (ast_autoservice_stop(chan) < 0) {
1731                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
1732                                 res = -1;
1733                         }
1734
1735                         if (!res && (gosub_result = pbx_builtin_getvar_helper(peer, "GOSUB_RESULT"))) {
1736                                 char *gosub_transfer_dest;
1737
1738                                 if (!strcasecmp(gosub_result, "BUSY")) {
1739                                         ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
1740                                         ast_set_flag64(peerflags, OPT_GO_ON);
1741                                         res = -1;
1742                                 } else if (!strcasecmp(gosub_result, "CONGESTION") || !strcasecmp(gosub_result, "CHANUNAVAIL")) {
1743                                         ast_copy_string(pa.status, gosub_result, sizeof(pa.status));
1744                                         ast_set_flag64(peerflags, OPT_GO_ON);   
1745                                         res = -1;
1746                                 } else if (!strcasecmp(gosub_result, "CONTINUE")) {
1747                                         /* hangup peer and keep chan alive assuming the macro has changed 
1748                                            the context / exten / priority or perhaps 
1749                                            the next priority in the current exten is desired.
1750                                         */
1751                                         ast_set_flag64(peerflags, OPT_GO_ON);   
1752                                         res = -1;
1753                                 } else if (!strcasecmp(gosub_result, "ABORT")) {
1754                                         /* Hangup both ends unless the caller has the g flag */
1755                                         res = -1;
1756                                 } else if (!strncasecmp(gosub_result, "GOTO:", 5) && (gosub_transfer_dest = ast_strdupa(gosub_result + 5))) {
1757                                         res = -1;
1758                                         /* perform a transfer to a new extension */
1759                                         if (strchr(gosub_transfer_dest, '^')) { /* context^exten^priority*/
1760                                                 replace_macro_delimiter(gosub_transfer_dest);
1761                                                 if (!ast_parseable_goto(chan, gosub_transfer_dest))
1762                                                         ast_set_flag64(peerflags, OPT_GO_ON);
1763                                         }
1764                                 }
1765                         }
1766                 }
1767
1768                 if (!res) {
1769                         if (calldurationlimit > 0) {
1770                                 peer->whentohangup = time(NULL) + calldurationlimit;
1771                         }
1772                         if (!ast_strlen_zero(dtmfcalled)) { 
1773                                 ast_verb(3, "Sending DTMF '%s' to the called party.\n", dtmfcalled);
1774                                 res = ast_dtmf_stream(peer, chan, dtmfcalled, 250, 0);
1775                         }
1776                         if (!ast_strlen_zero(dtmfcalling)) {
1777                                 ast_verb(3, "Sending DTMF '%s' to the calling party.\n", dtmfcalling);
1778                                 res = ast_dtmf_stream(chan, peer, dtmfcalling, 250, 0);
1779                         }
1780                 }
1781                 
1782                 if (res) {      /* some error */
1783                         res = -1;
1784                         end_time = time(NULL);
1785                 } else {
1786                         if (ast_test_flag64(peerflags, OPT_CALLEE_TRANSFER))
1787                                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1788                         if (ast_test_flag64(peerflags, OPT_CALLER_TRANSFER))
1789                                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
1790                         if (ast_test_flag64(peerflags, OPT_CALLEE_HANGUP))
1791                                 ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
1792                         if (ast_test_flag64(peerflags, OPT_CALLER_HANGUP))
1793                                 ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
1794                         if (ast_test_flag64(peerflags, OPT_CALLEE_MONITOR))
1795                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1796                         if (ast_test_flag64(peerflags, OPT_CALLER_MONITOR)) 
1797                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1798                         if (ast_test_flag64(peerflags, OPT_CALLEE_PARK))
1799                                 ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
1800                         if (ast_test_flag64(peerflags, OPT_CALLER_PARK))
1801                                 ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
1802                         if (ast_test_flag64(peerflags, OPT_CALLEE_MIXMONITOR))
1803                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMIXMON);
1804                         if (ast_test_flag64(peerflags, OPT_CALLER_MIXMONITOR))
1805                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMIXMON);
1806
1807                         if (moh) {
1808                                 moh = 0;
1809                                 ast_moh_stop(chan);
1810                         } else if (sentringing) {
1811                                 sentringing = 0;
1812                                 ast_indicate(chan, -1);
1813                         }
1814                         /* Be sure no generators are left on it */
1815                         ast_deactivate_generator(chan);
1816                         /* Make sure channels are compatible */
1817                         res = ast_channel_make_compatible(chan, peer);
1818                         if (res < 0) {
1819                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
1820                                 ast_hangup(peer);
1821                                 res = -1;
1822                                 goto done;
1823                         }
1824                         if (opermode && !strncmp(chan->name, "Zap", 3) && !strncmp(peer->name, "Zap", 3)) {
1825                                 /* what's this special handling for Zap <-> Zap ?
1826                                  * A: Zap to Zap calls are natively bridged at the kernel driver
1827                                  * level, so we need to ensure that this mode gets propagated
1828                                  * all the way down. */
1829                                 struct oprmode oprmode;
1830
1831                                 oprmode.peer = peer;
1832                                 oprmode.mode = opermode;
1833
1834                                 ast_channel_setoption(chan, AST_OPTION_OPRMODE, &oprmode, sizeof(oprmode), 0);
1835                         }
1836                         res = ast_bridge_call(chan, peer, &config);
1837                         end_time = time(NULL);
1838                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1839                         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", toast);
1840                 }
1841
1842                 snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1843                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", toast);
1844                 
1845                 
1846                 if (ast_test_flag64(&opts, OPT_PEER_H)) {
1847                         ast_log(LOG_NOTICE, "PEER context: %s; PEER exten: %s;  PEER priority: %d\n", 
1848                                         peer->context, peer->exten, peer->priority);
1849                 }
1850                 
1851                 strcpy(peer->context, chan->context);
1852
1853                 if (ast_test_flag64(&opts, OPT_PEER_H) && ast_exists_extension(peer, peer->context, "h", 1, peer->cid.cid_num)) {
1854                         int autoloopflag;
1855                         int found;
1856                         strcpy(peer->exten, "h");
1857                         peer->priority = 1;
1858                         autoloopflag = ast_test_flag(peer, AST_FLAG_IN_AUTOLOOP);       /* save value to restore at the end */
1859                         ast_set_flag(peer, AST_FLAG_IN_AUTOLOOP);
1860                         
1861                         while ((res = ast_spawn_extension(peer, peer->context, peer->exten, peer->priority, peer->cid.cid_num, &found, 1))) {
1862                                 peer->priority++;
1863                         }
1864                         if (found && res) {
1865                                 /* Something bad happened, or a hangup has been requested. */
1866                                 ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
1867                                 ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", peer->context, peer->exten, peer->priority, peer->name);
1868                         }
1869                         ast_set2_flag(peer, autoloopflag, AST_FLAG_IN_AUTOLOOP);  /* set it back the way it was */
1870                 }
1871                 if (res != AST_PBX_NO_HANGUP_PEER) {
1872                         if (!ast_check_hangup(chan))
1873                                 chan->hangupcause = peer->hangupcause;
1874                         ast_hangup(peer);
1875                 }
1876         }       
1877 out:
1878         if (moh) {
1879                 moh = 0;
1880                 ast_moh_stop(chan);
1881         } else if (sentringing) {
1882                 sentringing = 0;
1883                 ast_indicate(chan, -1);
1884         }
1885         ast_channel_early_bridge(chan, NULL);
1886         hanguptree(outgoing, NULL, 0);  /* In this case, there's no answer anywhere */
1887         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1888         senddialendevent(chan, pa.status);
1889         ast_debug(1, "Exiting with DIALSTATUS=%s.\n", pa.status);
1890         
1891         if ((ast_test_flag64(peerflags, OPT_GO_ON)) && !ast_check_hangup(chan) && (res != AST_PBX_KEEPALIVE)) {
1892                 if (calldurationlimit)
1893                         chan->whentohangup = 0;
1894                 res = 0;
1895         }
1896
1897 done:
1898         return res;
1899 }
1900
1901 static int dial_exec(struct ast_channel *chan, void *data)
1902 {
1903         struct ast_flags64 peerflags;
1904
1905         memset(&peerflags, 0, sizeof(peerflags));
1906
1907         return dial_exec_full(chan, data, &peerflags, NULL);
1908 }
1909
1910 static int retrydial_exec(struct ast_channel *chan, void *data)
1911 {
1912         char *parse;
1913         const char *context = NULL;
1914         int sleep = 0, loops = 0, res = -1;
1915         struct ast_flags64 peerflags = { 0, };
1916         AST_DECLARE_APP_ARGS(args,
1917                 AST_APP_ARG(announce);
1918                 AST_APP_ARG(sleep);
1919                 AST_APP_ARG(retries);
1920                 AST_APP_ARG(dialdata);
1921         );
1922
1923         if (ast_strlen_zero(data)) {
1924                 ast_log(LOG_WARNING, "RetryDial requires an argument!\n");
1925                 return -1;
1926         }       
1927
1928         parse = ast_strdupa(data);
1929         AST_STANDARD_APP_ARGS(args, parse);
1930
1931         if ((sleep = atoi(args.sleep))) {
1932                 sleep *= 1000;
1933         }
1934
1935         loops = atoi(args.retries);
1936
1937         if (!args.dialdata) {
1938                 ast_log(LOG_ERROR, "%s requires a 4th argument (dialdata)\n", rapp);
1939                 goto done;
1940         }
1941                 
1942         if (sleep < 1000)
1943                 sleep = 10000;
1944
1945         if (!loops)
1946                 loops = -1;     /* run forever */
1947         
1948         context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
1949
1950         res = 0;
1951         while (loops) {
1952                 int continue_exec;
1953
1954                 chan->data = "Retrying";
1955                 if (ast_test_flag(chan, AST_FLAG_MOH))
1956                         ast_moh_stop(chan);
1957
1958                 res = dial_exec_full(chan, args.dialdata, &peerflags, &continue_exec);
1959                 if (continue_exec)
1960                         break;
1961
1962                 if (res == 0) {
1963                         if (ast_test_flag64(&peerflags, OPT_DTMF_EXIT)) {
1964                                 if (!ast_strlen_zero(args.announce)) {
1965                                         if (ast_fileexists(args.announce, NULL, chan->language) > 0) {
1966                                                 if (!(res = ast_streamfile(chan, args.announce, chan->language)))                                                               
1967                                                         ast_waitstream(chan, AST_DIGIT_ANY);
1968                                         } else
1969                                                 ast_log(LOG_WARNING, "Announce file \"%s\" specified in Retrydial does not exist\n", args.announce);
1970                                 }
1971                                 if (!res && sleep) {
1972                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1973                                                 ast_moh_start(chan, NULL, NULL);
1974                                         res = ast_waitfordigit(chan, sleep);
1975                                 }
1976                         } else {
1977                                 if (!ast_strlen_zero(args.announce)) {
1978                                         if (ast_fileexists(args.announce, NULL, chan->language) > 0) {
1979                                                 if (!(res = ast_streamfile(chan, args.announce, chan->language)))
1980                                                         res = ast_waitstream(chan, "");
1981                                         } else
1982                                                 ast_log(LOG_WARNING, "Announce file \"%s\" specified in Retrydial does not exist\n", args.announce);
1983                                 }
1984                                 if (sleep) {
1985                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1986                                                 ast_moh_start(chan, NULL, NULL);
1987                                         if (!res)
1988                                                 res = ast_waitfordigit(chan, sleep);
1989                                 }
1990                         }
1991                 }
1992
1993                 if (res < 0)
1994                         break;
1995                 else if (res > 0) { /* Trying to send the call elsewhere (1 digit ext) */
1996                         if (onedigit_goto(chan, context, (char) res, 1)) {
1997                                 res = 0;
1998                                 break;
1999                         }
2000                 }
2001                 loops--;
2002         }
2003         if (loops == 0)
2004                 res = 0;
2005         else if (res == 1)
2006                 res = 0;
2007
2008         if (ast_test_flag(chan, AST_FLAG_MOH))
2009                 ast_moh_stop(chan);
2010  done:
2011         return res;
2012 }
2013
2014 static int unload_module(void)
2015 {
2016         int res;
2017         struct ast_context *con;
2018
2019         res = ast_unregister_application(app);
2020         res |= ast_unregister_application(rapp);
2021
2022         if ((con = ast_context_find("app_dial_gosub_virtual_context")))
2023         {
2024                 ast_context_remove_extension2(con, "s", 1, NULL);
2025                 ast_context_destroy(con, "app_dial"); /* leave nothing behind */
2026         }
2027         
2028         return res;
2029 }
2030
2031 static int load_module(void)
2032 {
2033         int res;
2034         struct ast_context *con;
2035
2036         con = ast_context_find("app_dial_gosub_virtual_context");
2037         if (!con)
2038                 con = ast_context_create(NULL, "app_dial_gosub_virtual_context", "app_dial");
2039         if (!con)
2040                 ast_log(LOG_ERROR, "Dial virtual context 'app_dial_gosub_virtual_context' does not exist and unable to create\n");
2041         else
2042                 ast_add_extension2(con, 1, "s", 1, NULL, NULL, "KeepAlive", ast_strdup(""), ast_free_ptr, "app_dial");
2043
2044         res = ast_register_application(app, dial_exec, synopsis, descrip);
2045         res |= ast_register_application(rapp, retrydial_exec, rsynopsis, rdescrip);
2046         
2047         return res;
2048 }
2049
2050 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialing Application");