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