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