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