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