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