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