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