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