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