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