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