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