d6df884e51444f84591cf6ba14fba4491ad6f37e
[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                 strcpy(status, "ANSWER");
1193                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1194                    we will always return with -1 so that it is hung up properly after the 
1195                    conversation.  */
1196                 hanguptree(outgoing, peer);
1197                 outgoing = NULL;
1198                 /* If appropriate, log that we have a destination channel */
1199                 if (chan->cdr)
1200                         ast_cdr_setdestchan(chan->cdr, peer->name);
1201                 if (peer->name)
1202                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
1203
1204                 number = (char *)pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER");
1205                 if (!number)
1206                         number = numsubst;
1207                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
1208                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
1209                         if (option_debug)
1210                                 ast_log(LOG_DEBUG, "app_dial: sendurl=%s.\n", args.url);
1211                         ast_channel_sendurl( peer, args.url );
1212                 }
1213                 if (ast_test_flag(&opts, OPT_PRIVACY) || ast_test_flag(&opts, OPT_SCREENING)) {
1214                         int res2;
1215                         int loopcount = 0;
1216                         if( privdb_val == AST_PRIVACY_UNKNOWN ) {
1217
1218                                 /* Get the user's intro, store it in priv-callerintros/$CID, 
1219                                    unless it is already there-- this should be done before the 
1220                                    call is actually dialed  */
1221
1222                                 /* all ring indications and moh for the caller has been halted as soon as the 
1223                                    target extension was picked up. We are going to have to kill some
1224                                    time and make the caller believe the peer hasn't picked up yet */
1225
1226                                 if (ast_test_flag(&opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1227                                         ast_indicate(chan, -1);
1228                                         ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK]);
1229                                 } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1230                                         ast_indicate(chan, AST_CONTROL_RINGING);
1231                                         sentringing++;
1232                                 }
1233
1234                                 /* Start autoservice on the other chan ?? */
1235                                 res2 = ast_autoservice_start(chan);
1236                                 /* Now Stream the File */
1237                                 if (!res2) {
1238                                         do {
1239                                                 if (!res2)
1240                                                         res2 = ast_play_and_wait(peer,"priv-callpending");
1241                                                 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! */
1242                                                         res2 = 0;
1243                                                 
1244                                                 /* priv-callpending script: 
1245                                                    "I have a caller waiting, who introduces themselves as:"
1246                                                 */
1247                                                 if (!res2)
1248                                                         res2 = ast_play_and_wait(peer,privintro);
1249                                                 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! */
1250                                                         res2 = 0;
1251                                                 /* now get input from the called party, as to their choice */
1252                                                 if( !res2 ) {
1253                                                         if( ast_test_flag(&opts, OPT_PRIVACY) )
1254                                                                 res2 = ast_play_and_wait(peer,"priv-callee-options");
1255                                                         if( ast_test_flag(&opts, OPT_SCREENING) )
1256                                                                 res2 = ast_play_and_wait(peer,"screen-callee-options");
1257                                                 }
1258                                                 /*! \page DialPrivacy Dial Privacy scripts
1259                                                 \par priv-callee-options script:
1260                                                         "Dial 1 if you wish this caller to reach you directly in the future,
1261                                                                 and immediately connect to their incoming call
1262                                                          Dial 2 if you wish to send this caller to voicemail now and 
1263                                                                 forevermore.
1264                                                          Dial 3 to send this callerr to the torture menus, now and forevermore.
1265                                                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1266                                                          Dial 5 to allow this caller to come straight thru to you in the future,
1267                                                                 but right now, just this once, send them to voicemail."
1268                                                 \par screen-callee-options script:
1269                                                         "Dial 1 if you wish to immediately connect to the incoming call
1270                                                          Dial 2 if you wish to send this caller to voicemail.
1271                                                          Dial 3 to send this callerr to the torture menus.
1272                                                          Dial 4 to send this caller to a simple "go away" menu.
1273                                                 */
1274                                                 if(!res2 || res2 < '1' || (ast_test_flag(&opts, OPT_PRIVACY) && res2 > '5') || (ast_test_flag(&opts, OPT_SCREENING) && res2 > '4') ) {
1275                                                         /* invalid option */
1276                                                         res2 = ast_play_and_wait(peer, "vm-sorry");
1277                                                 }
1278                                                 loopcount++; /* give the callee a couple chances to make a choice */
1279                                         } while( (!res2 || res2 < '1' || (ast_test_flag(&opts, OPT_PRIVACY) && res2 > '5') || (ast_test_flag(&opts, OPT_SCREENING) && res2 > '4')) && loopcount < 2 );
1280                                 }
1281
1282                                 switch(res2) {
1283                                 case '1':
1284                                         if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1285                                                 if (option_verbose > 2)
1286                                                         ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to ALLOW\n",
1287                                                                      opt_args[OPT_ARG_PRIVACY], privcid);
1288                                                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_ALLOW);
1289                                         }
1290                                         break;
1291                                 case '2':
1292                                         if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1293                                                 if (option_verbose > 2)
1294                                                         ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to DENY\n",
1295                                                                      opt_args[OPT_ARG_PRIVACY], privcid);
1296                                                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_DENY);
1297                                         }
1298                                         if (ast_test_flag(&opts, OPT_MUSICBACK)) {
1299                                                 ast_moh_stop(chan);
1300                                         } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1301                                                 ast_indicate(chan, -1);
1302                                                 sentringing=0;
1303                                         }
1304                                         res2 = ast_autoservice_stop(chan);
1305                                         ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1306                                         res=0;
1307                                         goto out;
1308                                 case '3':
1309                                         if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1310                                                 if (option_verbose > 2)
1311                                                         ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to TORTURE\n",
1312                                                                      opt_args[OPT_ARG_PRIVACY], privcid);
1313                                                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_TORTURE);
1314                                         }
1315                                         ast_copy_string(status, "TORTURE", sizeof(status));
1316                                         
1317                                         res = 0;
1318                                         if (ast_test_flag(&opts, OPT_MUSICBACK)) {
1319                                                 ast_moh_stop(chan);
1320                                         } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1321                                                 ast_indicate(chan, -1);
1322                                                 sentringing=0;
1323                                         }
1324                                         res2 = ast_autoservice_stop(chan);
1325                                         ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1326                                         goto out; /* Is this right? */
1327                                 case '4':
1328                                         if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1329                                                 if (option_verbose > 2)
1330                                                         ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to KILL\n",
1331                                                                      opt_args[OPT_ARG_PRIVACY], privcid);
1332                                                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_KILL);
1333                                         }
1334
1335                                         ast_copy_string(status, "DONTCALL", sizeof(status));
1336                                         res = 0;
1337                                         if (ast_test_flag(&opts, OPT_MUSICBACK)) {
1338                                                 ast_moh_stop(chan);
1339                                         } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1340                                                 ast_indicate(chan, -1);
1341                                                 sentringing=0;
1342                                         }
1343                                         res2 = ast_autoservice_stop(chan);
1344                                         ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1345                                         goto out; /* Is this right? */
1346                                 case '5':
1347                                         if( ast_test_flag(&opts, OPT_PRIVACY) ) {
1348                                                 if (option_verbose > 2)
1349                                                         ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to ALLOW\n",
1350                                                                      opt_args[OPT_ARG_PRIVACY], privcid);
1351                                                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], privcid, AST_PRIVACY_ALLOW);
1352                                                 if (ast_test_flag(&opts, OPT_MUSICBACK)) {
1353                                                         ast_moh_stop(chan);
1354                                                 } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1355                                                         ast_indicate(chan, -1);
1356                                                         sentringing=0;
1357                                                 }
1358                                                 res2 = ast_autoservice_stop(chan);
1359                                                 ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1360                                                 res=0;
1361                                                 goto out;
1362                                         } /* if not privacy, then 5 is the same as "default" case */
1363                                 default:
1364                                         /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1365                                         /* well, there seems basically two choices. Just patch the caller thru immediately,
1366                                                   or,... put 'em thru to voicemail. */
1367                                         /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1368                                         ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1369                                         if (ast_test_flag(&opts, OPT_MUSICBACK)) {
1370                                                 ast_moh_stop(chan);
1371                                         } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1372                                                 ast_indicate(chan, -1);
1373                                                 sentringing=0;
1374                                         }
1375                                         res2 = ast_autoservice_stop(chan);
1376                                         ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1377                                         res=0;
1378                                         goto out;
1379                                 }
1380                                 if (ast_test_flag(&opts, OPT_MUSICBACK)) {
1381                                         ast_moh_stop(chan);
1382                                 } else if (ast_test_flag(&opts, OPT_RINGBACK)) {
1383                                         ast_indicate(chan, -1);
1384                                         sentringing=0;
1385                                 }
1386                                 res2 = ast_autoservice_stop(chan);
1387                                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll 
1388                                    just clog things up, and it's not useful information, not being tied to a CID */
1389                                 if( strncmp(privcid,"NOCALLERID",10) == 0 || ast_test_flag(&opts, OPT_SCREEN_NOINTRO) ) {
1390                                         ast_filedelete(privintro, NULL);
1391                                         if( ast_fileexists(privintro, NULL, NULL ) > 0 )
1392                                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", privintro);
1393                                         else if (option_verbose > 2)
1394                                                 ast_verbose(VERBOSE_PREFIX_3 "Successfully deleted %s intro file\n", privintro);
1395                                 }
1396                         }
1397                 }
1398                 if (ast_test_flag(&opts, OPT_ANNOUNCE) && !ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
1399                         /* Start autoservice on the other chan */
1400                         res = ast_autoservice_start(chan);
1401                         /* Now Stream the File */
1402                         if (!res)
1403                                 res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
1404                         if (!res) {
1405                                 digit = ast_waitstream(peer, AST_DIGIT_ANY); 
1406                         }
1407                         /* Ok, done. stop autoservice */
1408                         res = ast_autoservice_stop(chan);
1409                         if (digit > 0 && !res)
1410                                 res = ast_senddigit(chan, digit); 
1411                         else
1412                                 res = digit;
1413
1414                 } else
1415                         res = 0;
1416
1417                 if (chan && peer && ast_test_flag(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
1418                         char *ch;
1419
1420                         for (ch = opt_args[OPT_ARG_GOTO]; *ch; ch++) {
1421                                 if (*ch == '^')
1422                                         *ch = '|';
1423                         }
1424                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
1425                         ast_parseable_goto(peer, opt_args[OPT_ARG_GOTO]);
1426                         peer->priority++;
1427                         ast_pbx_start(peer);
1428                         hanguptree(outgoing, NULL);
1429                         LOCAL_USER_REMOVE(u);
1430                         return 0;
1431                 }
1432
1433                 if (ast_test_flag(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
1434                         char *ch;
1435
1436                         res = ast_autoservice_start(chan);
1437                         if (res) {
1438                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
1439                                 res = -1;
1440                         }
1441
1442                         app = pbx_findapp("Macro");
1443
1444                         if (app && !res) {
1445                                 for (ch = opt_args[OPT_ARG_CALLEE_MACRO]; *ch; ch++) {
1446                                         if (*ch == '^')
1447                                                 *ch = '|';
1448                                 }
1449                                 res = pbx_exec(peer, app, opt_args[OPT_ARG_CALLEE_MACRO]);
1450                                 ast_log(LOG_DEBUG, "Macro exited with status %d\n", res);
1451                                 res = 0;
1452                         } else {
1453                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
1454                                 res = -1;
1455                         }
1456
1457                         if (ast_autoservice_stop(chan) < 0) {
1458                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
1459                                 res = -1;
1460                         }
1461
1462                         if (!res) {
1463                                 if ((macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
1464                                         if (!strcasecmp(macro_result, "BUSY")) {
1465                                                 ast_copy_string(status, macro_result, sizeof(status));
1466                                                 if (ast_opt_priority_jumping || ast_test_flag(&opts, OPT_PRIORITY_JUMP)) {
1467                                                         if (!ast_goto_if_exists(chan, NULL, NULL, chan->priority + 101)) {
1468                                                                 ast_set_flag(peerflags, OPT_GO_ON);
1469                                                         }
1470                                                 } else
1471                                                         ast_set_flag(peerflags, OPT_GO_ON);
1472                                                 res = -1;
1473                                         }
1474                                         else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
1475                                                 ast_copy_string(status, macro_result, sizeof(status));
1476                                                 ast_set_flag(peerflags, OPT_GO_ON);     
1477                                                 res = -1;
1478                                         }
1479                                         else if (!strcasecmp(macro_result, "CONTINUE")) {
1480                                                 /* hangup peer and keep chan alive assuming the macro has changed 
1481                                                    the context / exten / priority or perhaps 
1482                                                    the next priority in the current exten is desired.
1483                                                 */
1484                                                 ast_set_flag(peerflags, OPT_GO_ON);     
1485                                                 res = -1;
1486                                         } else if (!strcasecmp(macro_result, "ABORT")) {
1487                                                 /* Hangup both ends unless the caller has the g flag */
1488                                                 res = -1;
1489                                         } else if (!strncasecmp(macro_result, "GOTO:", 5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
1490                                                 res = -1;
1491                                                 /* perform a transfer to a new extension */
1492                                                 if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
1493                                                         /* no brainer mode... substitute ^ with | and feed it to builtin goto */
1494                                                         for (res = 0; res < strlen(macro_transfer_dest); res++)
1495                                                                 if (macro_transfer_dest[res] == '^')
1496                                                                         macro_transfer_dest[res] = '|';
1497
1498                                                         if (!ast_parseable_goto(chan, macro_transfer_dest))
1499                                                                 ast_set_flag(peerflags, OPT_GO_ON);
1500
1501                                                 }
1502                                         }
1503                                 }
1504                         }
1505                 }
1506
1507                 if (!res) {
1508                         if (calldurationlimit > 0) {
1509                                 time_t now;
1510
1511                                 time(&now);
1512                                 chan->whentohangup = now + calldurationlimit;
1513                         }
1514                         if (!ast_strlen_zero(dtmfcalled)) { 
1515                                 if (option_verbose > 2)
1516                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the called party.\n", dtmfcalled);
1517                                 res = ast_dtmf_stream(peer,chan,dtmfcalled,250);
1518                         }
1519                         if (!ast_strlen_zero(dtmfcalling)) {
1520                                 if (option_verbose > 2)
1521                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the calling party.\n", dtmfcalling);
1522                                 res = ast_dtmf_stream(chan,peer,dtmfcalling,250);
1523                         }
1524                 }
1525                 
1526                 if (!res) {
1527                         memset(&config,0,sizeof(struct ast_bridge_config));
1528                         if (play_to_caller)
1529                                 ast_set_flag(&(config.features_caller), AST_FEATURE_PLAY_WARNING);
1530                         if (play_to_callee)
1531                                 ast_set_flag(&(config.features_callee), AST_FEATURE_PLAY_WARNING);
1532                         if (ast_test_flag(peerflags, OPT_CALLEE_TRANSFER))
1533                                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1534                         if (ast_test_flag(peerflags, OPT_CALLER_TRANSFER))
1535                                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
1536                         if (ast_test_flag(peerflags, OPT_CALLEE_HANGUP))
1537                                 ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
1538                         if (ast_test_flag(peerflags, OPT_CALLER_HANGUP))
1539                                 ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
1540                         if (ast_test_flag(peerflags, OPT_CALLEE_MONITOR))
1541                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1542                         if (ast_test_flag(peerflags, OPT_CALLER_MONITOR)) 
1543                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1544
1545                         config.timelimit = timelimit;
1546                         config.play_warning = play_warning;
1547                         config.warning_freq = warning_freq;
1548                         config.warning_sound = warning_sound;
1549                         config.end_sound = end_sound;
1550                         config.start_sound = start_sound;
1551                         if (moh) {
1552                                 moh = 0;
1553                                 ast_moh_stop(chan);
1554                         } else if (sentringing) {
1555                                 sentringing = 0;
1556                                 ast_indicate(chan, -1);
1557                         }
1558                         /* Be sure no generators are left on it */
1559                         ast_deactivate_generator(chan);
1560                         /* Make sure channels are compatible */
1561                         res = ast_channel_make_compatible(chan, peer);
1562                         if (res < 0) {
1563                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
1564                                 ast_hangup(peer);
1565                                 LOCAL_USER_REMOVE(u);
1566                                 return -1;
1567                         }
1568                         res = ast_bridge_call(chan,peer,&config);
1569                         time(&end_time);
1570                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1571                         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", toast);
1572                         
1573                 } else {
1574                         time(&end_time);
1575                         res = -1;
1576                 }
1577                 snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1578                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", toast);
1579                 
1580                 if (res != AST_PBX_NO_HANGUP_PEER) {
1581                         if (!chan->_softhangup)
1582                                 chan->hangupcause = peer->hangupcause;
1583                         ast_hangup(peer);
1584                 }
1585         }       
1586 out:
1587         if (moh) {
1588                 moh = 0;
1589                 ast_moh_stop(chan);
1590         } else if (sentringing) {
1591                 sentringing = 0;
1592                 ast_indicate(chan, -1);
1593         }
1594         hanguptree(outgoing, NULL);
1595         pbx_builtin_setvar_helper(chan, "DIALSTATUS", status);
1596         if (option_debug)
1597                 ast_log(LOG_DEBUG, "Exiting with DIALSTATUS=%s.\n", status);
1598         
1599         if ((ast_test_flag(peerflags, OPT_GO_ON)) && (!chan->_softhangup) && (res != AST_PBX_KEEPALIVE))
1600                 res = 0;
1601         
1602         LOCAL_USER_REMOVE(u);    
1603         
1604         return res;
1605 }
1606
1607 static int dial_exec(struct ast_channel *chan, void *data)
1608 {
1609         struct ast_flags peerflags;
1610         memset(&peerflags, 0, sizeof(peerflags));
1611         return dial_exec_full(chan, data, &peerflags);
1612 }
1613
1614 static int retrydial_exec(struct ast_channel *chan, void *data)
1615 {
1616         char *announce = NULL, *dialdata = NULL;
1617         const char *context = NULL;
1618         int sleep = 0, loops = 0, res = 0;
1619         struct localuser *u;
1620         struct ast_flags peerflags;
1621         
1622         if (ast_strlen_zero(data)) {
1623                 ast_log(LOG_WARNING, "RetryDial requires an argument!\n");
1624                 return -1;
1625         }       
1626
1627         LOCAL_USER_ADD(u);
1628
1629         if (!(announce = ast_strdupa(data))) {
1630                 LOCAL_USER_REMOVE(u);
1631                 return -1;
1632         }
1633         
1634         memset(&peerflags, 0, sizeof(peerflags));
1635
1636         if ((dialdata = strchr(announce, '|'))) {
1637                 *dialdata = '\0';
1638                 dialdata++;
1639                 if ((sleep = atoi(dialdata))) {
1640                         sleep *= 1000;
1641                 } else {
1642                         ast_log(LOG_ERROR, "%s requires the numerical argument <sleep>\n",rapp);
1643                         LOCAL_USER_REMOVE(u);
1644                         return -1;
1645                 }
1646                 if ((dialdata = strchr(dialdata, '|'))) {
1647                         *dialdata = '\0';
1648                         dialdata++;
1649                         if (!(loops = atoi(dialdata))) {
1650                                 ast_log(LOG_ERROR, "%s requires the numerical argument <loops>\n",rapp);
1651                                 LOCAL_USER_REMOVE(u);
1652                                 return -1;
1653                         }
1654                 }
1655         }
1656         
1657         if ((dialdata = strchr(dialdata, '|'))) {
1658                 *dialdata = '\0';
1659                 dialdata++;
1660         } else {
1661                 ast_log(LOG_ERROR, "%s requires more arguments\n",rapp);
1662                 LOCAL_USER_REMOVE(u);
1663                 return -1;
1664         }
1665                 
1666         if (sleep < 1000)
1667                 sleep = 10000;
1668         
1669         if (!loops)
1670                 loops = -1;
1671         
1672         context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
1673         
1674         while (loops) {
1675                 chan->data = "Retrying";
1676                 if (ast_test_flag(chan, AST_FLAG_MOH))
1677                         ast_moh_stop(chan);
1678
1679                 if ((res = dial_exec_full(chan, dialdata, &peerflags)) == 0) {
1680                         if (ast_test_flag(&peerflags, OPT_DTMF_EXIT)) {
1681                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1682                                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1683                                 if (!res && sleep) {
1684                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1685                                                 ast_moh_start(chan, NULL);
1686                                         res = ast_waitfordigit(chan, sleep);
1687                                 }
1688                         } else {
1689                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1690                                         res = ast_waitstream(chan, "");
1691                                 if (sleep) {
1692                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1693                                                 ast_moh_start(chan, NULL);
1694                                         if (!res) 
1695                                                 res = ast_waitfordigit(chan, sleep);
1696                                 }
1697                         }
1698                 }
1699
1700                 if (res < 0)
1701                         break;
1702                 else if (res > 0) { /* Trying to send the call elsewhere (1 digit ext) */
1703                         if (onedigit_goto(chan, context, (char) res, 1)) {
1704                                 res = 0;
1705                                 break;
1706                         }
1707                 }
1708                 loops--;
1709         }
1710         
1711         if (ast_test_flag(chan, AST_FLAG_MOH))
1712                 ast_moh_stop(chan);
1713
1714         LOCAL_USER_REMOVE(u);
1715         return loops ? res : 0;
1716
1717 }
1718
1719 STATIC_MODULE int unload_module(void)
1720 {
1721         int res;
1722
1723         res = ast_unregister_application(app);
1724         res |= ast_unregister_application(rapp);
1725
1726         STANDARD_HANGUP_LOCALUSERS;
1727         
1728         return res;
1729 }
1730
1731 STATIC_MODULE int load_module(void)
1732 {
1733         int res;
1734
1735         res = ast_register_application(app, dial_exec, synopsis, descrip);
1736         res |= ast_register_application(rapp, retrydial_exec, rsynopsis, rdescrip);
1737         
1738         return res;
1739 }
1740
1741 STATIC_MODULE const char *description(void)
1742 {
1743         return tdesc;
1744 }
1745
1746 STATIC_MODULE int usecount(void)
1747 {
1748         int res;
1749         STANDARD_USECOUNT(res);
1750         return res;
1751 }
1752
1753 STATIC_MODULE const char *key(void)
1754 {
1755         return ASTERISK_GPL_KEY;
1756 }
1757
1758 STD_MOD(MOD_1, NULL, NULL, NULL);