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