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