Make SIP early media work more efficiently without so many reinvites
[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                                         if (option_verbose > 2)
477                                                 ast_verbose(VERBOSE_PREFIX_3 "Too many forwards from %s\n", c->name);
478                                         cause = AST_CAUSE_CONGESTION;
479                                         c = o->chan = NULL;
480                                 }
481                                 if (!c) {
482                                         ast_clear_flag(o, DIAL_STILLGOING);     
483                                         HANDLE_CAUSE(cause, in);
484                                 } else {
485                                         ast_rtp_make_compatible(c, in, single);
486                                         if (c->cid.cid_num)
487                                                 free(c->cid.cid_num);
488                                         c->cid.cid_num = NULL;
489                                         if (c->cid.cid_name)
490                                                 free(c->cid.cid_name);
491                                         c->cid.cid_name = NULL;
492
493                                         if (ast_test_flag(o, OPT_FORCECLID)) {
494                                                 c->cid.cid_num = ast_strdup(S_OR(in->macroexten, in->exten));
495                                                 ast_string_field_set(c, accountcode, winner->accountcode);
496                                                 c->cdrflags = winner->cdrflags;
497                                         } else {
498                                                 c->cid.cid_num = ast_strdup(in->cid.cid_num);
499                                                 c->cid.cid_name = ast_strdup(in->cid.cid_name);
500                                                 ast_string_field_set(c, accountcode, in->accountcode);
501                                                 c->cdrflags = in->cdrflags;
502                                         }
503
504                                         if (in->cid.cid_ani) {
505                                                 if (c->cid.cid_ani)
506                                                         free(c->cid.cid_ani);
507                                                 c->cid.cid_ani = ast_strdup(in->cid.cid_ani);
508                                         }
509                                         if (c->cid.cid_rdnis) 
510                                                 free(c->cid.cid_rdnis);
511                                         c->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
512                                         if (ast_call(c, tmpchan, 0)) {
513                                                 ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
514                                                 ast_clear_flag(o, DIAL_STILLGOING);     
515                                                 ast_hangup(c);
516                                                 c = o->chan = NULL;
517                                                 numnochan++;
518                                         } else {
519                                                 senddialevent(in, c);
520                                                 /* After calling, set callerid to extension */
521                                                 if (!ast_test_flag(peerflags, OPT_ORIGINAL_CLID)) {
522                                                         char cidname[AST_MAX_EXTENSION];
523                                                         ast_set_callerid(c, S_OR(in->macroexten, in->exten), get_cid_name(cidname, sizeof(cidname), in), NULL);
524                                                 }
525                                         }
526                                 }
527                                 /* Hangup the original channel now, in case we needed it */
528                                 ast_hangup(winner);
529                                 continue;
530                         }
531                         f = ast_read(winner);
532                         if (!f) {
533                                 in->hangupcause = c->hangupcause;
534                                 ast_hangup(c);
535                                 c = o->chan = NULL;
536                                 ast_clear_flag(o, DIAL_STILLGOING);
537                                 HANDLE_CAUSE(in->hangupcause, in);
538                                 continue;
539                         }
540                         if (f->frametype == AST_FRAME_CONTROL) {
541                                 switch(f->subclass) {
542                                 case AST_CONTROL_ANSWER:
543                                         /* This is our guy if someone answered. */
544                                         if (!peer) {
545                                                 if (option_verbose > 2)
546                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", c->name, in->name);
547                                                 peer = c;
548                                                 ast_copy_flags(peerflags, o,
549                                                                OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
550                                                                OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
551                                                                OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
552                                                                DIAL_NOFORWARDHTML);
553                                                 /* Setup early media if appropriate */
554                                                 ast_rtp_early_media(in, peer);
555                                         }
556                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
557                                         in->hangupcause = AST_CAUSE_NORMAL_CLEARING;
558                                         c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
559                                         break;
560                                 case AST_CONTROL_BUSY:
561                                         if (option_verbose > 2)
562                                                 ast_verbose(VERBOSE_PREFIX_3 "%s is busy\n", c->name);
563                                         in->hangupcause = c->hangupcause;
564                                         ast_hangup(c);
565                                         c = o->chan = NULL;
566                                         ast_clear_flag(o, DIAL_STILLGOING);     
567                                         HANDLE_CAUSE(AST_CAUSE_BUSY, in);
568                                         break;
569                                 case AST_CONTROL_CONGESTION:
570                                         if (option_verbose > 2)
571                                                 ast_verbose(VERBOSE_PREFIX_3 "%s is circuit-busy\n", c->name);
572                                         in->hangupcause = c->hangupcause;
573                                         ast_hangup(c);
574                                         c = o->chan = NULL;
575                                         ast_clear_flag(o, DIAL_STILLGOING);
576                                         HANDLE_CAUSE(AST_CAUSE_CONGESTION, in);
577                                         break;
578                                 case AST_CONTROL_RINGING:
579                                         if (option_verbose > 2)
580                                                 ast_verbose(VERBOSE_PREFIX_3 "%s is ringing\n", c->name);
581                                         /* Setup early media if appropriate */
582                                         if (single)
583                                                 ast_rtp_early_media(in, c);
584                                         if (!(*sentringing) && !ast_test_flag(outgoing, OPT_MUSICBACK)) {
585                                                 ast_indicate(in, AST_CONTROL_RINGING);
586                                                 (*sentringing)++;
587                                         }
588                                         break;
589                                 case AST_CONTROL_PROGRESS:
590                                         if (option_verbose > 2)
591                                                 ast_verbose (VERBOSE_PREFIX_3 "%s is making progress passing it to %s\n", c->name, in->name);
592                                         /* Setup early media if appropriate */
593                                         if (single)
594                                                 ast_rtp_early_media(in, c);
595                                         if (!ast_test_flag(outgoing, OPT_RINGBACK))
596                                                 ast_indicate(in, AST_CONTROL_PROGRESS);
597                                         break;
598                                 case AST_CONTROL_VIDUPDATE:
599                                         if (option_verbose > 2)
600                                                 ast_verbose (VERBOSE_PREFIX_3 "%s requested a video update, passing it to %s\n", c->name, in->name);
601                                         ast_indicate(in, AST_CONTROL_VIDUPDATE);
602                                         break;
603                                 case AST_CONTROL_PROCEEDING:
604                                         if (option_verbose > 2)
605                                                 ast_verbose (VERBOSE_PREFIX_3 "%s is proceeding passing it to %s\n", c->name, in->name);
606                                         if (single)
607                                                 ast_rtp_early_media(in, c);
608                                         if (!ast_test_flag(outgoing, OPT_RINGBACK))
609                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
610                                         break;
611                                 case AST_CONTROL_HOLD:
612                                         if (option_verbose > 2)
613                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s placed on hold\n", c->name);
614                                         ast_indicate(in, AST_CONTROL_HOLD);
615                                         break;
616                                 case AST_CONTROL_UNHOLD:
617                                         if (option_verbose > 2)
618                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s left from hold\n", c->name);
619                                         ast_indicate(in, AST_CONTROL_UNHOLD);
620                                         break;
621                                 case AST_CONTROL_OFFHOOK:
622                                 case AST_CONTROL_FLASH:
623                                         /* Ignore going off hook and flash */
624                                         break;
625                                 case -1:
626                                         if (!ast_test_flag(outgoing, OPT_RINGBACK | OPT_MUSICBACK)) {
627                                                 if (option_verbose > 2)
628                                                         ast_verbose(VERBOSE_PREFIX_3 "%s stopped sounds\n", c->name);
629                                                 ast_indicate(in, -1);
630                                                 (*sentringing) = 0;
631                                         }
632                                         break;
633                                 default:
634                                         if (option_debug)
635                                                 ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
636                                 }
637                         } else if (single) {
638                                 /* XXX are we sure the logic is correct ? or we should just switch on f->frametype ? */
639                                 if (f->frametype == AST_FRAME_VOICE && !ast_test_flag(outgoing, OPT_RINGBACK|OPT_MUSICBACK)) {
640                                         if (ast_write(in, f)) 
641                                                 ast_log(LOG_WARNING, "Unable to forward voice frame\n");
642                                 } else if (f->frametype == AST_FRAME_IMAGE && !ast_test_flag(outgoing, OPT_RINGBACK|OPT_MUSICBACK)) {
643                                         if (ast_write(in, f))
644                                                 ast_log(LOG_WARNING, "Unable to forward image\n");
645                                 } else if (f->frametype == AST_FRAME_TEXT && !ast_test_flag(outgoing, OPT_RINGBACK|OPT_MUSICBACK)) {
646                                         if (ast_write(in, f))
647                                                 ast_log(LOG_WARNING, "Unable to send text\n");
648                                 } else if (f->frametype == AST_FRAME_HTML && !ast_test_flag(outgoing, DIAL_NOFORWARDHTML)) {
649                                         if (ast_channel_sendhtml(in, f->subclass, f->data, f->datalen) == -1)
650                                                 ast_log(LOG_WARNING, "Unable to send URL\n");
651                                 }
652                         }
653                         ast_frfree(f);
654                 } /* end for */
655                 if (winner == in) {
656                         struct ast_frame *f = ast_read(in);
657 #if 0
658                         if (f && (f->frametype != AST_FRAME_VOICE))
659                                 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
660                         else if (!f || (f->frametype != AST_FRAME_VOICE))
661                                 printf("Hangup received on %s\n", in->name);
662 #endif
663                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
664                                 /* Got hung up */
665                                 *to = -1;
666                                 strcpy(status, "CANCEL");
667                                 if (f)
668                                         ast_frfree(f);
669                                 return NULL;
670                         }
671
672                         if (f && (f->frametype == AST_FRAME_DTMF)) {
673                                 if (ast_test_flag(peerflags, OPT_DTMF_EXIT)) {
674                                         const char *context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
675                                         if (onedigit_goto(in, context, (char) f->subclass, 1)) {
676                                                 if (option_verbose > 2)
677                                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
678                                                 *to=0;
679                                                 *result = f->subclass;
680                                                 strcpy(status, "CANCEL");
681                                                 ast_frfree(f);
682                                                 return NULL;
683                                         }
684                                 }
685
686                                 if (ast_test_flag(peerflags, OPT_CALLER_HANGUP) && 
687                                                   (f->subclass == '*')) { /* hmm it it not guaranteed to be '*' anymore. */
688                                         if (option_verbose > 2)
689                                                 ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
690                                         *to=0;
691                                         strcpy(status, "CANCEL");
692                                         ast_frfree(f);
693                                         return NULL;
694                                 }
695                         }
696
697                         /* Forward HTML stuff */
698                         if (single && f && (f->frametype == AST_FRAME_HTML) && !ast_test_flag(outgoing, DIAL_NOFORWARDHTML)) 
699                                 if(ast_channel_sendhtml(outgoing->chan, f->subclass, f->data, f->datalen) == -1)
700                                         ast_log(LOG_WARNING, "Unable to send URL\n");
701                         
702
703                         if (single && ((f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_DTMF)))  {
704                                 if (ast_write(outgoing->chan, f))
705                                         ast_log(LOG_WARNING, "Unable to forward voice\n");
706                         }
707                         if (single && (f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_VIDUPDATE)) {
708                                 if (option_verbose > 2)
709                                         ast_verbose(VERBOSE_PREFIX_3 "%s requested a video update, passing it to %s\n", in->name,outgoing->chan->name);
710                                 ast_indicate(outgoing->chan, AST_CONTROL_VIDUPDATE);
711                         }
712                         ast_frfree(f);
713                 }
714                 if (!*to && (option_verbose > 2))
715                         ast_verbose(VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
716         }
717
718         return peer;
719 }
720
721 static void replace_macro_delimiter(char *s)
722 {
723         for (; *s; s++)
724                 if (*s == '^')
725                         *s = '|';
726 }
727
728
729 /* returns true if there is a valid privacy reply */
730 static int valid_priv_reply(struct ast_flags *opts, int res)
731 {
732         if (res < '1')
733                 return 0;
734         if (ast_test_flag(opts, OPT_PRIVACY) && res <= '5')
735                 return 1;
736         if (ast_test_flag(opts, OPT_SCREENING) && res <= '4')
737                 return 1;
738         return 0;
739 }
740
741 static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags *peerflags)
742 {
743         int res = -1;
744         struct localuser *u;
745         char *rest, *cur;
746         struct dial_localuser *outgoing = NULL;
747         struct ast_channel *peer;
748         int to;
749         int numbusy = 0;
750         int numcongestion = 0;
751         int numnochan = 0;
752         int cause;
753         char numsubst[AST_MAX_EXTENSION];
754         char cidname[AST_MAX_EXTENSION];
755         int privdb_val = 0;
756         unsigned int calldurationlimit = 0;
757         long timelimit = 0;
758         long play_warning = 0;
759         long warning_freq = 0;
760         const char *warning_sound = NULL;
761         const char *end_sound = NULL;
762         const char *start_sound = NULL;
763         char *dtmfcalled = NULL, *dtmfcalling = NULL;
764         char status[256];
765         int play_to_caller = 0, play_to_callee = 0;
766         int sentringing = 0, moh = 0;
767         const char *outbound_group = NULL;
768         int result = 0;
769         time_t start_time;
770         char privintro[1024];
771         char privcid[256];
772         char *parse;
773         int opermode = 0;
774         AST_DECLARE_APP_ARGS(args,
775                              AST_APP_ARG(peers);
776                              AST_APP_ARG(timeout);
777                              AST_APP_ARG(options);
778                              AST_APP_ARG(url);
779         );
780         struct ast_flags opts = { 0, };
781         char *opt_args[OPT_ARG_ARRAY_SIZE];
782
783         if (ast_strlen_zero(data)) {
784                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
785                 return -1;
786         }
787
788         LOCAL_USER_ADD(u);
789
790         if (!(parse = ast_strdupa(data)))
791                 goto done;
792
793         AST_STANDARD_APP_ARGS(args, parse);
794
795         if (!ast_strlen_zero(args.options) &&
796                         ast_app_parse_options(dial_exec_options, &opts, opt_args, args.options))
797                 goto done;
798
799         if (ast_strlen_zero(args.peers)) {
800                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
801                 goto done;
802         }
803
804         if (ast_test_flag(&opts, OPT_OPERMODE)) {
805                 if (ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]))
806                         opermode = 1;
807                 else opermode = atoi(opt_args[OPT_ARG_OPERMODE]);
808                 if (option_verbose > 2)
809                         ast_verbose(VERBOSE_PREFIX_3 "Setting operator services mode to %d.\n", opermode);
810         }
811
812         if (ast_test_flag(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
813                 calldurationlimit = atoi(opt_args[OPT_ARG_DURATION_STOP]);
814                 if (!calldurationlimit) {
815                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
816                         goto done;
817                 }
818                 if (option_verbose > 2)
819                         ast_verbose(VERBOSE_PREFIX_3 "Setting call duration limit to %d seconds.\n", calldurationlimit);
820         }
821
822         if (ast_test_flag(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
823                 dtmfcalling = opt_args[OPT_ARG_SENDDTMF];
824                 dtmfcalled = strsep(&dtmfcalling, ":");
825         }
826
827         if (ast_test_flag(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
828                 char *limit_str, *warning_str, *warnfreq_str;
829                 const char *var;
830
831                 warnfreq_str = opt_args[OPT_ARG_DURATION_LIMIT];
832                 limit_str = strsep(&warnfreq_str, ":");
833                 warning_str = strsep(&warnfreq_str, ":");
834
835                 timelimit = atol(limit_str);
836                 if (warning_str)
837                         play_warning = atol(warning_str);
838                 if (warnfreq_str)
839                         warning_freq = atol(warnfreq_str);
840
841                 if (!timelimit) {
842                         ast_log(LOG_WARNING, "Dial does not accept L(%s), hanging up.\n", limit_str);
843                         goto done;
844                 } else if (play_warning > timelimit) {
845                         /* If the first warning is requested _after_ the entire call would end,
846                            and no warning frequency is requested, then turn off the warning. If
847                            a warning frequency is requested, reduce the 'first warning' time by
848                            that frequency until it falls within the call's total time limit.
849                         */
850
851                         if (!warning_freq) {
852                                 play_warning = 0;
853                         } else {
854                                 /* XXX fix this!! */
855                                 while (play_warning > timelimit)
856                                         play_warning -= warning_freq;
857                                 if (play_warning < 1)
858                                         play_warning = warning_freq = 0;
859                         }
860                 }
861
862                 var = pbx_builtin_getvar_helper(chan,"LIMIT_PLAYAUDIO_CALLER");
863                 play_to_caller = var ? ast_true(var) : 1;
864                 
865                 var = pbx_builtin_getvar_helper(chan,"LIMIT_PLAYAUDIO_CALLEE");
866                 play_to_callee = var ? ast_true(var) : 0;
867                 
868                 if (!play_to_caller && !play_to_callee)
869                         play_to_caller = 1;
870                 
871                 var = pbx_builtin_getvar_helper(chan,"LIMIT_WARNING_FILE");
872                 warning_sound = S_OR(var, "timeleft");
873                 
874                 var = pbx_builtin_getvar_helper(chan,"LIMIT_TIMEOUT_FILE");
875                 end_sound = S_OR(var, NULL);    /* XXX not much of a point in doing this! */
876                 
877                 var = pbx_builtin_getvar_helper(chan,"LIMIT_CONNECT_FILE");
878                 start_sound = S_OR(var, NULL);  /* XXX not much of a point in doing this! */
879
880                 /* undo effect of S(x) in case they are both used */
881                 calldurationlimit = 0;
882                 /* more efficient to do it like S(x) does since no advanced opts */
883                 if (!play_warning && !start_sound && !end_sound && timelimit) {
884                         calldurationlimit = timelimit / 1000;
885                         if (option_verbose > 2)
886                                 ast_verbose(VERBOSE_PREFIX_3 "Setting call duration limit to %d seconds.\n", calldurationlimit);
887                         timelimit = play_to_caller = play_to_callee = play_warning = warning_freq = 0;
888                 } else if (option_verbose > 2) {
889                         ast_verbose(VERBOSE_PREFIX_3 "Limit Data for this call:\n");
890                         ast_verbose(VERBOSE_PREFIX_4 "timelimit      = %ld\n", timelimit);
891                         ast_verbose(VERBOSE_PREFIX_4 "play_warning   = %ld\n", play_warning);
892                         ast_verbose(VERBOSE_PREFIX_4 "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
893                         ast_verbose(VERBOSE_PREFIX_4 "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
894                         ast_verbose(VERBOSE_PREFIX_4 "warning_freq   = %ld\n", warning_freq);
895                         ast_verbose(VERBOSE_PREFIX_4 "start_sound    = %s\n", start_sound);
896                         ast_verbose(VERBOSE_PREFIX_4 "warning_sound  = %s\n", warning_sound);
897                         ast_verbose(VERBOSE_PREFIX_4 "end_sound      = %s\n", end_sound);
898                 }
899         }
900
901         if (ast_test_flag(&opts, OPT_RESETCDR) && chan->cdr)
902                 ast_cdr_reset(chan->cdr, NULL);
903         if (ast_test_flag(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
904                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(chan->exten);
905         if (ast_test_flag(&opts, OPT_PRIVACY) || ast_test_flag(&opts, OPT_SCREENING)) {
906                 char callerid[60];
907                 char *l = chan->cid.cid_num;    /* XXX watch out, we are overwriting it */
908                 if (!ast_strlen_zero(l)) {
909                         ast_shrink_phone_number(l);
910                         if( ast_test_flag(&opts, OPT_PRIVACY) ) {
911                                 if (option_verbose > 2)
912                                         ast_verbose(VERBOSE_PREFIX_3  "Privacy DB is '%s', clid is '%s'\n",
913                                                      opt_args[OPT_ARG_PRIVACY], l);
914                                 privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
915                         }
916                         else {
917                                 if (option_verbose > 2)
918                                         ast_verbose(VERBOSE_PREFIX_3  "Privacy Screening, clid is '%s'\n", l);
919                                 privdb_val = AST_PRIVACY_UNKNOWN;
920                         }
921                 } else {
922                         char *tnam, *tn2;
923
924                         tnam = ast_strdupa(chan->name);
925                         /* clean the channel name so slashes don't try to end up in disk file name */
926                         for(tn2 = tnam; *tn2; tn2++) {
927                                 if( *tn2=='/')
928                                         *tn2 = '=';  /* any other chars to be afraid of? */
929                         }
930                         if (option_verbose > 2)
931                                 ast_verbose(VERBOSE_PREFIX_3  "Privacy-- callerid is empty\n");
932
933                         snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
934                         l = callerid;
935                         privdb_val = AST_PRIVACY_UNKNOWN;
936                 }
937                 
938                 ast_copy_string(privcid,l,sizeof(privcid));
939
940                 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 */  
941                         if (option_verbose > 2)
942                                 ast_verbose( VERBOSE_PREFIX_3  "CallerID set (%s); N option set; Screening should be off\n", privcid);
943                         privdb_val = AST_PRIVACY_ALLOW;
944                 }
945                 else if(ast_test_flag(&opts, OPT_SCREEN_NOCLID) && strncmp(privcid,"NOCALLERID",10) == 0 ) {
946                         if (option_verbose > 2)
947                                 ast_verbose( VERBOSE_PREFIX_3  "CallerID blank; N option set; Screening should happen; dbval is %d\n", privdb_val);
948                 }
949                 
950                 if(privdb_val == AST_PRIVACY_DENY ) {
951                         if (option_verbose > 2)
952                                 ast_verbose( VERBOSE_PREFIX_3  "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
953                         res=0;
954                         goto out;
955                 }
956                 else if(privdb_val == AST_PRIVACY_KILL ) {
957                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 201);
958                         res = 0;
959                         goto out; /* Is this right? */
960                 }
961                 else if(privdb_val == AST_PRIVACY_TORTURE ) {
962                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 301);
963                         res = 0;
964                         goto out; /* is this right??? */
965
966                 }
967                 else if(privdb_val == AST_PRIVACY_UNKNOWN ) {
968                         /* Get the user's intro, store it in priv-callerintros/$CID, 
969                            unless it is already there-- this should be done before the 
970                            call is actually dialed  */
971
972                         /* make sure the priv-callerintros dir exists? */
973
974                         snprintf(privintro,sizeof(privintro), "priv-callerintros/%s", privcid);
975                         if( ast_fileexists(privintro,NULL,NULL ) > 0 && strncmp(privcid,"NOCALLERID",10) != 0) {
976                                 /* the DELUX version of this code would allow this caller the
977                                    option to hear and retape their previously recorded intro.
978                                 */
979                         }
980                         else {
981                                 int duration; /* for feedback from play_and_wait */
982                                 /* the file doesn't exist yet. Let the caller submit his
983                                    vocal intro for posterity */
984                                 /* priv-recordintro script:
985
986                                    "At the tone, please say your name:"
987
988                                 */
989                                 ast_play_and_record(chan, "priv-recordintro", privintro, 4, "gsm", &duration, 128, 2000, 0);  /* NOTE: I've reduced the total time to 4 sec */
990                                                                                 /* don't think we'll need a lock removed, we took care of
991                                                                                    conflicts by naming the privintro file */
992                         }
993                 }
994         }
995
996         /* If a channel group has been specified, get it for use when we create peer channels */
997         outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP");
998
999         ast_copy_flags(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID | OPT_CALLER_HANGUP);
1000         /* loop through the list of dial destinations */
1001         rest = args.peers;
1002         while ((cur = strsep(&rest, "&")) ) {
1003                 struct dial_localuser *tmp;
1004                 /* Get a technology/[device:]number pair */
1005                 char *number = cur;
1006                 char *tech = strsep(&number, "/");
1007                 if (!number) {
1008                         ast_log(LOG_WARNING, "Dial argument takes format (technology/[device:]number1)\n");
1009                         goto out;
1010                 }
1011                 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1012                         goto out;
1013                 if (opts.flags) {
1014                         ast_copy_flags(tmp, &opts,
1015                                        OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1016                                        OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1017                                        OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1018                                        OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID);
1019                         ast_set2_flag(tmp, args.url, DIAL_NOFORWARDHTML);       
1020                 }
1021                 ast_copy_string(numsubst, number, sizeof(numsubst));
1022                 /* Request the peer */
1023                 tmp->chan = ast_request(tech, chan->nativeformats, numsubst, &cause);
1024                 if (!tmp->chan) {
1025                         /* If we can't, just go on to the next call */
1026                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n", tech, cause, ast_cause2str(cause));
1027                         HANDLE_CAUSE(cause, chan);
1028                         if (!rest)      /* we are on the last destination */
1029                                 chan->hangupcause = cause;
1030                         continue;
1031                 }
1032                 pbx_builtin_setvar_helper(tmp->chan, "DIALEDPEERNUMBER", numsubst);
1033                 if (!ast_strlen_zero(tmp->chan->call_forward)) {
1034                         char tmpchan[256];
1035                         char *stuff;
1036                         char *tech;
1037                         ast_copy_string(tmpchan, tmp->chan->call_forward, sizeof(tmpchan));
1038                         if ((stuff = strchr(tmpchan, '/'))) {
1039                                 *stuff++ = '\0';
1040                                 tech = tmpchan;
1041                         } else {
1042                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", tmp->chan->call_forward, tmp->chan->context);
1043                                 stuff = tmpchan;
1044                                 tech = "Local";
1045                         }
1046                         tmp->forwards++;
1047                         if (tmp->forwards < AST_MAX_FORWARDS) {
1048                                 if (option_verbose > 2)
1049                                         ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", chan->name, tech, stuff, tmp->chan->name);
1050                                 ast_hangup(tmp->chan);
1051                                 /* Setup parameters */
1052                                 tmp->chan = ast_request(tech, chan->nativeformats, stuff, &cause);
1053                                 if (!tmp->chan)
1054                                         ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s' (cause = %d)\n", tech, stuff, cause);
1055                         } else {
1056                                 if (option_verbose > 2)
1057                                         ast_verbose(VERBOSE_PREFIX_3 "Too many forwards from %s\n", tmp->chan->name);
1058                                 ast_hangup(tmp->chan);
1059                                 tmp->chan = NULL;
1060                                 cause = AST_CAUSE_CONGESTION;
1061                         }
1062                         if (!tmp->chan) {
1063                                 HANDLE_CAUSE(cause, chan);
1064                                 continue;
1065                         }
1066                 }
1067
1068                 /* Setup outgoing SDP to match incoming one */
1069                 ast_rtp_make_compatible(tmp->chan, chan, !outgoing && !rest);
1070                 
1071                 /* Inherit specially named variables from parent channel */
1072                 ast_channel_inherit_variables(chan, tmp->chan);
1073
1074                 tmp->chan->appl = "AppDial";
1075                 tmp->chan->data = "(Outgoing Line)";
1076                 tmp->chan->whentohangup = 0;
1077
1078                 if (tmp->chan->cid.cid_num)
1079                         free(tmp->chan->cid.cid_num);
1080                 tmp->chan->cid.cid_num = ast_strdup(chan->cid.cid_num);
1081
1082                 if (tmp->chan->cid.cid_name)
1083                         free(tmp->chan->cid.cid_name);
1084                 tmp->chan->cid.cid_name = ast_strdup(chan->cid.cid_name);
1085
1086                 if (tmp->chan->cid.cid_ani)
1087                         free(tmp->chan->cid.cid_ani);
1088                 tmp->chan->cid.cid_ani = ast_strdup(chan->cid.cid_ani);
1089                 
1090                 /* Copy language from incoming to outgoing */
1091                 ast_string_field_set(tmp->chan, language, chan->language);
1092                 ast_string_field_set(tmp->chan, accountcode, chan->accountcode);
1093                 tmp->chan->cdrflags = chan->cdrflags;
1094                 if (ast_strlen_zero(tmp->chan->musicclass))
1095                         ast_string_field_set(tmp->chan, musicclass, chan->musicclass);
1096                 /* XXX don't we free previous values ? */
1097                 tmp->chan->cid.cid_rdnis = ast_strdup(chan->cid.cid_rdnis);
1098                 /* Pass callingpres setting */
1099                 tmp->chan->cid.cid_pres = chan->cid.cid_pres;
1100                 /* Pass type of number */
1101                 tmp->chan->cid.cid_ton = chan->cid.cid_ton;
1102                 /* Pass type of tns */
1103                 tmp->chan->cid.cid_tns = chan->cid.cid_tns;
1104                 /* Presense of ADSI CPE on outgoing channel follows ours */
1105                 tmp->chan->adsicpe = chan->adsicpe;
1106                 /* Pass the transfer capability */
1107                 tmp->chan->transfercapability = chan->transfercapability;
1108
1109                 /* If we have an outbound group, set this peer channel to it */
1110                 if (outbound_group)
1111                         ast_app_group_set_channel(tmp->chan, outbound_group);
1112
1113                 /* Place the call, but don't wait on the answer */
1114                 res = ast_call(tmp->chan, numsubst, 0);
1115
1116                 /* Save the info in cdr's that we called them */
1117                 if (chan->cdr)
1118                         ast_cdr_setdestchan(chan->cdr, tmp->chan->name);
1119
1120                 /* check the results of ast_call */
1121                 if (res) {
1122                         /* Again, keep going even if there's an error */
1123                         if (option_debug)
1124                                 ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
1125                         else if (option_verbose > 2)
1126                                 ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", numsubst);
1127                         ast_hangup(tmp->chan);
1128                         tmp->chan = NULL;
1129                         continue;
1130                 } else {
1131                         senddialevent(chan, tmp->chan);
1132                         if (option_verbose > 2)
1133                                 ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", numsubst);
1134                         if (!ast_test_flag(peerflags, OPT_ORIGINAL_CLID))
1135                                 ast_set_callerid(tmp->chan, S_OR(chan->macroexten, chan->exten), get_cid_name(cidname, sizeof(cidname), chan), NULL);
1136                 }
1137                 /* Put them in the list of outgoing thingies...  We're ready now. 
1138                    XXX If we're forcibly removed, these outgoing calls won't get
1139                    hung up XXX */
1140                 ast_set_flag(tmp, DIAL_STILLGOING);     
1141                 tmp->next = outgoing;
1142                 outgoing = tmp;
1143                 /* If this line is up, don't try anybody else */
1144                 if (outgoing->chan->_state == AST_STATE_UP)
1145                         break;
1146         }
1147         
1148         if (ast_strlen_zero(args.timeout)) {
1149                 to = -1;
1150         } else {
1151                 to = atoi(args.timeout);
1152                 if (to > 0)
1153                         to *= 1000;
1154                 else
1155                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'\n", args.timeout);
1156         }
1157
1158         if (!outgoing) {
1159                 strcpy(status, "CHANUNAVAIL");
1160         } else {
1161                 /* Our status will at least be NOANSWER */
1162                 strcpy(status, "NOANSWER");
1163                 if (ast_test_flag(outgoing, OPT_MUSICBACK)) {
1164                         moh=1;
1165                         ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK]);
1166                 } else if (ast_test_flag(outgoing, OPT_RINGBACK)) {
1167                         ast_indicate(chan, AST_CONTROL_RINGING);
1168                         sentringing++;
1169                 }
1170         }
1171
1172         time(&start_time);
1173         peer = wait_for_answer(chan, outgoing, &to, peerflags, &sentringing, status, sizeof(status), numbusy, numnochan, numcongestion, ast_test_flag(&opts, OPT_PRIORITY_JUMP), &result);
1174         
1175         if (!peer) {
1176                 if (result) {
1177                         res = result;
1178                 } else if (to) { /* Musta gotten hung up */
1179                         res = -1;
1180                 } else { /* Nobody answered, next please? */
1181                         res = 0;
1182                 }
1183                 /* almost done, although the 'else' block is 400 lines */
1184         } else {
1185                 const char *number;
1186                 time_t end_time, answer_time = time(NULL);
1187
1188                 strcpy(status, "ANSWER");
1189                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1190                    we will always return with -1 so that it is hung up properly after the 
1191                    conversation.  */
1192                 hanguptree(outgoing, peer);
1193                 outgoing = NULL;
1194                 /* If appropriate, log that we have a destination channel */
1195                 if (chan->cdr)
1196                         ast_cdr_setdestchan(chan->cdr, peer->name);
1197                 if (peer->name)
1198                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
1199
1200                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER");
1201                 if (!number)
1202                         number = numsubst;
1203                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
1204                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
1205                         if (option_debug)
1206                                 ast_log(LOG_DEBUG, "app_dial: sendurl=%s.\n", args.url);
1207                         ast_channel_sendurl( peer, args.url );
1208                 }
1209                 if ( (ast_test_flag(&opts, OPT_PRIVACY) || ast_test_flag(&opts, OPT_SCREENING)) && privdb_val == AST_PRIVACY_UNKNOWN) {
1210                         int res2;
1211                         int loopcount = 0;
1212
1213                         /* Get the user's intro, store it in priv-callerintros/$CID, 
1214                            unless it is already there-- this should be done before the 
1215                            call is actually dialed  */
1216
1217                         /* all ring indications and moh for the caller has been halted as soon as the 
1218                            target extension was picked up. We are going to have to kill some
1219                            time and make the caller believe the peer hasn't picked up yet */
1220
1221                         if (ast_test_flag(&opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1222                                 ast_indicate(chan, -1);
1223                                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK]);
1224                         } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1225                                 ast_indicate(chan, AST_CONTROL_RINGING);
1226                                 sentringing++;
1227                         }
1228
1229                         /* Start autoservice on the other chan ?? */
1230                         res2 = ast_autoservice_start(chan);
1231                         /* Now Stream the File */
1232                         for (loopcount = 0; loopcount < 3; loopcount++) {
1233                                 if (res2 && loopcount == 0)     /* error in ast_autoservice_start() */
1234                                         break;
1235                                 if (!res2)      /* on timeout, play the message again */
1236                                         res2 = ast_play_and_wait(peer,"priv-callpending");
1237                                 if (!valid_priv_reply(&opts, res2))
1238                                         res2 = 0;
1239                                 
1240                                 /* priv-callpending script: 
1241                                    "I have a caller waiting, who introduces themselves as:"
1242                                 */
1243                                 if (!res2)
1244                                         res2 = ast_play_and_wait(peer,privintro);
1245                                 if (!valid_priv_reply(&opts, res2))
1246                                         res2 = 0;
1247                                 /* now get input from the called party, as to their choice */
1248                                 if( !res2 ) {
1249                                         /* XXX can we have both, or they are mutually exclusive ? */
1250                                         if( ast_test_flag(&opts, OPT_PRIVACY) )
1251                                                 res2 = ast_play_and_wait(peer,"priv-callee-options");
1252                                         if( ast_test_flag(&opts, OPT_SCREENING) )
1253                                                 res2 = ast_play_and_wait(peer,"screen-callee-options");
1254                                 }
1255                                 /*! \page DialPrivacy Dial Privacy scripts
1256                                 \par priv-callee-options script:
1257                                         "Dial 1 if you wish this caller to reach you directly in the future,
1258                                                 and immediately connect to their incoming call
1259                                          Dial 2 if you wish to send this caller to voicemail now and 
1260                                                 forevermore.
1261                                          Dial 3 to send this caller to the torture menus, now and forevermore.
1262                                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1263                                          Dial 5 to allow this caller to come straight thru to you in the future,
1264                                                 but right now, just this once, send them to voicemail."
1265                                 \par screen-callee-options script:
1266                                         "Dial 1 if you wish to immediately connect to the incoming call
1267                                          Dial 2 if you wish to send this caller to voicemail.
1268                                          Dial 3 to send this caller to the torture menus.
1269                                          Dial 4 to send this caller to a simple "go away" menu.
1270                                 */
1271                                 if (valid_priv_reply(&opts, res2))
1272                                         break;
1273                                 /* invalid option */
1274                                 res2 = ast_play_and_wait(peer, "vm-sorry");
1275                         }
1276
1277                         if (ast_test_flag(&opts, OPT_MUSICBACK)) {
1278                                 ast_moh_stop(chan);
1279                         } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1280                                 ast_indicate(chan, -1);
1281                                 sentringing=0;
1282                         }
1283                         ast_autoservice_stop(chan);
1284
1285                         switch (res2) {
1286                         case '1':
1287                                 if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1288                                         if (option_verbose > 2)
1289                                                 ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to ALLOW\n",
1290                                                              opt_args[OPT_ARG_PRIVACY], privcid);
1291                                         ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_ALLOW);
1292                                 }
1293                                 break;
1294                         case '2':
1295                                 if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1296                                         if (option_verbose > 2)
1297                                                 ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to DENY\n",
1298                                                              opt_args[OPT_ARG_PRIVACY], privcid);
1299                                         ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_DENY);
1300                                 }
1301                                 ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1302                                 res=0;
1303                                 goto out;
1304                         case '3':
1305                                 if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1306                                         if (option_verbose > 2)
1307                                                 ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to TORTURE\n",
1308                                                              opt_args[OPT_ARG_PRIVACY], privcid);
1309                                         ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_TORTURE);
1310                                 }
1311                                 ast_copy_string(status, "TORTURE", sizeof(status));
1312                                 
1313                                 res = 0;
1314                                 ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1315                                 goto out; /* Is this right? */
1316                         case '4':
1317                                 if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1318                                         if (option_verbose > 2)
1319                                                 ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to KILL\n",
1320                                                              opt_args[OPT_ARG_PRIVACY], privcid);
1321                                         ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_KILL);
1322                                 }
1323
1324                                 ast_copy_string(status, "DONTCALL", sizeof(status));
1325                                 res = 0;
1326                                 ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1327                                 goto out; /* Is this right? */
1328                         case '5':
1329                                 if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1330                                         if (option_verbose > 2)
1331                                                 ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to ALLOW\n",
1332                                                              opt_args[OPT_ARG_PRIVACY], privcid);
1333                                         ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_ALLOW);
1334                                         ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1335                                         res=0;
1336                                         goto out;
1337                                 } /* if not privacy, then 5 is the same as "default" case */
1338                         default:        /* bad input or -1 if failure to start autoservice */
1339                                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1340                                 /* well, there seems basically two choices. Just patch the caller thru immediately,
1341                                           or,... put 'em thru to voicemail. */
1342                                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1343                                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1344                                 ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1345                                 res=0;
1346                                 goto out;
1347                         }
1348
1349                         /* XXX once again, this path is only taken in the case '1', so it could be
1350                          * moved there, although i am not really sure that this is correct - maybe
1351                          * the check applies to other cases as well.
1352                          */
1353                         /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll 
1354                            just clog things up, and it's not useful information, not being tied to a CID */
1355                         if( strncmp(privcid,"NOCALLERID",10) == 0 || ast_test_flag(&opts, OPT_SCREEN_NOINTRO) ) {
1356                                 ast_filedelete(privintro, NULL);
1357                                 if( ast_fileexists(privintro, NULL, NULL ) > 0 )
1358                                         ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", privintro);
1359                                 else if (option_verbose > 2)
1360                                         ast_verbose(VERBOSE_PREFIX_3 "Successfully deleted %s intro file\n", privintro);
1361                         }
1362                 }
1363                 if (!ast_test_flag(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
1364                         res = 0;
1365                 } else {
1366                         int digit = 0;
1367                         /* Start autoservice on the other chan */
1368                         res = ast_autoservice_start(chan);
1369                         /* Now Stream the File */
1370                         if (!res)
1371                                 res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
1372                         if (!res) {
1373                                 digit = ast_waitstream(peer, AST_DIGIT_ANY); 
1374                         }
1375                         /* Ok, done. stop autoservice */
1376                         res = ast_autoservice_stop(chan);
1377                         if (digit > 0 && !res)
1378                                 res = ast_senddigit(chan, digit); 
1379                         else
1380                                 res = digit;
1381
1382                 }
1383
1384                 if (chan && peer && ast_test_flag(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
1385                         replace_macro_delimiter(opt_args[OPT_ARG_GOTO]);
1386                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
1387                         ast_parseable_goto(peer, opt_args[OPT_ARG_GOTO]);
1388                         peer->priority++;
1389                         ast_pbx_start(peer);
1390                         hanguptree(outgoing, NULL);
1391                         res = 0;
1392                         goto done;
1393                 }
1394
1395                 if (ast_test_flag(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
1396                         struct ast_app *theapp;
1397                         const char *macro_result;
1398
1399                         res = ast_autoservice_start(chan);
1400                         if (res) {
1401                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
1402                                 res = -1;
1403                         }
1404
1405                         theapp = pbx_findapp("Macro");
1406
1407                         if (theapp && !res) {   /* XXX why check res here ? */
1408                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_MACRO]);
1409                                 res = pbx_exec(peer, theapp, opt_args[OPT_ARG_CALLEE_MACRO]);
1410                                 ast_log(LOG_DEBUG, "Macro exited with status %d\n", res);
1411                                 res = 0;
1412                         } else {
1413                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
1414                                 res = -1;
1415                         }
1416
1417                         if (ast_autoservice_stop(chan) < 0) {
1418                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
1419                                 res = -1;
1420                         }
1421
1422                         if (!res && (macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
1423                                         char *macro_transfer_dest;
1424
1425                                         if (!strcasecmp(macro_result, "BUSY")) {
1426                                                 ast_copy_string(status, macro_result, sizeof(status));
1427                                                 if (ast_opt_priority_jumping || ast_test_flag(&opts, OPT_PRIORITY_JUMP)) {
1428                                                         if (!ast_goto_if_exists(chan, NULL, NULL, chan->priority + 101)) {
1429                                                                 ast_set_flag(peerflags, OPT_GO_ON);
1430                                                         }
1431                                                 } else
1432                                                         ast_set_flag(peerflags, OPT_GO_ON);
1433                                                 res = -1;
1434                                         } else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
1435                                                 ast_copy_string(status, macro_result, sizeof(status));
1436                                                 ast_set_flag(peerflags, OPT_GO_ON);     
1437                                                 res = -1;
1438                                         } else if (!strcasecmp(macro_result, "CONTINUE")) {
1439                                                 /* hangup peer and keep chan alive assuming the macro has changed 
1440                                                    the context / exten / priority or perhaps 
1441                                                    the next priority in the current exten is desired.
1442                                                 */
1443                                                 ast_set_flag(peerflags, OPT_GO_ON);     
1444                                                 res = -1;
1445                                         } else if (!strcasecmp(macro_result, "ABORT")) {
1446                                                 /* Hangup both ends unless the caller has the g flag */
1447                                                 res = -1;
1448                                         } else if (!strncasecmp(macro_result, "GOTO:", 5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
1449                                                 res = -1;
1450                                                 /* perform a transfer to a new extension */
1451                                                 if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
1452                                                         replace_macro_delimiter(macro_transfer_dest);
1453                                                         if (!ast_parseable_goto(chan, macro_transfer_dest))
1454                                                                 ast_set_flag(peerflags, OPT_GO_ON);
1455
1456                                                 }
1457                                         }
1458                         }
1459                 }
1460
1461                 if (!res) {
1462                         if (calldurationlimit > 0) {
1463                                 chan->whentohangup = time(NULL) + calldurationlimit;
1464                         }
1465                         if (!ast_strlen_zero(dtmfcalled)) { 
1466                                 if (option_verbose > 2)
1467                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the called party.\n", dtmfcalled);
1468                                 res = ast_dtmf_stream(peer,chan,dtmfcalled,250);
1469                         }
1470                         if (!ast_strlen_zero(dtmfcalling)) {
1471                                 if (option_verbose > 2)
1472                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the calling party.\n", dtmfcalling);
1473                                 res = ast_dtmf_stream(chan,peer,dtmfcalling,250);
1474                         }
1475                 }
1476                 
1477                 if (!res) {
1478                         struct ast_bridge_config config;
1479
1480                         memset(&config,0,sizeof(struct ast_bridge_config));
1481                         if (play_to_caller)
1482                                 ast_set_flag(&(config.features_caller), AST_FEATURE_PLAY_WARNING);
1483                         if (play_to_callee)
1484                                 ast_set_flag(&(config.features_callee), AST_FEATURE_PLAY_WARNING);
1485                         if (ast_test_flag(peerflags, OPT_CALLEE_TRANSFER))
1486                                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1487                         if (ast_test_flag(peerflags, OPT_CALLER_TRANSFER))
1488                                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
1489                         if (ast_test_flag(peerflags, OPT_CALLEE_HANGUP))
1490                                 ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
1491                         if (ast_test_flag(peerflags, OPT_CALLER_HANGUP))
1492                                 ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
1493                         if (ast_test_flag(peerflags, OPT_CALLEE_MONITOR))
1494                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1495                         if (ast_test_flag(peerflags, OPT_CALLER_MONITOR)) 
1496                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1497
1498                         config.timelimit = timelimit;
1499                         config.play_warning = play_warning;
1500                         config.warning_freq = warning_freq;
1501                         config.warning_sound = warning_sound;
1502                         config.end_sound = end_sound;
1503                         config.start_sound = start_sound;
1504                         if (moh) {
1505                                 moh = 0;
1506                                 ast_moh_stop(chan);
1507                         } else if (sentringing) {
1508                                 sentringing = 0;
1509                                 ast_indicate(chan, -1);
1510                         }
1511                         /* Be sure no generators are left on it */
1512                         ast_deactivate_generator(chan);
1513                         /* Make sure channels are compatible */
1514                         res = ast_channel_make_compatible(chan, peer);
1515                         if (res < 0) {
1516                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
1517                                 ast_hangup(peer);
1518                                 res = -1;
1519                                 goto done;
1520                         }
1521                         if (opermode && (!strncmp(chan->name,"Zap",3)) &&
1522                                 (!strncmp(peer->name,"Zap",3)))
1523                         {
1524                                 struct oprmode oprmode;
1525
1526                                 oprmode.peer = peer;
1527                                 oprmode.mode = opermode;
1528
1529                                 ast_channel_setoption(chan,
1530                                         AST_OPTION_OPRMODE,&oprmode,sizeof(struct oprmode),0);
1531                         }
1532                         res = ast_bridge_call(chan,peer,&config);
1533                         time(&end_time);
1534                         {
1535                                 char toast[80];
1536                                 snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1537                                 pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", toast);
1538                         }
1539                 } else {
1540                         time(&end_time);
1541                         res = -1;
1542                 }
1543                 {
1544                         char toast[80];
1545                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1546                         pbx_builtin_setvar_helper(chan, "DIALEDTIME", toast);
1547                 }
1548                 
1549                 if (res != AST_PBX_NO_HANGUP_PEER) {
1550                         if (!chan->_softhangup)
1551                                 chan->hangupcause = peer->hangupcause;
1552                         ast_hangup(peer);
1553                 }
1554         }       
1555 out:
1556         if (moh) {
1557                 moh = 0;
1558                 ast_moh_stop(chan);
1559         } else if (sentringing) {
1560                 sentringing = 0;
1561                 ast_indicate(chan, -1);
1562         }
1563         ast_rtp_early_media(chan, NULL);
1564         hanguptree(outgoing, NULL);
1565         pbx_builtin_setvar_helper(chan, "DIALSTATUS", status);
1566         if (option_debug)
1567                 ast_log(LOG_DEBUG, "Exiting with DIALSTATUS=%s.\n", status);
1568         
1569         if ((ast_test_flag(peerflags, OPT_GO_ON)) && (!chan->_softhangup) && (res != AST_PBX_KEEPALIVE))
1570                 res = 0;
1571
1572 done:
1573         LOCAL_USER_REMOVE(u);    
1574         return res;
1575 }
1576
1577 static int dial_exec(struct ast_channel *chan, void *data)
1578 {
1579         struct ast_flags peerflags;
1580         memset(&peerflags, 0, sizeof(peerflags));
1581         return dial_exec_full(chan, data, &peerflags);
1582 }
1583
1584 static int retrydial_exec(struct ast_channel *chan, void *data)
1585 {
1586         char *announce = NULL, *dialdata = NULL;
1587         const char *context = NULL;
1588         int sleep = 0, loops = 0, res = -1;
1589         struct localuser *u;
1590         struct ast_flags peerflags;
1591         
1592         if (ast_strlen_zero(data)) {
1593                 ast_log(LOG_WARNING, "RetryDial requires an argument!\n");
1594                 return -1;
1595         }       
1596
1597         LOCAL_USER_ADD(u);
1598
1599         if (!(announce = ast_strdupa(data)))
1600                 goto done;
1601
1602         memset(&peerflags, 0, sizeof(peerflags));
1603
1604         if ((dialdata = strchr(announce, '|'))) {
1605                 *dialdata++ = '\0';
1606                 if ((sleep = atoi(dialdata))) {
1607                         sleep *= 1000;
1608                 } else {
1609                         ast_log(LOG_ERROR, "%s requires the numerical argument <sleep>\n",rapp);
1610                         goto done;
1611                 }
1612                 if ((dialdata = strchr(dialdata, '|'))) {
1613                         *dialdata++ = '\0';
1614                         if (!(loops = atoi(dialdata))) {
1615                                 ast_log(LOG_ERROR, "%s requires the numerical argument <loops>\n",rapp);
1616                                 goto done;
1617                         }
1618                 }
1619         }
1620         
1621         if ((dialdata = strchr(dialdata, '|'))) {
1622                 *dialdata++ = '\0';
1623         } else {
1624                 ast_log(LOG_ERROR, "%s requires more arguments\n",rapp);
1625                 goto done;
1626         }
1627                 
1628         if (sleep < 1000)
1629                 sleep = 10000;
1630
1631         if (!loops)
1632                 loops = -1;     /* run forever */
1633         
1634         context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
1635
1636         res = 0;
1637         while (loops) {
1638                 chan->data = "Retrying";
1639                 if (ast_test_flag(chan, AST_FLAG_MOH))
1640                         ast_moh_stop(chan);
1641
1642                 if ((res = dial_exec_full(chan, dialdata, &peerflags)) == 0) {
1643                         if (ast_test_flag(&peerflags, OPT_DTMF_EXIT)) {
1644                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1645                                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1646                                 if (!res && sleep) {
1647                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1648                                                 ast_moh_start(chan, NULL);
1649                                         res = ast_waitfordigit(chan, sleep);
1650                                 }
1651                         } else {
1652                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1653                                         res = ast_waitstream(chan, "");
1654                                 if (sleep) {
1655                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1656                                                 ast_moh_start(chan, NULL);
1657                                         if (!res) 
1658                                                 res = ast_waitfordigit(chan, sleep);
1659                                 }
1660                         }
1661                 }
1662
1663                 if (res < 0)
1664                         break;
1665                 else if (res > 0) { /* Trying to send the call elsewhere (1 digit ext) */
1666                         if (onedigit_goto(chan, context, (char) res, 1)) {
1667                                 res = 0;
1668                                 break;
1669                         }
1670                 }
1671                 loops--;
1672         }
1673         if (loops == 0)
1674                 res = 0;
1675         
1676         if (ast_test_flag(chan, AST_FLAG_MOH))
1677                 ast_moh_stop(chan);
1678 done:
1679         LOCAL_USER_REMOVE(u);
1680         return res;
1681 }
1682
1683 static int unload_module(void *mod)
1684 {
1685         int res;
1686
1687         res = ast_unregister_application(app);
1688         res |= ast_unregister_application(rapp);
1689
1690         STANDARD_HANGUP_LOCALUSERS;
1691         
1692         return res;
1693 }
1694
1695 static int load_module(void *mod)
1696 {
1697         int res;
1698
1699         res = ast_register_application(app, dial_exec, synopsis, descrip);
1700         res |= ast_register_application(rapp, retrydial_exec, rsynopsis, rdescrip);
1701         
1702         return res;
1703 }
1704
1705 static const char *description(void)
1706 {
1707         return "Dialing Application";
1708 }
1709
1710 static const char *key(void)
1711 {
1712         return ASTERISK_GPL_KEY;
1713 }
1714
1715 STD_MOD(MOD_1, NULL, NULL, NULL);