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