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