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