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