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