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