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