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