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