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