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