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