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