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