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