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