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