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