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