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