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