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