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