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