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