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