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