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