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