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