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