Merge "Bridge system: Fix memory leaks and double frees on impart failure."
[asterisk/asterisk.git] / res / stasis / control.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * David M. Lee, II <dlee@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 Stasis application control support.
22  *
23  * \author David M. Lee, II <dlee@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_REGISTER_FILE()
29
30 #include "asterisk/stasis_channels.h"
31
32 #include "command.h"
33 #include "control.h"
34 #include "app.h"
35 #include "asterisk/dial.h"
36 #include "asterisk/bridge.h"
37 #include "asterisk/bridge_after.h"
38 #include "asterisk/bridge_basic.h"
39 #include "asterisk/frame.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/musiconhold.h"
42 #include "asterisk/app.h"
43
44 AST_LIST_HEAD(app_control_rules, stasis_app_control_rule);
45
46 struct stasis_app_control {
47         ast_cond_t wait_cond;
48         /*! Queue of commands to dispatch on the channel */
49         struct ao2_container *command_queue;
50         /*!
51          * The associated channel.
52          * Be very careful with the threading associated w/ manipulating
53          * the channel.
54          */
55         struct ast_channel *channel;
56         /*!
57          * When a channel is in a bridge, the bridge that it is in.
58          */
59         struct ast_bridge *bridge;
60         /*!
61          * Holding place for channel's PBX while imparted to a bridge.
62          */
63         struct ast_pbx *pbx;
64         /*!
65          * A list of rules to check before adding a channel to a bridge.
66          */
67         struct app_control_rules add_rules;
68         /*!
69          * A list of rules to check before removing a channel from a bridge.
70          */
71         struct app_control_rules remove_rules;
72         /*!
73          * Silence generator, when silence is being generated.
74          */
75         struct ast_silence_generator *silgen;
76         /*!
77          * The app for which this control was created
78          */
79         struct stasis_app *app;
80         /*!
81          * If channel is being dialed, the dial structure.
82          */
83         struct ast_dial *dial;
84         /*!
85          * When set, /c app_stasis should exit and continue in the dialplan.
86          */
87         int is_done:1;
88 };
89
90 static void control_dtor(void *obj)
91 {
92         struct stasis_app_control *control = obj;
93
94         ao2_cleanup(control->command_queue);
95
96         ast_channel_cleanup(control->channel);
97         ao2_cleanup(control->app);
98
99         ast_cond_destroy(&control->wait_cond);
100         AST_LIST_HEAD_DESTROY(&control->add_rules);
101         AST_LIST_HEAD_DESTROY(&control->remove_rules);
102 }
103
104 struct stasis_app_control *control_create(struct ast_channel *channel, struct stasis_app *app)
105 {
106         struct stasis_app_control *control;
107         int res;
108
109         control = ao2_alloc(sizeof(*control), control_dtor);
110         if (!control) {
111                 return NULL;
112         }
113
114         AST_LIST_HEAD_INIT(&control->add_rules);
115         AST_LIST_HEAD_INIT(&control->remove_rules);
116
117         res = ast_cond_init(&control->wait_cond, NULL);
118         if (res != 0) {
119                 ast_log(LOG_ERROR, "Error initializing ast_cond_t: %s\n",
120                         strerror(errno));
121                 ao2_ref(control, -1);
122                 return NULL;
123         }
124
125         control->app = ao2_bump(app);
126
127         ast_channel_ref(channel);
128         control->channel = channel;
129
130         control->command_queue = ao2_container_alloc_list(
131                 AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
132         if (!control->command_queue) {
133                 ao2_ref(control, -1);
134                 return NULL;
135         }
136
137         return control;
138 }
139
140 static void app_control_register_rule(
141         struct stasis_app_control *control,
142         struct app_control_rules *list, struct stasis_app_control_rule *obj)
143 {
144         SCOPED_AO2LOCK(lock, control->command_queue);
145         AST_LIST_INSERT_TAIL(list, obj, next);
146 }
147
148 static void app_control_unregister_rule(
149         struct stasis_app_control *control,
150         struct app_control_rules *list, struct stasis_app_control_rule *obj)
151 {
152         struct stasis_app_control_rule *rule;
153         SCOPED_AO2LOCK(lock, control->command_queue);
154         AST_RWLIST_TRAVERSE_SAFE_BEGIN(list, rule, next) {
155                 if (rule == obj) {
156                         AST_RWLIST_REMOVE_CURRENT(next);
157                         break;
158                 }
159         }
160         AST_RWLIST_TRAVERSE_SAFE_END;
161 }
162
163 /*!
164  * \internal
165  * \brief Checks to make sure each rule in the given list passes.
166  *
167  * \details Loops over a list of rules checking for rejections or failures.
168  *          If one rule fails its resulting error code is returned.
169  *
170  * \note Command queue should be locked before calling this function.
171  *
172  * \param control The stasis application control
173  * \param list The list of rules to check
174  *
175  * \retval 0 if all rules pass
176  * \retval non-zero error code if a rule fails
177  */
178 static enum stasis_app_control_channel_result app_control_check_rules(
179         const struct stasis_app_control *control,
180         struct app_control_rules *list)
181 {
182         int res = 0;
183         struct stasis_app_control_rule *rule;
184         AST_LIST_TRAVERSE(list, rule, next) {
185                 if ((res = rule->check_rule(control))) {
186                         return res;
187                 }
188         }
189         return res;
190 }
191
192 void stasis_app_control_register_add_rule(
193         struct stasis_app_control *control,
194         struct stasis_app_control_rule *rule)
195 {
196         return app_control_register_rule(control, &control->add_rules, rule);
197 }
198
199 void stasis_app_control_unregister_add_rule(
200         struct stasis_app_control *control,
201         struct stasis_app_control_rule *rule)
202 {
203         app_control_unregister_rule(control, &control->add_rules, rule);
204 }
205
206 void stasis_app_control_register_remove_rule(
207         struct stasis_app_control *control,
208         struct stasis_app_control_rule *rule)
209 {
210         return app_control_register_rule(control, &control->remove_rules, rule);
211 }
212
213 void stasis_app_control_unregister_remove_rule(
214         struct stasis_app_control *control,
215         struct stasis_app_control_rule *rule)
216 {
217         app_control_unregister_rule(control, &control->remove_rules, rule);
218 }
219
220 static int app_control_can_add_channel_to_bridge(
221         struct stasis_app_control *control)
222 {
223         return app_control_check_rules(control, &control->add_rules);
224 }
225
226 static int app_control_can_remove_channel_from_bridge(
227         struct stasis_app_control *control)
228 {
229         return app_control_check_rules(control, &control->remove_rules);
230 }
231
232 static int noop_cb(struct stasis_app_control *control,
233         struct ast_channel *chan, void *data)
234 {
235         return 0;
236 }
237
238 /*! Callback type to see if the command can execute
239     note: command_queue is locked during callback */
240 typedef int (*app_command_can_exec_cb)(struct stasis_app_control *control);
241
242 static struct stasis_app_command *exec_command_on_condition(
243         struct stasis_app_control *control, stasis_app_command_cb command_fn,
244         void *data, command_data_destructor_fn data_destructor,
245         app_command_can_exec_cb can_exec_fn)
246 {
247         int retval;
248         struct stasis_app_command *command;
249
250         command_fn = command_fn ? : noop_cb;
251
252         command = command_create(command_fn, data, data_destructor);
253         if (!command) {
254                 return NULL;
255         }
256
257         ao2_lock(control->command_queue);
258         if (control->is_done) {
259                 ao2_unlock(control->command_queue);
260                 ao2_ref(command, -1);
261                 return NULL;
262         }
263         if (can_exec_fn && (retval = can_exec_fn(control))) {
264                 ao2_unlock(control->command_queue);
265                 command_complete(command, retval);
266                 return command;
267         }
268
269         ao2_link_flags(control->command_queue, command, OBJ_NOLOCK);
270         ast_cond_signal(&control->wait_cond);
271         ao2_unlock(control->command_queue);
272
273         return command;
274 }
275
276 static struct stasis_app_command *exec_command(
277         struct stasis_app_control *control, stasis_app_command_cb command_fn,
278         void *data, command_data_destructor_fn data_destructor)
279 {
280         return exec_command_on_condition(control, command_fn, data, data_destructor, NULL);
281 }
282
283 static int app_control_add_role(struct stasis_app_control *control,
284                 struct ast_channel *chan, void *data)
285 {
286         char *role = data;
287
288         return ast_channel_add_bridge_role(chan, role);
289 }
290
291 int stasis_app_control_add_role(struct stasis_app_control *control, const char *role)
292 {
293         char *role_dup;
294
295         role_dup = ast_strdup(role);
296         if (!role_dup) {
297                 return -1;
298         }
299
300         stasis_app_send_command_async(control, app_control_add_role, role_dup, ast_free_ptr);
301
302         return 0;
303 }
304
305 static int app_control_clear_roles(struct stasis_app_control *control,
306                 struct ast_channel *chan, void *data)
307 {
308         ast_channel_clear_bridge_roles(chan);
309
310         return 0;
311 }
312
313 void stasis_app_control_clear_roles(struct stasis_app_control *control)
314 {
315         stasis_app_send_command_async(control, app_control_clear_roles, NULL, NULL);
316 }
317
318 int control_command_count(struct stasis_app_control *control)
319 {
320         return ao2_container_count(control->command_queue);
321 }
322
323 int control_is_done(struct stasis_app_control *control)
324 {
325         /* Called from stasis_app_exec thread; no lock needed */
326         return control->is_done;
327 }
328
329 void control_mark_done(struct stasis_app_control *control)
330 {
331         /* Locking necessary to sync with other threads adding commands to the queue. */
332         ao2_lock(control->command_queue);
333         control->is_done = 1;
334         ao2_unlock(control->command_queue);
335 }
336
337 struct stasis_app_control_continue_data {
338         char context[AST_MAX_CONTEXT];
339         char extension[AST_MAX_EXTENSION];
340         int priority;
341 };
342
343 static int app_control_continue(struct stasis_app_control *control,
344         struct ast_channel *chan, void *data)
345 {
346         struct stasis_app_control_continue_data *continue_data = data;
347
348         ast_assert(control->channel != NULL);
349
350         /* If we're in a Stasis bridge, depart it before going back to the
351          * dialplan */
352         if (stasis_app_get_bridge(control)) {
353                 ast_bridge_depart(control->channel);
354         }
355
356         /* Called from stasis_app_exec thread; no lock needed */
357         ast_explicit_goto(control->channel, continue_data->context, continue_data->extension, continue_data->priority);
358
359         control_mark_done(control);
360
361         return 0;
362 }
363
364 int stasis_app_control_continue(struct stasis_app_control *control, const char *context, const char *extension, int priority)
365 {
366         struct stasis_app_control_continue_data *continue_data;
367
368         if (!(continue_data = ast_calloc(1, sizeof(*continue_data)))) {
369                 return -1;
370         }
371         ast_copy_string(continue_data->context, S_OR(context, ""), sizeof(continue_data->context));
372         ast_copy_string(continue_data->extension, S_OR(extension, ""), sizeof(continue_data->extension));
373         if (priority > 0) {
374                 continue_data->priority = priority;
375         } else {
376                 continue_data->priority = -1;
377         }
378
379         stasis_app_send_command_async(control, app_control_continue, continue_data, ast_free_ptr);
380
381         return 0;
382 }
383
384 static int app_control_redirect(struct stasis_app_control *control,
385         struct ast_channel *chan, void *data)
386 {
387         char *endpoint = data;
388         int res;
389
390         ast_assert(control->channel != NULL);
391         ast_assert(endpoint != NULL);
392
393         res = ast_transfer(control->channel, endpoint);
394         if (!res) {
395                 ast_log(LOG_NOTICE, "Unsupported transfer requested on channel '%s'\n",
396                         ast_channel_name(control->channel));
397                 return 0;
398         }
399
400         return 0;
401 }
402
403 int stasis_app_control_redirect(struct stasis_app_control *control, const char *endpoint)
404 {
405         char *endpoint_data = ast_strdup(endpoint);
406
407         if (!endpoint_data) {
408                 return -1;
409         }
410
411         stasis_app_send_command_async(control, app_control_redirect, endpoint_data, ast_free_ptr);
412
413         return 0;
414 }
415
416 struct stasis_app_control_dtmf_data {
417         int before;
418         int between;
419         unsigned int duration;
420         int after;
421         char dtmf[];
422 };
423
424 static int app_control_dtmf(struct stasis_app_control *control,
425         struct ast_channel *chan, void *data)
426 {
427         struct stasis_app_control_dtmf_data *dtmf_data = data;
428
429         if (ast_channel_state(chan) != AST_STATE_UP) {
430                 ast_indicate(chan, AST_CONTROL_PROGRESS);
431         }
432
433         if (dtmf_data->before) {
434                 ast_safe_sleep(chan, dtmf_data->before);
435         }
436
437         ast_dtmf_stream(chan, NULL, dtmf_data->dtmf, dtmf_data->between, dtmf_data->duration);
438
439         if (dtmf_data->after) {
440                 ast_safe_sleep(chan, dtmf_data->after);
441         }
442
443         return 0;
444 }
445
446 int stasis_app_control_dtmf(struct stasis_app_control *control, const char *dtmf, int before, int between, unsigned int duration, int after)
447 {
448         struct stasis_app_control_dtmf_data *dtmf_data;
449
450         if (!(dtmf_data = ast_calloc(1, sizeof(*dtmf_data) + strlen(dtmf) + 1))) {
451                 return -1;
452         }
453
454         dtmf_data->before = before;
455         dtmf_data->between = between;
456         dtmf_data->duration = duration;
457         dtmf_data->after = after;
458         strcpy(dtmf_data->dtmf, dtmf);
459
460         stasis_app_send_command_async(control, app_control_dtmf, dtmf_data, ast_free_ptr);
461
462         return 0;
463 }
464
465 static int app_control_ring(struct stasis_app_control *control,
466         struct ast_channel *chan, void *data)
467 {
468         ast_indicate(control->channel, AST_CONTROL_RINGING);
469
470         return 0;
471 }
472
473 int stasis_app_control_ring(struct stasis_app_control *control)
474 {
475         stasis_app_send_command_async(control, app_control_ring, NULL, NULL);
476
477         return 0;
478 }
479
480 static int app_control_ring_stop(struct stasis_app_control *control,
481         struct ast_channel *chan, void *data)
482 {
483         ast_indicate(control->channel, -1);
484
485         return 0;
486 }
487
488 int stasis_app_control_ring_stop(struct stasis_app_control *control)
489 {
490         stasis_app_send_command_async(control, app_control_ring_stop, NULL, NULL);
491
492         return 0;
493 }
494
495 struct stasis_app_control_mute_data {
496         enum ast_frame_type frametype;
497         unsigned int direction;
498 };
499
500 static int app_control_mute(struct stasis_app_control *control,
501         struct ast_channel *chan, void *data)
502 {
503         struct stasis_app_control_mute_data *mute_data = data;
504         SCOPED_CHANNELLOCK(lockvar, chan);
505
506         ast_channel_suppress(control->channel, mute_data->direction, mute_data->frametype);
507
508         return 0;
509 }
510
511 int stasis_app_control_mute(struct stasis_app_control *control, unsigned int direction, enum ast_frame_type frametype)
512 {
513         struct stasis_app_control_mute_data *mute_data;
514
515         if (!(mute_data = ast_calloc(1, sizeof(*mute_data)))) {
516                 return -1;
517         }
518
519         mute_data->direction = direction;
520         mute_data->frametype = frametype;
521
522         stasis_app_send_command_async(control, app_control_mute, mute_data, ast_free_ptr);
523
524         return 0;
525 }
526
527 static int app_control_unmute(struct stasis_app_control *control,
528         struct ast_channel *chan, void *data)
529 {
530         struct stasis_app_control_mute_data *mute_data = data;
531         SCOPED_CHANNELLOCK(lockvar, chan);
532
533         ast_channel_unsuppress(control->channel, mute_data->direction, mute_data->frametype);
534
535         return 0;
536 }
537
538 int stasis_app_control_unmute(struct stasis_app_control *control, unsigned int direction, enum ast_frame_type frametype)
539 {
540         struct stasis_app_control_mute_data *mute_data;
541
542         if (!(mute_data = ast_calloc(1, sizeof(*mute_data)))) {
543                 return -1;
544         }
545
546         mute_data->direction = direction;
547         mute_data->frametype = frametype;
548
549         stasis_app_send_command_async(control, app_control_unmute, mute_data, ast_free_ptr);
550
551         return 0;
552 }
553
554 /*!
555  * \brief structure for queuing ARI channel variable setting
556  *
557  * It may seem weird to define this custom structure given that we already have
558  * ast_var_t and ast_variable defined elsewhere. The problem with those is that
559  * they are not tolerant of NULL channel variable value pointers. In fact, in both
560  * cases, the best they could do is to have a zero-length variable value. However,
561  * when un-setting a channel variable, it is important to pass a NULL value, not
562  * a zero-length string.
563  */
564 struct chanvar {
565         /*! Name of variable to set/unset */
566         char *name;
567         /*! Value of variable to set. If unsetting, this will be NULL */
568         char *value;
569 };
570
571 static void free_chanvar(void *data)
572 {
573         struct chanvar *var = data;
574
575         ast_free(var->name);
576         ast_free(var->value);
577         ast_free(var);
578 }
579
580 static int app_control_set_channel_var(struct stasis_app_control *control,
581         struct ast_channel *chan, void *data)
582 {
583         struct chanvar *var = data;
584
585         pbx_builtin_setvar_helper(control->channel, var->name, var->value);
586
587         return 0;
588 }
589
590 int stasis_app_control_set_channel_var(struct stasis_app_control *control, const char *variable, const char *value)
591 {
592         struct chanvar *var;
593
594         var = ast_calloc(1, sizeof(*var));
595         if (!var) {
596                 return -1;
597         }
598
599         var->name = ast_strdup(variable);
600         if (!var->name) {
601                 free_chanvar(var);
602                 return -1;
603         }
604
605         /* It's kosher for value to be NULL. It means the variable is being unset */
606         if (value) {
607                 var->value = ast_strdup(value);
608                 if (!var->value) {
609                         free_chanvar(var);
610                         return -1;
611                 }
612         }
613
614         stasis_app_send_command_async(control, app_control_set_channel_var, var, free_chanvar);
615
616         return 0;
617 }
618
619 static int app_control_hold(struct stasis_app_control *control,
620         struct ast_channel *chan, void *data)
621 {
622         ast_indicate(control->channel, AST_CONTROL_HOLD);
623
624         return 0;
625 }
626
627 void stasis_app_control_hold(struct stasis_app_control *control)
628 {
629         stasis_app_send_command_async(control, app_control_hold, NULL, NULL);
630 }
631
632 static int app_control_unhold(struct stasis_app_control *control,
633         struct ast_channel *chan, void *data)
634 {
635         ast_indicate(control->channel, AST_CONTROL_UNHOLD);
636
637         return 0;
638 }
639
640 void stasis_app_control_unhold(struct stasis_app_control *control)
641 {
642         stasis_app_send_command_async(control, app_control_unhold, NULL, NULL);
643 }
644
645 static int app_control_moh_start(struct stasis_app_control *control,
646         struct ast_channel *chan, void *data)
647 {
648         char *moh_class = data;
649
650         if (ast_channel_state(chan) != AST_STATE_UP) {
651                 ast_indicate(chan, AST_CONTROL_PROGRESS);
652         }
653
654         ast_moh_start(chan, moh_class, NULL);
655
656         return 0;
657 }
658
659 void stasis_app_control_moh_start(struct stasis_app_control *control, const char *moh_class)
660 {
661         char *data = NULL;
662
663         if (!ast_strlen_zero(moh_class)) {
664                 data = ast_strdup(moh_class);
665         }
666
667         stasis_app_send_command_async(control, app_control_moh_start, data, ast_free_ptr);
668 }
669
670 static int app_control_moh_stop(struct stasis_app_control *control,
671         struct ast_channel *chan, void *data)
672 {
673         ast_moh_stop(chan);
674         return 0;
675 }
676
677 void stasis_app_control_moh_stop(struct stasis_app_control *control)
678 {
679         stasis_app_send_command_async(control, app_control_moh_stop, NULL, NULL);
680 }
681
682 static int app_control_silence_start(struct stasis_app_control *control,
683         struct ast_channel *chan, void *data)
684 {
685         if (ast_channel_state(chan) != AST_STATE_UP) {
686                 ast_indicate(chan, AST_CONTROL_PROGRESS);
687         }
688
689         if (control->silgen) {
690                 /* We have a silence generator, but it may have been implicitly
691                  * disabled by media actions (music on hold, playing media,
692                  * etc.) Just stop it and restart a new one.
693                  */
694                 ast_channel_stop_silence_generator(
695                         control->channel, control->silgen);
696         }
697
698         ast_debug(3, "%s: Starting silence generator\n",
699                 stasis_app_control_get_channel_id(control));
700         control->silgen = ast_channel_start_silence_generator(control->channel);
701
702         if (!control->silgen) {
703                 ast_log(LOG_WARNING,
704                         "%s: Failed to start silence generator.\n",
705                         stasis_app_control_get_channel_id(control));
706         }
707
708         return 0;
709 }
710
711 void stasis_app_control_silence_start(struct stasis_app_control *control)
712 {
713         stasis_app_send_command_async(control, app_control_silence_start, NULL, NULL);
714 }
715
716 void control_silence_stop_now(struct stasis_app_control *control)
717 {
718         if (control->silgen) {
719                 ast_debug(3, "%s: Stopping silence generator\n",
720                         stasis_app_control_get_channel_id(control));
721                 ast_channel_stop_silence_generator(
722                         control->channel, control->silgen);
723                 control->silgen = NULL;
724         }
725 }
726
727 static int app_control_silence_stop(struct stasis_app_control *control,
728         struct ast_channel *chan, void *data)
729 {
730         control_silence_stop_now(control);
731         return 0;
732 }
733
734 void stasis_app_control_silence_stop(struct stasis_app_control *control)
735 {
736         stasis_app_send_command_async(control, app_control_silence_stop, NULL, NULL);
737 }
738
739 struct ast_channel_snapshot *stasis_app_control_get_snapshot(
740         const struct stasis_app_control *control)
741 {
742         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
743         struct ast_channel_snapshot *snapshot;
744
745         msg = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(),
746                 stasis_app_control_get_channel_id(control));
747         if (!msg) {
748                 return NULL;
749         }
750
751         snapshot = stasis_message_data(msg);
752         ast_assert(snapshot != NULL);
753
754         ao2_ref(snapshot, +1);
755         return snapshot;
756 }
757
758 static int app_send_command_on_condition(struct stasis_app_control *control,
759                                          stasis_app_command_cb command_fn, void *data,
760                                          command_data_destructor_fn data_destructor,
761                                          app_command_can_exec_cb can_exec_fn)
762 {
763         RAII_VAR(struct stasis_app_command *, command, NULL, ao2_cleanup);
764
765         if (control == NULL || control->is_done) {
766                 /* If exec_command_on_condition fails, it calls the data_destructor.
767                  * In order to provide consistent behavior, we'll also call the data_destructor
768                  * on this error path. This way, callers never have to call the
769                  * data_destructor themselves.
770                  */
771                 if (data_destructor) {
772                         data_destructor(data);
773                 }
774                 return -1;
775         }
776
777         command = exec_command_on_condition(
778                 control, command_fn, data, data_destructor, can_exec_fn);
779         if (!command) {
780                 return -1;
781         }
782
783         return command_join(command);
784 }
785
786 int stasis_app_send_command(struct stasis_app_control *control,
787         stasis_app_command_cb command_fn, void *data, command_data_destructor_fn data_destructor)
788 {
789         return app_send_command_on_condition(control, command_fn, data, data_destructor, NULL);
790 }
791
792 int stasis_app_send_command_async(struct stasis_app_control *control,
793         stasis_app_command_cb command_fn, void *data,
794         command_data_destructor_fn data_destructor)
795 {
796         RAII_VAR(struct stasis_app_command *, command, NULL, ao2_cleanup);
797
798         if (control == NULL || control->is_done) {
799                 /* If exec_command fails, it calls the data_destructor. In order to
800                  * provide consistent behavior, we'll also call the data_destructor
801                  * on this error path. This way, callers never have to call the
802                  * data_destructor themselves.
803                  */
804                 if (data_destructor) {
805                         data_destructor(data);
806                 }
807                 return -1;
808         }
809
810         command = exec_command(control, command_fn, data, data_destructor);
811         if (!command) {
812                 return -1;
813         }
814
815         return 0;
816 }
817
818 struct ast_bridge *stasis_app_get_bridge(struct stasis_app_control *control)
819 {
820         if (!control) {
821                 return NULL;
822         } else {
823                 SCOPED_AO2LOCK(lock, control);
824                 return control->bridge;
825         }
826 }
827
828 static int bridge_channel_depart(struct stasis_app_control *control,
829         struct ast_channel *chan, void *data)
830 {
831         struct ast_bridge_channel *bridge_channel = data;
832
833         {
834                 SCOPED_CHANNELLOCK(lock, chan);
835
836                 if (bridge_channel != ast_channel_internal_bridge_channel(chan)) {
837                         ast_debug(3, "%s: Channel is no longer in departable state\n",
838                                 ast_channel_uniqueid(chan));
839                         return -1;
840                 }
841         }
842
843         ast_debug(3, "%s: Channel departing bridge\n",
844                 ast_channel_uniqueid(chan));
845
846         ast_bridge_depart(chan);
847
848         return 0;
849 }
850
851 static void bridge_after_cb(struct ast_channel *chan, void *data)
852 {
853         struct stasis_app_control *control = data;
854         SCOPED_AO2LOCK(lock, control);
855         struct ast_bridge_channel *bridge_channel;
856
857         ast_debug(3, "%s, %s: Channel leaving bridge\n",
858                 ast_channel_uniqueid(chan), control->bridge->uniqueid);
859
860         ast_assert(chan == control->channel);
861
862         /* Restore the channel's PBX */
863         ast_channel_pbx_set(control->channel, control->pbx);
864         control->pbx = NULL;
865
866         app_unsubscribe_bridge(control->app, control->bridge);
867
868         /* No longer in the bridge */
869         control->bridge = NULL;
870
871         /* Get the bridge channel so we don't depart from the wrong bridge */
872         ast_channel_lock(chan);
873         bridge_channel = ast_channel_get_bridge_channel(chan);
874         ast_channel_unlock(chan);
875
876         /* Depart this channel from the bridge using the command queue if possible */
877         stasis_app_send_command_async(control, bridge_channel_depart, bridge_channel, __ao2_cleanup);
878         if (stasis_app_channel_is_stasis_end_published(chan)) {
879                 /* The channel has had a StasisEnd published on it, but until now had remained in
880                  * the bridging system. This means that the channel moved from a Stasis bridge to a
881                  * non-Stasis bridge and is now exiting the bridging system. Because of this, the
882                  * channel needs to exit the Stasis application and go to wherever the non-Stasis
883                  * bridge has directed it to go. If the non-Stasis bridge has not set up an after
884                  * bridge destination, then the channel should be hung up.
885                  */
886                 int hangup_flag;
887
888                 hangup_flag = ast_bridge_setup_after_goto(chan) ? AST_SOFTHANGUP_DEV : AST_SOFTHANGUP_ASYNCGOTO;
889                 ast_channel_lock(chan);
890                 ast_softhangup_nolock(chan, hangup_flag);
891                 ast_channel_unlock(chan);
892         }
893 }
894
895 static void bridge_after_cb_failed(enum ast_bridge_after_cb_reason reason,
896         void *data)
897 {
898         struct stasis_app_control *control = data;
899
900         bridge_after_cb(control->channel, data);
901
902         ast_debug(3, "  reason: %s\n",
903                 ast_bridge_after_cb_reason_string(reason));
904 }
905
906 int control_swap_channel_in_bridge(struct stasis_app_control *control, struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap)
907 {
908         int res;
909
910         if (!control || !bridge) {
911                 return -1;
912         }
913
914         ast_debug(3, "%s: Adding to bridge %s\n",
915                 stasis_app_control_get_channel_id(control),
916                 bridge->uniqueid);
917
918         ast_assert(chan != NULL);
919
920         /* Depart whatever Stasis bridge we're currently in. */
921         if (stasis_app_get_bridge(control)) {
922                 /* Note that it looks like there's a race condition here, since
923                  * we don't have control locked. But this happens from the
924                  * control callback thread, so there won't be any other
925                  * concurrent attempts to bridge.
926                  */
927                 ast_bridge_depart(chan);
928         }
929
930
931         res = ast_bridge_set_after_callback(chan, bridge_after_cb,
932                 bridge_after_cb_failed, control);
933         if (res != 0) {
934                 ast_log(LOG_ERROR, "Error setting after-bridge callback\n");
935                 return -1;
936         }
937
938         {
939                 /* pbx and bridge are modified by the bridging impart thread.
940                  * It shouldn't happen concurrently, but we still need to lock
941                  * for the memory fence.
942                  */
943                 SCOPED_AO2LOCK(lock, control);
944
945                 /* Ensure the controlling application is subscribed early enough
946                  * to receive the ChannelEnteredBridge message. This works in concert
947                  * with the subscription handled in the Stasis application execution
948                  * loop */
949                 app_subscribe_bridge(control->app, bridge);
950
951                 /* Save off the channel's PBX */
952                 ast_assert(control->pbx == NULL);
953                 if (!control->pbx) {
954                         control->pbx = ast_channel_pbx(chan);
955                         ast_channel_pbx_set(chan, NULL);
956                 }
957
958                 res = ast_bridge_impart(bridge,
959                         chan,
960                         swap,
961                         NULL, /* features */
962                         AST_BRIDGE_IMPART_CHAN_DEPARTABLE);
963                 if (res != 0) {
964                         ast_log(LOG_ERROR, "Error adding channel to bridge\n");
965                         ast_channel_pbx_set(chan, control->pbx);
966                         control->pbx = NULL;
967                         return -1;
968                 }
969
970                 ast_assert(stasis_app_get_bridge(control) == NULL);
971                 control->bridge = bridge;
972         }
973         return 0;
974 }
975
976 int control_add_channel_to_bridge(struct stasis_app_control *control, struct ast_channel *chan, void *data)
977 {
978         return control_swap_channel_in_bridge(control, data, chan, NULL);
979 }
980
981 int stasis_app_control_add_channel_to_bridge(
982         struct stasis_app_control *control, struct ast_bridge *bridge)
983 {
984         ast_debug(3, "%s: Sending channel add_to_bridge command\n",
985                         stasis_app_control_get_channel_id(control));
986
987         return app_send_command_on_condition(
988                 control, control_add_channel_to_bridge, bridge, NULL,
989                 app_control_can_add_channel_to_bridge);
990 }
991
992 static int app_control_remove_channel_from_bridge(
993         struct stasis_app_control *control,
994         struct ast_channel *chan, void *data)
995 {
996         struct ast_bridge *bridge = data;
997
998         if (!control) {
999                 return -1;
1000         }
1001
1002         /* We should only depart from our own bridge */
1003         ast_debug(3, "%s: Departing bridge %s\n",
1004                 stasis_app_control_get_channel_id(control),
1005                 bridge->uniqueid);
1006
1007         if (bridge != stasis_app_get_bridge(control)) {
1008                 ast_log(LOG_WARNING, "%s: Not in bridge %s; not removing\n",
1009                         stasis_app_control_get_channel_id(control),
1010                         bridge->uniqueid);
1011                 return -1;
1012         }
1013
1014         ast_bridge_depart(chan);
1015         return 0;
1016 }
1017
1018 int stasis_app_control_remove_channel_from_bridge(
1019         struct stasis_app_control *control, struct ast_bridge *bridge)
1020 {
1021         ast_debug(3, "%s: Sending channel remove_from_bridge command\n",
1022                         stasis_app_control_get_channel_id(control));
1023         return app_send_command_on_condition(
1024                 control, app_control_remove_channel_from_bridge, bridge, NULL,
1025                 app_control_can_remove_channel_from_bridge);
1026 }
1027
1028 const char *stasis_app_control_get_channel_id(
1029         const struct stasis_app_control *control)
1030 {
1031         return ast_channel_uniqueid(control->channel);
1032 }
1033
1034 void stasis_app_control_publish(
1035         struct stasis_app_control *control, struct stasis_message *message)
1036 {
1037         if (!control || !control->channel || !message) {
1038                 return;
1039         }
1040         stasis_publish(ast_channel_topic(control->channel), message);
1041 }
1042
1043 int stasis_app_control_queue_control(struct stasis_app_control *control,
1044         enum ast_control_frame_type frame_type)
1045 {
1046         return ast_queue_control(control->channel, frame_type);
1047 }
1048
1049 void control_flush_queue(struct stasis_app_control *control)
1050 {
1051         struct ao2_iterator iter;
1052         struct stasis_app_command *command;
1053
1054         iter = ao2_iterator_init(control->command_queue, AO2_ITERATOR_UNLINK);
1055         while ((command = ao2_iterator_next(&iter))) {
1056                 command_complete(command, -1);
1057                 ao2_ref(command, -1);
1058         }
1059         ao2_iterator_destroy(&iter);
1060 }
1061
1062 int control_dispatch_all(struct stasis_app_control *control,
1063         struct ast_channel *chan)
1064 {
1065         int count = 0;
1066         struct ao2_iterator iter;
1067         struct stasis_app_command *command;
1068
1069         ast_assert(control->channel == chan);
1070
1071         iter = ao2_iterator_init(control->command_queue, AO2_ITERATOR_UNLINK);
1072         while ((command = ao2_iterator_next(&iter))) {
1073                 command_invoke(command, control, chan);
1074                 ao2_ref(command, -1);
1075                 ++count;
1076         }
1077         ao2_iterator_destroy(&iter);
1078
1079         return count;
1080 }
1081
1082 void control_wait(struct stasis_app_control *control)
1083 {
1084         if (!control) {
1085                 return;
1086         }
1087
1088         ast_assert(control->command_queue != NULL);
1089
1090         ao2_lock(control->command_queue);
1091         while (ao2_container_count(control->command_queue) == 0) {
1092                 int res = ast_cond_wait(&control->wait_cond,
1093                         ao2_object_get_lockaddr(control->command_queue));
1094                 if (res < 0) {
1095                         ast_log(LOG_ERROR, "Error waiting on command queue\n");
1096                         break;
1097                 }
1098         }
1099         ao2_unlock(control->command_queue);
1100 }
1101
1102 int control_prestart_dispatch_all(struct stasis_app_control *control,
1103         struct ast_channel *chan)
1104 {
1105         struct ao2_container *command_queue;
1106         int count = 0;
1107         struct ao2_iterator iter;
1108         struct stasis_app_command *command;
1109
1110         ast_channel_lock(chan);
1111         command_queue = command_prestart_get_container(chan);
1112         ast_channel_unlock(chan);
1113         if (!command_queue) {
1114                 return 0;
1115         }
1116
1117         iter = ao2_iterator_init(command_queue, AO2_ITERATOR_UNLINK);
1118
1119         while ((command = ao2_iterator_next(&iter))) {
1120                 command_invoke(command, control, chan);
1121                 ao2_cleanup(command);
1122                 ++count;
1123         }
1124
1125         ao2_iterator_destroy(&iter);
1126         ao2_cleanup(command_queue);
1127         return count;
1128 }
1129
1130 struct stasis_app *control_app(struct stasis_app_control *control)
1131 {
1132         return control->app;
1133 }
1134
1135 static void app_control_dial_destroy(void *data)
1136 {
1137         struct ast_dial *dial = data;
1138
1139         ast_dial_join(dial);
1140         ast_dial_destroy(dial);
1141 }
1142
1143 static int app_control_remove_dial(struct stasis_app_control *control,
1144         struct ast_channel *chan, void *data)
1145 {
1146         if (ast_dial_state(control->dial) != AST_DIAL_RESULT_ANSWERED) {
1147                 ast_softhangup(chan, AST_SOFTHANGUP_EXPLICIT);
1148         }
1149         control->dial = NULL;
1150         return 0;
1151 }
1152
1153 static void on_dial_state(struct ast_dial *dial)
1154 {
1155         enum ast_dial_result state;
1156         struct stasis_app_control *control;
1157         struct ast_channel *chan;
1158
1159         state = ast_dial_state(dial);
1160         control = ast_dial_get_user_data(dial);
1161
1162         switch (state) {
1163         case AST_DIAL_RESULT_ANSWERED:
1164                 /* Need to steal the reference to the answered channel so that dial doesn't
1165                  * try to hang it up when we destroy the dial structure.
1166                  */
1167                 chan = ast_dial_answered_steal(dial);
1168                 ast_channel_unref(chan);
1169                 /* Fall through intentionally */
1170         case AST_DIAL_RESULT_INVALID:
1171         case AST_DIAL_RESULT_FAILED:
1172         case AST_DIAL_RESULT_TIMEOUT:
1173         case AST_DIAL_RESULT_HANGUP:
1174         case AST_DIAL_RESULT_UNANSWERED:
1175                 /* The dial has completed, so we need to break the Stasis loop so
1176                  * that the channel's frames are handled in the proper place now.
1177                  */
1178                 stasis_app_send_command_async(control, app_control_remove_dial, dial, app_control_dial_destroy);
1179                 break;
1180         case AST_DIAL_RESULT_TRYING:
1181         case AST_DIAL_RESULT_RINGING:
1182         case AST_DIAL_RESULT_PROGRESS:
1183         case AST_DIAL_RESULT_PROCEEDING:
1184                 break;
1185         }
1186 }
1187
1188 static int app_control_dial(struct stasis_app_control *control,
1189         struct ast_channel *chan, void *data)
1190 {
1191         struct ast_dial *dial = data;
1192
1193         ast_dial_set_state_callback(dial, on_dial_state);
1194         /* The dial API gives the option of providing a caller channel, but for
1195          * Stasis, we really don't want to do that. The Dial API will take liberties such
1196          * as passing frames along to the calling channel (think ringing, progress, etc.).
1197          * This is not desirable in ARI applications since application writers should have
1198          * control over what does/does not get indicated to the calling channel
1199          */
1200         ast_dial_run(dial, NULL, 1);
1201         control->dial = dial;
1202
1203         return 0;
1204 }
1205
1206 struct ast_dial *stasis_app_get_dial(struct stasis_app_control *control)
1207 {
1208         return control->dial;
1209 }
1210
1211 int stasis_app_control_dial(struct stasis_app_control *control, struct ast_dial *dial)
1212 {
1213         return stasis_app_send_command_async(control, app_control_dial, dial, NULL);
1214 }