Issue 9869 - replace malloc and memset with ast_calloc, and other coding guidelines...
[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         enum ast_dial_result state;                        /*!< Status of dial */
52         void *options[AST_DIAL_OPTION_MAX];                /*!< Global options */
53         ast_dial_state_callback state_callback;            /*!< Status callback */
54         AST_LIST_HEAD_NOLOCK(, ast_dial_channel) channels; /*!< Channels being dialed */
55         pthread_t thread;                                  /*!< Thread (if running in async) */
56 };
57
58 /*! \brief Dialing channel structure. Contains per-channel dialing options, asterisk channel, and more! */
59 struct ast_dial_channel {
60         int num;                               /*!< Unique number for dialed channel */
61         const char *tech;                      /*!< Technology being dialed */
62         const char *device;                    /*!< Device being dialed */
63         void *options[AST_DIAL_OPTION_MAX];    /*!< Channel specific options */
64         int cause;                             /*!< Cause code in case of failure */
65         struct ast_channel *owner;             /*!< Asterisk channel */
66         AST_LIST_ENTRY(ast_dial_channel) list; /*!< Linked list information */
67 };
68
69 /*! \brief Typedef for dial option enable */
70 typedef void *(*ast_dial_option_cb_enable)(void *data);
71
72 /*! \brief Typedef for dial option disable */
73 typedef int (*ast_dial_option_cb_disable)(void *data);
74
75 /*! \brief Structure for 'ANSWER_EXEC' option */
76 struct answer_exec_struct {
77         char app[AST_MAX_APP]; /*!< Application name */
78         char *args;            /*!< Application arguments */
79 };
80
81 /*! \brief Enable function for 'ANSWER_EXEC' option */
82 static void *answer_exec_enable(void *data)
83 {
84         struct answer_exec_struct *answer_exec = NULL;
85         char *app = ast_strdupa((char*)data), *args = NULL;
86
87         /* Not giving any data to this option is bad, mmmk? */
88         if (ast_strlen_zero(app))
89                 return NULL;
90
91         /* Create new data structure */
92         if (!(answer_exec = ast_calloc(1, sizeof(*answer_exec))))
93                 return NULL;
94         
95         /* Parse out application and arguments */
96         if ((args = strchr(app, '|'))) {
97                 *args++ = '\0';
98                 answer_exec->args = ast_strdup(args);
99         }
100
101         /* Copy application name */
102         ast_copy_string(answer_exec->app, app, sizeof(answer_exec->app));
103
104         return answer_exec;
105 }
106
107 /*! \brief Disable function for 'ANSWER_EXEC' option */
108 static int answer_exec_disable(void *data)
109 {
110         struct answer_exec_struct *answer_exec = data;
111
112         /* Make sure we have a value */
113         if (!answer_exec)
114                 return -1;
115
116         /* If arguments are present, free them too */
117         if (answer_exec->args)
118                 ast_free(answer_exec->args);
119
120         /* This is simple - just free the structure */
121         ast_free(answer_exec);
122
123         return 0;
124 }
125
126 static void *music_enable(void *data)
127 {
128         return ast_strdup(data);
129 }
130
131 static int music_disable(void *data)
132 {
133         if (!data)
134                 return -1;
135
136         ast_free(data);
137
138         return 0;
139 }
140
141 /*! \brief Application execution function for 'ANSWER_EXEC' option */
142 static void answer_exec_run(struct ast_channel *chan, char *app, char *args)
143 {
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         return;
154 }
155
156 /*! \brief Options structure - maps options to respective handlers (enable/disable). This list MUST be perfectly kept in order, or else madness will happen. */
157 static const struct ast_option_types {
158         enum ast_dial_option option;
159         ast_dial_option_cb_enable enable;
160         ast_dial_option_cb_disable disable;
161 } option_types[] = {
162         { AST_DIAL_OPTION_RINGING, NULL, NULL },                                  /*!< Always indicate ringing to caller */
163         { AST_DIAL_OPTION_ANSWER_EXEC, answer_exec_enable, answer_exec_disable }, /*!< Execute application upon answer in async mode */
164         { AST_DIAL_OPTION_MUSIC, music_enable, music_disable },                   /*!< Play music to the caller instead of ringing */
165         { AST_DIAL_OPTION_MAX, NULL, NULL },                                      /*!< Terminator of list */
166 };
167
168 /*! \brief free the buffer if allocated, and set the pointer to the second arg */
169 #define S_REPLACE(s, new_val)           \
170         do {                            \
171                 if (s)                  \
172                         free(s);        \
173                 s = (new_val);          \
174         } while (0)
175
176 /*! \brief Maximum number of channels we can watch at a time */
177 #define AST_MAX_WATCHERS 256
178
179 /*! \brief Macro for finding the option structure to use on a dialed channel */
180 #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])
181
182 /*! \brief Macro that determines whether a channel is the caller or not */
183 #define IS_CALLER(chan, owner) (chan == owner ? 1 : 0)
184
185 /*! \brief New dialing structure
186  * \note Create a dialing structure
187  * \return Returns a calloc'd ast_dial structure, NULL on failure
188  */
189 struct ast_dial *ast_dial_create(void)
190 {
191         struct ast_dial *dial = NULL;
192
193         /* Allocate new memory for structure */
194         if (!(dial = ast_calloc(1, sizeof(*dial))))
195                 return NULL;
196
197         /* Initialize list of channels */
198         AST_LIST_HEAD_INIT_NOLOCK(&dial->channels);
199
200         /* Initialize thread to NULL */
201         dial->thread = AST_PTHREADT_NULL;
202
203         return dial;
204 }
205
206 /*! \brief Append a channel
207  * \note Appends a channel to a dialing structure
208  * \return Returns channel reference number on success, -1 on failure
209  */
210 int ast_dial_append(struct ast_dial *dial, const char *tech, const char *device)
211 {
212         struct ast_dial_channel *channel = NULL;
213
214         /* Make sure we have required arguments */
215         if (!dial || !tech || !device)
216                 return -1;
217
218         /* Allocate new memory for dialed channel structure */
219         if (!(channel = ast_calloc(1, sizeof(*channel))))
220                 return -1;
221
222         /* Record technology and device for when we actually dial */
223         channel->tech = tech;
224         channel->device = device;
225
226         /* Grab reference number from dial structure */
227         channel->num = ast_atomic_fetchadd_int(&dial->num, +1);
228
229         /* Insert into channels list */
230         AST_LIST_INSERT_TAIL(&dial->channels, channel, list);
231
232         return channel->num;
233 }
234
235 /*! \brief Helper function that does the beginning dialing */
236 static int begin_dial(struct ast_dial *dial, struct ast_channel *chan)
237 {
238         struct ast_dial_channel *channel = NULL;
239         int success = 0, res = 0;
240
241         /* Iterate through channel list, requesting and calling each one */
242         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
243                 char numsubst[AST_MAX_EXTENSION];
244
245                 /* Copy device string over */
246                 ast_copy_string(numsubst, channel->device, sizeof(numsubst));
247
248                 /* Request that the channel be created */
249                 if (!(channel->owner = ast_request(channel->tech, 
250                         chan ? chan->nativeformats : AST_FORMAT_AUDIO_MASK, numsubst, &channel->cause))) {
251                         continue;
252                 }
253
254                 channel->owner->appl = "AppDial2";
255                 channel->owner->data = "(Outgoing Line)";
256                 channel->owner->whentohangup = 0;
257
258                 /* Inherit everything from he who spawned this Dial */
259                 if (chan) {
260                         ast_channel_inherit_variables(chan, channel->owner);
261
262                         /* Copy over callerid information */
263                         S_REPLACE(channel->owner->cid.cid_num, ast_strdup(chan->cid.cid_num));
264                         S_REPLACE(channel->owner->cid.cid_name, ast_strdup(chan->cid.cid_name));
265                         S_REPLACE(channel->owner->cid.cid_ani, ast_strdup(chan->cid.cid_ani));
266                         S_REPLACE(channel->owner->cid.cid_rdnis, ast_strdup(chan->cid.cid_rdnis));
267         
268                         ast_string_field_set(channel->owner, language, chan->language);
269                         ast_string_field_set(channel->owner, accountcode, chan->accountcode);
270                         channel->owner->cdrflags = chan->cdrflags;
271                         if (ast_strlen_zero(channel->owner->musicclass))
272                                 ast_string_field_set(channel->owner, musicclass, chan->musicclass);
273         
274                         channel->owner->cid.cid_pres = chan->cid.cid_pres;
275                         channel->owner->cid.cid_ton = chan->cid.cid_ton;
276                         channel->owner->cid.cid_tns = chan->cid.cid_tns;
277                         channel->owner->adsicpe = chan->adsicpe;
278                         channel->owner->transfercapability = chan->transfercapability;
279                 }
280
281                 /* Actually call the device */
282                 if ((res = ast_call(channel->owner, numsubst, 0))) {
283                         ast_hangup(channel->owner);
284                         channel->owner = NULL;
285                 } else {
286                         success++;
287                         if (option_verbose > 2)
288                                 ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", numsubst);
289                 }
290         }
291
292         /* If number of failures matches the number of channels, then this truly failed */
293         return success;
294 }
295
296 /*! \brief Helper function that finds the dialed channel based on owner */
297 static struct ast_dial_channel *find_relative_dial_channel(struct ast_dial *dial, struct ast_channel *owner)
298 {
299         struct ast_dial_channel *channel = NULL;
300
301         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
302                 if (channel->owner == owner)
303                         break;
304         }
305
306         return channel;
307 }
308
309 static void set_state(struct ast_dial *dial, enum ast_dial_result state)
310 {
311         dial->state = state;
312
313         if (dial->state_callback)
314                 dial->state_callback(dial);
315 }
316
317 /*! \brief Helper function that handles control frames WITH owner */
318 static void handle_frame(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_frame *fr, struct ast_channel *chan)
319 {
320         if (fr->frametype == AST_FRAME_CONTROL) {
321                 switch (fr->subclass) {
322                 case AST_CONTROL_ANSWER:
323                         if (option_verbose > 2)
324                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", channel->owner->name, chan->name);
325                         AST_LIST_REMOVE(&dial->channels, channel, list);
326                         AST_LIST_INSERT_HEAD(&dial->channels, channel, list);
327                         set_state(dial, AST_DIAL_RESULT_ANSWERED);
328                         break;
329                 case AST_CONTROL_BUSY:
330                         if (option_verbose > 2)
331                                 ast_verbose(VERBOSE_PREFIX_3 "%s is busy\n", channel->owner->name);
332                         ast_hangup(channel->owner);
333                         channel->owner = NULL;
334                         break;
335                 case AST_CONTROL_CONGESTION:
336                         if (option_verbose > 2)
337                                 ast_verbose(VERBOSE_PREFIX_3 "%s is circuit-busy\n", channel->owner->name);
338                         ast_hangup(channel->owner);
339                         channel->owner = NULL;
340                         break;
341                 case AST_CONTROL_RINGING:
342                         if (option_verbose > 2)
343                                 ast_verbose(VERBOSE_PREFIX_3 "%s is ringing\n", channel->owner->name);
344                         if (!dial->options[AST_DIAL_OPTION_MUSIC])
345                                 ast_indicate(chan, AST_CONTROL_RINGING);
346                         set_state(dial, AST_DIAL_RESULT_RINGING);
347                         break;
348                 case AST_CONTROL_PROGRESS:
349                         if (option_verbose > 2)
350                                 ast_verbose (VERBOSE_PREFIX_3 "%s is making progress, passing it to %s\n", channel->owner->name, chan->name);
351                         ast_indicate(chan, AST_CONTROL_PROGRESS);
352                         set_state(dial, AST_DIAL_RESULT_PROGRESS);
353                         break;
354                 case AST_CONTROL_VIDUPDATE:
355                         if (option_verbose > 2)
356                                 ast_verbose (VERBOSE_PREFIX_3 "%s requested a video update, passing it to %s\n", channel->owner->name, chan->name);
357                         ast_indicate(chan, AST_CONTROL_VIDUPDATE);
358                         break;
359                 case AST_CONTROL_PROCEEDING:
360                         if (option_verbose > 2)
361                                 ast_verbose (VERBOSE_PREFIX_3 "%s is proceeding, passing it to %s\n", channel->owner->name, chan->name);
362                         ast_indicate(chan, AST_CONTROL_PROCEEDING);
363                         set_state(dial, AST_DIAL_RESULT_PROCEEDING);
364                         break;
365                 case AST_CONTROL_HOLD:
366                         if (option_verbose > 2)
367                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s placed on hold\n", chan->name);
368                         ast_indicate(chan, AST_CONTROL_HOLD);
369                         break;
370                 case AST_CONTROL_UNHOLD:
371                         if (option_verbose > 2)
372                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s left from hold\n", chan->name);
373                         ast_indicate(chan, AST_CONTROL_UNHOLD);
374                         break;
375                 case AST_CONTROL_OFFHOOK:
376                 case AST_CONTROL_FLASH:
377                         break;
378                 case -1:
379                         /* Prod the channel */
380                         ast_indicate(chan, -1);
381                         break;
382                 default:
383                         break;
384                 }
385         }
386
387         return;
388 }
389
390 /*! \brief Helper function that handles control frames WITHOUT owner */
391 static void handle_frame_ownerless(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_frame *fr)
392 {
393         /* If we have no owner we can only update the state of the dial structure, so only look at control frames */
394         if (fr->frametype != AST_FRAME_CONTROL)
395                 return;
396
397         switch (fr->subclass) {
398         case AST_CONTROL_ANSWER:
399                 if (option_verbose > 2)
400                         ast_verbose( VERBOSE_PREFIX_3 "%s answered\n", channel->owner->name);
401                 AST_LIST_REMOVE(&dial->channels, channel, list);
402                 AST_LIST_INSERT_HEAD(&dial->channels, channel, list);
403                 set_state(dial, AST_DIAL_RESULT_ANSWERED);
404                 break;
405         case AST_CONTROL_BUSY:
406                 if (option_verbose > 2)
407                         ast_verbose(VERBOSE_PREFIX_3 "%s is busy\n", channel->owner->name);
408                 ast_hangup(channel->owner);
409                 channel->owner = NULL;
410                 break;
411         case AST_CONTROL_CONGESTION:
412                 if (option_verbose > 2)
413                         ast_verbose(VERBOSE_PREFIX_3 "%s is circuit-busy\n", channel->owner->name);
414                 ast_hangup(channel->owner);
415                 channel->owner = NULL;
416                 break;
417         case AST_CONTROL_RINGING:
418                 if (option_verbose > 2)
419                         ast_verbose(VERBOSE_PREFIX_3 "%s is ringing\n", channel->owner->name);
420                 set_state(dial, AST_DIAL_RESULT_RINGING);
421                 break;
422         case AST_CONTROL_PROGRESS:
423                 if (option_verbose > 2)
424                         ast_verbose (VERBOSE_PREFIX_3 "%s is making progress\n", channel->owner->name);
425                 set_state(dial, AST_DIAL_RESULT_PROGRESS);
426                 break;
427         case AST_CONTROL_PROCEEDING:
428                 if (option_verbose > 2)
429                         ast_verbose (VERBOSE_PREFIX_3 "%s is proceeding\n", channel->owner->name);
430                 set_state(dial, AST_DIAL_RESULT_PROCEEDING);
431                 break;
432         default:
433                 break;
434         }
435
436         return;
437 }
438
439 /*! \brief Helper function that basically keeps tabs on dialing attempts */
440 static enum ast_dial_result monitor_dial(struct ast_dial *dial, struct ast_channel *chan)
441 {
442         int timeout = -1, count = 0;
443         struct ast_channel *cs[AST_MAX_WATCHERS], *who = NULL;
444         struct ast_dial_channel *channel = NULL;
445         struct answer_exec_struct *answer_exec = NULL;
446
447         set_state(dial, AST_DIAL_RESULT_TRYING);
448
449         /* If the "always indicate ringing" option is set, change state to ringing and indicate to the owner if present */
450         if (dial->options[AST_DIAL_OPTION_RINGING]) {
451                 set_state(dial, AST_DIAL_RESULT_RINGING);
452                 if (chan)
453                         ast_indicate(chan, AST_CONTROL_RINGING);
454         } else if (chan && dial->options[AST_DIAL_OPTION_MUSIC] && 
455                 !ast_strlen_zero(dial->options[AST_DIAL_OPTION_MUSIC])) {
456                 char *original_moh = ast_strdupa(chan->musicclass);
457                 ast_indicate(chan, -1);
458                 ast_string_field_set(chan, musicclass, dial->options[AST_DIAL_OPTION_MUSIC]);
459                 ast_moh_start(chan, dial->options[AST_DIAL_OPTION_MUSIC], NULL);
460                 ast_string_field_set(chan, musicclass, original_moh);
461         }
462
463         /* Go into an infinite loop while we are trying */
464         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)) {
465                 int pos = 0;
466                 struct ast_frame *fr = NULL;
467
468                 /* Set up channel structure array */
469                 pos = count = 0;
470                 if (chan)
471                         cs[pos++] = chan;
472
473                 /* Add channels we are attempting to dial */
474                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
475                         if (channel->owner) {
476                                 cs[pos++] = channel->owner;
477                                 count++;
478                         }
479                 }
480
481                 /* If we have no outbound channels in progress, switch state to unanswered and stop */
482                 if (!count) {
483                         set_state(dial, AST_DIAL_RESULT_UNANSWERED);
484                         break;
485                 }
486
487                 /* Just to be safe... */
488                 if (dial->thread == AST_PTHREADT_STOP)
489                         break;
490
491                 /* Wait for frames from channels */
492                 who = ast_waitfor_n(cs, pos, &timeout);
493
494                 /* Check to see if our thread is being cancelled */
495                 if (dial->thread == AST_PTHREADT_STOP)
496                         break;
497
498                 /* If we are not being cancelled and we have no channel, then timeout was tripped */
499                 if (!who)
500                         continue;
501
502                 /* Find relative dial channel */
503                 if (!chan || !IS_CALLER(chan, who))
504                         channel = find_relative_dial_channel(dial, who);
505
506                 /* Attempt to read in a frame */
507                 if (!(fr = ast_read(who))) {
508                         /* If this is the caller then we switch state to hangup and stop */
509                         if (chan && IS_CALLER(chan, who)) {
510                                 set_state(dial, AST_DIAL_RESULT_HANGUP);
511                                 break;
512                         }
513                         ast_hangup(who);
514                         channel->owner = NULL;
515                         continue;
516                 }
517
518                 /* Process the frame */
519                 if (chan)
520                         handle_frame(dial, channel, fr, chan);
521                 else
522                         handle_frame_ownerless(dial, channel, fr);
523
524                 /* Free the received frame and start all over */
525                 ast_frfree(fr);
526         }
527
528         /* Do post-processing from loop */
529         if (dial->state == AST_DIAL_RESULT_ANSWERED) {
530                 /* Hangup everything except that which answered */
531                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
532                         if (!channel->owner || channel->owner == who)
533                                 continue;
534                         ast_hangup(channel->owner);
535                         channel->owner = NULL;
536                 }
537                 /* If ANSWER_EXEC is enabled as an option, execute application on answered channel */
538                 if ((channel = find_relative_dial_channel(dial, who)) && (answer_exec = FIND_RELATIVE_OPTION(dial, channel, AST_DIAL_OPTION_ANSWER_EXEC)))
539                         answer_exec_run(who, answer_exec->app, answer_exec->args);
540
541                 if (chan && dial->options[AST_DIAL_OPTION_MUSIC] && 
542                         !ast_strlen_zero(dial->options[AST_DIAL_OPTION_MUSIC])) {
543                         ast_moh_stop(chan);
544                 }
545         } else if (dial->state == AST_DIAL_RESULT_HANGUP) {
546                 /* Hangup everything */
547                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
548                         if (!channel->owner)
549                                 continue;
550                         ast_hangup(channel->owner);
551                         channel->owner = NULL;
552                 }
553         }
554
555         return dial->state;
556 }
557
558 /*! \brief Dial async thread function */
559 static void *async_dial(void *data)
560 {
561         struct ast_dial *dial = data;
562
563         /* This is really really simple... we basically pass monitor_dial a NULL owner and it changes it's behavior */
564         monitor_dial(dial, NULL);
565
566         return NULL;
567 }
568
569 /*! \brief Execute dialing synchronously or asynchronously
570  * \note Dials channels in a dial structure.
571  * \return Returns dial result code. (TRYING/INVALID/FAILED/ANSWERED/TIMEOUT/UNANSWERED).
572  */
573 enum ast_dial_result ast_dial_run(struct ast_dial *dial, struct ast_channel *chan, int async)
574 {
575         enum ast_dial_result res = AST_DIAL_RESULT_TRYING;
576
577         /* Ensure required arguments are passed */
578         if (!dial || (!chan && !async)) {
579                 ast_log(LOG_DEBUG, "invalid #1\n");
580                 return AST_DIAL_RESULT_INVALID;
581         }
582
583         /* If there are no channels to dial we can't very well try to dial them */
584         if (AST_LIST_EMPTY(&dial->channels)) {
585                 ast_log(LOG_DEBUG, "invalid #2\n");
586                 return AST_DIAL_RESULT_INVALID;
587         }
588
589         /* Dial each requested channel */
590         if (!begin_dial(dial, chan))
591                 return AST_DIAL_RESULT_FAILED;
592
593         /* If we are running async spawn a thread and send it away... otherwise block here */
594         if (async) {
595                 dial->state = AST_DIAL_RESULT_TRYING;
596                 /* Try to create a thread */
597                 if (ast_pthread_create(&dial->thread, NULL, async_dial, dial)) {
598                         /* Failed to create the thread - hangup all dialed channels and return failed */
599                         ast_dial_hangup(dial);
600                         res = AST_DIAL_RESULT_FAILED;
601                 }
602         } else {
603                 res = monitor_dial(dial, chan);
604         }
605
606         return res;
607 }
608
609 /*! \brief Return channel that answered
610  * \note Returns the Asterisk channel that answered
611  * \param dial Dialing structure
612  */
613 struct ast_channel *ast_dial_answered(struct ast_dial *dial)
614 {
615         if (!dial)
616                 return NULL;
617
618         return ((dial->state == AST_DIAL_RESULT_ANSWERED) ? AST_LIST_FIRST(&dial->channels)->owner : NULL);
619 }
620
621 /*! \brief Return state of dial
622  * \note Returns the state of the dial attempt
623  * \param dial Dialing structure
624  */
625 enum ast_dial_result ast_dial_state(struct ast_dial *dial)
626 {
627         return dial->state;
628 }
629
630 /*! \brief Cancel async thread
631  * \note Cancel a running async thread
632  * \param dial Dialing structure
633  */
634 enum ast_dial_result ast_dial_join(struct ast_dial *dial)
635 {
636         pthread_t thread;
637
638         /* If the dial structure is not running in async, return failed */
639         if (dial->thread == AST_PTHREADT_NULL)
640                 return AST_DIAL_RESULT_FAILED;
641
642         /* Record thread */
643         thread = dial->thread;
644
645         /* Stop the thread */
646         dial->thread = AST_PTHREADT_STOP;
647
648         /* Now we signal it with SIGURG so it will break out of it's waitfor */
649         pthread_kill(thread, SIGURG);
650
651         /* Finally wait for the thread to exit */
652         pthread_join(thread, NULL);
653
654         /* Yay thread is all gone */
655         dial->thread = AST_PTHREADT_NULL;
656
657         return dial->state;
658 }
659
660 /*! \brief Hangup channels
661  * \note Hangup all active channels
662  * \param dial Dialing structure
663  */
664 void ast_dial_hangup(struct ast_dial *dial)
665 {
666         struct ast_dial_channel *channel = NULL;
667
668         if (!dial)
669                 return;
670         
671         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
672                 if (channel->owner) {
673                         ast_hangup(channel->owner);
674                         channel->owner = NULL;
675                 }
676         }
677
678         return;
679 }
680
681 /*! \brief Destroys a dialing structure
682  * \note Destroys (free's) the given ast_dial structure
683  * \param dial Dialing structure to free
684  * \return Returns 0 on success, -1 on failure
685  */
686 int ast_dial_destroy(struct ast_dial *dial)
687 {
688         int i = 0;
689         struct ast_dial_channel *channel = NULL;
690
691         if (!dial)
692                 return -1;
693         
694         /* Hangup and deallocate all the dialed channels */
695         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
696                 /* Disable any enabled options */
697                 for (i = 0; i < AST_DIAL_OPTION_MAX; i++) {
698                         if (!channel->options[i])
699                                 continue;
700                         if (option_types[i].disable)
701                                 option_types[i].disable(channel->options[i]);
702                         channel->options[i] = NULL;
703                 }
704                 /* Hang up channel if need be */
705                 if (channel->owner) {
706                         ast_hangup(channel->owner);
707                         channel->owner = NULL;
708                 }
709                 /* Free structure */
710                 ast_free(channel);
711         }
712        
713         /* Disable any enabled options globally */
714         for (i = 0; i < AST_DIAL_OPTION_MAX; i++) {
715                 if (!dial->options[i])
716                         continue;
717                 if (option_types[i].disable)
718                         option_types[i].disable(dial->options[i]);
719                 dial->options[i] = NULL;
720         }
721
722         /* Free structure */
723         ast_free(dial);
724
725         return 0;
726 }
727
728 /*! \brief Enables an option globally
729  * \param dial Dial structure to enable option on
730  * \param option Option to enable
731  * \param data Data to pass to this option (not always needed)
732  * \return Returns 0 on success, -1 on failure
733  */
734 int ast_dial_option_global_enable(struct ast_dial *dial, enum ast_dial_option option, void *data)
735 {
736         /* If the option is already enabled, return failure */
737         if (dial->options[option])
738                 return -1;
739
740         /* Execute enable callback if it exists, if not simply make sure the value is set */
741         if (option_types[option].enable)
742                 dial->options[option] = option_types[option].enable(data);
743         else
744                 dial->options[option] = (void*)1;
745
746         return 0;
747 }
748
749 /*! \brief Enables an option per channel
750  * \param dial Dial structure
751  * \param num Channel number to enable option on
752  * \param option Option to enable
753  * \param data Data to pass to this option (not always needed)
754  * \return Returns 0 on success, -1 on failure
755  */
756 int ast_dial_option_enable(struct ast_dial *dial, int num, enum ast_dial_option option, void *data)
757 {
758         struct ast_dial_channel *channel = NULL;
759
760         /* Ensure we have required arguments */
761         if (!dial || AST_LIST_EMPTY(&dial->channels))
762                 return -1;
763         
764         /* Look for channel, we can sort of cheat and predict things - the last channel in the list will probably be what they want */
765         if (AST_LIST_LAST(&dial->channels)->num != num) {
766                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
767                         if (channel->num == num)
768                                 break;
769                 }
770         } else {
771                 channel = AST_LIST_LAST(&dial->channels);
772         }
773
774         /* If none found, return failure */
775         if (!channel)
776                 return -1;
777
778         /* If the option is already enabled, return failure */
779         if (channel->options[option])
780                 return -1;
781
782         /* Execute enable callback if it exists, if not simply make sure the value is set */
783         if (option_types[option].enable)
784                 channel->options[option] = option_types[option].enable(data);
785         else
786                 channel->options[option] = (void*)1;
787
788         return 0;
789 }
790
791 /*! \brief Disables an option globally
792  * \param dial Dial structure to disable option on
793  * \param option Option to disable
794  * \return Returns 0 on success, -1 on failure
795  */
796 int ast_dial_option_global_disable(struct ast_dial *dial, enum ast_dial_option option)
797 {
798         /* If the option is not enabled, return failure */
799         if (!dial->options[option])
800                 return -1;
801
802         /* Execute callback of option to disable if it exists */
803         if (option_types[option].disable)
804                 option_types[option].disable(dial->options[option]);
805
806         /* Finally disable option on the structure */
807         dial->options[option] = NULL;
808
809         return 0;
810 }
811
812 /*! \brief Disables an option per channel
813  * \param dial Dial structure
814  * \param num Channel number to disable option on
815  * \param option Option to disable
816  * \return Returns 0 on success, -1 on failure
817  */
818 int ast_dial_option_disable(struct ast_dial *dial, int num, enum ast_dial_option option)
819 {
820         struct ast_dial_channel *channel = NULL;
821
822         /* Ensure we have required arguments */
823         if (!dial || AST_LIST_EMPTY(&dial->channels))
824                 return -1;
825
826         /* Look for channel, we can sort of cheat and predict things - the last channel in the list will probably be what they want */
827         if (AST_LIST_LAST(&dial->channels)->num != num) {
828                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
829                         if (channel->num == num)
830                                 break;
831                 }
832         } else {
833                 channel = AST_LIST_LAST(&dial->channels);
834         }
835
836         /* If none found, return failure */
837         if (!channel)
838                 return -1;
839
840         /* If the option is not enabled, return failure */
841         if (!channel->options[option])
842                 return -1;
843
844         /* Execute callback of option to disable it if it exists */
845         if (option_types[option].disable)
846                 option_types[option].disable(channel->options[option]);
847
848         /* Finally disable the option on the structure */
849         channel->options[option] = NULL;
850
851         return 0;
852 }
853
854 void ast_dial_set_state_callback(struct ast_dial *dial, ast_dial_state_callback callback)
855 {
856         dial->state_callback = callback;
857 }