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