b07f9990e0485e8f130bc9a060555e416fc36be5
[asterisk/asterisk.git] / apps / app_dial.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Trivial application to dial a channel and send an URL on answer
5  * 
6  * Copyright (C) 1999 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdlib.h>
15 #include <errno.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <sys/time.h>
21 #include <sys/signal.h>
22 #include <netinet/in.h>
23
24 #include "asterisk.h"
25
26 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
27
28 #include "asterisk/lock.h"
29 #include "asterisk/file.h"
30 #include "asterisk/logger.h"
31 #include "asterisk/channel.h"
32 #include "asterisk/pbx.h"
33 #include "asterisk/options.h"
34 #include "asterisk/module.h"
35 #include "asterisk/translate.h"
36 #include "asterisk/say.h"
37 #include "asterisk/config.h"
38 #include "asterisk/features.h"
39 #include "asterisk/musiconhold.h"
40 #include "asterisk/callerid.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/app.h"
43 #include "asterisk/causes.h"
44 #include "asterisk/manager.h"
45 #include "asterisk/privacy.h"
46
47 static char *tdesc = "Dialing Application";
48
49 static char *app = "Dial";
50
51 static char *synopsis = "Place a call and connect to the current channel";
52
53 static char *descrip =
54 "  Dial(Technology/resource[&Technology2/resource2...][|timeout][|options][|URL]):\n"
55 "Requests one or more channels and places specified outgoing calls on them.\n"
56 "As soon as a channel answers, the Dial app will answer the originating\n"
57 "channel (if it needs to be answered) and will bridge a call with the channel\n"
58 "which first answered. All other calls placed by the Dial app will be hung up.\n"
59 "If a timeout is not specified, the Dial application will wait indefinitely\n"
60 "until either one of the called channels answers, the user hangs up, or all\n"
61 "channels return busy or error. In general, the dialer will return 0 if it\n"
62 "was unable to place the call, or the timeout expired. However, if all\n"
63 "channels were busy, and there exists an extension with priority n+101 (where\n"
64 "n is the priority of the dialer instance), then it will be the next\n"
65 "executed extension (this allows you to setup different behavior on busy from\n"
66 "no-answer).\n"
67 "  For the Privacy and Screening Modes, the DIALSTATUS variable will be set to DONTCALL, \n"
68 "if the called party chooses to send the calling party to the 'Go Away' script, and \n"
69 "the DIALSTATUS variable will be set to TORTURE, if the called party wants to send the caller to \n"
70 "the TORTURE scripts\n"
71 "  This application returns -1 if the originating channel hangs up, or if the\n"
72 "call is bridged and either of the parties in the bridge terminate the call.\n"
73 "The option string may contain zero or more of the following characters:\n"
74 "      'd' -- allow the calling user to dial a 1 digit extension while waiting for a call to\n"
75 "             be answered exiting to that extension if it exists in the context defined by\n"
76 "             ${EXITCONTEXT} or the current context.\n"
77 "      't' -- allow the called user to transfer the calling user by hitting #.\n"
78 "      'T' -- allow the calling user to transfer the call by hitting #.\n"
79 "      'w' -- allow the called user to write the conversation to disk via app_monitor\n"
80 "      'W' -- allow the calling user to write the conversation to disk via app_monitor\n"
81 "      'f' -- Forces callerid to be set as the extension of the line \n"
82 "             making/redirecting the outgoing call. For example, some PSTNs\n"
83 "             don't allow callerids from other extensions then the ones\n"
84 "             that are assigned to you.\n"
85 "      'o' -- Original (inbound) Caller*ID should be placed on the outbound leg of the call\n" 
86 "             instead of using the destination extension (old style asterisk behavior)\n"
87 "      'r' -- indicate ringing to the calling party, pass no audio until answered.\n"
88 "      'm[(class)]' -- provide hold music to the calling party until answered (optionally\n"
89 "                      with the specified class.\n"
90 "      'M(x[^arg])' -- Executes the macro (x with ^ delim arg list) upon connect of the call.\n"
91 "                      Also, the macro can set the MACRO_RESULT variable to do the following:\n"
92 "                     -- ABORT - Hangup both legs of the call.\n"
93 "                     -- CONGESTION - Behave as if line congestion was encountered.\n"
94 "                     -- BUSY - Behave as if a busy signal was encountered. (n+101)\n"
95 "                     -- CONTINUE - Hangup the called party and continue on in the dialplan.\n"
96 "                     -- GOTO:<context>^<exten>^<priority> - Transfer the call.\n"
97 "      'h' -- allow callee to hang up by hitting *.\n"
98 "      'H' -- allow caller to hang up by hitting *.\n"
99 "      'C' -- reset call detail record for this call.\n"
100 "      'P[(x)]' -- privacy mode, using 'x' as database if provided, or the extension is used if not provided.\n"
101 "      'p' -- screening mode.  Basically Privacy mode without memory.\n"
102 "       'n' -- modifier for screen/privacy mode. No intros are to be saved in the priv-callerintros dir.\n"
103 "       'N' -- modifier for screen/privacy mode. if callerID is present, do not screen the call.\n"
104 "      'g' -- goes on in context if the destination channel hangs up\n"
105 "      'G(context^exten^pri)' -- If the call is answered transfer both parties to the specified exten.\n"
106 "      'A(x)' -- play an announcement to the called party, using x as file\n"
107 "      'S(x)' -- hangup the call after x seconds AFTER called party picked up\n"        
108 "      'D([called][:calling])'  -- Send DTMF strings *after* called party has answered, but before the\n"
109 "             call gets bridged. The 'called' DTMF string is sent to the called party, and the\n"
110 "             'calling' DTMF string is sent to the calling party. Both parameters can be used alone.\n"         
111 "      'L(x[:y][:z])' -- Limit the call to 'x' ms warning when 'y' ms are left\n"
112 "             repeated every 'z' ms) Only 'x' is required, 'y' and 'z' are optional.\n"
113 "             The following special variables are optional:\n"
114 "             * LIMIT_PLAYAUDIO_CALLER    yes|no (default yes)\n"
115 "                                         Play sounds to the caller.\n"
116 "             * LIMIT_PLAYAUDIO_CALLEE    yes|no\n"
117 "                                         Play sounds to the callee.\n"
118 "             * LIMIT_TIMEOUT_FILE        File to play when time is up.\n"
119 "             * LIMIT_CONNECT_FILE        File to play when call begins.\n"
120 "             * LIMIT_WARNING_FILE        File to play as warning if 'y' is defined.\n"
121 "                        'timeleft' is a special sound macro to auto-say the time \n"
122 "                        left and is the default.\n"
123 "       'j' -- Do not jump to n+101 if all of the channels were busy.\n\n"
124 "  In addition to transferring the call, a call may be parked and then picked\n"
125 "up by another user.\n"
126 "  The optional URL will be sent to the called party if the channel supports it.\n"
127 "  If the OUTBOUND_GROUP variable is set, all peer channels created by this\n"
128 "  application will be put into that group (as in SetGroup).\n"
129 "  This application sets the following channel variables upon completion:\n"
130 "      DIALEDTIME    Time from dial to answer\n" 
131 "      ANSWEREDTIME  Time for actual call\n"
132 "      DIALSTATUS    The status of the call as a text string, one of\n"
133 "             CHANUNAVAIL | CONGESTION | NOANSWER | BUSY | ANSWER | CANCEL | DONTCALL | TORTURE\n"
134 "";
135
136 /* RetryDial App by Anthony Minessale II <anthmct@yahoo.com> Jan/2005 */
137 static char *rapp = "RetryDial";
138 static char *rsynopsis = "Place a call, retrying on failure allowing optional exit extension.";
139 static char *rdescrip =
140 "  RetryDial(announce|sleep|loops|Technology/resource[&Technology2/resource2...][|timeout][|options][|URL]):\n"
141 "Attempt to place a call.  If no channel can be reached, play the file defined by 'announce'\n"
142 "waiting 'sleep' seconds to retry the call.  If the specified number of attempts matches \n"
143 "'loops' the call will continue in the dialplan.  If 'loops' is set to 0, the call will retry endlessly.\n\n"
144 "While waiting, a 1 digit extension may be dialed.  If that extension exists in either\n"
145 "the context defined in ${EXITCONTEXT} or the current one, The call will transfer\n"
146 "to that extension immmediately.\n\n"
147 "All arguments after 'loops' are passed directly to the Dial() application.\n"
148 "";
149
150
151 /* We define a customer "local user" structure because we
152    use it not only for keeping track of what is in use but
153    also for keeping track of who we're dialing. */
154
155 #define DIAL_STILLGOING                 (1 << 0)
156 #define DIAL_ALLOWREDIRECT_IN           (1 << 1)
157 #define DIAL_ALLOWREDIRECT_OUT          (1 << 2)
158 #define DIAL_ALLOWDISCONNECT_IN         (1 << 3)
159 #define DIAL_ALLOWDISCONNECT_OUT        (1 << 4)
160 #define DIAL_RINGBACKONLY               (1 << 5)
161 #define DIAL_MUSICONHOLD                (1 << 6)
162 #define DIAL_FORCECALLERID              (1 << 7)
163 #define DIAL_MONITOR_IN                 (1 << 8)
164 #define DIAL_MONITOR_OUT                (1 << 9)
165 #define DIAL_GO_ON                      (1 << 10)
166 #define DIAL_HALT_ON_DTMF               (1 << 11)
167 #define DIAL_PRESERVE_CALLERID          (1 << 12)
168 #define DIAL_NOFORWARDHTML              (1 << 13)
169
170 struct localuser {
171         struct ast_channel *chan;
172         unsigned int flags;
173         int forwards;
174         struct localuser *next;
175 };
176
177 LOCAL_USER_DECL;
178
179 static void hanguptree(struct localuser *outgoing, struct ast_channel *exception)
180 {
181         /* Hang up a tree of stuff */
182         struct localuser *oo;
183         while (outgoing) {
184                 /* Hangup any existing lines we have open */
185                 if (outgoing->chan && (outgoing->chan != exception))
186                         ast_hangup(outgoing->chan);
187                 oo = outgoing;
188                 outgoing=outgoing->next;
189                 free(oo);
190         }
191 }
192
193 #define AST_MAX_FORWARDS   8
194
195 #define AST_MAX_WATCHERS 256
196
197 #define HANDLE_CAUSE(cause, chan) do { \
198         switch(cause) { \
199         case AST_CAUSE_BUSY: \
200                 if (chan->cdr) \
201                         ast_cdr_busy(chan->cdr); \
202                 numbusy++; \
203                 break; \
204         case AST_CAUSE_CONGESTION: \
205                 if (chan->cdr) \
206                         ast_cdr_busy(chan->cdr); \
207                 numcongestion++; \
208                 break; \
209         case AST_CAUSE_UNREGISTERED: \
210                 if (chan->cdr) \
211                         ast_cdr_busy(chan->cdr); \
212                 numnochan++; \
213                 break; \
214         default: \
215                 numnochan++; \
216                 break; \
217         } \
218 } while (0)
219
220
221 static int onedigit_goto(struct ast_channel *chan, char *context, char exten, int pri) 
222 {
223         char rexten[2] = { exten, '\0' };
224
225         if (context) {
226                 if (!ast_goto_if_exists(chan, context, rexten, pri))
227                         return 1;
228         } else {
229                 if (!ast_goto_if_exists(chan, chan->context, rexten, pri))
230                         return 1;
231                 else if (!ast_strlen_zero(chan->macrocontext)) {
232                         if (!ast_goto_if_exists(chan, chan->macrocontext, rexten, pri))
233                                 return 1;
234                 }
235         }
236         return 0;
237 }
238
239
240 static char *get_cid_name(char *name, int namelen, struct ast_channel *chan)
241 {
242         char *context;
243         char *exten;
244         if (!ast_strlen_zero(chan->macrocontext))
245                 context = chan->macrocontext;
246         else
247                 context = chan->context;
248
249         if (!ast_strlen_zero(chan->macroexten))
250                 exten = chan->macroexten;
251         else
252                 exten = chan->exten;
253
254         if (ast_get_hint(NULL, 0, name, namelen, chan, context, exten))
255                 return name;
256         else
257                 return "";
258 }
259
260 static void senddialevent(struct ast_channel *src, struct ast_channel *dst)
261 {
262         manager_event(EVENT_FLAG_CALL, "Dial", 
263                            "Source: %s\r\n"
264                            "Destination: %s\r\n"
265                            "CallerID: %s\r\n"
266                            "CallerIDName: %s\r\n"
267                            "SrcUniqueID: %s\r\n"
268                            "DestUniqueID: %s\r\n",
269                            src->name, dst->name, src->cid.cid_num ? src->cid.cid_num : "<unknown>",
270                            src->cid.cid_name ? src->cid.cid_name : "<unknown>", src->uniqueid,
271                            dst->uniqueid);
272 }
273
274 static struct ast_channel *wait_for_answer(struct ast_channel *in, struct localuser *outgoing, int *to, struct ast_flags *peerflags, int *sentringing, char *status, size_t statussize, int busystart, int nochanstart, int congestionstart, int nojump, int *result)
275 {
276         struct localuser *o;
277         int found;
278         int numlines;
279         int numbusy = busystart;
280         int numcongestion = congestionstart;
281         int numnochan = nochanstart;
282         int prestart = busystart + congestionstart + nochanstart;
283         int cause;
284         int orig = *to;
285         struct ast_frame *f;
286         struct ast_channel *peer = NULL;
287         struct ast_channel *watchers[AST_MAX_WATCHERS];
288         int pos;
289         int single;
290         struct ast_channel *winner;
291         char *context = NULL;
292         char cidname[AST_MAX_EXTENSION];
293
294         single = (outgoing && !outgoing->next && !ast_test_flag(outgoing, DIAL_MUSICONHOLD | DIAL_RINGBACKONLY));
295         
296         if (single) {
297                 /* Turn off hold music, etc */
298                 ast_deactivate_generator(in);
299                 /* If we are calling a single channel, make them compatible for in-band tone purpose */
300                 ast_channel_make_compatible(outgoing->chan, in);
301         }
302         
303         
304         while (*to && !peer) {
305                 o = outgoing;
306                 found = -1;
307                 pos = 1;
308                 numlines = prestart;
309                 watchers[0] = in;
310                 while (o) {
311                         /* Keep track of important channels */
312                         if (ast_test_flag(o, DIAL_STILLGOING) && o->chan) {
313                                 watchers[pos++] = o->chan;
314                                 found = 1;
315                         }
316                         o = o->next;
317                         numlines++;
318                 }
319                 if (found < 0) {
320                         if (numlines == (numbusy + numcongestion + numnochan)) {
321                                 if (option_verbose > 2)
322                                         ast_verbose( VERBOSE_PREFIX_2 "Everyone is busy/congested at this time (%d:%d/%d/%d)\n", numlines, numbusy, numcongestion, numnochan);
323                                 if (numbusy)
324                                         strcpy(status, "BUSY"); 
325                                 else if (numcongestion)
326                                         strcpy(status, "CONGESTION");
327                                 else if (numnochan)
328                                         strcpy(status, "CHANUNAVAIL");
329                                 /* See if there is a special busy message */
330                                 if (!nojump && ast_exists_extension(in, in->context, in->exten, in->priority + 101, in->cid.cid_num)) 
331                                         in->priority+=100;
332                         } else {
333                                 if (option_verbose > 2)
334                                         ast_verbose( VERBOSE_PREFIX_2 "No one is available to answer at this time (%d:%d/%d/%d)\n", numlines, numbusy, numcongestion, numnochan);
335                         }
336                         *to = 0;
337                         return NULL;
338                 }
339                 winner = ast_waitfor_n(watchers, pos, to);
340                 o = outgoing;
341                 while (o) {
342                         if (ast_test_flag(o, DIAL_STILLGOING) && o->chan && (o->chan->_state == AST_STATE_UP)) {
343                                 if (!peer) {
344                                         if (option_verbose > 2)
345                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
346                                         peer = o->chan;
347                                         ast_copy_flags(peerflags, o, DIAL_ALLOWREDIRECT_IN|DIAL_ALLOWREDIRECT_OUT|DIAL_ALLOWDISCONNECT_IN|DIAL_ALLOWDISCONNECT_OUT|DIAL_NOFORWARDHTML);
348                                 }
349                         } else if (o->chan && (o->chan == winner)) {
350                                 if (!ast_strlen_zero(o->chan->call_forward)) {
351                                         char tmpchan[256]="";
352                                         char *stuff;
353                                         char *tech;
354                                         ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
355                                         if ((stuff = strchr(tmpchan, '/'))) {
356                                                 *stuff = '\0';
357                                                 stuff++;
358                                                 tech = tmpchan;
359                                         } else {
360                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
361                                                 stuff = tmpchan;
362                                                 tech = "Local";
363                                         }
364                                         /* Before processing channel, go ahead and check for forwarding */
365                                         o->forwards++;
366                                         if (o->forwards < AST_MAX_FORWARDS) {
367                                                 if (option_verbose > 2)
368                                                         ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
369                                                 /* Setup parameters */
370                                                 o->chan = ast_request(tech, in->nativeformats, stuff, &cause);
371                                                 if (!o->chan)
372                                                         ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s' (cause = %d)\n", tech, stuff, cause);
373                                         } else {
374                                                 if (option_verbose > 2)
375                                                         ast_verbose(VERBOSE_PREFIX_3 "Too many forwards from %s\n", o->chan->name);
376                                                 cause = AST_CAUSE_CONGESTION;
377                                                 o->chan = NULL;
378                                         }
379                                         if (!o->chan) {
380                                                 ast_clear_flag(o, DIAL_STILLGOING);     
381                                                 HANDLE_CAUSE(cause, in);
382                                         } else {
383                                                 if (o->chan->cid.cid_num)
384                                                         free(o->chan->cid.cid_num);
385                                                 o->chan->cid.cid_num = NULL;
386                                                 if (o->chan->cid.cid_name)
387                                                         free(o->chan->cid.cid_name);
388                                                 o->chan->cid.cid_name = NULL;
389
390                                                 if (ast_test_flag(o, DIAL_FORCECALLERID)) {
391                                                         char *newcid = NULL;
392
393                                                         if (strlen(in->macroexten))
394                                                                 newcid = in->macroexten;
395                                                         else
396                                                                 newcid = in->exten;
397                                                         o->chan->cid.cid_num = strdup(newcid);
398                                                         ast_copy_string(o->chan->accountcode, winner->accountcode, sizeof(o->chan->accountcode));
399                                                         o->chan->cdrflags = winner->cdrflags;
400                                                         if (!o->chan->cid.cid_num)
401                                                                 ast_log(LOG_WARNING, "Out of memory\n");
402                                                 } else {
403                                                         if (in->cid.cid_num) {
404                                                                 o->chan->cid.cid_num = strdup(in->cid.cid_num);
405                                                                 if (!o->chan->cid.cid_num)
406                                                                         ast_log(LOG_WARNING, "Out of memory\n");        
407                                                         }
408                                                         if (in->cid.cid_name) {
409                                                                 o->chan->cid.cid_name = strdup(in->cid.cid_name);
410                                                                 if (!o->chan->cid.cid_name)
411                                                                         ast_log(LOG_WARNING, "Out of memory\n");        
412                                                         }
413                                                         ast_copy_string(o->chan->accountcode, in->accountcode, sizeof(o->chan->accountcode));
414                                                         o->chan->cdrflags = in->cdrflags;
415                                                 }
416
417                                                 if (in->cid.cid_ani) {
418                                                         if (o->chan->cid.cid_ani)
419                                                                 free(o->chan->cid.cid_ani);
420                                                         o->chan->cid.cid_ani = malloc(strlen(in->cid.cid_ani) + 1);
421                                                         if (o->chan->cid.cid_ani)
422                                                                 ast_copy_string(o->chan->cid.cid_ani, in->cid.cid_ani, sizeof(o->chan->cid.cid_ani));
423                                                         else
424                                                                 ast_log(LOG_WARNING, "Out of memory\n");
425                                                 }
426                                                 if (o->chan->cid.cid_rdnis) 
427                                                         free(o->chan->cid.cid_rdnis);
428                                                 if (!ast_strlen_zero(in->macroexten))
429                                                         o->chan->cid.cid_rdnis = strdup(in->macroexten);
430                                                 else
431                                                         o->chan->cid.cid_rdnis = strdup(in->exten);
432                                                 if (ast_call(o->chan, tmpchan, 0)) {
433                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
434                                                         ast_clear_flag(o, DIAL_STILLGOING);     
435                                                         ast_hangup(o->chan);
436                                                         o->chan = NULL;
437                                                         numnochan++;
438                                                 } else {
439                                                         senddialevent(in, o->chan);
440                                                         /* After calling, set callerid to extension */
441                                                         if (!ast_test_flag(peerflags, DIAL_PRESERVE_CALLERID))
442                                                                 ast_set_callerid(o->chan, ast_strlen_zero(in->macroexten) ? in->exten : in->macroexten, get_cid_name(cidname, sizeof(cidname), in), NULL);
443                                                 }
444                                         }
445                                         /* Hangup the original channel now, in case we needed it */
446                                         ast_hangup(winner);
447                                         continue;
448                                 }
449                                 f = ast_read(winner);
450                                 if (f) {
451                                         if (f->frametype == AST_FRAME_CONTROL) {
452                                                 switch(f->subclass) {
453                                             case AST_CONTROL_ANSWER:
454                                                         /* This is our guy if someone answered. */
455                                                         if (!peer) {
456                                                                 if (option_verbose > 2)
457                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
458                                                                 peer = o->chan;
459                                                                 ast_copy_flags(peerflags, o, DIAL_ALLOWREDIRECT_IN|DIAL_ALLOWREDIRECT_OUT|DIAL_ALLOWDISCONNECT_IN|DIAL_ALLOWDISCONNECT_OUT|DIAL_NOFORWARDHTML);
460                                                         }
461                                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */
462                                                         in->hangupcause = AST_CAUSE_NORMAL_CLEARING;
463                                                         o->chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
464                                                         break;
465                                                 case AST_CONTROL_BUSY:
466                                                         if (option_verbose > 2)
467                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
468                                                         in->hangupcause = o->chan->hangupcause;
469                                                         ast_hangup(o->chan);
470                                                         o->chan = NULL;
471                                                         ast_clear_flag(o, DIAL_STILLGOING);     
472                                                         HANDLE_CAUSE(AST_CAUSE_BUSY, in);
473                                                         break;
474                                                 case AST_CONTROL_CONGESTION:
475                                                         if (option_verbose > 2)
476                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
477                                                         in->hangupcause = o->chan->hangupcause;
478                                                         ast_hangup(o->chan);
479                                                         o->chan = NULL;
480                                                         ast_clear_flag(o, DIAL_STILLGOING);
481                                                         HANDLE_CAUSE(AST_CAUSE_CONGESTION, in);
482                                                         break;
483                                                 case AST_CONTROL_RINGING:
484                                                         if (option_verbose > 2)
485                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
486                                                         if (!(*sentringing) && !ast_test_flag(outgoing, DIAL_MUSICONHOLD)) {
487                                                                 ast_indicate(in, AST_CONTROL_RINGING);
488                                                                 (*sentringing)++;
489                                                         }
490                                                         break;
491                                                 case AST_CONTROL_PROGRESS:
492                                                         if (option_verbose > 2)
493                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s is making progress passing it to %s\n", o->chan->name,in->name);
494                                                         if (!ast_test_flag(outgoing, DIAL_RINGBACKONLY))
495                                                                 ast_indicate(in, AST_CONTROL_PROGRESS);
496                                                         break;
497                                                 case AST_CONTROL_PROCEEDING:
498                                                         if (option_verbose > 2)
499                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s is proceeding passing it to %s\n", o->chan->name,in->name);
500                                                         if (!ast_test_flag(outgoing, DIAL_RINGBACKONLY))
501                                                                 ast_indicate(in, AST_CONTROL_PROCEEDING);
502                                                         break;
503                                                 case AST_CONTROL_HOLD:
504                                                         if (option_verbose > 2)
505                                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s placed on hold\n", o->chan->name);
506                                                         ast_indicate(in, AST_CONTROL_HOLD);
507                                                         break;
508                                                 case AST_CONTROL_UNHOLD:
509                                                         if (option_verbose > 2)
510                                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s left from hold\n", o->chan->name);
511                                                         ast_indicate(in, AST_CONTROL_UNHOLD);
512                                                         break;
513                                                 case AST_CONTROL_OFFHOOK:
514                                                 case AST_CONTROL_FLASH:
515                                                         /* Ignore going off hook and flash */
516                                                         break;
517                                                 case -1:
518                                                         if (!ast_test_flag(outgoing, DIAL_RINGBACKONLY | DIAL_MUSICONHOLD)) {
519                                                                 if (option_verbose > 2)
520                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s stopped sounds\n", o->chan->name);
521                                                                 ast_indicate(in, -1);
522                                                                 (*sentringing) = 0;
523                                                         }
524                                                         break;
525                                                 default:
526                                                         ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
527                                                 }
528                                         } else if (single && (f->frametype == AST_FRAME_VOICE) && 
529                                                                 !(ast_test_flag(outgoing, DIAL_RINGBACKONLY|DIAL_MUSICONHOLD))) {
530                                                 if (ast_write(in, f)) 
531                                                         ast_log(LOG_DEBUG, "Unable to forward frame\n");
532                                         } else if (single && (f->frametype == AST_FRAME_IMAGE) && 
533                                                                 !(ast_test_flag(outgoing, DIAL_RINGBACKONLY|DIAL_MUSICONHOLD))) {
534                                                 if (ast_write(in, f))
535                                                         ast_log(LOG_DEBUG, "Unable to forward image\n");
536                                         } else if (single && (f->frametype == AST_FRAME_TEXT) && 
537                                                                 !(ast_test_flag(outgoing, DIAL_RINGBACKONLY|DIAL_MUSICONHOLD))) {
538                                                 if (ast_write(in, f))
539                                                         ast_log(LOG_DEBUG, "Unable to text\n");
540                                         } else if (single && (f->frametype == AST_FRAME_HTML) && !ast_test_flag(outgoing, DIAL_NOFORWARDHTML))
541                                                 ast_channel_sendhtml(in, f->subclass, f->data, f->datalen);
542
543                                         ast_frfree(f);
544                                 } else {
545                                         in->hangupcause = o->chan->hangupcause;
546                                         ast_hangup(o->chan);
547                                         o->chan = NULL;
548                                         ast_clear_flag(o, DIAL_STILLGOING);
549                                 }
550                         }
551                         o = o->next;
552                 }
553                 if (winner == in) {
554                         f = ast_read(in);
555 #if 0
556                         if (f && (f->frametype != AST_FRAME_VOICE))
557                                         printf("Frame type: %d, %d\n", f->frametype, f->subclass);
558                         else if (!f || (f->frametype != AST_FRAME_VOICE))
559                                 printf("Hangup received on %s\n", in->name);
560 #endif
561                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
562                                 /* Got hung up */
563                                 *to=-1;
564                                 strcpy(status, "CANCEL");
565                                 if (f)
566                                         ast_frfree(f);
567                                 return NULL;
568                         }
569
570                         if (f && (f->frametype == AST_FRAME_DTMF)) {
571                                 if (ast_test_flag(peerflags, DIAL_HALT_ON_DTMF)) {
572                                         context = pbx_builtin_getvar_helper(in, "EXITCONTEXT");
573                                         if (onedigit_goto(in, context, (char) f->subclass, 1)) {
574                                                 if (option_verbose > 3)
575                                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
576                                                 *to=0;
577                                                 *result = f->subclass;
578                                                 strcpy(status, "CANCEL");
579                                                 ast_frfree(f);
580                                                 return NULL;
581                                         }
582                                 }
583
584                                 if (ast_test_flag(peerflags, DIAL_ALLOWDISCONNECT_OUT) && 
585                                                   (f->subclass == '*')) { /* hmm it it not guarenteed to be '*' anymore. */
586                                         if (option_verbose > 3)
587                                                 ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
588                                         *to=0;
589                                         strcpy(status, "CANCEL");
590                                         ast_frfree(f);
591                                         return NULL;
592                                 }
593                         }
594
595                         /* Forward HTML stuff */
596                         if (single && f && (f->frametype == AST_FRAME_HTML) && !ast_test_flag(outgoing, DIAL_NOFORWARDHTML)) 
597                                 ast_channel_sendhtml(outgoing->chan, f->subclass, f->data, f->datalen);
598                         
599
600                         if (single && ((f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_DTMF)))  {
601                                 if (ast_write(outgoing->chan, f))
602                                         ast_log(LOG_WARNING, "Unable to forward voice\n");
603                                 ast_frfree(f);
604                         }
605                 }
606                 if (!*to && (option_verbose > 2))
607                         ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
608         }
609
610         return peer;
611         
612 }
613
614
615 static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags *peerflags)
616 {
617         int res=-1;
618         struct localuser *u;
619         char *info, *peers, *timeout, *tech, *number, *rest, *cur;
620         char  privdb[256] = "", *s;
621         char  privcid[256] = "";
622         char privintro[1024];
623         char  announcemsg[256] = "", *ann;
624         struct localuser *outgoing=NULL, *tmp;
625         struct ast_channel *peer;
626         int to;
627         int hasmacro = 0;
628         int privacy=0;
629         int screen=0;
630         int no_save_intros = 0;
631         int no_screen_callerid = 0;
632         int announce=0;
633         int resetcdr=0;
634         int numbusy = 0;
635         int numcongestion = 0;
636         int numnochan = 0;
637         int cause;
638         char numsubst[AST_MAX_EXTENSION];
639         char restofit[AST_MAX_EXTENSION];
640         char cidname[AST_MAX_EXTENSION];
641         char *transfer = NULL;
642         char *newnum;
643         char *l;
644         char *url=NULL; /* JDG */
645         int privdb_val=0;
646         unsigned int calldurationlimit=0;
647         char *cdl;
648         time_t now;
649         struct ast_bridge_config config;
650         long timelimit = 0;
651         long play_warning = 0;
652         long warning_freq=0;
653         char *warning_sound=NULL;
654         char *end_sound=NULL;
655         char *start_sound=NULL;
656         char *limitptr;
657         char limitdata[256];
658         char *sdtmfptr;
659         char *dtmfcalled=NULL, *dtmfcalling=NULL;
660         char *stack,*var;
661         char *mac = NULL, *macroname = NULL;
662         char status[256]="";
663         char toast[80];
664         int play_to_caller=0,play_to_callee=0;
665         int playargs=0, sentringing=0, moh=0;
666         char *mohclass = NULL;
667         char *outbound_group = NULL;
668         char *macro_result = NULL, *macro_transfer_dest = NULL;
669         int digit = 0, result = 0;
670         time_t start_time, answer_time, end_time;
671         struct ast_app *app = NULL;
672         char *dblgoto = NULL;
673         int nojump = 0;
674
675         if (!data) {
676                 ast_log(LOG_WARNING, "Dial requires an argument (technology1/number1&technology2/number2...|optional timeout|options)\n");
677                 return -1;
678         }
679
680         if (!(info = ast_strdupa(data))) {
681                 ast_log(LOG_WARNING, "Unable to dupe data :(\n");
682                 return -1;
683         }
684         LOCAL_USER_ADD(u);
685         
686         peers = info;
687         if (peers) {
688                 
689                 timeout = strchr(info, '|');
690                 if (timeout) {
691                         *timeout = '\0';
692                         timeout++;
693                         transfer = strchr(timeout, '|');
694                         if (transfer) {
695                                 *transfer = '\0';
696                                 transfer++;
697                                 /* JDG */
698                                 url = strchr(transfer, '|');
699                                 if (url) {
700                                         *url = '\0';
701                                         url++;
702                                         if (option_debug)
703                                                 ast_log(LOG_DEBUG, "DIAL WITH URL=%s_\n", url);
704                                 } else 
705                                         if (option_debug) {
706                                                 ast_log(LOG_DEBUG, "SIMPLE DIAL (NO URL)\n");
707                                         }
708                                 /* /JDG */
709                         }
710                 }
711         } else
712                 timeout = NULL;
713         if (!peers || ast_strlen_zero(peers)) {
714                 ast_log(LOG_WARNING, "Dial argument takes format (technology1/number1&technology2/number2...|optional timeout)\n");
715                 goto out;
716         }
717         
718
719         if (transfer) {
720
721                 /* Extract call duration limit */
722                 if ((cdl = strstr(transfer, "S("))) {
723                         calldurationlimit=atoi(cdl+2);
724                         if (option_verbose > 2)
725                                 ast_verbose(VERBOSE_PREFIX_3 "Setting call duration limit to %d seconds.\n",calldurationlimit);                 
726                 } 
727
728                 /* Extract DTMF strings to send upon successfull connect */
729                 if ((sdtmfptr = strstr(transfer, "D("))) {
730                         dtmfcalled = ast_strdupa(sdtmfptr + 2);
731                         dtmfcalling = strchr(dtmfcalled, ')');
732                         if (dtmfcalling)
733                                 *dtmfcalling = '\0';
734                         dtmfcalling = strchr(dtmfcalled, ':');
735                         if (dtmfcalling) {
736                                 *dtmfcalling = '\0';
737                                 dtmfcalling++;
738                         }                               
739                         /* Overwrite with X's what was the sdtmf info */
740                         while (*sdtmfptr && (*sdtmfptr != ')')) 
741                                 *(sdtmfptr++) = 'X';
742                         if (*sdtmfptr)
743                                 *sdtmfptr = 'X';
744                         else 
745                                 ast_log(LOG_WARNING, "D( Data lacking trailing ')'\n");
746                 }
747   
748                 /* XXX LIMIT SUPPORT */
749                 if ((limitptr = strstr(transfer, "L("))) {
750                         ast_copy_string(limitdata, limitptr + 2, sizeof(limitdata));
751                         /* Overwrite with X's what was the limit info */
752                         while (*limitptr && (*limitptr != ')')) 
753                                 *(limitptr++) = 'X';
754                         if (*limitptr)
755                                 *limitptr = 'X';
756                         /* Now find the end */
757                         limitptr = strchr(limitdata, ')');
758                         if (limitptr)
759                                 *limitptr = '\0';
760                         else
761                                 ast_log(LOG_WARNING, "Limit Data lacking trailing ')'\n");
762
763                         var = pbx_builtin_getvar_helper(chan,"LIMIT_PLAYAUDIO_CALLER");
764                         play_to_caller = var ? ast_true(var) : 1;
765                   
766                         var = pbx_builtin_getvar_helper(chan,"LIMIT_PLAYAUDIO_CALLEE");
767                         play_to_callee = var ? ast_true(var) : 0;
768                   
769                         if (!play_to_caller && !play_to_callee)
770                                 play_to_caller=1;
771                   
772                         var = pbx_builtin_getvar_helper(chan,"LIMIT_WARNING_FILE");
773                         warning_sound = var ? var : "timeleft";
774
775                         var = pbx_builtin_getvar_helper(chan,"LIMIT_TIMEOUT_FILE");
776                         end_sound = var ? var : NULL;
777
778                         var = pbx_builtin_getvar_helper(chan,"LIMIT_CONNECT_FILE");
779                         start_sound = var ? var : NULL;
780
781                         var=stack=limitdata;
782
783                         var = strsep(&stack, ":");
784                         if (var) {
785                                 timelimit = atol(var);
786                                 playargs++;
787                                 var = strsep(&stack, ":");
788                                 if (var) {
789                                         play_warning = atol(var);
790                                         playargs++;
791                                         var = strsep(&stack, ":");
792                                         if (var) {
793                                                 warning_freq = atol(var);
794                                                 playargs++;
795                                         }
796                                 }
797                         }
798                   
799                         if (!timelimit) {
800                                 timelimit=play_to_caller=play_to_callee=play_warning=warning_freq=0;
801                                 warning_sound=NULL;
802                         }
803                         /* undo effect of S(x) in case they are both used */
804                         calldurationlimit=0; 
805                         /* more efficient do it like S(x) does since no advanced opts*/
806                         if (!play_warning && !start_sound && !end_sound && timelimit) { 
807                                 calldurationlimit=timelimit/1000;
808                                 timelimit=play_to_caller=play_to_callee=play_warning=warning_freq=0;
809                         } else if (option_verbose > 2) {
810                                 ast_verbose(VERBOSE_PREFIX_3"Limit Data:\n");
811                                 ast_verbose(VERBOSE_PREFIX_3"timelimit=%ld\n",timelimit);
812                                 ast_verbose(VERBOSE_PREFIX_3"play_warning=%ld\n",play_warning);
813                                 ast_verbose(VERBOSE_PREFIX_3"play_to_caller=%s\n",play_to_caller ? "yes" : "no");
814                                 ast_verbose(VERBOSE_PREFIX_3"play_to_callee=%s\n",play_to_callee ? "yes" : "no");
815                                 ast_verbose(VERBOSE_PREFIX_3"warning_freq=%ld\n",warning_freq);
816                                 ast_verbose(VERBOSE_PREFIX_3"start_sound=%s\n",start_sound ? start_sound : "UNDEF");
817                                 ast_verbose(VERBOSE_PREFIX_3"warning_sound=%s\n",warning_sound ? warning_sound : "UNDEF");
818                                 ast_verbose(VERBOSE_PREFIX_3"end_sound=%s\n",end_sound ? end_sound : "UNDEF");
819                         }
820                 }
821                 
822                 /* XXX ANNOUNCE SUPPORT */
823                 if ((ann = strstr(transfer, "A("))) {
824                         announce = 1;
825                         ast_copy_string(announcemsg, ann + 2, sizeof(announcemsg));
826                         /* Overwrite with X's what was the announce info */
827                         while (*ann && (*ann != ')')) 
828                                 *(ann++) = 'X';
829                         if (*ann)
830                                 *ann = 'X';
831                         /* Now find the end of the announce */
832                         ann = strchr(announcemsg, ')');
833                         if (ann)
834                                 *ann = '\0';
835                         else {
836                                 ast_log(LOG_WARNING, "Transfer with Announce spec lacking trailing ')'\n");
837                                 announce = 0;
838                         }
839                 }
840
841                 /* Get the goto from the dial option string */
842                 if ((mac = strstr(transfer, "G("))) {
843
844
845                         dblgoto = ast_strdupa(mac + 2);
846                         while (*mac && (*mac != ')'))
847                                 *(mac++) = 'X';
848                         if (*mac) {
849                                 *mac = 'X';
850                                 mac = strchr(dblgoto, ')');
851                                 if (mac)
852                                         *mac = '\0';
853                                 else {
854                                         ast_log(LOG_WARNING, "Goto flag set without trailing ')'\n");
855                                         dblgoto = NULL;
856                                 }
857                         } else {
858                                 ast_log(LOG_WARNING, "Could not find exten to which we should jump.\n");
859                                 dblgoto = NULL;
860                         }
861                 }
862
863                 /* Get the macroname from the dial option string */
864                 if ((mac = strstr(transfer, "M("))) {
865                         hasmacro = 1;
866                         macroname = ast_strdupa(mac + 2);
867                         while (*mac && (*mac != ')'))
868                                 *(mac++) = 'X';
869                         if (*mac) {
870                                 *mac = 'X';
871                                 mac = strchr(macroname, ')');
872                                 if (mac)
873                                         *mac = '\0';
874                                 else {
875                                         ast_log(LOG_WARNING, "Macro flag set without trailing ')'\n");
876                                         hasmacro = 0;
877                                 }
878                         } else {
879                                 ast_log(LOG_WARNING, "Could not find macro to which we should jump.\n");
880                                 hasmacro = 0;
881                         }
882                 }
883                 /* Get music on hold class */
884                 if ((mac = strstr(transfer, "m("))) {
885                         mohclass = ast_strdupa(mac + 2);
886                         mac++; /* Leave the "m" in the string */
887                         while (*mac && (*mac != ')'))
888                                 *(mac++) = 'X';
889                         if (*mac) {
890                                 *mac = 'X';
891                                 mac = strchr(mohclass, ')');
892                                 if (mac)
893                                         *mac = '\0';
894                                 else {
895                                         ast_log(LOG_WARNING, "Music on hold class specified without trailing ')'\n");
896                                         mohclass = NULL;
897                                 }
898                         } else {
899                                 ast_log(LOG_WARNING, "Could not find music on hold class to use, assuming default.\n");
900                                 mohclass=NULL;
901                         }
902                 }
903                 /* Extract privacy info from transfer */
904                 if ((s = strstr(transfer, "P("))) {
905                         privacy = 1;
906                         ast_copy_string(privdb, s + 2, sizeof(privdb));
907                         /* Overwrite with X's what was the privacy info */
908                         while (*s && (*s != ')')) 
909                                 *(s++) = 'X';
910                         if (*s)
911                                 *s = 'X';
912                         /* Now find the end of the privdb */
913                         s = strchr(privdb, ')');
914                         if (s)
915                                 *s = '\0';
916                         else {
917                                 ast_log(LOG_WARNING, "Transfer with privacy lacking trailing ')'\n");
918                                 privacy = 0;
919                         }
920                 } else if (strchr(transfer, 'P')) {
921                         /* No specified privdb */
922                         privacy = 1;
923                 } else if (strchr(transfer, 'p')) {
924                         screen = 1;
925                 } else if (strchr(transfer, 'C')) {
926                         resetcdr = 1;
927                 } else if (strchr(transfer, 'j')) {
928                         nojump = 1;
929                 }
930                 if (strchr(transfer, 'n')) {
931                         no_save_intros = 1;
932                 } 
933                 if (strchr(transfer, 'N')) {
934                         no_screen_callerid = 1;
935                 }
936         }
937         if (resetcdr && chan->cdr)
938                 ast_cdr_reset(chan->cdr, 0);
939         if (ast_strlen_zero(privdb) && privacy) {
940                 /* If privdb is not specified and we are using privacy, copy from extension */
941                 ast_copy_string(privdb, chan->exten, sizeof(privdb));
942         }
943         if (privacy || screen) {
944                 char callerid[60];
945
946                 l = chan->cid.cid_num;
947                 if (l && !ast_strlen_zero(l)) {
948                         ast_shrink_phone_number(l);
949                         if( privacy ) {
950                                 if (option_verbose > 2)
951                                         ast_verbose( VERBOSE_PREFIX_3  "Privacy DB is '%s', privacy is %d, clid is '%s'\n", privdb, privacy, l);
952                                 privdb_val = ast_privacy_check(privdb, l);
953                         }
954                         else {
955                                 if (option_verbose > 2)
956                                         ast_verbose( VERBOSE_PREFIX_3  "Privacy Screening, clid is '%s'\n", l);
957                                 privdb_val = AST_PRIVACY_UNKNOWN;
958                         }
959                 } else {
960                         char *tnam, *tn2;
961
962                         tnam = ast_strdupa(chan->name);
963                         /* clean the channel name so slashes don't try to end up in disk file name */
964                         for(tn2 = tnam; *tn2; tn2++) {
965                                 if( *tn2=='/')
966                                         *tn2 = '=';  /* any other chars to be afraid of? */
967                         }
968                         if (option_verbose > 2)
969                                 ast_verbose( VERBOSE_PREFIX_3  "Privacy-- callerid is empty\n");
970
971                         snprintf(callerid, sizeof(callerid), "NOCALLERID_%s%s", chan->exten, tnam);
972                         l = callerid;
973                         privdb_val = AST_PRIVACY_UNKNOWN;
974                 }
975                 
976                 ast_copy_string(privcid,l,sizeof(privcid));
977
978                 if( strncmp(privcid,"NOCALLERID",10) != 0 && no_screen_callerid ) { /* if callerid is set, and no_screen_callerid is set also */  
979                         if (option_verbose > 2)
980                                 ast_verbose( VERBOSE_PREFIX_3  "CallerID set (%s); N option set; Screening should be off\n", privcid);
981                         privdb_val = AST_PRIVACY_ALLOW;
982                 }
983                 else if( no_screen_callerid && strncmp(privcid,"NOCALLERID",10) == 0 ) {
984                         if (option_verbose > 2)
985                                 ast_verbose( VERBOSE_PREFIX_3  "CallerID blank; N option set; Screening should happen; dbval is %d\n", privdb_val);
986                 }
987                 
988                 if( privdb_val == AST_PRIVACY_DENY ) {
989                         ast_verbose( VERBOSE_PREFIX_3  "Privacy DB reports PRIVACY_DENY for this callerid. Dial reports unavailable\n");
990                         res=0;
991                         goto out;
992                 }
993                 else if( privdb_val == AST_PRIVACY_KILL ) {
994                         if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 201, chan->cid.cid_num)) 
995                                 chan->priority+=200;
996
997                         res = 0;
998                         goto out; /* Is this right? */
999                 }
1000                 else if( privdb_val == AST_PRIVACY_TORTURE ) {
1001                         if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 301, chan->cid.cid_num)) 
1002                                 chan->priority+=300;
1003                         res = 0;
1004                         goto out; /* is this right??? */
1005
1006                 }
1007                 else if( privdb_val == AST_PRIVACY_UNKNOWN ) {
1008                         /* Get the user's intro, store it in priv-callerintros/$CID, 
1009                            unless it is already there-- this should be done before the 
1010                            call is actually dialed  */
1011
1012                         /* make sure the priv-callerintros dir exists? */
1013
1014                         snprintf(privintro,sizeof(privintro),"priv-callerintros/%s", privcid);
1015                         if( ast_fileexists(privintro,NULL,NULL ) > 0 && strncmp(privcid,"NOCALLERID",10) != 0) {
1016                                 /* the DELUX version of this code would allow this caller the
1017                                    option to hear and retape their previously recorded intro.
1018                                 */
1019                         }
1020                         else {
1021                                 int duration; /* for feedback from play_and_wait */
1022                                 /* the file doesn't exist yet. Let the caller submit his
1023                                    vocal intro for posterity */
1024                                 /* priv-recordintro script:
1025
1026                                    "At the tone, please say your name:"
1027
1028                                 */
1029                                 ast_play_and_record(chan, "priv-recordintro", privintro, 4, "gsm", &duration, 128, 2000, 0);  /* NOTE: I've reduced the total time to 4 sec */
1030                                                                                                                         /* don't think we'll need a lock removed, we took care of
1031                                                                                                                            conflicts by naming the privintro file */
1032                         }
1033                 }
1034         }
1035
1036         /* If a channel group has been specified, get it for use when we create peer channels */
1037         outbound_group = pbx_builtin_getvar_helper(chan, "OUTBOUND_GROUP");
1038
1039         cur = peers;
1040         do {
1041                 /* Remember where to start next time */
1042                 rest = strchr(cur, '&');
1043                 if (rest) {
1044                         *rest = 0;
1045                         rest++;
1046                 }
1047                 /* Get a technology/[device:]number pair */
1048                 tech = cur;
1049                 number = strchr(tech, '/');
1050                 if (!number) {
1051                         ast_log(LOG_WARNING, "Dial argument takes format (technology1/[device:]number1&technology2/[device:]number2...|optional timeout)\n");
1052                         goto out;
1053                 }
1054                 *number = '\0';
1055                 number++;
1056                 tmp = malloc(sizeof(struct localuser));
1057                 if (!tmp) {
1058                         ast_log(LOG_WARNING, "Out of memory\n");
1059                         goto out;
1060                 }
1061                 memset(tmp, 0, sizeof(struct localuser));
1062                 if (transfer) {
1063                         ast_set2_flag(tmp, strchr(transfer, 't'), DIAL_ALLOWREDIRECT_IN);
1064                         ast_set2_flag(tmp, strchr(transfer, 'T'), DIAL_ALLOWREDIRECT_OUT);
1065                         ast_set2_flag(tmp, strchr(transfer, 'r'), DIAL_RINGBACKONLY);   
1066                         ast_set2_flag(tmp, strchr(transfer, 'm'), DIAL_MUSICONHOLD);    
1067                         ast_set2_flag(tmp, strchr(transfer, 'H'), DIAL_ALLOWDISCONNECT_OUT);    
1068                         ast_set2_flag(peerflags, strchr(transfer, 'H'), DIAL_ALLOWDISCONNECT_OUT);      
1069                         ast_set2_flag(tmp, strchr(transfer, 'h'), DIAL_ALLOWDISCONNECT_IN);
1070                         ast_set2_flag(peerflags, strchr(transfer, 'h'), DIAL_ALLOWDISCONNECT_IN);
1071                         ast_set2_flag(tmp, strchr(transfer, 'f'), DIAL_FORCECALLERID);  
1072                         ast_set2_flag(tmp, url, DIAL_NOFORWARDHTML);    
1073                         ast_set2_flag(peerflags, strchr(transfer, 'w'), DIAL_MONITOR_IN);       
1074                         ast_set2_flag(peerflags, strchr(transfer, 'W'), DIAL_MONITOR_OUT);      
1075                         ast_set2_flag(peerflags, strchr(transfer, 'd'), DIAL_HALT_ON_DTMF);     
1076                         ast_set2_flag(peerflags, strchr(transfer, 'g'), DIAL_GO_ON);    
1077                         ast_set2_flag(peerflags, strchr(transfer, 'o'), DIAL_PRESERVE_CALLERID);        
1078                 }
1079                 ast_copy_string(numsubst, number, sizeof(numsubst));
1080                 /* If we're dialing by extension, look at the extension to know what to dial */
1081                 if ((newnum = strstr(numsubst, "BYEXTENSION"))) {
1082                         /* strlen("BYEXTENSION") == 11 */
1083                         ast_copy_string(restofit, newnum + 11, sizeof(restofit));
1084                         snprintf(newnum, sizeof(numsubst) - (newnum - numsubst), "%s%s", chan->exten,restofit);
1085                         if (option_debug)
1086                                 ast_log(LOG_DEBUG, "Dialing by extension %s\n", numsubst);
1087                 }
1088                 /* Request the peer */
1089                 tmp->chan = ast_request(tech, chan->nativeformats, numsubst, &cause);
1090                 if (!tmp->chan) {
1091                         /* If we can't, just go on to the next call */
1092                         ast_log(LOG_NOTICE, "Unable to create channel of type '%s' (cause %d - %s)\n", tech, cause, ast_cause2str(cause));
1093                         HANDLE_CAUSE(cause, chan);
1094                         cur = rest;
1095                         continue;
1096                 }
1097                 pbx_builtin_setvar_helper(tmp->chan, "DIALEDPEERNUMBER", numsubst);
1098                 if (!ast_strlen_zero(tmp->chan->call_forward)) {
1099                         char tmpchan[256]="";
1100                         char *stuff;
1101                         char *tech;
1102                         ast_copy_string(tmpchan, tmp->chan->call_forward, sizeof(tmpchan));
1103                         if ((stuff = strchr(tmpchan, '/'))) {
1104                                 *stuff = '\0';
1105                                 stuff++;
1106                                 tech = tmpchan;
1107                         } else {
1108                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", tmp->chan->call_forward, tmp->chan->context);
1109                                 stuff = tmpchan;
1110                                 tech = "Local";
1111                         }
1112                         tmp->forwards++;
1113                         if (tmp->forwards < AST_MAX_FORWARDS) {
1114                                 if (option_verbose > 2)
1115                                         ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", chan->name, tech, stuff, tmp->chan->name);
1116                                 ast_hangup(tmp->chan);
1117                                 /* Setup parameters */
1118                                 tmp->chan = ast_request(tech, chan->nativeformats, stuff, &cause);
1119                                 if (!tmp->chan)
1120                                         ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s' (cause = %d)\n", tech, stuff, cause);
1121                         } else {
1122                                 if (option_verbose > 2)
1123                                         ast_verbose(VERBOSE_PREFIX_3 "Too many forwards from %s\n", tmp->chan->name);
1124                                 ast_hangup(tmp->chan);
1125                                 tmp->chan = NULL;
1126                                 cause = AST_CAUSE_CONGESTION;
1127                         }
1128                         if (!tmp->chan) {
1129                                 HANDLE_CAUSE(cause, chan);
1130                                 cur = rest;
1131                                 continue;
1132                         }
1133                 }
1134
1135                 /* Inherit specially named variables from parent channel */
1136                 ast_channel_inherit_variables(chan, tmp->chan);
1137
1138                 tmp->chan->appl = "AppDial";
1139                 tmp->chan->data = "(Outgoing Line)";
1140                 tmp->chan->whentohangup = 0;
1141                 if (tmp->chan->cid.cid_num)
1142                         free(tmp->chan->cid.cid_num);
1143                 tmp->chan->cid.cid_num = NULL;
1144                 if (tmp->chan->cid.cid_name)
1145                         free(tmp->chan->cid.cid_name);
1146                 tmp->chan->cid.cid_name = NULL;
1147                 if (tmp->chan->cid.cid_ani)
1148                         free(tmp->chan->cid.cid_ani);
1149                 tmp->chan->cid.cid_ani = NULL;
1150
1151                 if (chan->cid.cid_num) 
1152                         tmp->chan->cid.cid_num = strdup(chan->cid.cid_num);
1153                 if (chan->cid.cid_name) 
1154                         tmp->chan->cid.cid_name = strdup(chan->cid.cid_name);
1155                 if (chan->cid.cid_ani) 
1156                         tmp->chan->cid.cid_ani = strdup(chan->cid.cid_ani);
1157                 
1158                 /* Copy language from incoming to outgoing */
1159                 ast_copy_string(tmp->chan->language, chan->language, sizeof(tmp->chan->language));
1160                 ast_copy_string(tmp->chan->accountcode, chan->accountcode, sizeof(tmp->chan->accountcode));
1161                 tmp->chan->cdrflags = chan->cdrflags;
1162                 if (ast_strlen_zero(tmp->chan->musicclass))
1163                         ast_copy_string(tmp->chan->musicclass, chan->musicclass, sizeof(tmp->chan->musicclass));
1164                 if (chan->cid.cid_rdnis)
1165                         tmp->chan->cid.cid_rdnis = strdup(chan->cid.cid_rdnis);
1166                 /* Pass callingpres setting */
1167                 tmp->chan->cid.cid_pres = chan->cid.cid_pres;
1168                 /* Pass type of number */
1169                 tmp->chan->cid.cid_ton = chan->cid.cid_ton;
1170                 /* Pass type of tns */
1171                 tmp->chan->cid.cid_tns = chan->cid.cid_tns;
1172                 /* Presense of ADSI CPE on outgoing channel follows ours */
1173                 tmp->chan->adsicpe = chan->adsicpe;
1174                 /* Pass the transfer capability */
1175                 tmp->chan->transfercapability = chan->transfercapability;
1176
1177                 /* If we have an outbound group, set this peer channel to it */
1178                 if (outbound_group)
1179                         ast_app_group_set_channel(tmp->chan, outbound_group);
1180
1181                 /* Place the call, but don't wait on the answer */
1182                 res = ast_call(tmp->chan, numsubst, 0);
1183
1184                 /* Save the info in cdr's that we called them */
1185                 if (chan->cdr)
1186                         ast_cdr_setdestchan(chan->cdr, tmp->chan->name);
1187
1188                 /* check the results of ast_call */
1189                 if (res) {
1190                         /* Again, keep going even if there's an error */
1191                         if (option_debug)
1192                                 ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
1193                         else if (option_verbose > 2)
1194                                 ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", numsubst);
1195                         ast_hangup(tmp->chan);
1196                         tmp->chan = NULL;
1197                         cur = rest;
1198                         continue;
1199                 } else {
1200                         senddialevent(chan, tmp->chan);
1201                         if (option_verbose > 2)
1202                                 ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", numsubst);
1203                         if (!ast_test_flag(peerflags, DIAL_PRESERVE_CALLERID))
1204                                 ast_set_callerid(tmp->chan, ast_strlen_zero(chan->macroexten) ? chan->exten : chan->macroexten, get_cid_name(cidname, sizeof(cidname), chan), NULL);
1205                 }
1206                 /* Put them in the list of outgoing thingies...  We're ready now. 
1207                    XXX If we're forcibly removed, these outgoing calls won't get
1208                    hung up XXX */
1209                 ast_set_flag(tmp, DIAL_STILLGOING);     
1210                 tmp->next = outgoing;
1211                 outgoing = tmp;
1212                 /* If this line is up, don't try anybody else */
1213                 if (outgoing->chan->_state == AST_STATE_UP)
1214                         break;
1215                 cur = rest;
1216         } while (cur);
1217         
1218         if (timeout && !ast_strlen_zero(timeout)) {
1219                 to = atoi(timeout);
1220                 if (to > 0)
1221                         to *= 1000;
1222                 else
1223                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'\n", timeout);
1224         } else
1225                 to = -1;
1226
1227         if (outgoing) {
1228                 /* Our status will at least be NOANSWER */
1229                 strcpy(status, "NOANSWER");
1230                 if (ast_test_flag(outgoing, DIAL_MUSICONHOLD)) {
1231                         moh=1;
1232                         ast_moh_start(chan, mohclass);
1233                 } else if (ast_test_flag(outgoing, DIAL_RINGBACKONLY)) {
1234                         ast_indicate(chan, AST_CONTROL_RINGING);
1235                         sentringing++;
1236                 }
1237         } else
1238                 strcpy(status, "CHANUNAVAIL");
1239
1240         time(&start_time);
1241         peer = wait_for_answer(chan, outgoing, &to, peerflags, &sentringing, status, sizeof(status), numbusy, numnochan, numcongestion, nojump, &result);
1242         
1243         if (!peer) {
1244                 if (result) {
1245                         res = result;
1246                 }
1247                 else if (to) 
1248                         /* Musta gotten hung up */
1249                         res = -1;
1250                 else 
1251                         /* Nobody answered, next please? */
1252                         res=0;
1253                 
1254                 goto out;
1255         }
1256         if (peer) {
1257                 time(&answer_time);
1258 #ifdef OSP_SUPPORT
1259                 /* Once call is answered, ditch the OSP Handle */
1260                 pbx_builtin_setvar_helper(chan, "_OSPHANDLE", "");
1261 #endif
1262                 strcpy(status, "ANSWER");
1263                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1264                    we will always return with -1 so that it is hung up properly after the 
1265                    conversation.  */
1266                 hanguptree(outgoing, peer);
1267                 outgoing = NULL;
1268                 /* If appropriate, log that we have a destination channel */
1269                 if (chan->cdr)
1270                         ast_cdr_setdestchan(chan->cdr, peer->name);
1271                 if (peer->name)
1272                         pbx_builtin_setvar_helper(chan, "DIALEDPEERNAME", peer->name);
1273
1274                 number = pbx_builtin_getvar_helper(peer, "DIALEDPEERNUMBER");
1275                 if (!number)
1276                         number = numsubst;
1277                 pbx_builtin_setvar_helper(chan, "DIALEDPEERNUMBER", number);
1278                 /* JDG: sendurl */
1279                 if ( url && !ast_strlen_zero(url) && ast_channel_supports_html(peer) ) {
1280                         ast_log(LOG_DEBUG, "app_dial: sendurl=%s.\n", url);
1281                         ast_channel_sendurl( peer, url );
1282                 } /* /JDG */
1283                 if( privacy || screen ) {
1284                         int res2;
1285                         int loopcount = 0;
1286                         if( privdb_val == AST_PRIVACY_UNKNOWN ) {
1287
1288                                 /* Get the user's intro, store it in priv-callerintros/$CID, 
1289                                    unless it is already there-- this should be done before the 
1290                                    call is actually dialed  */
1291
1292                                 /* all ring indications and moh for the caller has been halted as soon as the 
1293                                    target extension was picked up. We are going to have to kill some
1294                                    time and make the caller believe the peer hasn't picked up yet */
1295
1296                                 if ( strchr(transfer, 'm') ) {
1297                                         ast_indicate(chan, -1);
1298                                         ast_moh_start(chan, mohclass);
1299                                 } else if ( strchr(transfer, 'r') ) {
1300                                         ast_indicate(chan, AST_CONTROL_RINGING);
1301                                         sentringing++;
1302                                 }
1303
1304                                 /* Start autoservice on the other chan ?? */
1305                                 res2 = ast_autoservice_start(chan);
1306                                 /* Now Stream the File */
1307                                 if (!res2) {
1308                                         do {
1309                                                 if (!res2)
1310                                                         res2 = ast_play_and_wait(peer,"priv-callpending");
1311                                                 if( res2 < '1' || (privacy && res2>'5') || (screen && res2 > '4') ) /* uh, interrupting with a bad answer is ... ignorable! */
1312                                                         res2 = 0;
1313                                                 
1314                                                 /* priv-callpending script: 
1315                                                    "I have a caller waiting, who introduces themselves as:"
1316                                                 */
1317                                                 if (!res2)
1318                                                         res2 = ast_play_and_wait(peer,privintro);
1319                                                 if( res2 < '1' || (privacy && res2>'5') || (screen && res2 > '4') ) /* uh, interrupting with a bad answer is ... ignorable! */
1320                                                         res2 = 0;
1321                                                 /* now get input from the called party, as to their choice */
1322                                                 if( !res2 ) {
1323                                                         if( privacy )
1324                                                                 res2 = ast_play_and_wait(peer,"priv-callee-options");
1325                                                         if( screen )
1326                                                                 res2 = ast_play_and_wait(peer,"screen-callee-options");
1327                                                 }
1328                                                 /* priv-callee-options script:
1329                                                         "Dial 1 if you wish this caller to reach you directly in the future,
1330                                                                 and immediately connect to their incoming call
1331                                                          Dial 2 if you wish to send this caller to voicemail now and 
1332                                                                 forevermore.
1333                                                          Dial 3 to send this callerr to the torture menus, now and forevermore.
1334                                                          Dial 4 to send this caller to a simple "go away" menu, now and forevermore.
1335                                                          Dial 5 to allow this caller to come straight thru to you in the future,
1336                                                 but right now, just this once, send them to voicemail."
1337                                                 */
1338                                 
1339                                                 /* screen-callee-options script:
1340                                                         "Dial 1 if you wish to immediately connect to the incoming call
1341                                                          Dial 2 if you wish to send this caller to voicemail.
1342                                                          Dial 3 to send this callerr to the torture menus.
1343                                                          Dial 4 to send this caller to a simple "go away" menu.
1344                                                 */
1345                                                 if( !res2 || res2 < '1' || (privacy && res2 > '5') || (screen && res2 > '4') ) {
1346                                                         /* invalid option */
1347                                                         res2 = ast_play_and_wait(peer,"vm-sorry");
1348                                                 }
1349                                                 loopcount++; /* give the callee a couple chances to make a choice */
1350                                         } while( (!res2 || res2 < '1' || (privacy && res2 > '5') || (screen && res2 > '4')) && loopcount < 2 );
1351                                 }
1352
1353                                 switch(res2) {
1354                                 case '1':
1355                                         if( privacy ) {
1356                                                 if (option_verbose > 2)
1357                                                         ast_verbose( VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to ALLOW\n", privdb, privcid);
1358                                                 ast_privacy_set(privdb,privcid,AST_PRIVACY_ALLOW);
1359                                         }
1360                                         break;
1361                                 case '2':
1362                                         if( privacy ) {
1363                                                 if (option_verbose > 2)
1364                                                         ast_verbose( VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to DENY\n", privdb, privcid);
1365                                                 ast_privacy_set(privdb,privcid,AST_PRIVACY_DENY);
1366                                         }
1367                                         if ( strchr(transfer, 'm') ) {
1368                                                 ast_moh_stop(chan);
1369                                         } else if ( strchr(transfer, 'r') ) {
1370                                                 ast_indicate(chan, -1);
1371                                                 sentringing=0;
1372                                         }
1373                                         res2 = ast_autoservice_stop(chan);
1374                                         ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1375                                         res=0;
1376                                         goto out;
1377                                         break;
1378                                 case '3':
1379                                         if( privacy ) {
1380                                                 ast_privacy_set(privdb,privcid,AST_PRIVACY_TORTURE);
1381                                                 if (option_verbose > 2)
1382                                                         ast_verbose( VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to TORTURE\n", privdb, privcid);
1383                                         }
1384                                         ast_copy_string(status, "TORTURE", sizeof(status));
1385                                         
1386                                         res = 0;
1387                                         if ( strchr(transfer, 'm') ) {
1388                                                 ast_moh_stop(chan);
1389                                         } else if ( strchr(transfer, 'r') ) {
1390                                                 ast_indicate(chan, -1);
1391                                                 sentringing=0;
1392                                         }
1393                                         res2 = ast_autoservice_stop(chan);
1394                                         ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1395                                         goto out; /* Is this right? */
1396                                         break;
1397                                 case '4':
1398                                         if( privacy ) {
1399                                                 if (option_verbose > 2)
1400                                                         ast_verbose( VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to KILL\n", privdb, privcid);
1401                                                 ast_privacy_set(privdb,privcid,AST_PRIVACY_KILL);
1402                                         }
1403
1404                                         ast_copy_string(status, "DONTCALL", sizeof(status));
1405                                         res = 0;
1406                                         if ( strchr(transfer, 'm') ) {
1407                                                 ast_moh_stop(chan);
1408                                         } else if ( strchr(transfer, 'r') ) {
1409                                                 ast_indicate(chan, -1);
1410                                                 sentringing=0;
1411                                         }
1412                                         res2 = ast_autoservice_stop(chan);
1413                                         ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1414                                         goto out; /* Is this right? */
1415                                         break;
1416                                 case '5':
1417                                         if( privacy ) {
1418                                                 if (option_verbose > 2)
1419                                                         ast_verbose( VERBOSE_PREFIX_3 "--Set privacy database entry %s/%s to ALLOW\n", privdb, privcid);
1420                                                 ast_privacy_set(privdb,privcid,AST_PRIVACY_ALLOW);
1421                                         
1422                                                 if ( strchr(transfer, 'm') ) {
1423                                                         ast_moh_stop(chan);
1424                                                 } else if ( strchr(transfer, 'r') ) {
1425                                                         ast_indicate(chan, -1);
1426                                                         sentringing=0;
1427                                                 }
1428                                                 res2 = ast_autoservice_stop(chan);
1429                                                 ast_hangup(peer); /* hang up on the caller -- he didn't want to talk anyway! */
1430                                                 res=0;
1431                                                 goto out;
1432                                                 break;
1433                                         } /* if not privacy, then 5 is the same as "default" case */
1434                                 default:
1435                                         /* well, if the user messes up, ... he had his chance... What Is The Best Thing To Do?  */
1436                                         /* well, there seems basically two choices. Just patch the caller thru immediately,
1437                                                   or,... put 'em thru to voicemail. */
1438                                         /* since the callee may have hung up, let's do the voicemail thing, no database decision */
1439                                         if (option_verbose > 2)
1440                                                 ast_log(LOG_NOTICE,"privacy: no valid response from the callee. Sending the caller to voicemail, the callee isn't responding\n");
1441                                         if ( strchr(transfer, 'm') ) {
1442                                                 ast_moh_stop(chan);
1443                                         } else if ( strchr(transfer, 'r') ) {
1444                                                 ast_indicate(chan, -1);
1445                                                 sentringing=0;
1446                                         }
1447                                         res2 = ast_autoservice_stop(chan);
1448                                         ast_hangup(peer); /* hang up on the callee -- he didn't want to talk anyway! */
1449                                         res=0;
1450                                         goto out;
1451                                         break;
1452                                 }
1453                                 if ( strchr(transfer, 'm') ) {
1454                                         ast_moh_stop(chan);
1455                                 } else if ( strchr(transfer, 'r') ) {
1456                                         ast_indicate(chan, -1);
1457                                         sentringing=0;
1458                                 }
1459                                 res2 = ast_autoservice_stop(chan);
1460                                 /* if the intro is NOCALLERID, then there's no reason to leave it on disk, it'll 
1461                                    just clog things up, and it's not useful information, not being tied to a CID */
1462                                 if( strncmp(privcid,"NOCALLERID",10) == 0 || no_save_intros ) {
1463                                         ast_filedelete(privintro, NULL);
1464                                         if( ast_fileexists(privintro,NULL,NULL ) > 0 )
1465                                                 ast_log(LOG_NOTICE,"privacy: ast_filedelete didn't do its job on %s\n", privintro);
1466                                         else if (option_verbose > 2)
1467                                                 ast_verbose( VERBOSE_PREFIX_3 "Successfully deleted %s intro file\n", privintro);
1468                                 }
1469                         }
1470                 }
1471                 if (announce && announcemsg) {
1472                         /* Start autoservice on the other chan */
1473                         res = ast_autoservice_start(chan);
1474                         /* Now Stream the File */
1475                         if (!res)
1476                                 res = ast_streamfile(peer,announcemsg,peer->language);
1477                         if (!res) {
1478                                 digit = ast_waitstream(peer, AST_DIGIT_ANY); 
1479                         }
1480                         /* Ok, done. stop autoservice */
1481                         res = ast_autoservice_stop(chan);
1482                         if (digit > 0 && !res)
1483                                 res = ast_senddigit(chan, digit); 
1484                         else
1485                                 res = digit;
1486
1487                 } else
1488                         res = 0;
1489
1490                 if (chan && peer && dblgoto) {
1491                         for (mac=dblgoto; *mac; mac++) {
1492                                 if(*mac == '^') {
1493                                         *mac = '|';
1494                                 }
1495                         }
1496                         ast_parseable_goto(chan, dblgoto);
1497                         ast_parseable_goto(peer, dblgoto);
1498                         peer->priority++;
1499                         ast_pbx_start(peer);
1500                         hanguptree(outgoing, NULL);
1501                         LOCAL_USER_REMOVE(u);
1502                         return 0;
1503                 }
1504
1505                 if (hasmacro && macroname) {
1506                         res = ast_autoservice_start(chan);
1507                         if (res) {
1508                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
1509                                 res = -1;
1510                         }
1511
1512                         app = pbx_findapp("Macro");
1513
1514                         if (app && !res) {
1515                                 for (res=0;res<strlen(macroname);res++)
1516                                         if (macroname[res] == '^')
1517                                                 macroname[res] = '|';
1518                                 res = pbx_exec(peer, app, macroname, 1);
1519                                 ast_log(LOG_DEBUG, "Macro exited with status %d\n", res);
1520                                 res = 0;
1521                         } else {
1522                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
1523                                 res = -1;
1524                         }
1525
1526                         if (ast_autoservice_stop(chan) < 0) {
1527                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
1528                                 res = -1;
1529                         }
1530
1531                         if (!res) {
1532                                 if ((macro_result = pbx_builtin_getvar_helper(peer, "MACRO_RESULT"))) {
1533                                         if (!strcasecmp(macro_result, "BUSY")) {
1534                                                 ast_copy_string(status, macro_result, sizeof(status));
1535                                                 if (!ast_goto_if_exists(chan, NULL, NULL, chan->priority + 101)) {
1536                                                         ast_set_flag(peerflags, DIAL_GO_ON);
1537                                                 }
1538                                                 res = -1;
1539                                         }
1540                                         else if (!strcasecmp(macro_result, "CONGESTION") || !strcasecmp(macro_result, "CHANUNAVAIL")) {
1541                                                 ast_copy_string(status, macro_result, sizeof(status));
1542                                                 ast_set_flag(peerflags, DIAL_GO_ON);    
1543                                                 res = -1;
1544                                         }
1545                                         else if (!strcasecmp(macro_result, "CONTINUE")) {
1546                                                 /* hangup peer and keep chan alive assuming the macro has changed 
1547                                                    the context / exten / priority or perhaps 
1548                                                    the next priority in the current exten is desired.
1549                                                 */
1550                                                 ast_set_flag(peerflags, DIAL_GO_ON);    
1551                                                 res = -1;
1552                                         } else if (!strcasecmp(macro_result, "ABORT")) {
1553                                                 /* Hangup both ends unless the caller has the g flag */
1554                                                 res = -1;
1555                                         } else if (!strncasecmp(macro_result, "GOTO:",5) && (macro_transfer_dest = ast_strdupa(macro_result + 5))) {
1556                                                 res = -1;
1557                                                 /* perform a transfer to a new extension */
1558                                                 if (strchr(macro_transfer_dest,'^')) { /* context^exten^priority*/
1559                                                         /* no brainer mode... substitute ^ with | and feed it to builtin goto */
1560                                                         for (res=0;res<strlen(macro_transfer_dest);res++)
1561                                                                 if (macro_transfer_dest[res] == '^')
1562                                                                         macro_transfer_dest[res] = '|';
1563
1564                                                         if (!ast_parseable_goto(chan, macro_transfer_dest))
1565                                                                 ast_set_flag(peerflags, DIAL_GO_ON);
1566
1567                                                 }
1568                                         }
1569                                 }
1570                         }
1571                 }
1572
1573                 if (!res) {
1574                         if (calldurationlimit > 0) {
1575                                 time(&now);
1576                                 chan->whentohangup = now + calldurationlimit;
1577                         }
1578                         if (dtmfcalled && !ast_strlen_zero(dtmfcalled)) { 
1579                                 if (option_verbose > 2)
1580                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the called party.\n",dtmfcalled);
1581                                 res = ast_dtmf_stream(peer,chan,dtmfcalled,250);
1582                         }
1583                         if (dtmfcalling && !ast_strlen_zero(dtmfcalling)) {
1584                                 if (option_verbose > 2)
1585                                         ast_verbose(VERBOSE_PREFIX_3 "Sending DTMF '%s' to the calling party.\n",dtmfcalling);
1586                                 res = ast_dtmf_stream(chan,peer,dtmfcalling,250);
1587                         }
1588                 }
1589                 
1590                 if (!res) {
1591                         memset(&config,0,sizeof(struct ast_bridge_config));
1592                         if (play_to_caller)
1593                                 ast_set_flag(&(config.features_caller), AST_FEATURE_PLAY_WARNING);
1594                         if (play_to_callee)
1595                                 ast_set_flag(&(config.features_callee), AST_FEATURE_PLAY_WARNING);
1596                         if (ast_test_flag(peerflags, DIAL_ALLOWREDIRECT_IN))
1597                                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1598                         if (ast_test_flag(peerflags, DIAL_ALLOWREDIRECT_OUT))
1599                                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
1600                         if (ast_test_flag(peerflags, DIAL_ALLOWDISCONNECT_IN))
1601                                 ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
1602                         if (ast_test_flag(peerflags, DIAL_ALLOWDISCONNECT_OUT))
1603                                 ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
1604                         if (ast_test_flag(peerflags, DIAL_MONITOR_IN))
1605                                 ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1606                         if (ast_test_flag(peerflags, DIAL_MONITOR_OUT)) 
1607                                 ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1608
1609                         config.timelimit = timelimit;
1610                         config.play_warning = play_warning;
1611                         config.warning_freq = warning_freq;
1612                         config.warning_sound = warning_sound;
1613                         config.end_sound = end_sound;
1614                         config.start_sound = start_sound;
1615                         if (moh) {
1616                                 moh = 0;
1617                                 ast_moh_stop(chan);
1618                         } else if (sentringing) {
1619                                 sentringing = 0;
1620                                 ast_indicate(chan, -1);
1621                         }
1622                         /* Be sure no generators are left on it */
1623                         ast_deactivate_generator(chan);
1624                         /* Make sure channels are compatible */
1625                         res = ast_channel_make_compatible(chan, peer);
1626                         if (res < 0) {
1627                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", chan->name, peer->name);
1628                                 ast_hangup(peer);
1629                                 return -1;
1630                         }
1631                         res = ast_bridge_call(chan,peer,&config);
1632                         time(&end_time);
1633                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1634                         pbx_builtin_setvar_helper(chan, "DIALEDTIME", toast);
1635                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1636                         pbx_builtin_setvar_helper(chan, "ANSWEREDTIME", toast);
1637                         
1638                 } else 
1639                         res = -1;
1640                 
1641                 if (res != AST_PBX_NO_HANGUP_PEER) {
1642                         if (!chan->_softhangup)
1643                                 chan->hangupcause = peer->hangupcause;
1644                         ast_hangup(peer);
1645                 }
1646         }       
1647 out:
1648         if (moh) {
1649                 moh = 0;
1650                 ast_moh_stop(chan);
1651         } else if (sentringing) {
1652                 sentringing = 0;
1653                 ast_indicate(chan, -1);
1654         }
1655         hanguptree(outgoing, NULL);
1656         pbx_builtin_setvar_helper(chan, "DIALSTATUS", status);
1657         ast_log(LOG_DEBUG, "Exiting with DIALSTATUS=%s.\n", status);
1658         
1659         LOCAL_USER_REMOVE(u);
1660         
1661         if ((ast_test_flag(peerflags, DIAL_GO_ON)) && (!chan->_softhangup) && (res != AST_PBX_KEEPALIVE))
1662             res=0;
1663             
1664         return res;
1665 }
1666
1667 static int dial_exec(struct ast_channel *chan, void *data)
1668 {
1669         struct ast_flags peerflags;
1670         memset(&peerflags, 0, sizeof(peerflags));
1671         return dial_exec_full(chan, data, &peerflags);
1672 }
1673
1674 static int retrydial_exec(struct ast_channel *chan, void *data)
1675 {
1676         char *announce = NULL, *context = NULL, *dialdata = NULL;
1677         int sleep = 0, loops = 0, res = 0;
1678         struct localuser *u = NULL;
1679         struct ast_flags peerflags;
1680         
1681         memset(&peerflags, 0, sizeof(peerflags));
1682
1683         LOCAL_USER_ADD(u);
1684         
1685         if (!data || !(announce = ast_strdupa(data))) {
1686                 ast_log(LOG_ERROR, "Out of memory!\n");
1687                 LOCAL_USER_REMOVE(u);
1688                 return -1;
1689         }
1690         
1691         if ((dialdata = strchr(announce, '|'))) {
1692                 *dialdata = '\0';
1693                 dialdata++;
1694                 if ((sleep = atoi(dialdata))) {
1695                         sleep *= 1000;
1696                 } else {
1697                         ast_log(LOG_ERROR, "%s requires the numerical argument <sleep>\n",rapp);
1698                         LOCAL_USER_REMOVE(u);
1699                         return -1;
1700                 }
1701                 if ((dialdata = strchr(dialdata, '|'))) {
1702                         *dialdata = '\0';
1703                         dialdata++;
1704                         if (!(loops = atoi(dialdata))) {
1705                                 ast_log(LOG_ERROR, "%s requires the numerical argument <loops>\n",rapp);
1706                                 LOCAL_USER_REMOVE(u);
1707                                 return -1;
1708                         }
1709                 }
1710         }
1711         
1712         if ((dialdata = strchr(dialdata, '|'))) {
1713                 *dialdata = '\0';
1714                 dialdata++;
1715         } else {
1716                 ast_log(LOG_ERROR, "%s requires more arguments\n",rapp);
1717                 LOCAL_USER_REMOVE(u);
1718                 return -1;
1719         }
1720                 
1721         if (sleep < 1000)
1722                 sleep = 10000;
1723         
1724         if (!loops)
1725                 loops = -1;
1726         
1727         context = pbx_builtin_getvar_helper(chan, "EXITCONTEXT");
1728         
1729         while (loops) {
1730                 chan->data = "Retrying";
1731                 if (ast_test_flag(chan, AST_FLAG_MOH))
1732                         ast_moh_stop(chan);
1733
1734                 if ((res = dial_exec_full(chan, dialdata, &peerflags)) == 0) {
1735                         if (ast_test_flag(&peerflags, DIAL_HALT_ON_DTMF)) {
1736                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1737                                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1738                                 if (!res && sleep) {
1739                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1740                                                 ast_moh_start(chan, NULL);
1741                                         res = ast_waitfordigit(chan, sleep);
1742                                 }
1743                         } else {
1744                                 if (!(res = ast_streamfile(chan, announce, chan->language)))
1745                                         res = ast_waitstream(chan, "");
1746                                 if (sleep) {
1747                                         if (!ast_test_flag(chan, AST_FLAG_MOH))
1748                                                 ast_moh_start(chan, NULL);
1749                                         if (!res) 
1750                                                 res = ast_waitfordigit(chan, sleep);
1751                                 }
1752                         }
1753                 }
1754
1755                 if (res < 0)
1756                         break;
1757                 else if (res > 0) { /* Trying to send the call elsewhere (1 digit ext) */
1758                         if (onedigit_goto(chan, context, (char) res, 1)) {
1759                                 res = 0;
1760                                 break;
1761                         }
1762                 }
1763                 loops--;
1764         }
1765         
1766         if (ast_test_flag(chan, AST_FLAG_MOH))
1767                 ast_moh_stop(chan);
1768
1769         LOCAL_USER_REMOVE(u);
1770         return loops ? res : 0;
1771
1772 }
1773
1774 int unload_module(void)
1775 {
1776         STANDARD_HANGUP_LOCALUSERS;
1777         ast_unregister_application(app);
1778         return ast_unregister_application(rapp);
1779 }
1780
1781 int load_module(void)
1782 {
1783         int res;
1784         if (!(res = ast_register_application(app, dial_exec, synopsis, descrip)))
1785                 res = ast_register_application(rapp, retrydial_exec, rsynopsis, rdescrip);
1786         return res;
1787 }
1788
1789 char *description(void)
1790 {
1791         return tdesc;
1792 }
1793
1794 int usecount(void)
1795 {
1796         int res;
1797         STANDARD_USECOUNT(res);
1798         return res;
1799 }
1800
1801 char *key()
1802 {
1803         return ASTERISK_GPL_KEY;
1804 }