Move origination to use the dialing API and send Stasis messages on dial begin and...
[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)
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                 ast_channel_publish_dial(chan, channel->owner, channel->device, NULL);
357                 res = 1;
358                 ast_verb(3, "Called %s\n", numsubst);
359         }
360
361         return res;
362 }
363
364 /*! \brief Helper function that does the beginning dialing per dial structure */
365 static int begin_dial(struct ast_dial *dial, struct ast_channel *chan)
366 {
367         struct ast_dial_channel *channel = NULL;
368         int success = 0;
369
370         /* Iterate through channel list, requesting and calling each one */
371         AST_LIST_LOCK(&dial->channels);
372         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
373                 success += begin_dial_channel(channel, chan);
374         }
375         AST_LIST_UNLOCK(&dial->channels);
376
377         /* If number of failures matches the number of channels, then this truly failed */
378         return success;
379 }
380
381 /*! \brief Helper function to handle channels that have been call forwarded */
382 static int handle_call_forward(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_channel *chan)
383 {
384         struct ast_channel *original = channel->owner;
385         char *tmp = ast_strdupa(ast_channel_call_forward(channel->owner));
386         char *tech = "Local", *device = tmp, *stuff;
387
388         /* If call forwarding is disabled just drop the original channel and don't attempt to dial the new one */
389         if (FIND_RELATIVE_OPTION(dial, channel, AST_DIAL_OPTION_DISABLE_CALL_FORWARDING)) {
390                 ast_hangup(original);
391                 channel->owner = NULL;
392                 return 0;
393         }
394
395         /* Figure out the new destination */
396         if ((stuff = strchr(tmp, '/'))) {
397                 *stuff++ = '\0';
398                 tech = tmp;
399                 device = stuff;
400         }
401
402         /* Drop old destination information */
403         ast_free(channel->tech);
404         ast_free(channel->device);
405
406         /* Update the dial channel with the new destination information */
407         channel->tech = ast_strdup(tech);
408         channel->device = ast_strdup(device);
409         AST_LIST_UNLOCK(&dial->channels);
410
411         /* Finally give it a go... send it out into the world */
412         begin_dial_channel(channel, chan);
413
414         /* Drop the original channel */
415         ast_hangup(original);
416
417         return 0;
418 }
419
420 /*! \brief Helper function that finds the dialed channel based on owner */
421 static struct ast_dial_channel *find_relative_dial_channel(struct ast_dial *dial, struct ast_channel *owner)
422 {
423         struct ast_dial_channel *channel = NULL;
424
425         AST_LIST_LOCK(&dial->channels);
426         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
427                 if (channel->owner == owner)
428                         break;
429         }
430         AST_LIST_UNLOCK(&dial->channels);
431
432         return channel;
433 }
434
435 static void set_state(struct ast_dial *dial, enum ast_dial_result state)
436 {
437         dial->state = state;
438
439         if (dial->state_callback)
440                 dial->state_callback(dial);
441 }
442
443 /*! \brief Helper function that handles control frames WITH owner */
444 static void handle_frame(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_frame *fr, struct ast_channel *chan)
445 {
446         if (fr->frametype == AST_FRAME_CONTROL) {
447                 switch (fr->subclass.integer) {
448                 case AST_CONTROL_ANSWER:
449                         ast_verb(3, "%s answered %s\n", ast_channel_name(channel->owner), ast_channel_name(chan));
450                         AST_LIST_LOCK(&dial->channels);
451                         AST_LIST_REMOVE(&dial->channels, channel, list);
452                         AST_LIST_INSERT_HEAD(&dial->channels, channel, list);
453                         AST_LIST_UNLOCK(&dial->channels);
454                         ast_channel_publish_dial(chan, channel->owner, channel->device, "ANSWER");
455                         set_state(dial, AST_DIAL_RESULT_ANSWERED);
456                         break;
457                 case AST_CONTROL_BUSY:
458                         ast_verb(3, "%s is busy\n", ast_channel_name(channel->owner));
459                         ast_channel_publish_dial(chan, channel->owner, channel->device, "BUSY");
460                         ast_hangup(channel->owner);
461                         channel->owner = NULL;
462                         break;
463                 case AST_CONTROL_CONGESTION:
464                         ast_verb(3, "%s is circuit-busy\n", ast_channel_name(channel->owner));
465                         ast_channel_publish_dial(chan, channel->owner, channel->device, "CONGESTION");
466                         ast_hangup(channel->owner);
467                         channel->owner = NULL;
468                         break;
469                 case AST_CONTROL_INCOMPLETE:
470                         ast_verb(3, "%s dialed Incomplete extension %s\n", ast_channel_name(channel->owner), ast_channel_exten(channel->owner));
471                         ast_indicate(chan, AST_CONTROL_INCOMPLETE);
472                         break;
473                 case AST_CONTROL_RINGING:
474                         ast_verb(3, "%s is ringing\n", ast_channel_name(channel->owner));
475                         if (!dial->options[AST_DIAL_OPTION_MUSIC])
476                                 ast_indicate(chan, AST_CONTROL_RINGING);
477                         set_state(dial, AST_DIAL_RESULT_RINGING);
478                         break;
479                 case AST_CONTROL_PROGRESS:
480                         ast_verb(3, "%s is making progress, passing it to %s\n", ast_channel_name(channel->owner), ast_channel_name(chan));
481                         ast_indicate(chan, AST_CONTROL_PROGRESS);
482                         set_state(dial, AST_DIAL_RESULT_PROGRESS);
483                         break;
484                 case AST_CONTROL_VIDUPDATE:
485                         ast_verb(3, "%s requested a video update, passing it to %s\n", ast_channel_name(channel->owner), ast_channel_name(chan));
486                         ast_indicate(chan, AST_CONTROL_VIDUPDATE);
487                         break;
488                 case AST_CONTROL_SRCUPDATE:
489                         ast_verb(3, "%s requested a source update, passing it to %s\n", ast_channel_name(channel->owner), ast_channel_name(chan));
490                         ast_indicate(chan, AST_CONTROL_SRCUPDATE);
491                         break;
492                 case AST_CONTROL_CONNECTED_LINE:
493                         ast_verb(3, "%s connected line has changed, passing it to %s\n", ast_channel_name(channel->owner), ast_channel_name(chan));
494                         if (ast_channel_connected_line_sub(channel->owner, chan, fr, 1) &&
495                                 ast_channel_connected_line_macro(channel->owner, chan, fr, 1, 1)) {
496                                 ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE, fr->data.ptr, fr->datalen);
497                         }
498                         break;
499                 case AST_CONTROL_REDIRECTING:
500                         ast_verb(3, "%s redirecting info has changed, passing it to %s\n", ast_channel_name(channel->owner), ast_channel_name(chan));
501                         if (ast_channel_redirecting_sub(channel->owner, chan, fr, 1) &&
502                                 ast_channel_redirecting_macro(channel->owner, chan, fr, 1, 1)) {
503                                 ast_indicate_data(chan, AST_CONTROL_REDIRECTING, fr->data.ptr, fr->datalen);
504                         }
505                         break;
506                 case AST_CONTROL_PROCEEDING:
507                         ast_verb(3, "%s is proceeding, passing it to %s\n", ast_channel_name(channel->owner), ast_channel_name(chan));
508                         ast_indicate(chan, AST_CONTROL_PROCEEDING);
509                         set_state(dial, AST_DIAL_RESULT_PROCEEDING);
510                         break;
511                 case AST_CONTROL_HOLD:
512                         ast_verb(3, "Call on %s placed on hold\n", ast_channel_name(chan));
513                         ast_indicate(chan, AST_CONTROL_HOLD);
514                         break;
515                 case AST_CONTROL_UNHOLD:
516                         ast_verb(3, "Call on %s left from hold\n", ast_channel_name(chan));
517                         ast_indicate(chan, AST_CONTROL_UNHOLD);
518                         break;
519                 case AST_CONTROL_OFFHOOK:
520                 case AST_CONTROL_FLASH:
521                         break;
522                 case AST_CONTROL_PVT_CAUSE_CODE:
523                         ast_indicate_data(chan, AST_CONTROL_PVT_CAUSE_CODE, fr->data.ptr, fr->datalen);
524                         break;
525                 case -1:
526                         /* Prod the channel */
527                         ast_indicate(chan, -1);
528                         break;
529                 default:
530                         break;
531                 }
532         }
533
534         return;
535 }
536
537 /*! \brief Helper function that handles control frames WITHOUT owner */
538 static void handle_frame_ownerless(struct ast_dial *dial, struct ast_dial_channel *channel, struct ast_frame *fr)
539 {
540         /* If we have no owner we can only update the state of the dial structure, so only look at control frames */
541         if (fr->frametype != AST_FRAME_CONTROL)
542                 return;
543
544         switch (fr->subclass.integer) {
545         case AST_CONTROL_ANSWER:
546                 ast_verb(3, "%s answered\n", ast_channel_name(channel->owner));
547                 AST_LIST_LOCK(&dial->channels);
548                 AST_LIST_REMOVE(&dial->channels, channel, list);
549                 AST_LIST_INSERT_HEAD(&dial->channels, channel, list);
550                 AST_LIST_UNLOCK(&dial->channels);
551                 ast_channel_publish_dial(NULL, channel->owner, channel->device, "ANSWER");
552                 set_state(dial, AST_DIAL_RESULT_ANSWERED);
553                 break;
554         case AST_CONTROL_BUSY:
555                 ast_verb(3, "%s is busy\n", ast_channel_name(channel->owner));
556                 ast_channel_publish_dial(NULL, channel->owner, channel->device, "BUSY");
557                 ast_hangup(channel->owner);
558                 channel->owner = NULL;
559                 break;
560         case AST_CONTROL_CONGESTION:
561                 ast_verb(3, "%s is circuit-busy\n", ast_channel_name(channel->owner));
562                 ast_channel_publish_dial(NULL, channel->owner, channel->device, "CONGESTION");
563                 ast_hangup(channel->owner);
564                 channel->owner = NULL;
565                 break;
566         case AST_CONTROL_RINGING:
567                 ast_verb(3, "%s is ringing\n", ast_channel_name(channel->owner));
568                 set_state(dial, AST_DIAL_RESULT_RINGING);
569                 break;
570         case AST_CONTROL_PROGRESS:
571                 ast_verb(3, "%s is making progress\n", ast_channel_name(channel->owner));
572                 set_state(dial, AST_DIAL_RESULT_PROGRESS);
573                 break;
574         case AST_CONTROL_PROCEEDING:
575                 ast_verb(3, "%s is proceeding\n", ast_channel_name(channel->owner));
576                 set_state(dial, AST_DIAL_RESULT_PROCEEDING);
577                 break;
578         default:
579                 break;
580         }
581
582         return;
583 }
584
585 /*! \brief Helper function to handle when a timeout occurs on dialing attempt */
586 static int handle_timeout_trip(struct ast_dial *dial, struct timeval start)
587 {
588         struct ast_dial_channel *channel = NULL;
589         int diff = ast_tvdiff_ms(ast_tvnow(), start), lowest_timeout = -1, new_timeout = -1;
590
591         /* If there is no difference yet return the dial timeout so we can go again, we were likely interrupted */
592         if (!diff) {
593                 return dial->timeout;
594         }
595
596         /* If the global dial timeout tripped switch the state to timeout so our channel loop will drop every channel */
597         if (diff >= dial->timeout) {
598                 set_state(dial, AST_DIAL_RESULT_TIMEOUT);
599                 new_timeout = 0;
600         }
601
602         /* Go through dropping out channels that have met their timeout */
603         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
604                 if (dial->state == AST_DIAL_RESULT_TIMEOUT || diff >= channel->timeout) {
605                         ast_hangup(channel->owner);
606                         channel->owner = NULL;
607                 } else if ((lowest_timeout == -1) || (lowest_timeout > channel->timeout)) {
608                         lowest_timeout = channel->timeout;
609                 }
610         }
611
612         /* Calculate the new timeout using the lowest timeout found */
613         if (lowest_timeout >= 0)
614                 new_timeout = lowest_timeout - diff;
615
616         return new_timeout;
617 }
618
619 /*! \since 12
620  * \internal \brief Convert a hangup cause to a publishable dial status
621  */
622 static const char *hangup_cause_to_dial_status(int hangup_cause)
623 {
624         switch(hangup_cause) {
625         case AST_CAUSE_BUSY:
626                 return "BUSY";
627         case AST_CAUSE_CONGESTION:
628                 return "CONGESTION";
629         case AST_CAUSE_NO_ROUTE_DESTINATION:
630         case AST_CAUSE_UNREGISTERED:
631                 return "CHANUNAVAIL";
632         case AST_CAUSE_NO_ANSWER:
633         default:
634                 return "NOANSWER";
635         }
636 }
637
638 /*! \brief Helper function that basically keeps tabs on dialing attempts */
639 static enum ast_dial_result monitor_dial(struct ast_dial *dial, struct ast_channel *chan)
640 {
641         int timeout = -1;
642         struct ast_channel *cs[AST_MAX_WATCHERS], *who = NULL;
643         struct ast_dial_channel *channel = NULL;
644         struct answer_exec_struct *answer_exec = NULL;
645         struct timeval start;
646
647         set_state(dial, AST_DIAL_RESULT_TRYING);
648
649         /* If the "always indicate ringing" option is set, change state to ringing and indicate to the owner if present */
650         if (dial->options[AST_DIAL_OPTION_RINGING]) {
651                 set_state(dial, AST_DIAL_RESULT_RINGING);
652                 if (chan)
653                         ast_indicate(chan, AST_CONTROL_RINGING);
654         } else if (chan && dial->options[AST_DIAL_OPTION_MUSIC] &&
655                 !ast_strlen_zero(dial->options[AST_DIAL_OPTION_MUSIC])) {
656                 char *original_moh = ast_strdupa(ast_channel_musicclass(chan));
657                 ast_indicate(chan, -1);
658                 ast_channel_musicclass_set(chan, dial->options[AST_DIAL_OPTION_MUSIC]);
659                 ast_moh_start(chan, dial->options[AST_DIAL_OPTION_MUSIC], NULL);
660                 ast_channel_musicclass_set(chan, original_moh);
661         }
662
663         /* Record start time for timeout purposes */
664         start = ast_tvnow();
665
666         /* We actually figured out the maximum timeout we can do as they were added, so we can directly access the info */
667         timeout = dial->actual_timeout;
668
669         /* Go into an infinite loop while we are trying */
670         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)) {
671                 int pos = 0, count = 0;
672                 struct ast_frame *fr = NULL;
673
674                 /* Set up channel structure array */
675                 pos = count = 0;
676                 if (chan)
677                         cs[pos++] = chan;
678
679                 /* Add channels we are attempting to dial */
680                 AST_LIST_LOCK(&dial->channels);
681                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
682                         if (channel->owner) {
683                                 cs[pos++] = channel->owner;
684                                 count++;
685                         }
686                 }
687                 AST_LIST_UNLOCK(&dial->channels);
688
689                 /* If we have no outbound channels in progress, switch state to unanswered and stop */
690                 if (!count) {
691                         set_state(dial, AST_DIAL_RESULT_UNANSWERED);
692                         break;
693                 }
694
695                 /* Just to be safe... */
696                 if (dial->thread == AST_PTHREADT_STOP)
697                         break;
698
699                 /* Wait for frames from channels */
700                 who = ast_waitfor_n(cs, pos, &timeout);
701
702                 /* Check to see if our thread is being canceled */
703                 if (dial->thread == AST_PTHREADT_STOP)
704                         break;
705
706                 /* If the timeout no longer exists OR if we got no channel it basically means the timeout was tripped, so handle it */
707                 if (!timeout || !who) {
708                         timeout = handle_timeout_trip(dial, start);
709                         continue;
710                 }
711
712                 /* Find relative dial channel */
713                 if (!chan || !IS_CALLER(chan, who))
714                         channel = find_relative_dial_channel(dial, who);
715
716                 /* See if this channel has been forwarded elsewhere */
717                 if (!ast_strlen_zero(ast_channel_call_forward(who))) {
718                         handle_call_forward(dial, channel, chan);
719                         continue;
720                 }
721
722                 /* Attempt to read in a frame */
723                 if (!(fr = ast_read(who))) {
724                         /* If this is the caller then we switch state to hangup and stop */
725                         if (chan && IS_CALLER(chan, who)) {
726                                 set_state(dial, AST_DIAL_RESULT_HANGUP);
727                                 break;
728                         }
729                         if (chan)
730                                 ast_poll_channel_del(chan, channel->owner);
731                         ast_channel_publish_dial(chan, who, channel->device, hangup_cause_to_dial_status(ast_channel_hangupcause(who)));
732                         ast_hangup(who);
733                         channel->owner = NULL;
734                         continue;
735                 }
736
737                 /* Process the frame */
738                 if (chan)
739                         handle_frame(dial, channel, fr, chan);
740                 else
741                         handle_frame_ownerless(dial, channel, fr);
742
743                 /* Free the received frame and start all over */
744                 ast_frfree(fr);
745         }
746
747         /* Do post-processing from loop */
748         if (dial->state == AST_DIAL_RESULT_ANSWERED) {
749                 /* Hangup everything except that which answered */
750                 AST_LIST_LOCK(&dial->channels);
751                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
752                         if (!channel->owner || channel->owner == who)
753                                 continue;
754                         if (chan)
755                                 ast_poll_channel_del(chan, channel->owner);
756                         ast_channel_publish_dial(chan, channel->owner, channel->device, "CANCEL");
757                         ast_hangup(channel->owner);
758                         channel->owner = NULL;
759                 }
760                 AST_LIST_UNLOCK(&dial->channels);
761                 /* If ANSWER_EXEC is enabled as an option, execute application on answered channel */
762                 if ((channel = find_relative_dial_channel(dial, who)) && (answer_exec = FIND_RELATIVE_OPTION(dial, channel, AST_DIAL_OPTION_ANSWER_EXEC))) {
763                         channel->is_running_app = 1;
764                         answer_exec_run(dial, channel, answer_exec->app, answer_exec->args);
765                         channel->is_running_app = 0;
766                 }
767
768                 if (chan && dial->options[AST_DIAL_OPTION_MUSIC] &&
769                         !ast_strlen_zero(dial->options[AST_DIAL_OPTION_MUSIC])) {
770                         ast_moh_stop(chan);
771                 }
772         } else if (dial->state == AST_DIAL_RESULT_HANGUP) {
773                 /* Hangup everything */
774                 AST_LIST_LOCK(&dial->channels);
775                 AST_LIST_TRAVERSE(&dial->channels, channel, list) {
776                         if (!channel->owner)
777                                 continue;
778                         if (chan)
779                                 ast_poll_channel_del(chan, channel->owner);
780                         ast_channel_publish_dial(chan, channel->owner, channel->device, "CANCEL");
781                         ast_hangup(channel->owner);
782                         channel->owner = NULL;
783                 }
784                 AST_LIST_UNLOCK(&dial->channels);
785         }
786
787         return dial->state;
788 }
789
790 /*! \brief Dial async thread function */
791 static void *async_dial(void *data)
792 {
793         struct ast_dial *dial = data;
794         if (dial->callid) {
795                 ast_callid_threadassoc_add(dial->callid);
796         }
797
798         /* This is really really simple... we basically pass monitor_dial a NULL owner and it changes it's behavior */
799         monitor_dial(dial, NULL);
800
801         return NULL;
802 }
803
804 /*! \brief Execute dialing synchronously or asynchronously
805  * \note Dials channels in a dial structure.
806  * \return Returns dial result code. (TRYING/INVALID/FAILED/ANSWERED/TIMEOUT/UNANSWERED).
807  */
808 enum ast_dial_result ast_dial_run(struct ast_dial *dial, struct ast_channel *chan, int async)
809 {
810         enum ast_dial_result res = AST_DIAL_RESULT_TRYING;
811
812         /* Ensure required arguments are passed */
813         if (!dial) {
814                 ast_debug(1, "invalid #1\n");
815                 return AST_DIAL_RESULT_INVALID;
816         }
817
818         /* If there are no channels to dial we can't very well try to dial them */
819         if (AST_LIST_EMPTY(&dial->channels)) {
820                 ast_debug(1, "invalid #2\n");
821                 return AST_DIAL_RESULT_INVALID;
822         }
823
824         /* Dial each requested channel */
825         if (!begin_dial(dial, chan))
826                 return AST_DIAL_RESULT_FAILED;
827
828         /* If we are running async spawn a thread and send it away... otherwise block here */
829         if (async) {
830                 /* reference be released at dial destruction if it isn't NULL */
831                 dial->callid = ast_read_threadstorage_callid();
832                 dial->state = AST_DIAL_RESULT_TRYING;
833                 /* Try to create a thread */
834                 if (ast_pthread_create(&dial->thread, NULL, async_dial, dial)) {
835                         /* Failed to create the thread - hangup all dialed channels and return failed */
836                         ast_dial_hangup(dial);
837                         res = AST_DIAL_RESULT_FAILED;
838                 }
839         } else {
840                 res = monitor_dial(dial, chan);
841         }
842
843         return res;
844 }
845
846 /*! \brief Return channel that answered
847  * \note Returns the Asterisk channel that answered
848  * \param dial Dialing structure
849  */
850 struct ast_channel *ast_dial_answered(struct ast_dial *dial)
851 {
852         if (!dial)
853                 return NULL;
854
855         return ((dial->state == AST_DIAL_RESULT_ANSWERED) ? AST_LIST_FIRST(&dial->channels)->owner : NULL);
856 }
857
858 /*! \brief Steal the channel that answered
859  * \note Returns the Asterisk channel that answered and removes it from the dialing structure
860  * \param dial Dialing structure
861  */
862 struct ast_channel *ast_dial_answered_steal(struct ast_dial *dial)
863 {
864         struct ast_channel *chan = NULL;
865
866         if (!dial)
867                 return NULL;
868
869         if (dial->state == AST_DIAL_RESULT_ANSWERED) {
870                 chan = AST_LIST_FIRST(&dial->channels)->owner;
871                 AST_LIST_FIRST(&dial->channels)->owner = NULL;
872         }
873
874         return chan;
875 }
876
877 /*! \brief Return state of dial
878  * \note Returns the state of the dial attempt
879  * \param dial Dialing structure
880  */
881 enum ast_dial_result ast_dial_state(struct ast_dial *dial)
882 {
883         return dial->state;
884 }
885
886 /*! \brief Cancel async thread
887  * \note Cancel a running async thread
888  * \param dial Dialing structure
889  */
890 enum ast_dial_result ast_dial_join(struct ast_dial *dial)
891 {
892         pthread_t thread;
893
894         /* If the dial structure is not running in async, return failed */
895         if (dial->thread == AST_PTHREADT_NULL)
896                 return AST_DIAL_RESULT_FAILED;
897
898         /* Record thread */
899         thread = dial->thread;
900
901         /* Boom, commence locking */
902         ast_mutex_lock(&dial->lock);
903
904         /* Stop the thread */
905         dial->thread = AST_PTHREADT_STOP;
906
907         /* If the answered channel is running an application we have to soft hangup it, can't just poke the thread */
908         AST_LIST_LOCK(&dial->channels);
909         if (AST_LIST_FIRST(&dial->channels)->is_running_app) {
910                 struct ast_channel *chan = AST_LIST_FIRST(&dial->channels)->owner;
911                 if (chan) {
912                         ast_channel_lock(chan);
913                         ast_softhangup(chan, AST_SOFTHANGUP_EXPLICIT);
914                         ast_channel_unlock(chan);
915                 }
916         } else {
917                 /* Now we signal it with SIGURG so it will break out of it's waitfor */
918                 pthread_kill(thread, SIGURG);
919         }
920         AST_LIST_UNLOCK(&dial->channels);
921
922         /* Yay done with it */
923         ast_mutex_unlock(&dial->lock);
924
925         /* Finally wait for the thread to exit */
926         pthread_join(thread, NULL);
927
928         /* Yay thread is all gone */
929         dial->thread = AST_PTHREADT_NULL;
930
931         return dial->state;
932 }
933
934 /*! \brief Hangup channels
935  * \note Hangup all active channels
936  * \param dial Dialing structure
937  */
938 void ast_dial_hangup(struct ast_dial *dial)
939 {
940         struct ast_dial_channel *channel = NULL;
941
942         if (!dial)
943                 return;
944
945         AST_LIST_LOCK(&dial->channels);
946         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
947                 if (channel->owner) {
948                         ast_hangup(channel->owner);
949                         channel->owner = NULL;
950                 }
951         }
952         AST_LIST_UNLOCK(&dial->channels);
953
954         return;
955 }
956
957 /*! \brief Destroys a dialing structure
958  * \note Destroys (free's) the given ast_dial structure
959  * \param dial Dialing structure to free
960  * \return Returns 0 on success, -1 on failure
961  */
962 int ast_dial_destroy(struct ast_dial *dial)
963 {
964         int i = 0;
965         struct ast_dial_channel *channel = NULL;
966
967         if (!dial)
968                 return -1;
969
970         /* Hangup and deallocate all the dialed channels */
971         AST_LIST_LOCK(&dial->channels);
972         AST_LIST_TRAVERSE_SAFE_BEGIN(&dial->channels, channel, list) {
973                 /* Disable any enabled options */
974                 for (i = 0; i < AST_DIAL_OPTION_MAX; i++) {
975                         if (!channel->options[i])
976                                 continue;
977                         if (option_types[i].disable)
978                                 option_types[i].disable(channel->options[i]);
979                         channel->options[i] = NULL;
980                 }
981                 /* Hang up channel if need be */
982                 if (channel->owner) {
983                         ast_hangup(channel->owner);
984                         channel->owner = NULL;
985                 }
986                 /* Free structure */
987                 ast_free(channel->tech);
988                 ast_free(channel->device);
989                 AST_LIST_REMOVE_CURRENT(list);
990                 ast_free(channel);
991         }
992         AST_LIST_TRAVERSE_SAFE_END;
993         AST_LIST_UNLOCK(&dial->channels);
994
995         /* Disable any enabled options globally */
996         for (i = 0; i < AST_DIAL_OPTION_MAX; i++) {
997                 if (!dial->options[i])
998                         continue;
999                 if (option_types[i].disable)
1000                         option_types[i].disable(dial->options[i]);
1001                 dial->options[i] = NULL;
1002         }
1003
1004         /* Lock be gone! */
1005         ast_mutex_destroy(&dial->lock);
1006
1007         /* Get rid of the reference to the ast_callid */
1008         if (dial->callid) {
1009                 ast_callid_unref(dial->callid);
1010         }
1011
1012         /* Free structure */
1013         ast_free(dial);
1014
1015         return 0;
1016 }
1017
1018 /*! \brief Enables an option globally
1019  * \param dial Dial structure to enable option on
1020  * \param option Option to enable
1021  * \param data Data to pass to this option (not always needed)
1022  * \return Returns 0 on success, -1 on failure
1023  */
1024 int ast_dial_option_global_enable(struct ast_dial *dial, enum ast_dial_option option, void *data)
1025 {
1026         /* If the option is already enabled, return failure */
1027         if (dial->options[option])
1028                 return -1;
1029
1030         /* Execute enable callback if it exists, if not simply make sure the value is set */
1031         if (option_types[option].enable)
1032                 dial->options[option] = option_types[option].enable(data);
1033         else
1034                 dial->options[option] = (void*)1;
1035
1036         return 0;
1037 }
1038
1039 /*! \brief Helper function for finding a channel in a dial structure based on number
1040  */
1041 static struct ast_dial_channel *find_dial_channel(struct ast_dial *dial, int num)
1042 {
1043         struct ast_dial_channel *channel = AST_LIST_LAST(&dial->channels);
1044
1045         /* We can try to predict programmer behavior, the last channel they added is probably the one they wanted to modify */
1046         if (channel->num == num)
1047                 return channel;
1048
1049         /* Hrm not at the end... looking through the list it is! */
1050         AST_LIST_LOCK(&dial->channels);
1051         AST_LIST_TRAVERSE(&dial->channels, channel, list) {
1052                 if (channel->num == num)
1053                         break;
1054         }
1055         AST_LIST_UNLOCK(&dial->channels);
1056
1057         return channel;
1058 }
1059
1060 /*! \brief Enables an option per channel
1061  * \param dial Dial structure
1062  * \param num Channel number to enable option on
1063  * \param option Option to enable
1064  * \param data Data to pass to this option (not always needed)
1065  * \return Returns 0 on success, -1 on failure
1066  */
1067 int ast_dial_option_enable(struct ast_dial *dial, int num, enum ast_dial_option option, void *data)
1068 {
1069         struct ast_dial_channel *channel = NULL;
1070
1071         /* Ensure we have required arguments */
1072         if (!dial || AST_LIST_EMPTY(&dial->channels))
1073                 return -1;
1074
1075         if (!(channel = find_dial_channel(dial, num)))
1076                 return -1;
1077
1078         /* If the option is already enabled, return failure */
1079         if (channel->options[option])
1080                 return -1;
1081
1082         /* Execute enable callback if it exists, if not simply make sure the value is set */
1083         if (option_types[option].enable)
1084                 channel->options[option] = option_types[option].enable(data);
1085         else
1086                 channel->options[option] = (void*)1;
1087
1088         return 0;
1089 }
1090
1091 /*! \brief Disables an option globally
1092  * \param dial Dial structure to disable option on
1093  * \param option Option to disable
1094  * \return Returns 0 on success, -1 on failure
1095  */
1096 int ast_dial_option_global_disable(struct ast_dial *dial, enum ast_dial_option option)
1097 {
1098         /* If the option is not enabled, return failure */
1099         if (!dial->options[option]) {
1100                 return -1;
1101         }
1102
1103         /* Execute callback of option to disable if it exists */
1104         if (option_types[option].disable)
1105                 option_types[option].disable(dial->options[option]);
1106
1107         /* Finally disable option on the structure */
1108         dial->options[option] = NULL;
1109
1110         return 0;
1111 }
1112
1113 /*! \brief Disables an option per channel
1114  * \param dial Dial structure
1115  * \param num Channel number to disable option on
1116  * \param option Option to disable
1117  * \return Returns 0 on success, -1 on failure
1118  */
1119 int ast_dial_option_disable(struct ast_dial *dial, int num, enum ast_dial_option option)
1120 {
1121         struct ast_dial_channel *channel = NULL;
1122
1123         /* Ensure we have required arguments */
1124         if (!dial || AST_LIST_EMPTY(&dial->channels))
1125                 return -1;
1126
1127         if (!(channel = find_dial_channel(dial, num)))
1128                 return -1;
1129
1130         /* If the option is not enabled, return failure */
1131         if (!channel->options[option])
1132                 return -1;
1133
1134         /* Execute callback of option to disable it if it exists */
1135         if (option_types[option].disable)
1136                 option_types[option].disable(channel->options[option]);
1137
1138         /* Finally disable the option on the structure */
1139         channel->options[option] = NULL;
1140
1141         return 0;
1142 }
1143
1144 int ast_dial_reason(struct ast_dial *dial, int num)
1145 {
1146         struct ast_dial_channel *channel;
1147
1148         if (!dial || AST_LIST_EMPTY(&dial->channels) || !(channel = find_dial_channel(dial, num))) {
1149                 return -1;
1150         }
1151
1152         return channel->cause;
1153 }
1154
1155 struct ast_channel *ast_dial_get_channel(struct ast_dial *dial, int num)
1156 {
1157         struct ast_dial_channel *channel;
1158
1159         if (!dial || AST_LIST_EMPTY(&dial->channels) || !(channel = find_dial_channel(dial, num))) {
1160                 return NULL;
1161         }
1162
1163         return channel->owner;
1164 }
1165
1166 void ast_dial_set_state_callback(struct ast_dial *dial, ast_dial_state_callback callback)
1167 {
1168         dial->state_callback = callback;
1169 }
1170
1171 void ast_dial_set_user_data(struct ast_dial *dial, void *user_data)
1172 {
1173         dial->user_data = user_data;
1174 }
1175
1176 void *ast_dial_get_user_data(struct ast_dial *dial)
1177 {
1178         return dial->user_data;
1179 }
1180
1181 /*! \brief Set the maximum time (globally) allowed for trying to ring phones
1182  * \param dial The dial structure to apply the time limit to
1183  * \param timeout Maximum time allowed
1184  * \return nothing
1185  */
1186 void ast_dial_set_global_timeout(struct ast_dial *dial, int timeout)
1187 {
1188         dial->timeout = timeout;
1189
1190         if (dial->timeout > 0 && (dial->actual_timeout > dial->timeout || dial->actual_timeout == -1))
1191                 dial->actual_timeout = dial->timeout;
1192
1193         return;
1194 }
1195
1196 /*! \brief Set the maximum time (per channel) allowed for trying to ring the phone
1197  * \param dial The dial structure the channel belongs to
1198  * \param num Channel number to set timeout on
1199  * \param timeout Maximum time allowed
1200  * \return nothing
1201  */
1202 void ast_dial_set_timeout(struct ast_dial *dial, int num, int timeout)
1203 {
1204         struct ast_dial_channel *channel = NULL;
1205
1206         if (!(channel = find_dial_channel(dial, num)))
1207                 return;
1208
1209         channel->timeout = timeout;
1210
1211         if (channel->timeout > 0 && (dial->actual_timeout > channel->timeout || dial->actual_timeout == -1))
1212                 dial->actual_timeout = channel->timeout;
1213
1214         return;
1215 }