Merged revisions 64756 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                 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                                 if (f)
755                                         ast_frfree(f);
756                                 return NULL;
757                         }
758
759                         /* now f is guaranteed non-NULL */
760                         if (f->frametype == AST_FRAME_DTMF) {
761                                 if (ast_test_flag(peerflags, OPT_DTMF_EXIT)) {
762                                         const char *context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
763                                         if (onedigit_goto(in, context, (char) f->subclass, 1)) {
764                                                 if (option_verbose > 2)
765                                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
766                                                 *to=0;
767                                                 *result = f->subclass;
768                                                 strcpy(pa->status, "CANCEL");
769                                                 ast_frfree(f);
770                                                 return NULL;
771                                         }
772                                 }
773
774                                 if (ast_test_flag(peerflags, OPT_CALLER_HANGUP) && 
775                                                   (f->subclass == '*')) { /* hmm it it not guaranteed to be '*' anymore. */
776                                         if (option_verbose > 2)
777                                                 ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
778                                         *to=0;
779                                         strcpy(pa->status, "CANCEL");
780                                         ast_frfree(f);
781                                         return NULL;
782                                 }
783                         }
784
785                         /* Forward HTML stuff */
786                         if (single && (f->frametype == AST_FRAME_HTML) && !ast_test_flag(outgoing, DIAL_NOFORWARDHTML)) 
787                                 if(ast_channel_sendhtml(outgoing->chan, f->subclass, f->data, f->datalen) == -1)
788                                         ast_log(LOG_WARNING, "Unable to send URL\n");
789                         
790
791                         if (single && ((f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_DTMF_BEGIN) || (f->frametype == AST_FRAME_DTMF_END)))  {
792                                 if (ast_write(outgoing->chan, f))
793                                         ast_log(LOG_WARNING, "Unable to forward voice or dtmf\n");
794                         }
795                         if (single && (f->frametype == AST_FRAME_CONTROL) && 
796                                 ((f->subclass == AST_CONTROL_HOLD) || 
797                                  (f->subclass == AST_CONTROL_UNHOLD) || 
798                                  (f->subclass == AST_CONTROL_VIDUPDATE))) {
799                                 if (option_verbose > 2)
800                                         ast_verbose(VERBOSE_PREFIX_3 "%s requested special control %d, passing it to %s\n", in->name, f->subclass, outgoing->chan->name);
801                                 ast_indicate_data(outgoing->chan, f->subclass, f->data, f->datalen);
802                         }
803                         ast_frfree(f);
804                 }
805                 if (!*to && (option_verbose > 2))
806                         ast_verbose(VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
807         }
808
809         return peer;
810 }
811
812 static void replace_macro_delimiter(char *s)
813 {
814         for (; *s; s++)
815                 if (*s == '^')
816                         *s = '|';
817 }
818
819
820 /* returns true if there is a valid privacy reply */
821 static int valid_priv_reply(struct ast_flags *opts, int res)
822 {
823         if (res < '1')
824                 return 0;
825         if (ast_test_flag(opts, OPT_PRIVACY) && res <= '5')
826                 return 1;
827         if (ast_test_flag(opts, OPT_SCREENING) && res <= '4')
828                 return 1;
829         return 0;
830 }
831
832 static int do_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
833         char *parse, unsigned int *calldurationlimit)
834 {
835         char *stringp = ast_strdupa(parse);
836         char *limit_str, *warning_str, *warnfreq_str;
837         const char *var;
838         int play_to_caller=0,play_to_callee=0;
839         int delta;
840
841         limit_str = strsep(&stringp, ":");
842         warning_str = strsep(&stringp, ":");
843         warnfreq_str = strsep(&stringp, ":");
844
845         config->timelimit = atol(limit_str);
846         if (warning_str)
847                 config->play_warning = atol(warning_str);
848         if (warnfreq_str)
849                 config->warning_freq = atol(warnfreq_str);
850
851         if (!config->timelimit) {
852                 ast_log(LOG_WARNING, "Dial does not accept L(%s), hanging up.\n", limit_str);
853                 config->timelimit = config->play_warning = config->warning_freq = 0;
854                 config->warning_sound = NULL;
855                 return -1;      /* error */
856         } else if ( (delta = config->play_warning - config->timelimit) > 0) {
857                 int w = config->warning_freq;
858
859                 /* If the first warning is requested _after_ the entire call would end,
860                    and no warning frequency is requested, then turn off the warning. If
861                    a warning frequency is requested, reduce the 'first warning' time by
862                    that frequency until it falls within the call's total time limit.
863                    Graphically:
864                                   timelim->|    delta        |<-playwarning
865                         0__________________|_________________|
866                                          | w  |    |    |    |
867
868                    so the number of intervals to cut is 1+(delta-1)/w
869                 */
870
871                 if (w == 0) {
872                         config->play_warning = 0;
873                 } else {
874                         config->play_warning -= w * ( 1 + (delta-1)/w );
875                         if (config->play_warning < 1)
876                                 config->play_warning = config->warning_freq = 0;
877                 }
878         }
879
880         var = pbx_builtin_getvar_helper(chan,"LIMIT_PLAYAUDIO_CALLER");
881         play_to_caller = var ? ast_true(var) : 1;
882         
883         var = pbx_builtin_getvar_helper(chan,"LIMIT_PLAYAUDIO_CALLEE");
884         play_to_callee = var ? ast_true(var) : 0;
885         
886         if (!play_to_caller && !play_to_callee)
887                 play_to_caller = 1;
888         
889         var = pbx_builtin_getvar_helper(chan,"LIMIT_WARNING_FILE");
890         config->warning_sound = S_OR(var, "timeleft");
891
892         /* The code looking at config wants a NULL, not just "", to decide
893          * that the message should not be played, so we replace "" with NULL.
894          * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
895          * not found.
896          */
897         var = pbx_builtin_getvar_helper(chan,"LIMIT_TIMEOUT_FILE");
898         config->end_sound = S_OR(var, NULL);
899         var = pbx_builtin_getvar_helper(chan,"LIMIT_CONNECT_FILE");
900         config->start_sound = S_OR(var, NULL);
901
902         /* undo effect of S(x) in case they are both used */
903         *calldurationlimit = 0;
904         /* more efficient to do it like S(x) does since no advanced opts */
905         if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
906                 *calldurationlimit = config->timelimit / 1000;
907                 if (option_verbose > 2)
908                         ast_verbose(VERBOSE_PREFIX_3 "Setting call duration limit to %d seconds.\n",
909                                 *calldurationlimit);
910                 config->timelimit = play_to_caller = play_to_callee =
911                 config->play_warning = config->warning_freq = 0;
912         } else if (option_verbose > 2) {
913                 ast_verbose(VERBOSE_PREFIX_3 "Limit Data for this call:\n");
914                 ast_verbose(VERBOSE_PREFIX_4 "timelimit      = %ld\n", config->timelimit);
915                 ast_verbose(VERBOSE_PREFIX_4 "play_warning   = %ld\n", config->play_warning);
916                 ast_verbose(VERBOSE_PREFIX_4 "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
917                 ast_verbose(VERBOSE_PREFIX_4 "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
918                 ast_verbose(VERBOSE_PREFIX_4 "warning_freq   = %ld\n", config->warning_freq);
919                 ast_verbose(VERBOSE_PREFIX_4 "start_sound    = %s\n", S_OR(config->start_sound, ""));
920                 ast_verbose(VERBOSE_PREFIX_4 "warning_sound  = %s\n", config->warning_sound);
921                 ast_verbose(VERBOSE_PREFIX_4 "end_sound      = %s\n", S_OR(config->end_sound, ""));
922         }
923         if (play_to_caller)
924                 ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
925         if (play_to_callee)
926                 ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
927         return 0;
928 }
929
930 static int do_privacy(struct ast_channel *chan, struct ast_channel *peer,
931     struct ast_flags *opts, char **opt_args, struct privacy_args *pa)
932 {
933
934         int res2;
935         int loopcount = 0;
936
937         /* Get the user's intro, store it in priv-callerintros/$CID, 
938            unless it is already there-- this should be done before the 
939            call is actually dialed  */
940
941         /* all ring indications and moh for the caller has been halted as soon as the 
942            target extension was picked up. We are going to have to kill some
943            time and make the caller believe the peer hasn't picked up yet */
944
945         if (ast_test_flag(opts, OPT_MUSICBACK) && !ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
946                 char *original_moh = ast_strdupa(chan->musicclass);
947                 ast_indicate(chan, -1);
948                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
949                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
950                 ast_string_field_set(chan, musicclass, original_moh);
951         } else if (ast_test_flag(opts, OPT_RINGBACK)) {
952                 ast_indicate(chan, AST_CONTROL_RINGING);
953                 pa->sentringing++;
954         }
955
956         /* Start autoservice on the other chan ?? */
957         res2 = ast_autoservice_start(chan);
958         /* Now Stream the File */
959         for (loopcount = 0; loopcount < 3; loopcount++) {
960                 if (res2 && loopcount == 0)     /* error in ast_autoservice_start() */
961                         break;
962                 if (!res2)      /* on timeout, play the message again */
963                         res2 = ast_play_and_wait(peer,"priv-callpending");
964                 if (!valid_priv_reply(opts, res2))
965                         res2 = 0;
966                 /* priv-callpending script: 
967                    "I have a caller waiting, who introduces themselves as:"
968                 */
969                 if (!res2)
970                         res2 = ast_play_and_wait(peer, pa->privintro);
971                 if (!valid_priv_reply(opts, res2))
972                         res2 = 0;
973                 /* now get input from the called party, as to their choice */
974                 if( !res2 ) {
975                         /* XXX can we have both, or they are mutually exclusive ? */
976                         if( ast_test_flag(opts, OPT_PRIVACY) )
977                                 res2 = ast_play_and_wait(peer,"priv-callee-options");
978                         if( ast_test_flag(opts, OPT_SCREENING) )
979                                 res2 = ast_play_and_wait(peer,"screen-callee-options");
980                 }
981                 /*! \page DialPrivacy Dial Privacy scripts
982                 \par priv-callee-options script:
983                         "Dial 1 if you wish this caller to reach you directly in the future,
984                                 and immediately connect to their incoming call
985                          Dial 2 if you wish to send this caller to voicemail now and 
986                                 forevermore.
987                          Dial 3 to send this caller to the torture menus, now and forevermore.
988                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
989                          Dial 5 to allow this caller to come straight thru to you in the future,
990                                 but right now, just this once, send them to voicemail."
991                 \par screen-callee-options script:
992                         "Dial 1 if you wish to immediately connect to the incoming call
993                          Dial 2 if you wish to send this caller to voicemail.
994                          Dial 3 to send this caller to the torture menus.
995                          Dial 4 to send this caller to a simple "go away" menu.
996                 */
997                 if (valid_priv_reply(opts, res2))
998                         break;
999                 /* invalid option */
1000                 res2 = ast_play_and_wait(peer, "vm-sorry");
1001         }
1002
1003         if (ast_test_flag(opts, OPT_MUSICBACK)) {
1004                 ast_moh_stop(chan);
1005         } else if (ast_test_flag(opts, OPT_RINGBACK)) {
1006                 ast_indicate(chan, -1);
1007                 pa->sentringing=0;
1008         }
1009         ast_autoservice_stop(chan);
1010         if(ast_test_flag(opts, OPT_PRIVACY) && (res2 >= '1' && res2 <= '5')) {
1011                 /* map keypresses to various things, the index is res2 - '1' */
1012                 static const char *_val[] = { "ALLOW", "DENY", "TORTURE", "KILL", "ALLOW" };
1013                 static const int _flag[] = { AST_PRIVACY_ALLOW, AST_PRIVACY_DENY, AST_PRIVACY_TORTURE, AST_PRIVACY_KILL, AST_PRIVACY_ALLOW};
1014                 int i = res2 - '1';
1015                 if (option_verbose > 2)
1016                         ast_verbose(VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to %s\n",
1017                                              opt_args[OPT_ARG_PRIVACY], pa->privcid, _val[i]);
1018                 ast_privacy_set(opt_args[OPT_ARG_PRIVACY], pa->privcid, _flag[i]);
1019         }
1020         switch (res2) {
1021         case '1':
1022                 break;
1023         case '2':
1024                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1025                 break;
1026         case '3':
1027                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1028                 break;
1029         case '4':
1030                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1031                 break;
1032         case '5':
1033                 /* XXX should we set status to DENY ? */
1034                 if( ast_test_flag(opts, OPT_PRIVACY) )
1035                         break;
1036                 /* if not privacy, then 5 is the same as "default" case */
1037         default:        /* bad input or -1 if failure to start autoservice */
1038                 /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1039                 /* well, there seems basically two choices. Just patch the caller thru immediately,
1040                           or,... put 'em thru to voicemail. */
1041                 /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1042                 ast_log(LOG_NOTICE, "privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1043                 /* XXX should we set status to DENY ? */
1044                 /* XXX what about the privacy flags ? */
1045                 break;
1046         }
1047
1048         if (res2 == '1') {      /* the only case where we actually connect */
1049                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll 
1050                    just clog things up, and it's not useful information, not being tied to a CID */
1051                 if( strncmp(pa->privcid,"NOCALLERID",10) == 0 || ast_test_flag(opts, OPT_SCREEN_NOINTRO) ) {
1052                         ast_filedelete(pa->privintro, NULL);
1053                         if( ast_fileexists(pa->privintro, NULL, NULL ) > 0 )
1054                                 ast_log(LOG_NOTICE, "privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1055                         else if (option_verbose > 2)
1056                                 ast_verbose(VERBOSE_PREFIX_3 "Successfully deleted %s intro file\n", pa->privintro);
1057                 }
1058                 return 0;       /* the good exit path */
1059         } else {
1060                 ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1061                 return -1;
1062         }
1063 }
1064
1065 /*! \brief returns 1 if successful, 0 or <0 if the caller should 'goto out' */
1066 static int setup_privacy_args(struct privacy_args *pa,
1067         struct ast_flags *opts, char *opt_args[], struct ast_channel *chan)
1068 {
1069         char callerid[60];
1070         int res;
1071         char *l;
1072
1073         if (!ast_strlen_zero(chan->cid.cid_num)) {
1074                 l = ast_strdupa(chan->cid.cid_num);
1075                 ast_shrink_phone_number(l);
1076                 if (ast_test_flag(opts, OPT_PRIVACY) ) {
1077                         if (option_verbose > 2)
1078                                 ast_verbose(VERBOSE_PREFIX_3  "Privacy DB is '%s', clid is '%s'\n",
1079                                              opt_args[OPT_ARG_PRIVACY], l);
1080                         pa->privdb_val = ast_privacy_check(opt_args[OPT_ARG_PRIVACY], l);
1081                 } else {
1082                         if (option_verbose > 2)
1083                                 ast_verbose(VERBOSE_PREFIX_3  "Privacy Screening, clid is '%s'\n", l);
1084                         pa->privdb_val = AST_PRIVACY_UNKNOWN;
1085                 }
1086         } else {
1087                 char *tnam, *tn2;
1088
1089                 tnam = ast_strdupa(chan->name);
1090                 /* clean the channel name so slashes don't try to end up in disk file name */
1091                 for (tn2 = tnam; *tn2; tn2++) {
1092                         if (*tn2=='/')  /* any other chars to be afraid of? */
1093                                 *tn2 = '=';
1094                 }
1095                 if (option_verbose > 2)
1096                         ast_verbose(VERBOSE_PREFIX_3  "Privacy-- callerid is empty\n");
1097
1098                 snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
1099                 l = callerid;
1100                 pa->privdb_val = AST_PRIVACY_UNKNOWN;
1101         }
1102         
1103         ast_copy_string(pa->privcid,l,sizeof(pa->privcid));
1104
1105         if( strncmp(pa->privcid,"NOCALLERID",10) != 0 && ast_test_flag(opts, OPT_SCREEN_NOCLID) ) { /* if callerid is set, and ast_test_flag(&opts, OPT_SCREEN_NOCLID) is set also */  
1106                 if (option_verbose > 2)
1107                         ast_verbose( VERBOSE_PREFIX_3  "CallerID set (%s); N option set; Screening should be off\n", pa->privcid);
1108                 pa->privdb_val = AST_PRIVACY_ALLOW;
1109         } else if (ast_test_flag(opts, OPT_SCREEN_NOCLID) && strncmp(pa->privcid,"NOCALLERID",10) == 0 ) {
1110                 if (option_verbose > 2)
1111                         ast_verbose( VERBOSE_PREFIX_3  "CallerID blank; N option set; Screening should happen; dbval is %d\n", pa->privdb_val);
1112         }
1113         
1114         if (pa->privdb_val == AST_PRIVACY_DENY ) {
1115                 ast_copy_string(pa->status, "NOANSWER", sizeof(pa->status));
1116                 if (option_verbose > 2)
1117                         ast_verbose( VERBOSE_PREFIX_3  "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
1118                 return 0;
1119         } else if (pa->privdb_val == AST_PRIVACY_KILL ) {
1120                 ast_copy_string(pa->status, "DONTCALL", sizeof(pa->status));
1121                 if (ast_opt_priority_jumping || ast_test_flag(opts, OPT_PRIORITY_JUMP)) {
1122                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 201);
1123                 }
1124                 return 0; /* Is this right? */
1125         } else if (pa->privdb_val == AST_PRIVACY_TORTURE ) {
1126                 ast_copy_string(pa->status, "TORTURE", sizeof(pa->status));
1127                 if (ast_opt_priority_jumping || ast_test_flag(opts, OPT_PRIORITY_JUMP)) {
1128                         ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 301);
1129                 }
1130                 return 0; /* is this right??? */
1131         } else if (pa->privdb_val == AST_PRIVACY_UNKNOWN ) {
1132                 /* Get the user's intro, store it in priv-callerintros/$CID, 
1133                    unless it is already there-- this should be done before the 
1134                    call is actually dialed  */
1135
1136                 /* make sure the priv-callerintros dir actually exists */
1137                 snprintf(pa->privintro, sizeof(pa->privintro), "%s/sounds/priv-callerintros", ast_config_AST_DATA_DIR);
1138                 if (mkdir(pa->privintro, 0755) && errno != EEXIST) {
1139                         ast_log(LOG_WARNING, "privacy: can't create directory priv-callerintros: %s\n", strerror(errno));
1140                         return -1;
1141                 }
1142
1143                 snprintf(pa->privintro,sizeof(pa->privintro), "priv-callerintros/%s", pa->privcid);
1144                 if (ast_fileexists(pa->privintro,NULL,NULL ) > 0 && strncmp(pa->privcid,"NOCALLERID",10) != 0) {
1145                         /* the DELUX version of this code would allow this caller the
1146                            option to hear and retape their previously recorded intro.
1147                         */
1148                 } else {
1149                         int duration; /* for feedback from play_and_wait */
1150                         /* the file doesn't exist yet. Let the caller submit his
1151                            vocal intro for posterity */
1152                         /* priv-recordintro script:
1153
1154                            "At the tone, please say your name:"
1155
1156                         */
1157                         ast_answer(chan);
1158                         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 */
1159                                                                         /* don't think we'll need a lock removed, we took care of
1160                                                                            conflicts by naming the pa.privintro file */
1161                         if (res == -1) {
1162                                 /* Delete the file regardless since they hung up during recording */
1163                                 ast_filedelete(pa->privintro, NULL);
1164                                 if (ast_fileexists(pa->privintro,NULL,NULL ) > 0 )
1165                                         ast_log(LOG_NOTICE,"privacy: ast_filedelete didn't do its job on %s\n", pa->privintro);
1166                                 else if (option_verbose > 2)
1167                                         ast_verbose( VERBOSE_PREFIX_3 "Successfully deleted %s intro file\n", pa->privintro);
1168                                 return -1;
1169                         }
1170                         if (!ast_streamfile(chan, "vm-dialout", chan->language) )
1171                                 ast_waitstream(chan, "");
1172                 }
1173         }
1174         return 1;       /* success */
1175 }
1176
1177 static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags *peerflags, int *continue_exec)
1178 {
1179         int res = -1;   /* default: error */
1180         struct ast_module_user *u;
1181         char *rest, *cur;       /* scan the list of destinations */
1182         struct chanlist *outgoing = NULL;       /* list of destinations */
1183         struct ast_channel *peer;
1184         int to; /* timeout */
1185         struct cause_args num = { chan, 0, 0, 0 };
1186         int cause;
1187         char numsubst[256];
1188         char cidname[AST_MAX_EXTENSION];
1189
1190         struct ast_bridge_config config;
1191         unsigned int calldurationlimit = 0;
1192         char *dtmfcalled = NULL, *dtmfcalling = NULL;
1193         struct privacy_args pa = {
1194                 .sentringing = 0,
1195                 .privdb_val = 0,
1196                 .status = "INVALIDARGS",
1197         };
1198         int sentringing = 0, moh = 0;
1199         const char *outbound_group = NULL;
1200         int result = 0;
1201         time_t start_time;
1202         char *parse;
1203         int opermode = 0;
1204         AST_DECLARE_APP_ARGS(args,
1205                              AST_APP_ARG(peers);
1206                              AST_APP_ARG(timeout);
1207                              AST_APP_ARG(options);
1208                              AST_APP_ARG(url);
1209         );
1210         struct ast_flags opts = { 0, };
1211         char *opt_args[OPT_ARG_ARRAY_SIZE];
1212
1213         if (ast_strlen_zero(data)) {
1214                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1215                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1216                 return -1;
1217         }
1218
1219         u = ast_module_user_add(chan);  /* XXX is this the right place ? */
1220
1221         parse = ast_strdupa(data);
1222         
1223         AST_STANDARD_APP_ARGS(args, parse);
1224
1225         memset(&config,0,sizeof(struct ast_bridge_config));
1226
1227         if (!ast_strlen_zero(args.options) &&
1228                         ast_app_parse_options(dial_exec_options, &opts, opt_args, args.options)) {
1229                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1230                 goto done;
1231         }
1232
1233         if (ast_strlen_zero(args.peers)) {
1234                 ast_log(LOG_WARNING, "Dial requires an argument (technology/number)\n");
1235                 pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1236                 goto done;
1237         }
1238
1239         if (ast_test_flag(&opts, OPT_OPERMODE)) {
1240                 opermode = ast_strlen_zero(opt_args[OPT_ARG_OPERMODE]) ? 1 : atoi(opt_args[OPT_ARG_OPERMODE]);
1241                 if (option_verbose > 2)
1242                         ast_verbose(VERBOSE_PREFIX_3 "Setting operator services mode to %d.\n", opermode);
1243         }
1244         
1245         if (ast_test_flag(&opts, OPT_DURATION_STOP) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_STOP])) {
1246                 calldurationlimit = atoi(opt_args[OPT_ARG_DURATION_STOP]);
1247                 if (!calldurationlimit) {
1248                         ast_log(LOG_WARNING, "Dial does not accept S(%s), hanging up.\n", opt_args[OPT_ARG_DURATION_STOP]);
1249                         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1250                         goto done;
1251                 }
1252                 if (option_verbose > 2)
1253                         ast_verbose(VERBOSE_PREFIX_3 "Setting call duration limit to %d seconds.\n", calldurationlimit);
1254         }
1255
1256         if (ast_test_flag(&opts, OPT_SENDDTMF) && !ast_strlen_zero(opt_args[OPT_ARG_SENDDTMF])) {
1257                 dtmfcalling = opt_args[OPT_ARG_SENDDTMF];
1258                 dtmfcalled = strsep(&dtmfcalling, ":");
1259         }
1260
1261         if (ast_test_flag(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
1262                 if (do_timelimit(chan, &config, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
1263                         goto done;
1264         }
1265
1266         if (ast_test_flag(&opts, OPT_RESETCDR) && chan->cdr)
1267                 ast_cdr_reset(chan->cdr, NULL);
1268         if (ast_test_flag(&opts, OPT_PRIVACY) && ast_strlen_zero(opt_args[OPT_ARG_PRIVACY]))
1269                 opt_args[OPT_ARG_PRIVACY] = ast_strdupa(chan->exten);
1270
1271         if (ast_test_flag(&opts, OPT_PRIVACY) || ast_test_flag(&opts, OPT_SCREENING)) {
1272                 res = setup_privacy_args(&pa, &opts, opt_args, chan);
1273                 if (res <= 0)
1274                         goto out;
1275                 res = -1;       /* reset default */
1276         }
1277
1278         if (continue_exec)
1279                 *continue_exec = 0;
1280         
1281         /* If a channel group has been specified, get it for use when we create peer channels */
1282         if ((outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP_ONCE"))) {
1283                 outbound_group = ast_strdupa(outbound_group);
1284                 pbx_builtin_setvar_helper(chan, "OUTBOUND_GROUP_ONCE", NULL);
1285         } else {
1286                 outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP");
1287         }
1288             
1289         ast_copy_flags(peerflags, &opts, OPT_DTMF_EXIT | OPT_GO_ON | OPT_ORIGINAL_CLID | OPT_CALLER_HANGUP | OPT_IGNORE_FORWARDING);
1290         /* loop through the list of dial destinations */
1291         rest = args.peers;
1292         while ((cur = strsep(&rest, "&")) ) {
1293                 struct chanlist *tmp;
1294                 struct ast_channel *tc; /* channel for this destination */
1295                 /* Get a technology/[device:]number pair */
1296                 char *number = cur;
1297                 char *tech = strsep(&number, "/");
1298                 if (!number) {
1299                         ast_log(LOG_WARNING, "Dial argument takes format (technology/[device:]number1)\n");
1300                         goto out;
1301                 }
1302                 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1303                         goto out;
1304                 if (opts.flags) {
1305                         ast_copy_flags(tmp, &opts,
1306                                        OPT_CALLEE_TRANSFER | OPT_CALLER_TRANSFER |
1307                                        OPT_CALLEE_HANGUP | OPT_CALLER_HANGUP |
1308                                        OPT_CALLEE_MONITOR | OPT_CALLER_MONITOR |
1309                                        OPT_CALLEE_PARK | OPT_CALLER_PARK |
1310                                        OPT_RINGBACK | OPT_MUSICBACK | OPT_FORCECLID);
1311                         ast_set2_flag(tmp, args.url, DIAL_NOFORWARDHTML);       
1312                 }
1313                 ast_copy_string(numsubst, number, sizeof(numsubst));
1314                 /* Request the peer */
1315                 tc = ast_request(tech, chan->nativeformats, numsubst, &cause);
1316                 if (!tc) {
1317                         /* If we can't, just go on to the next call */
1318                         ast_log(LOG_WARNING, "Unable to create channel of type '%s' (cause %d - %s)\n",
1319                                     tech, cause, ast_cause2str(cause));
1320                         handle_cause(cause, &num);
1321                         if (!rest)      /* we are on the last destination */
1322                                 chan->hangupcause = cause;
1323                         free(tmp);
1324                         continue;
1325                 }
1326                 pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", numsubst);
1327                 if (!ast_strlen_zero(tc->call_forward)) {
1328                         char tmpchan[256];
1329                         char *stuff;
1330                         char *tech;
1331                         ast_copy_string(tmpchan, tc->call_forward, sizeof(tmpchan));
1332                         if ((stuff = strchr(tmpchan, '/'))) {
1333                                 *stuff++ = '\0';
1334                                 tech = tmpchan;
1335                         } else {
1336                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", tc->call_forward, tc->context);
1337                                 stuff = tmpchan;
1338                                 tech = "Local";
1339                         }
1340                         tmp->forwards++;
1341                         if (tmp->forwards < AST_MAX_FORWARDS) {
1342                                 if (option_verbose > 2)
1343                                         ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n",
1344                                         chan->name, tech, stuff, tc->name);
1345                                 ast_hangup(tc);
1346                                 /* If we have been told to ignore forwards, just set this channel to null
1347                                  * and continue processing extensions normally */
1348                                 if (ast_test_flag(&opts, OPT_IGNORE_FORWARDING)) {
1349                                         tc = NULL;
1350                                         cause = AST_CAUSE_BUSY;
1351                                         if (option_verbose > 2)
1352                                                 ast_verbose(VERBOSE_PREFIX_3 "Forwarding %s to '%s/%s' prevented.\n",
1353                                                         chan->name, tech, stuff);
1354                                 } else {
1355                                         tc = ast_request(tech, chan->nativeformats, stuff, &cause);
1356                                 }
1357                                 if (!tc)
1358                                         ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s' (cause = %d)\n", tech, stuff, cause);
1359                                 else
1360                                         ast_channel_inherit_variables(chan, tc);
1361                         } else {
1362                                 if (option_verbose > 2)
1363                                         ast_verbose(VERBOSE_PREFIX_3 "Too many forwards from %s\n", tc->name);
1364                                 ast_hangup(tc);
1365                                 tc = NULL;
1366                                 cause = AST_CAUSE_CONGESTION;
1367                         }
1368                         if (!tc) {
1369                                 handle_cause(cause, &num);
1370                                 free(tmp);
1371                                 continue;
1372                         }
1373                 }
1374
1375                 /* Setup outgoing SDP to match incoming one */
1376                 ast_rtp_make_compatible(tc, chan, !outgoing && !rest);
1377                 
1378                 /* Inherit specially named variables from parent channel */
1379                 ast_channel_inherit_variables(chan, tc);
1380
1381                 tc->appl = "AppDial";
1382                 tc->data = "(Outgoing Line)";
1383                 tc->whentohangup = 0;
1384
1385                 S_REPLACE(tc->cid.cid_num, ast_strdup(chan->cid.cid_num));
1386                 S_REPLACE(tc->cid.cid_name, ast_strdup(chan->cid.cid_name));
1387                 S_REPLACE(tc->cid.cid_ani, ast_strdup(chan->cid.cid_ani));
1388                 S_REPLACE(tc->cid.cid_rdnis, ast_strdup(chan->cid.cid_rdnis));
1389                 
1390                 /* Copy language from incoming to outgoing */
1391                 ast_string_field_set(tc, language, chan->language);
1392                 ast_string_field_set(tc, accountcode, chan->accountcode);
1393                 tc->cdrflags = chan->cdrflags;
1394                 if (ast_strlen_zero(tc->musicclass))
1395                         ast_string_field_set(tc, musicclass, chan->musicclass);
1396                 /* Pass callingpres, type of number, tns, ADSI CPE, transfer capability */
1397                 tc->cid.cid_pres = chan->cid.cid_pres;
1398                 tc->cid.cid_ton = chan->cid.cid_ton;
1399                 tc->cid.cid_tns = chan->cid.cid_tns;
1400                 tc->adsicpe = chan->adsicpe;
1401                 tc->transfercapability = chan->transfercapability;
1402
1403                 /* If we have an outbound group, set this peer channel to it */
1404                 if (outbound_group)
1405                         ast_app_group_set_channel(tc, outbound_group);
1406
1407                 /* Inherit context and extension */
1408                 if (!ast_strlen_zero(chan->macrocontext))
1409                         ast_copy_string(tc->dialcontext, chan->macrocontext, sizeof(tc->dialcontext));
1410                 else
1411                         ast_copy_string(tc->dialcontext, chan->context, sizeof(tc->dialcontext));
1412                 if (!ast_strlen_zero(chan->macroexten))
1413                         ast_copy_string(tc->exten, chan->macroexten, sizeof(tc->exten));
1414                 else
1415                         ast_copy_string(tc->exten, chan->exten, sizeof(tc->exten));
1416
1417                 res = ast_call(tc, numsubst, 0);        /* Place the call, but don't wait on the answer */
1418
1419                 /* Save the info in cdr's that we called them */
1420                 if (chan->cdr)
1421                         ast_cdr_setdestchan(chan->cdr, tc->name);
1422
1423                 /* check the results of ast_call */
1424                 if (res) {
1425                         /* Again, keep going even if there's an error */
1426                         if (option_debug)
1427                                 ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
1428                         if (option_verbose > 2)
1429                                 ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", numsubst);
1430                         ast_hangup(tc);
1431                         tc = NULL;
1432                         free(tmp);
1433                         continue;
1434                 } else {
1435                         senddialevent(chan, tc);
1436                         if (option_verbose > 2)
1437                                 ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", numsubst);
1438                         if (!ast_test_flag(peerflags, OPT_ORIGINAL_CLID))
1439                                 ast_set_callerid(tc, S_OR(chan->macroexten, chan->exten), get_cid_name(cidname, sizeof(cidname), chan), NULL);
1440                 }
1441                 /* Put them in the list of outgoing thingies...  We're ready now. 
1442                    XXX If we're forcibly removed, these outgoing calls won't get
1443                    hung up XXX */
1444                 ast_set_flag(tmp, DIAL_STILLGOING);     
1445                 tmp->chan = tc;
1446                 tmp->next = outgoing;
1447                 outgoing = tmp;
1448                 /* If this line is up, don't try anybody else */
1449                 if (outgoing->chan->_state == AST_STATE_UP)
1450                         break;
1451         }
1452         
1453         if (ast_strlen_zero(args.timeout)) {
1454                 to = -1;
1455         } else {
1456                 to = atoi(args.timeout);
1457                 if (to > 0)
1458                         to *= 1000;
1459                 else
1460                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'\n", args.timeout);
1461         }
1462
1463         if (!outgoing) {
1464                 strcpy(pa.status, "CHANUNAVAIL");
1465         } else {
1466                 /* Our status will at least be NOANSWER */
1467                 strcpy(pa.status, "NOANSWER");
1468                 if (ast_test_flag(outgoing, OPT_MUSICBACK)) {
1469                         moh = 1;
1470                         if (!ast_strlen_zero(opt_args[OPT_ARG_MUSICBACK])) {
1471                                 char *original_moh = ast_strdupa(chan->musicclass);
1472                                 ast_string_field_set(chan, musicclass, opt_args[OPT_ARG_MUSICBACK]);
1473                                 ast_moh_start(chan, opt_args[OPT_ARG_MUSICBACK], NULL);
1474                                 ast_string_field_set(chan, musicclass, original_moh);
1475                         } else {
1476                                 ast_moh_start(chan, NULL, NULL);
1477                         }
1478                         ast_indicate(chan, AST_CONTROL_PROGRESS);
1479                 } else if (ast_test_flag(outgoing, OPT_RINGBACK)) {
1480                         ast_indicate(chan, AST_CONTROL_RINGING);
1481                         sentringing++;
1482                 }
1483         }
1484
1485         time(&start_time);
1486         peer = wait_for_answer(chan, outgoing, &to, peerflags, &pa, &num, ast_test_flag(&opts, OPT_PRIORITY_JUMP), &result);
1487         
1488         if (!peer) {
1489                 if (result) {
1490                         res = result;
1491                 } else if (to) { /* Musta gotten hung up */
1492                         res = -1;
1493                 } else { /* Nobody answered, next please? */
1494                         res = 0;
1495                 }
1496                 /* almost done, although the 'else' block is 400 lines */
1497         } else {
1498                 const char *number;
1499                 time_t end_time, answer_time = time(NULL);
1500                 char toast[80]; /* buffer to set variables */
1501
1502                 strcpy(pa.status, "ANSWER");
1503                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1504                    we will always return with -1 so that it is hung up properly after the 
1505                    conversation.  */
1506                 hanguptree(outgoing, peer);
1507                 outgoing = NULL;
1508                 /* If appropriate, log that we have a destination channel */
1509                 if (chan->cdr)
1510                         ast_cdr_setdestchan(chan->cdr, peer->name);
1511                 if (peer->name)
1512                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
1513
1514                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER");
1515                 if (!number)
1516                         number = numsubst;
1517                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
1518                 if (!ast_strlen_zero(args.url) && ast_channel_supports_html(peer) ) {
1519                         if (option_debug)
1520                                 ast_log(LOG_DEBUG, "app_dial: sendurl=%s.\n", args.url);
1521                         ast_channel_sendurl( peer, args.url );
1522                 }
1523                 if ( (ast_test_flag(&opts, OPT_PRIVACY) || ast_test_flag(&opts, OPT_SCREENING)) && pa.privdb_val == AST_PRIVACY_UNKNOWN) {
1524                         if (do_privacy(chan, peer, &opts, opt_args, &pa)) {
1525                                 res = 0;
1526                                 goto out;
1527                         }
1528                 }
1529                 if (!ast_test_flag(&opts, OPT_ANNOUNCE) || ast_strlen_zero(opt_args[OPT_ARG_ANNOUNCE])) {
1530                         res = 0;
1531                 } else {
1532                         int digit = 0;
1533                         /* Start autoservice on the other chan */
1534                         res = ast_autoservice_start(chan);
1535                         /* Now Stream the File */
1536                         if (!res)
1537                                 res = ast_streamfile(peer, opt_args[OPT_ARG_ANNOUNCE], peer->language);
1538                         if (!res) {
1539                                 digit = ast_waitstream(peer, AST_DIGIT_ANY); 
1540                         }
1541                         /* Ok, done. stop autoservice */
1542                         res = ast_autoservice_stop(chan);
1543                         if (digit > 0 && !res)
1544                                 res = ast_senddigit(chan, digit); 
1545                         else
1546                                 res = digit;
1547
1548                 }
1549
1550                 if (chan && peer && ast_test_flag(&opts, OPT_GOTO) && !ast_strlen_zero(opt_args[OPT_ARG_GOTO])) {
1551                         replace_macro_delimiter(opt_args[OPT_ARG_GOTO]);
1552                         ast_parseable_goto(chan, opt_args[OPT_ARG_GOTO]);
1553                         ast_parseable_goto(peer, opt_args[OPT_ARG_GOTO]);
1554                         peer->priority++;
1555                         ast_pbx_start(peer);
1556                         hanguptree(outgoing, NULL);
1557                         if (continue_exec)
1558                                 *continue_exec = 1;
1559                         res = 0;
1560                         goto done;
1561                 }
1562
1563                 if (ast_test_flag(&opts, OPT_CALLEE_MACRO) && !ast_strlen_zero(opt_args[OPT_ARG_CALLEE_MACRO])) {
1564                         struct ast_app *theapp;
1565                         const char *macro_result;
1566
1567                         res = ast_autoservice_start(chan);
1568                         if (res) {
1569                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
1570                                 res = -1;
1571                         }
1572
1573                         theapp = pbx_findapp("Macro");
1574
1575                         if (theapp && !res) {   /* XXX why check res here ? */
1576                                 replace_macro_delimiter(opt_args[OPT_ARG_CALLEE_MACRO]);
1577                                 res = pbx_exec(peer, theapp, opt_args[OPT_ARG_CALLEE_MACRO]);
1578                                 if (option_debug)
1579                                         ast_log(LOG_DEBUG, "Macro exited with status %d\n", res);
1580                                 res = 0;
1581                         } else {
1582                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
1583                                 res = -1;
1584                         }
1585
1586                         if (ast_autoservice_stop(chan) < 0) {
1587                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
1588                                 res = -1;
1589                         }
1590
1591                         if (!res && (macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
1592                                 char *macro_transfer_dest;
1593
1594                                 if (!strcasecmp(macro_result, "BUSY")) {
1595                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
1596                                         if (ast_opt_priority_jumping || ast_test_flag(&opts, OPT_PRIORITY_JUMP)) {
1597                                                 if (!ast_goto_if_exists(chan, NULL, NULL, chan->priority + 101)) {
1598                                                         ast_set_flag(peerflags, OPT_GO_ON);
1599                                                 }
1600                                         } else
1601                                                 ast_set_flag(peerflags, OPT_GO_ON);
1602                                         res = -1;
1603                                 } else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
1604                                         ast_copy_string(pa.status, macro_result, sizeof(pa.status));
1605                                         ast_set_flag(peerflags, OPT_GO_ON);     
1606                                         res = -1;
1607                                 } else if (!strcasecmp(macro_result, "CONTINUE")) {
1608                                         /* hangup peer and keep chan alive assuming the macro has changed 
1609                                            the context / exten / priority or perhaps 
1610                                            the next priority in the current exten is desired.
1611                                         */
1612                                         ast_set_flag(peerflags, OPT_GO_ON);     
1613                                         res = -1;
1614                                 } else if (!strcasecmp(macro_result, "ABORT")) {
1615                                         /* Hangup both ends unless the caller has the g flag */
1616                                         res = -1;
1617                                 } else if (!strncasecmp(macro_result, "GOTO:", 5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
1618                                         res = -1;
1619                                         /* perform a transfer to a new extension */
1620                                         if (strchr(macro_transfer_dest, '^')) { /* context^exten^priority*/
1621                                                 replace_macro_delimiter(macro_transfer_dest);
1622                                                 if (!ast_parseable_goto(chan, macro_transfer_dest))
1623                                                         ast_set_flag(peerflags, OPT_GO_ON);
1624                                         }
1625                                 }
1626                         }
1627                 }
1628
1629                 if (!res) {
1630                         if (calldurationlimit > 0) {
1631                                 chan->whentohangup = time(NULL) + calldurationlimit;
1632                         }
1633                         if (!ast_strlen_zero(dtmfcalled)) { 
1634                                 if (option_verbose > 2)
1635                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the called party.\n", dtmfcalled);
1636                                 res = ast_dtmf_stream(peer,chan,dtmfcalled,250);
1637                         }
1638                         if (!ast_strlen_zero(dtmfcalling)) {
1639                                 if (option_verbose > 2)
1640                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the calling party.\n", dtmfcalling);
1641                                 res = ast_dtmf_stream(chan,peer,dtmfcalling,250);
1642                         }
1643                 }
1644                 
1645                 if (res) {      /* some error */
1646                         res = -1;
1647                         end_time = time(NULL);
1648                 } else {
1649                         if (ast_test_flag(peerflags, OPT_CALLEE_TRANSFER))
1650                                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1651                         if (ast_test_flag(peerflags, OPT_CALLER_TRANSFER))
1652                                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
1653                         if (ast_test_flag(peerflags, OPT_CALLEE_HANGUP))
1654                                 ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
1655                         if (ast_test_flag(peerflags, OPT_CALLER_HANGUP))
1656                                 ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
1657                         if (ast_test_flag(peerflags, OPT_CALLEE_MONITOR))
1658                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1659                         if (ast_test_flag(peerflags, OPT_CALLER_MONITOR)) 
1660                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1661                         if (ast_test_flag(peerflags, OPT_CALLEE_PARK))
1662                                 ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
1663                         if (ast_test_flag(peerflags, OPT_CALLER_PARK))
1664                                 ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
1665
1666                         if (moh) {
1667                                 moh = 0;
1668                                 ast_moh_stop(chan);
1669                         } else if (sentringing) {
1670                                 sentringing = 0;
1671                                 ast_indicate(chan, -1);
1672                         }
1673                         /* Be sure no generators are left on it */
1674                         ast_deactivate_generator(chan);
1675                         /* Make sure channels are compatible */
1676                         res = ast_channel_make_compatible(chan, peer);
1677                         if (res < 0) {
1678                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
1679                                 ast_hangup(peer);
1680                                 res = -1;
1681                                 goto done;
1682                         }
1683                         if (opermode && !strncmp(chan->name,"Zap",3) && !strncmp(peer->name,"Zap",3)) {
1684                                 /* XXX what's this special handling for Zap <-> Zap ? */
1685                                 struct oprmode oprmode;
1686
1687                                 oprmode.peer = peer;
1688                                 oprmode.mode = opermode;
1689
1690                                 ast_channel_setoption(chan,
1691                                         AST_OPTION_OPRMODE,&oprmode,sizeof(struct oprmode),0);
1692                         }
1693                         res = ast_bridge_call(chan,peer,&config);
1694                         end_time = time(NULL);
1695                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1696                         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", toast);
1697                 }
1698
1699                 snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1700                 pbx_builtin_setvar_helper(chan, "DIALEDTIME", toast);
1701
1702                 if (res != AST_PBX_NO_HANGUP_PEER) {
1703                         if (!chan->_softhangup)
1704                                 chan->hangupcause = peer->hangupcause;
1705                         ast_hangup(peer);
1706                 }
1707         }       
1708 out:
1709         if (moh) {
1710                 moh = 0;
1711                 ast_moh_stop(chan);
1712         } else if (sentringing) {
1713                 sentringing = 0;
1714                 ast_indicate(chan, -1);
1715         }
1716         ast_channel_early_bridge(chan, NULL);
1717         hanguptree(outgoing, NULL);
1718         pbx_builtin_setvar_helper(chan, "DIALSTATUS", pa.status);
1719         senddialendevent(chan, pa.status);
1720         if (option_debug)
1721                 ast_log(LOG_DEBUG, "Exiting with DIALSTATUS=%s.\n", pa.status);
1722         
1723         if ((ast_test_flag(peerflags, OPT_GO_ON)) && (!chan->_softhangup) && (res != AST_PBX_KEEPALIVE))
1724                 res = 0;
1725
1726 done:
1727         ast_module_user_remove(u);      /* XXX probably not the right place for this. */
1728         return res;
1729 }
1730
1731 static int dial_exec(struct ast_channel *chan, void *data)
1732 {
1733         struct ast_flags peerflags;
1734
1735         memset(&peerflags, 0, sizeof(peerflags));
1736
1737         return dial_exec_full(chan, data, &peerflags, NULL);
1738 }
1739
1740 static int retrydial_exec(struct ast_channel *chan, void *data)
1741 {
1742         char *announce = NULL, *dialdata = NULL;
1743         const char *context = NULL;
1744         int sleep = 0, loops = 0, res = -1;
1745         struct ast_module_user *u;
1746         struct ast_flags peerflags;
1747         
1748         if (ast_strlen_zero(data)) {
1749                 ast_log(LOG_WARNING, "RetryDial requires an argument!\n");
1750                 return -1;
1751         }       
1752
1753         u = ast_module_user_add(chan);
1754
1755         announce = ast_strdupa(data);
1756
1757         memset(&peerflags, 0, sizeof(peerflags));
1758
1759         if ((dialdata = strchr(announce, '|'))) {
1760                 *dialdata++ = '\0';
1761                 if ((sleep = atoi(dialdata))) {
1762                         sleep *= 1000;
1763                 } else {
1764                         ast_log(LOG_ERROR, "%s requires the numerical argument <sleep>\n",rapp);
1765                         goto done;
1766                 }
1767                 if ((dialdata = strchr(dialdata, '|'))) {
1768                         *dialdata++ = '\0';
1769                         if (!(loops = atoi(dialdata))) {
1770                                 ast_log(LOG_ERROR, "%s requires the numerical argument <loops>\n",rapp);
1771                                 goto done;
1772                         }
1773                 }
1774         }
1775         
1776         if ((dialdata = strchr(dialdata, '|'))) {
1777                 *dialdata++ = '\0';
1778         } else {
1779                 ast_log(LOG_ERROR, "%s requires more arguments\n",rapp);
1780                 goto done;
1781         }
1782                 
1783         if (sleep < 1000)
1784                 sleep = 10000;
1785
1786         if (!loops)
1787                 loops = -1;     /* run forever */
1788         
1789         context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
1790
1791         res = 0;
1792         while (loops) {
1793                 int continue_exec;
1794
1795                 chan->data = "Retrying";
1796                 if (ast_test_flag(chan, AST_FLAG_MOH))
1797                         ast_moh_stop(chan);
1798
1799                 res = dial_exec_full(chan, dialdata, &peerflags, &continue_exec);
1800                 if (continue_exec)
1801                         break;
1802                 if (res == 0) {
1803                         if (ast_test_flag(&peerflags, OPT_DTMF_EXIT)) {
1804                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1805                                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1806                                 if (!res && sleep) {
1807                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1808                                                 ast_moh_start(chan, NULL, NULL);
1809                                         res = ast_waitfordigit(chan, sleep);
1810                                 }
1811                         } else {
1812                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1813                                         res = ast_waitstream(chan, "");
1814                                 if (sleep) {
1815                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1816                                                 ast_moh_start(chan, NULL, NULL);
1817                                         if (!res) 
1818                                                 res = ast_waitfordigit(chan, sleep);
1819                                 }
1820                         }
1821                 }
1822
1823                 if (res < 0)
1824                         break;
1825                 else if (res > 0) { /* Trying to send the call elsewhere (1 digit ext) */
1826                         if (onedigit_goto(chan, context, (char) res, 1)) {
1827                                 res = 0;
1828                                 break;
1829                         }
1830                 }
1831                 loops--;
1832         }
1833         if (loops == 0)
1834                 res = 0;
1835         else if (res == 1)
1836                 res = 0;
1837
1838         if (ast_test_flag(chan, AST_FLAG_MOH))
1839                 ast_moh_stop(chan);
1840  done:
1841         ast_module_user_remove(u);
1842         return res;
1843 }
1844
1845 static int unload_module(void)
1846 {
1847         int res;
1848
1849         res = ast_unregister_application(app);
1850         res |= ast_unregister_application(rapp);
1851
1852         ast_module_user_hangup_all();
1853         
1854         return res;
1855 }
1856
1857 static int load_module(void)
1858 {
1859         int res;
1860
1861         res = ast_register_application(app, dial_exec, synopsis, descrip);
1862         res |= ast_register_application(rapp, retrydial_exec, rsynopsis, rdescrip);
1863         
1864         return res;
1865 }
1866
1867 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialing Application");