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