Add support for call forwarding and timeouts to the dialing API.
[asterisk/asterisk.git] / main / dial.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2007, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Dialing API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/time.h>
34 #include <signal.h>
35 #include <errno.h>
36 #include <unistd.h>
37
38 #include "asterisk/logger.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/options.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/linkedlists.h"
44 #include "asterisk/dial.h"
45 #include "asterisk/pbx.h"
46 #include "asterisk/musiconhold.h"
47
48 /*! \brief Main dialing structure. Contains global options, channels being dialed, and more! */
49 struct ast_dial {
50         int num;                                           /*!< Current number to give to next dialed channel */
51         int timeout;                                       /*!< Maximum time allowed for dial attempts */
52         int actual_timeout;                                /*!< Actual timeout based on all factors (ie: channels) */
53         enum ast_dial_result state;                        /*!< Status of dial */
54         void *options[AST_DIAL_OPTION_MAX];                /*!< Global options */
55         ast_dial_state_callback state_callback;            /*!< Status callback */
56         AST_LIST_HEAD_NOLOCK(, ast_dial_channel) channels; /*!< Channels being dialed */
57         pthread_t thread;                                  /*!< Thread (if running in async) */
58 };
59
60 /*! \brief Dialing channel structure. Contains per-channel dialing options, asterisk channel, and more! */
61 struct ast_dial_channel {
62         int num;                               /*!< Unique number for dialed channel */
63         int timeout;                           /*!< Maximum time allowed for attempt */
64         char *tech;                            /*!< Technology being dialed */
65         char *device;                          /*!< Device being dialed */
66         void *options[AST_DIAL_OPTION_MAX];    /*!< Channel specific options */
67         int cause;                             /*!< Cause code in case of failure */
68         struct ast_channel *owner;             /*!< Asterisk channel */
69         AST_LIST_ENTRY(ast_dial_channel) list; /*!< Linked list information */
70 };
71
72 /*! \brief Typedef for dial option enable */
73 typedef void *(*ast_dial_option_cb_enable)(void *data);
74
75 /*! \brief Typedef for dial option disable */
76 typedef int (*ast_dial_option_cb_disable)(void *data);
77
78 /*! \brief Structure for 'ANSWER_EXEC' option */
79 struct answer_exec_struct {
80         char app[AST_MAX_APP]; /*!< Application name */
81         char *args;            /*!< Application arguments */
82 };
83
84 /*! \brief Enable function for 'ANSWER_EXEC' option */
85 static void *answer_exec_enable(void *data)
86 {
87         struct answer_exec_struct *answer_exec = NULL;
88         char *app = ast_strdupa((char*)data), *args = NULL;
89
90         /* Not giving any data to this option is bad, mmmk? */
91         if (ast_strlen_zero(app))
92                 return NULL;
93
94         /* Create new data structure */
95         if (!(answer_exec = ast_calloc(1, sizeof(*answer_exec))))
96                 return NULL;
97         
98         /* Parse out application and arguments */
99         if ((args = strchr(app, '|'))) {
100                 *args++ = '\0';
101                 answer_exec->args = ast_strdup(args);
102         }
103
104         /* Copy application name */
105         ast_copy_string(answer_exec->app, app, sizeof(answer_exec->app));
106
107         return answer_exec;
108 }
109
110 /*! \brief Disable function for 'ANSWER_EXEC' option */
111 static int answer_exec_disable(void *data)
112 {
113         struct answer_exec_struct *answer_exec = data;
114
115         /* Make sure we have a value */
116         if (!answer_exec)
117                 return -1;
118
119         /* If arguments are present, free them too */
120         if (answer_exec->args)
121                 ast_free(answer_exec->args);
122
123         /* This is simple - just free the structure */
124         ast_free(answer_exec);
125
126         return 0;
127 }
128
129 static void *music_enable(void *data)
130 {
131         return ast_strdup(data);
132 }
133
134 static int music_disable(void *data)
135 {
136         if (!data)
137                 return -1;
138
139         ast_free(data);
140
141         return 0;
142 }
143
144 /*! \brief Application execution function for 'ANSWER_EXEC' option */
145 static void answer_exec_run(struct ast_channel *chan, char *app, char *args)
146 {
147         struct ast_app *ast_app = pbx_findapp(app);
148
149         /* If the application was not found, return immediately */
150         if (!ast_app)
151                 return;
152
153         /* All is well... execute the application */
154         pbx_exec(chan, ast_app, args);
155
156         return;
157 }
158
159 /*! \brief Options structure - maps options to respective handlers (enable/disable). This list MUST be perfectly kept in order, or else madness will happen. */
160 static const struct ast_option_types {
161         enum ast_dial_option option;
162         ast_dial_option_cb_enable enable;
163         ast_dial_option_cb_disable disable;
164 } option_types[] = {
165         { AST_DIAL_OPTION_RINGING, NULL, NULL },                                  /*!< Always indicate ringing to caller */
166         { AST_DIAL_OPTION_ANSWER_EXEC, answer_exec_enable, answer_exec_disable }, /*!< Execute application upon answer in async mode */
167         { AST_DIAL_OPTION_MUSIC, music_enable, music_disable },                   /*!< Play music to the caller instead of ringing */
168         { AST_DIAL_OPTION_DISABLE_CALL_FORWARDING, NULL, NULL },                  /*!< Disable call forwarding on channels */
169         { AST_DIAL_OPTION_MAX, NULL, NULL },                                      /*!< Terminator of list */
170 };
171
172 /*! \brief free the buffer if allocated, and set the pointer to the second arg */
173 #define S_REPLACE(s, new_val)           \
174         do {                            \
175                 if (s)                  \
176                         free(s);        \
177                 s = (new_val);          \
178         } while (0)
179
180 /*! \brief Maximum number of channels we can watch at a time */
181 #define AST_MAX_WATCHERS 256
182
183 /*! \brief Macro for finding the option structure to use on a dialed channel */
184 #define FIND_RELATIVE_OPTION(dial, dial_channel, ast_dial_option) (dial_channel->options[ast_dial_option] ? dial_channel->options[ast_dial_option] : dial->options[ast_dial_option])
185
186 /*! \brief Macro that determines whether a channel is the caller or not */
187 #define IS_CALLER(chan, owner) (chan == owner ? 1 : 0)
188
189 /*! \brief New dialing structure
190  * \note Create a dialing structure
191  * \return Returns a calloc'd ast_dial structure, NULL on failure
192  */
193 struct ast_dial *ast_dial_create(void)
194 {
195         struct ast_dial *dial = NULL;
196
197         /* Allocate new memory for structure */
198         if (!(dial = ast_calloc(1, sizeof(*dial))))
199                 return NULL;
200
201         /* Initialize list of channels */
202         AST_LIST_HEAD_INIT_NOLOCK(&dial->channels);
203
204         /* Initialize thread to NULL */
205         dial->thread = AST_PTHREADT_NULL;
206
207         /* No timeout exists... yet */
208         dial->timeout = -1;
209         dial->actual_timeout = -1;
210
211         return dial;
212 }
213
214 /*! \brief Append a channel
215  * \note Appends a channel to a dialing structure
216  * \return Returns channel reference number on success, -1 on failure
217  */
218 int ast_dial_append(struct ast_dial *dial, const char *tech, const char *device)
219 {
220         struct ast_dial_channel *channel = NULL;
221
222         /* Make sure we have required arguments */
223         if (!dial || !tech || !device)
224                 return -1;
225
226         /* Allocate new memory for dialed channel structure */
227         if (!(channel = ast_calloc(1, sizeof(*channel))))
228                 return -1;
229
230         /* Record technology and device for when we actually dial */
231         channel->tech = ast_strdup(tech);
232         channel->device = ast_strdup(device);
233
234         /* Grab reference number from dial structure */
235         channel->num = ast_atomic_fetchadd_int(&dial->num, +1);
236
237         /* No timeout exists... yet */
238         channel->timeout = -1;
239
240         /* Insert into channels list */
241         AST_LIST_INSERT_TAIL(&dial->channels, channel, list);
242
243         return channel->num;
244 }
245
246 /*! \brief Helper function that does the beginning dialing per-appended channel */
247 static int begin_dial_channel(struct ast_dial_channel *channel, struct ast_channel *chan)
248 {
249         char numsubst[AST_MAX_EXTENSION];
250         int res = 1;
251
252         /* Copy device string over */
253         ast_copy_string(numsubst, channel->device, sizeof(numsubst));
254
255         /* If we fail to create our owner channel bail out */
256         if (!(channel->owner = ast_request(channel->tech, chan ? chan->nativeformats : AST_FORMAT_AUDIO_MASK, numsubst, &channel->cause)))
257                 return -1;
258
259         channel->owner->appl = "AppDial2";
260         channel->owner->data = "(Outgoing Line)";
261         channel->owner->whentohangup = 0;
262
263         /* Inherit everything from he who spawned this dial */
264         if (chan) {
265                 ast_channel_inherit_variables(chan, channel->owner);
266
267                 /* Copy over callerid information */
268                 S_REPLACE(channel->owner->cid.cid_num, ast_strdup(chan->cid.cid_num));
269                 S_REPLACE(channel->owner->cid.cid_name, ast_strdup(chan->cid.cid_name));
270                 S_REPLACE(channel->owner->cid.cid_ani, ast_strdup(chan->cid.cid_ani));
271                 S_REPLACE(channel->owner->cid.cid_rdnis, ast_strdup(chan->cid.cid_rdnis));
272
273                 ast_string_field_set(channel->owner, language, chan->language);
274                 ast_string_field_set(channel->owner, accountcode, chan->accountcode);
275                 channel->owner->cdrflags = chan->cdrflags;
276                 if (ast_strlen_zero(channel->owner->musicclass))
277                         ast_string_field_set(channel->owner, musicclass, chan->musicclass);
278
279                 channel->owner->cid.cid_pres = chan->cid.cid_pres;
280                 channel->owner->cid.cid_ton = chan->cid.cid_ton;
281                 channel->owner->cid.cid_tns = chan->cid.cid_tns;
282                 channel->owner->adsicpe = chan->adsicpe;
283                 channel->owner->transfercapability = chan->transfercapability;
284         }
285
286         /* Attempt to actually call this device */
287         if ((res = ast_call(channel->owner, numsubst, 0))) {
288                 res = 0;
289                 ast_hangup(channel->owner);
290                 channel->owner = NULL;
291         } else {
292                 res = 1;
293                 ast_verb(3, "Called %s\n", numsubst);
294         }
295
296         return res;
297 }
298
299 /*! \brief Helper function that does the beginning dialing per dial structure */
300 static int begin_dial(struct ast_dial *dial, struct ast_channel *chan)
301 {
302         struct ast_dial_channel *channel = NULL;
303         int success = 0;
304
305         /* Iterate through channel list, requesting and calling each one */
306         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
307                 success += begin_dial_channel(channel, chan);
308         }
309
310         /* If number of failures matches the number of channels, then this truly failed */
311         return success;
312 }
313
314 /*! \brief Helper function to handle channels that have been call forwarded */
315 static int handle_call_forward(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_channel *chan)
316 {
317         struct ast_channel *original = channel->owner;
318         char *tmp = ast_strdupa(channel->owner->call_forward);
319         char *tech = "Local", *device = tmp, *stuff;
320
321         /* If call forwarding is disabled just drop the original channel and don't attempt to dial the new one */
322         if (FIND_RELATIVE_OPTION(dial, channel, AST_DIAL_OPTION_DISABLE_CALL_FORWARDING)) {
323                 ast_hangup(original);
324                 channel->owner = NULL;
325                 return 0;
326         }
327
328         /* Figure out the new destination */
329         if ((stuff = strchr(tmp, '/'))) {
330                 *stuff++ = '\0';
331                 tech = tmp;
332                 device = stuff;
333         }
334
335         /* Drop old destination information */
336         ast_free(channel->tech);
337         ast_free(channel->device);
338
339         /* Update the dial channel with the new destination information */
340         channel->tech = ast_strdup(tech);
341         channel->device = ast_strdup(device);
342
343         /* Finally give it a go... send it out into the world */
344         begin_dial_channel(channel, chan);
345
346         /* Drop the original channel */
347         ast_hangup(original);
348
349         return 0;
350 }
351
352 /*! \brief Helper function that finds the dialed channel based on owner */
353 static struct ast_dial_channel *find_relative_dial_channel(struct ast_dial *dial, struct ast_channel *owner)
354 {
355         struct ast_dial_channel *channel = NULL;
356
357         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
358                 if (channel->owner == owner)
359                         break;
360         }
361
362         return channel;
363 }
364
365 static void set_state(struct ast_dial *dial, enum ast_dial_result state)
366 {
367         dial->state = state;
368
369         if (dial->state_callback)
370                 dial->state_callback(dial);
371 }
372
373 /*! \brief Helper function that handles control frames WITH owner */
374 static void handle_frame(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_frame *fr, struct ast_channel *chan)
375 {
376         if (fr->frametype == AST_FRAME_CONTROL) {
377                 switch (fr->subclass) {
378                 case AST_CONTROL_ANSWER:
379                         ast_verb(3, "%s answered %s\n", channel->owner->name, chan->name);
380                         AST_LIST_REMOVE(&dial->channels, channel, list);
381                         AST_LIST_INSERT_HEAD(&dial->channels, channel, list);
382                         set_state(dial, AST_DIAL_RESULT_ANSWERED);
383                         break;
384                 case AST_CONTROL_BUSY:
385                         ast_verb(3, "%s is busy\n", channel->owner->name);
386                         ast_hangup(channel->owner);
387                         channel->owner = NULL;
388                         break;
389                 case AST_CONTROL_CONGESTION:
390                         ast_verb(3, "%s is circuit-busy\n", channel->owner->name);
391                         ast_hangup(channel->owner);
392                         channel->owner = NULL;
393                         break;
394                 case AST_CONTROL_RINGING:
395                         ast_verb(3, "%s is ringing\n", channel->owner->name);
396                         if (!dial->options[AST_DIAL_OPTION_MUSIC])
397                                 ast_indicate(chan, AST_CONTROL_RINGING);
398                         set_state(dial, AST_DIAL_RESULT_RINGING);
399                         break;
400                 case AST_CONTROL_PROGRESS:
401                         ast_verb(3, "%s is making progress, passing it to %s\n", channel->owner->name, chan->name);
402                         ast_indicate(chan, AST_CONTROL_PROGRESS);
403                         set_state(dial, AST_DIAL_RESULT_PROGRESS);
404                         break;
405                 case AST_CONTROL_VIDUPDATE:
406                         ast_verb(3, "%s requested a video update, passing it to %s\n", channel->owner->name, chan->name);
407                         ast_indicate(chan, AST_CONTROL_VIDUPDATE);
408                         break;
409                 case AST_CONTROL_PROCEEDING:
410                         ast_verb(3, "%s is proceeding, passing it to %s\n", channel->owner->name, chan->name);
411                         ast_indicate(chan, AST_CONTROL_PROCEEDING);
412                         set_state(dial, AST_DIAL_RESULT_PROCEEDING);
413                         break;
414                 case AST_CONTROL_HOLD:
415                         ast_verb(3, "Call on %s placed on hold\n", chan->name);
416                         ast_indicate(chan, AST_CONTROL_HOLD);
417                         break;
418                 case AST_CONTROL_UNHOLD:
419                         ast_verb(3, "Call on %s left from hold\n", chan->name);
420                         ast_indicate(chan, AST_CONTROL_UNHOLD);
421                         break;
422                 case AST_CONTROL_OFFHOOK:
423                 case AST_CONTROL_FLASH:
424                         break;
425                 case -1:
426                         /* Prod the channel */
427                         ast_indicate(chan, -1);
428                         break;
429                 default:
430                         break;
431                 }
432         }
433
434         return;
435 }
436
437 /*! \brief Helper function that handles control frames WITHOUT owner */
438 static void handle_frame_ownerless(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_frame *fr)
439 {
440         /* If we have no owner we can only update the state of the dial structure, so only look at control frames */
441         if (fr->frametype != AST_FRAME_CONTROL)
442                 return;
443
444         switch (fr->subclass) {
445         case AST_CONTROL_ANSWER:
446                 ast_verb(3, "%s answered\n", channel->owner->name);
447                 AST_LIST_REMOVE(&dial->channels, channel, list);
448                 AST_LIST_INSERT_HEAD(&dial->channels, channel, list);
449                 set_state(dial, AST_DIAL_RESULT_ANSWERED);
450                 break;
451         case AST_CONTROL_BUSY:
452                 ast_verb(3, "%s is busy\n", channel->owner->name);
453                 ast_hangup(channel->owner);
454                 channel->owner = NULL;
455                 break;
456         case AST_CONTROL_CONGESTION:
457                 ast_verb(3, "%s is circuit-busy\n", channel->owner->name);
458                 ast_hangup(channel->owner);
459                 channel->owner = NULL;
460                 break;
461         case AST_CONTROL_RINGING:
462                 ast_verb(3, "%s is ringing\n", channel->owner->name);
463                 set_state(dial, AST_DIAL_RESULT_RINGING);
464                 break;
465         case AST_CONTROL_PROGRESS:
466                 ast_verb(3, "%s is making progress\n", channel->owner->name);
467                 set_state(dial, AST_DIAL_RESULT_PROGRESS);
468                 break;
469         case AST_CONTROL_PROCEEDING:
470                 ast_verb(3, "%s is proceeding\n", channel->owner->name);
471                 set_state(dial, AST_DIAL_RESULT_PROCEEDING);
472                 break;
473         default:
474                 break;
475         }
476
477         return;
478 }
479
480 /*! \brief Helper function to handle when a timeout occurs on dialing attempt */
481 static int handle_timeout_trip(struct ast_dial *dial, struct timeval start)
482 {
483         struct ast_dial_channel *channel = NULL;
484         int diff = ast_tvdiff_ms(ast_tvnow(), start), lowest_timeout = -1, new_timeout = -1;
485
486         /* If the global dial timeout tripped switch the state to timeout so our channel loop will drop every channel */
487         if (diff >= dial->timeout) {
488                 set_state(dial, AST_DIAL_RESULT_TIMEOUT);
489                 new_timeout = 0;
490         }
491
492         /* Go through dropping out channels that have met their timeout */
493         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
494                 if (dial->state == AST_DIAL_RESULT_TIMEOUT || diff >= channel->timeout) {
495                         ast_hangup(channel->owner);
496                         channel->owner = NULL;
497                 } else if ((lowest_timeout == -1) || (lowest_timeout > channel->timeout)) {
498                         lowest_timeout = channel->timeout;
499                 }
500         }
501
502         /* Calculate the new timeout using the lowest timeout found */
503         if (lowest_timeout >= 0)
504                 new_timeout = lowest_timeout - diff;
505
506         return new_timeout;
507 }
508
509 /*! \brief Helper function that basically keeps tabs on dialing attempts */
510 static enum ast_dial_result monitor_dial(struct ast_dial *dial, struct ast_channel *chan)
511 {
512         int timeout = -1;
513         struct ast_channel *cs[AST_MAX_WATCHERS], *who = NULL;
514         struct ast_dial_channel *channel = NULL;
515         struct answer_exec_struct *answer_exec = NULL;
516         struct timeval start;
517
518         set_state(dial, AST_DIAL_RESULT_TRYING);
519
520         /* If the "always indicate ringing" option is set, change state to ringing and indicate to the owner if present */
521         if (dial->options[AST_DIAL_OPTION_RINGING]) {
522                 set_state(dial, AST_DIAL_RESULT_RINGING);
523                 if (chan)
524                         ast_indicate(chan, AST_CONTROL_RINGING);
525         } else if (chan && dial->options[AST_DIAL_OPTION_MUSIC] && 
526                 !ast_strlen_zero(dial->options[AST_DIAL_OPTION_MUSIC])) {
527                 char *original_moh = ast_strdupa(chan->musicclass);
528                 ast_indicate(chan, -1);
529                 ast_string_field_set(chan, musicclass, dial->options[AST_DIAL_OPTION_MUSIC]);
530                 ast_moh_start(chan, dial->options[AST_DIAL_OPTION_MUSIC], NULL);
531                 ast_string_field_set(chan, musicclass, original_moh);
532         }
533
534         /* Record start time for timeout purposes */
535         start = ast_tvnow();
536
537         /* We actually figured out the maximum timeout we can do as they were added, so we can directly access the info */
538         timeout = dial->actual_timeout;
539
540         /* Go into an infinite loop while we are trying */
541         while ((dial->state != AST_DIAL_RESULT_UNANSWERED) && (dial->state != AST_DIAL_RESULT_ANSWERED) && (dial->state != AST_DIAL_RESULT_HANGUP) && (dial->state != AST_DIAL_RESULT_TIMEOUT)) {
542                 int pos = 0, count = 0;
543                 struct ast_frame *fr = NULL;
544
545                 /* Set up channel structure array */
546                 pos = count = 0;
547                 if (chan)
548                         cs[pos++] = chan;
549
550                 /* Add channels we are attempting to dial */
551                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
552                         if (channel->owner) {
553                                 cs[pos++] = channel->owner;
554                                 count++;
555                         }
556                 }
557
558                 /* If we have no outbound channels in progress, switch state to unanswered and stop */
559                 if (!count) {
560                         set_state(dial, AST_DIAL_RESULT_UNANSWERED);
561                         break;
562                 }
563
564                 /* Just to be safe... */
565                 if (dial->thread == AST_PTHREADT_STOP)
566                         break;
567
568                 /* Wait for frames from channels */
569                 who = ast_waitfor_n(cs, pos, &timeout);
570
571                 /* Check to see if our thread is being cancelled */
572                 if (dial->thread == AST_PTHREADT_STOP)
573                         break;
574
575                 /* If the timeout no longer exists OR if we got no channel it basically means the timeout was tripped, so handle it */
576                 if (!timeout || !who) {
577                         timeout = handle_timeout_trip(dial, start);
578                         continue;
579                 }
580
581                 /* Find relative dial channel */
582                 if (!chan || !IS_CALLER(chan, who))
583                         channel = find_relative_dial_channel(dial, who);
584
585                 /* See if this channel has been forwarded elsewhere */
586                 if (!ast_strlen_zero(who->call_forward)) {
587                         handle_call_forward(dial, channel, chan);
588                         continue;
589                 }
590
591                 /* Attempt to read in a frame */
592                 if (!(fr = ast_read(who))) {
593                         /* If this is the caller then we switch state to hangup and stop */
594                         if (chan && IS_CALLER(chan, who)) {
595                                 set_state(dial, AST_DIAL_RESULT_HANGUP);
596                                 break;
597                         }
598                         ast_hangup(who);
599                         channel->owner = NULL;
600                         continue;
601                 }
602
603                 /* Process the frame */
604                 if (chan)
605                         handle_frame(dial, channel, fr, chan);
606                 else
607                         handle_frame_ownerless(dial, channel, fr);
608
609                 /* Free the received frame and start all over */
610                 ast_frfree(fr);
611         }
612
613         /* Do post-processing from loop */
614         if (dial->state == AST_DIAL_RESULT_ANSWERED) {
615                 /* Hangup everything except that which answered */
616                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
617                         if (!channel->owner || channel->owner == who)
618                                 continue;
619                         ast_hangup(channel->owner);
620                         channel->owner = NULL;
621                 }
622                 /* If ANSWER_EXEC is enabled as an option, execute application on answered channel */
623                 if ((channel = find_relative_dial_channel(dial, who)) && (answer_exec = FIND_RELATIVE_OPTION(dial, channel, AST_DIAL_OPTION_ANSWER_EXEC)))
624                         answer_exec_run(who, answer_exec->app, answer_exec->args);
625
626                 if (chan && dial->options[AST_DIAL_OPTION_MUSIC] && 
627                         !ast_strlen_zero(dial->options[AST_DIAL_OPTION_MUSIC])) {
628                         ast_moh_stop(chan);
629                 }
630         } else if (dial->state == AST_DIAL_RESULT_HANGUP) {
631                 /* Hangup everything */
632                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
633                         if (!channel->owner)
634                                 continue;
635                         ast_hangup(channel->owner);
636                         channel->owner = NULL;
637                 }
638         }
639
640         return dial->state;
641 }
642
643 /*! \brief Dial async thread function */
644 static void *async_dial(void *data)
645 {
646         struct ast_dial *dial = data;
647
648         /* This is really really simple... we basically pass monitor_dial a NULL owner and it changes it's behavior */
649         monitor_dial(dial, NULL);
650
651         return NULL;
652 }
653
654 /*! \brief Execute dialing synchronously or asynchronously
655  * \note Dials channels in a dial structure.
656  * \return Returns dial result code. (TRYING/INVALID/FAILED/ANSWERED/TIMEOUT/UNANSWERED).
657  */
658 enum ast_dial_result ast_dial_run(struct ast_dial *dial, struct ast_channel *chan, int async)
659 {
660         enum ast_dial_result res = AST_DIAL_RESULT_TRYING;
661
662         /* Ensure required arguments are passed */
663         if (!dial || (!chan && !async)) {
664                 ast_debug(1, "invalid #1\n");
665                 return AST_DIAL_RESULT_INVALID;
666         }
667
668         /* If there are no channels to dial we can't very well try to dial them */
669         if (AST_LIST_EMPTY(&dial->channels)) {
670                 ast_debug(1, "invalid #2\n");
671                 return AST_DIAL_RESULT_INVALID;
672         }
673
674         /* Dial each requested channel */
675         if (!begin_dial(dial, chan))
676                 return AST_DIAL_RESULT_FAILED;
677
678         /* If we are running async spawn a thread and send it away... otherwise block here */
679         if (async) {
680                 dial->state = AST_DIAL_RESULT_TRYING;
681                 /* Try to create a thread */
682                 if (ast_pthread_create(&dial->thread, NULL, async_dial, dial)) {
683                         /* Failed to create the thread - hangup all dialed channels and return failed */
684                         ast_dial_hangup(dial);
685                         res = AST_DIAL_RESULT_FAILED;
686                 }
687         } else {
688                 res = monitor_dial(dial, chan);
689         }
690
691         return res;
692 }
693
694 /*! \brief Return channel that answered
695  * \note Returns the Asterisk channel that answered
696  * \param dial Dialing structure
697  */
698 struct ast_channel *ast_dial_answered(struct ast_dial *dial)
699 {
700         if (!dial)
701                 return NULL;
702
703         return ((dial->state == AST_DIAL_RESULT_ANSWERED) ? AST_LIST_FIRST(&dial->channels)->owner : NULL);
704 }
705
706 /*! \brief Return state of dial
707  * \note Returns the state of the dial attempt
708  * \param dial Dialing structure
709  */
710 enum ast_dial_result ast_dial_state(struct ast_dial *dial)
711 {
712         return dial->state;
713 }
714
715 /*! \brief Cancel async thread
716  * \note Cancel a running async thread
717  * \param dial Dialing structure
718  */
719 enum ast_dial_result ast_dial_join(struct ast_dial *dial)
720 {
721         pthread_t thread;
722
723         /* If the dial structure is not running in async, return failed */
724         if (dial->thread == AST_PTHREADT_NULL)
725                 return AST_DIAL_RESULT_FAILED;
726
727         /* Record thread */
728         thread = dial->thread;
729
730         /* Stop the thread */
731         dial->thread = AST_PTHREADT_STOP;
732
733         /* Now we signal it with SIGURG so it will break out of it's waitfor */
734         pthread_kill(thread, SIGURG);
735
736         /* Finally wait for the thread to exit */
737         pthread_join(thread, NULL);
738
739         /* Yay thread is all gone */
740         dial->thread = AST_PTHREADT_NULL;
741
742         return dial->state;
743 }
744
745 /*! \brief Hangup channels
746  * \note Hangup all active channels
747  * \param dial Dialing structure
748  */
749 void ast_dial_hangup(struct ast_dial *dial)
750 {
751         struct ast_dial_channel *channel = NULL;
752
753         if (!dial)
754                 return;
755         
756         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
757                 if (channel->owner) {
758                         ast_hangup(channel->owner);
759                         channel->owner = NULL;
760                 }
761         }
762
763         return;
764 }
765
766 /*! \brief Destroys a dialing structure
767  * \note Destroys (free's) the given ast_dial structure
768  * \param dial Dialing structure to free
769  * \return Returns 0 on success, -1 on failure
770  */
771 int ast_dial_destroy(struct ast_dial *dial)
772 {
773         int i = 0;
774         struct ast_dial_channel *channel = NULL;
775
776         if (!dial)
777                 return -1;
778         
779         /* Hangup and deallocate all the dialed channels */
780         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
781                 /* Disable any enabled options */
782                 for (i = 0; i < AST_DIAL_OPTION_MAX; i++) {
783                         if (!channel->options[i])
784                                 continue;
785                         if (option_types[i].disable)
786                                 option_types[i].disable(channel->options[i]);
787                         channel->options[i] = NULL;
788                 }
789                 /* Hang up channel if need be */
790                 if (channel->owner) {
791                         ast_hangup(channel->owner);
792                         channel->owner = NULL;
793                 }
794                 /* Free structure */
795                 ast_free(channel->tech);
796                 ast_free(channel->device);
797                 ast_free(channel);
798         }
799        
800         /* Disable any enabled options globally */
801         for (i = 0; i < AST_DIAL_OPTION_MAX; i++) {
802                 if (!dial->options[i])
803                         continue;
804                 if (option_types[i].disable)
805                         option_types[i].disable(dial->options[i]);
806                 dial->options[i] = NULL;
807         }
808
809         /* Free structure */
810         ast_free(dial);
811
812         return 0;
813 }
814
815 /*! \brief Enables an option globally
816  * \param dial Dial structure to enable option on
817  * \param option Option to enable
818  * \param data Data to pass to this option (not always needed)
819  * \return Returns 0 on success, -1 on failure
820  */
821 int ast_dial_option_global_enable(struct ast_dial *dial, enum ast_dial_option option, void *data)
822 {
823         /* If the option is already enabled, return failure */
824         if (dial->options[option])
825                 return -1;
826
827         /* Execute enable callback if it exists, if not simply make sure the value is set */
828         if (option_types[option].enable)
829                 dial->options[option] = option_types[option].enable(data);
830         else
831                 dial->options[option] = (void*)1;
832
833         return 0;
834 }
835
836 /*! \brief Helper function for finding a channel in a dial structure based on number
837  */
838 static struct ast_dial_channel *find_dial_channel(struct ast_dial *dial, int num)
839 {
840         struct ast_dial_channel *channel = AST_LIST_LAST(&dial->channels);
841
842         /* We can try to predict programmer behavior, the last channel they added is probably the one they wanted to modify */
843         if (channel->num == num)
844                 return channel;
845
846         /* Hrm not at the end... looking through the list it is! */
847         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
848                 if (channel->num == num)
849                         break;
850         }
851         
852         return channel;
853 }
854
855 /*! \brief Enables an option per channel
856  * \param dial Dial structure
857  * \param num Channel number to enable option on
858  * \param option Option to enable
859  * \param data Data to pass to this option (not always needed)
860  * \return Returns 0 on success, -1 on failure
861  */
862 int ast_dial_option_enable(struct ast_dial *dial, int num, enum ast_dial_option option, void *data)
863 {
864         struct ast_dial_channel *channel = NULL;
865
866         /* Ensure we have required arguments */
867         if (!dial || AST_LIST_EMPTY(&dial->channels))
868                 return -1;
869
870         if (!(channel = find_dial_channel(dial, num)))
871                 return -1;
872
873         /* If the option is already enabled, return failure */
874         if (channel->options[option])
875                 return -1;
876
877         /* Execute enable callback if it exists, if not simply make sure the value is set */
878         if (option_types[option].enable)
879                 channel->options[option] = option_types[option].enable(data);
880         else
881                 channel->options[option] = (void*)1;
882
883         return 0;
884 }
885
886 /*! \brief Disables an option globally
887  * \param dial Dial structure to disable option on
888  * \param option Option to disable
889  * \return Returns 0 on success, -1 on failure
890  */
891 int ast_dial_option_global_disable(struct ast_dial *dial, enum ast_dial_option option)
892 {
893         /* If the option is not enabled, return failure */
894         if (!dial->options[option])
895                 return -1;
896
897         /* Execute callback of option to disable if it exists */
898         if (option_types[option].disable)
899                 option_types[option].disable(dial->options[option]);
900
901         /* Finally disable option on the structure */
902         dial->options[option] = NULL;
903
904         return 0;
905 }
906
907 /*! \brief Disables an option per channel
908  * \param dial Dial structure
909  * \param num Channel number to disable option on
910  * \param option Option to disable
911  * \return Returns 0 on success, -1 on failure
912  */
913 int ast_dial_option_disable(struct ast_dial *dial, int num, enum ast_dial_option option)
914 {
915         struct ast_dial_channel *channel = NULL;
916
917         /* Ensure we have required arguments */
918         if (!dial || AST_LIST_EMPTY(&dial->channels))
919                 return -1;
920
921         if (!(channel = find_dial_channel(dial, num)))
922                 return -1;
923
924         /* If the option is not enabled, return failure */
925         if (!channel->options[option])
926                 return -1;
927
928         /* Execute callback of option to disable it if it exists */
929         if (option_types[option].disable)
930                 option_types[option].disable(channel->options[option]);
931
932         /* Finally disable the option on the structure */
933         channel->options[option] = NULL;
934
935         return 0;
936 }
937
938 void ast_dial_set_state_callback(struct ast_dial *dial, ast_dial_state_callback callback)
939 {
940         dial->state_callback = callback;
941 }
942
943 /*! \brief Set the maximum time (globally) allowed for trying to ring phones
944  * \param dial The dial structure to apply the time limit to
945  * \param timeout Maximum time allowed
946  * \return nothing
947  */
948 void ast_dial_set_global_timeout(struct ast_dial *dial, int timeout)
949 {
950         dial->timeout = timeout;
951
952         if (dial->timeout > 0 && dial->actual_timeout > dial->timeout)
953                 dial->actual_timeout = dial->timeout;
954
955         return;
956 }
957
958 /*! \brief Set the maximum time (per channel) allowed for trying to ring the phone
959  * \param dial The dial structure the channel belongs to
960  * \param num Channel number to set timeout on
961  * \param timeout Maximum time allowed
962  * \return nothing
963  */
964 void ast_dial_set_timeout(struct ast_dial *dial, int num, int timeout)
965 {
966         struct ast_dial_channel *channel = NULL;
967
968         if (!(channel = find_dial_channel(dial, num)))
969                 return;
970
971         channel->timeout = timeout;
972
973         if (channel->timeout > 0 && dial->actual_timeout > channel->timeout)
974                 dial->actual_timeout = channel->timeout;
975
976         return;
977 }