ARI: Fix a crash caused by hanging during playback to a channel in a bridge
[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_FILE_VERSION(__FILE__, "$Revision$")
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          * When set, /c app_stasis should exit and continue in the dialplan.
82          */
83         int is_done:1;
84 };
85
86 static void control_dtor(void *obj)
87 {
88         struct stasis_app_control *control = obj;
89
90         AST_LIST_HEAD_DESTROY(&control->add_rules);
91         AST_LIST_HEAD_DESTROY(&control->remove_rules);
92
93         /* We may have a lingering silence generator; free it */
94         ast_channel_stop_silence_generator(control->channel, control->silgen);
95         control->silgen = NULL;
96
97         ao2_cleanup(control->command_queue);
98         ast_cond_destroy(&control->wait_cond);
99         ao2_cleanup(control->app);
100 }
101
102 struct stasis_app_control *control_create(struct ast_channel *channel, struct stasis_app *app)
103 {
104         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
105         int res;
106
107         control = ao2_alloc(sizeof(*control), control_dtor);
108         if (!control) {
109                 return NULL;
110         }
111
112         control->app = ao2_bump(app);
113
114         res = ast_cond_init(&control->wait_cond, NULL);
115         if (res != 0) {
116                 ast_log(LOG_ERROR, "Error initializing ast_cond_t: %s\n",
117                         strerror(errno));
118                 return NULL;
119         }
120
121         control->command_queue = ao2_container_alloc_list(
122                 AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
123
124         if (!control->command_queue) {
125                 return NULL;
126         }
127
128         control->channel = channel;
129
130         AST_LIST_HEAD_INIT(&control->add_rules);
131         AST_LIST_HEAD_INIT(&control->remove_rules);
132
133         ao2_ref(control, +1);
134         return control;
135 }
136
137 static void app_control_register_rule(
138         const struct stasis_app_control *control,
139         struct app_control_rules *list, struct stasis_app_control_rule *obj)
140 {
141         SCOPED_AO2LOCK(lock, control->command_queue);
142         AST_LIST_INSERT_TAIL(list, obj, next);
143 }
144
145 static void app_control_unregister_rule(
146         const struct stasis_app_control *control,
147         struct app_control_rules *list, struct stasis_app_control_rule *obj)
148 {
149         struct stasis_app_control_rule *rule;
150         SCOPED_AO2LOCK(lock, control->command_queue);
151         AST_RWLIST_TRAVERSE_SAFE_BEGIN(list, rule, next) {
152                 if (rule == obj) {
153                         AST_RWLIST_REMOVE_CURRENT(next);
154                         break;
155                 }
156         }
157         AST_RWLIST_TRAVERSE_SAFE_END;
158 }
159
160 /*!
161  * \internal
162  * \brief Checks to make sure each rule in the given list passes.
163  *
164  * \details Loops over a list of rules checking for rejections or failures.
165  *          If one rule fails its resulting error code is returned.
166  *
167  * \note Command queue should be locked before calling this function.
168  *
169  * \param control The stasis application control
170  * \param list The list of rules to check
171  *
172  * \retval 0 if all rules pass
173  * \retval non-zero error code if a rule fails
174  */
175 static enum stasis_app_control_channel_result app_control_check_rules(
176         const struct stasis_app_control *control,
177         struct app_control_rules *list)
178 {
179         int res = 0;
180         struct stasis_app_control_rule *rule;
181         AST_LIST_TRAVERSE(list, rule, next) {
182                 if ((res = rule->check_rule(control))) {
183                         return res;
184                 }
185         }
186         return res;
187 }
188
189 void stasis_app_control_register_add_rule(
190         struct stasis_app_control *control,
191         struct stasis_app_control_rule *rule)
192 {
193         return app_control_register_rule(control, &control->add_rules, rule);
194 }
195
196 void stasis_app_control_unregister_add_rule(
197         struct stasis_app_control *control,
198         struct stasis_app_control_rule *rule)
199 {
200         app_control_unregister_rule(control, &control->add_rules, rule);
201 }
202
203 void stasis_app_control_register_remove_rule(
204         struct stasis_app_control *control,
205         struct stasis_app_control_rule *rule)
206 {
207         return app_control_register_rule(control, &control->remove_rules, rule);
208 }
209
210 void stasis_app_control_unregister_remove_rule(
211         struct stasis_app_control *control,
212         struct stasis_app_control_rule *rule)
213 {
214         app_control_unregister_rule(control, &control->remove_rules, rule);
215 }
216
217 static int app_control_can_add_channel_to_bridge(
218         struct stasis_app_control *control)
219 {
220         return app_control_check_rules(control, &control->add_rules);
221 }
222
223 static int app_control_can_remove_channel_from_bridge(
224         struct stasis_app_control *control)
225 {
226         return app_control_check_rules(control, &control->remove_rules);
227 }
228
229 static int noop_cb(struct stasis_app_control *control,
230         struct ast_channel *chan, void *data)
231 {
232         return 0;
233 }
234
235 /*! Callback type to see if the command can execute
236     note: command_queue is locked during callback */
237 typedef int (*app_command_can_exec_cb)(struct stasis_app_control *control);
238
239 static struct stasis_app_command *exec_command_on_condition(
240         struct stasis_app_control *control, stasis_app_command_cb command_fn,
241         void *data, command_data_destructor_fn data_destructor,
242         app_command_can_exec_cb can_exec_fn)
243 {
244         int retval;
245         struct stasis_app_command *command;
246
247         command_fn = command_fn ? : noop_cb;
248
249         command = command_create(command_fn, data, data_destructor);
250         if (!command) {
251                 return NULL;
252         }
253
254         ao2_lock(control->command_queue);
255         if (can_exec_fn && (retval = can_exec_fn(control))) {
256                 ao2_unlock(control->command_queue);
257                 command_complete(command, retval);
258                 return command;
259         }
260
261         ao2_link_flags(control->command_queue, command, OBJ_NOLOCK);
262         ast_cond_signal(&control->wait_cond);
263         ao2_unlock(control->command_queue);
264
265         return command;
266 }
267
268 static struct stasis_app_command *exec_command(
269         struct stasis_app_control *control, stasis_app_command_cb command_fn,
270         void *data, command_data_destructor_fn data_destructor)
271 {
272         return exec_command_on_condition(control, command_fn, data, data_destructor, NULL);
273 }
274
275 struct stasis_app_control_dial_data {
276         char endpoint[AST_CHANNEL_NAME];
277         int timeout;
278 };
279
280 static int app_control_dial(struct stasis_app_control *control,
281         struct ast_channel *chan, void *data)
282 {
283         RAII_VAR(struct ast_dial *, dial, ast_dial_create(), ast_dial_destroy);
284         struct stasis_app_control_dial_data *dial_data = data;
285         enum ast_dial_result res;
286         char *tech, *resource;
287         struct ast_channel *new_chan;
288         RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
289
290         tech = dial_data->endpoint;
291         if (!(resource = strchr(tech, '/'))) {
292                 return -1;
293         }
294         *resource++ = '\0';
295
296         if (!dial) {
297                 ast_log(LOG_ERROR, "Failed to create dialing structure.\n");
298                 return -1;
299         }
300
301         if (ast_dial_append(dial, tech, resource, NULL) < 0) {
302                 ast_log(LOG_ERROR, "Failed to add %s/%s to dialing structure.\n", tech, resource);
303                 return -1;
304         }
305
306         ast_dial_set_global_timeout(dial, dial_data->timeout);
307
308         res = ast_dial_run(dial, NULL, 0);
309         if (res != AST_DIAL_RESULT_ANSWERED || !(new_chan = ast_dial_answered_steal(dial))) {
310                 return -1;
311         }
312
313         if (!(bridge = ast_bridge_basic_new())) {
314                 ast_log(LOG_ERROR, "Failed to create basic bridge.\n");
315                 return -1;
316         }
317
318         if (ast_bridge_impart(bridge, new_chan, NULL, NULL,
319                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
320                 ast_hangup(new_chan);
321         } else {
322                 control_add_channel_to_bridge(control, chan, bridge);
323         }
324
325         return 0;
326 }
327
328 int stasis_app_control_dial(struct stasis_app_control *control, const char *endpoint, const char *exten, const char *context,
329                             int timeout)
330 {
331         struct stasis_app_control_dial_data *dial_data;
332
333         if (!(dial_data = ast_calloc(1, sizeof(*dial_data)))) {
334                 return -1;
335         }
336
337         if (!ast_strlen_zero(endpoint)) {
338                 ast_copy_string(dial_data->endpoint, endpoint, sizeof(dial_data->endpoint));
339         } else if (!ast_strlen_zero(exten) && !ast_strlen_zero(context)) {
340                 snprintf(dial_data->endpoint, sizeof(dial_data->endpoint), "Local/%s@%s", exten, context);
341         } else {
342                 return -1;
343         }
344
345         if (timeout > 0) {
346                 dial_data->timeout = timeout * 1000;
347         } else if (timeout == -1) {
348                 dial_data->timeout = -1;
349         } else {
350                 dial_data->timeout = 30000;
351         }
352
353         stasis_app_send_command_async(control, app_control_dial, dial_data, ast_free_ptr);
354
355         return 0;
356 }
357
358 int stasis_app_control_add_role(struct stasis_app_control *control, const char *role)
359 {
360         return ast_channel_add_bridge_role(control->channel, role);
361 }
362
363 void stasis_app_control_clear_roles(struct stasis_app_control *control)
364 {
365         ast_channel_clear_bridge_roles(control->channel);
366 }
367
368 int control_command_count(struct stasis_app_control *control)
369 {
370         return ao2_container_count(control->command_queue);
371 }
372
373 int control_is_done(struct stasis_app_control *control)
374 {
375         /* Called from stasis_app_exec thread; no lock needed */
376         return control->is_done;
377 }
378
379 void control_mark_done(struct stasis_app_control *control)
380 {
381         control->is_done = 1;
382 }
383
384 struct stasis_app_control_continue_data {
385         char context[AST_MAX_CONTEXT];
386         char extension[AST_MAX_EXTENSION];
387         int priority;
388 };
389
390 static int app_control_continue(struct stasis_app_control *control,
391         struct ast_channel *chan, void *data)
392 {
393         struct stasis_app_control_continue_data *continue_data = data;
394
395         ast_assert(control->channel != NULL);
396
397         /* If we're in a Stasis bridge, depart it before going back to the
398          * dialplan */
399         if (stasis_app_get_bridge(control)) {
400                 ast_bridge_depart(control->channel);
401         }
402
403         /* Called from stasis_app_exec thread; no lock needed */
404         ast_explicit_goto(control->channel, continue_data->context, continue_data->extension, continue_data->priority);
405
406         control->is_done = 1;
407
408         return 0;
409 }
410
411 int stasis_app_control_continue(struct stasis_app_control *control, const char *context, const char *extension, int priority)
412 {
413         struct stasis_app_control_continue_data *continue_data;
414
415         if (!(continue_data = ast_calloc(1, sizeof(*continue_data)))) {
416                 return -1;
417         }
418         ast_copy_string(continue_data->context, S_OR(context, ""), sizeof(continue_data->context));
419         ast_copy_string(continue_data->extension, S_OR(extension, ""), sizeof(continue_data->extension));
420         if (priority > 0) {
421                 continue_data->priority = priority;
422         } else {
423                 continue_data->priority = -1;
424         }
425
426         stasis_app_send_command_async(control, app_control_continue, continue_data, ast_free_ptr);
427
428         return 0;
429 }
430
431 struct stasis_app_control_dtmf_data {
432         int before;
433         int between;
434         unsigned int duration;
435         int after;
436         char dtmf[];
437 };
438
439 static int app_control_dtmf(struct stasis_app_control *control,
440         struct ast_channel *chan, void *data)
441 {
442         struct stasis_app_control_dtmf_data *dtmf_data = data;
443
444         if (ast_channel_state(chan) != AST_STATE_UP) {
445                 ast_indicate(chan, AST_CONTROL_PROGRESS);
446         }
447
448         if (dtmf_data->before) {
449                 ast_safe_sleep(chan, dtmf_data->before);
450         }
451
452         ast_dtmf_stream(chan, NULL, dtmf_data->dtmf, dtmf_data->between, dtmf_data->duration);
453
454         if (dtmf_data->after) {
455                 ast_safe_sleep(chan, dtmf_data->after);
456         }
457
458         return 0;
459 }
460
461 int stasis_app_control_dtmf(struct stasis_app_control *control, const char *dtmf, int before, int between, unsigned int duration, int after)
462 {
463         struct stasis_app_control_dtmf_data *dtmf_data;
464
465         if (!(dtmf_data = ast_calloc(1, sizeof(*dtmf_data) + strlen(dtmf) + 1))) {
466                 return -1;
467         }
468
469         dtmf_data->before = before;
470         dtmf_data->between = between;
471         dtmf_data->duration = duration;
472         dtmf_data->after = after;
473         strcpy(dtmf_data->dtmf, dtmf);
474
475         stasis_app_send_command_async(control, app_control_dtmf, dtmf_data, ast_free_ptr);
476
477         return 0;
478 }
479
480 static int app_control_ring(struct stasis_app_control *control,
481         struct ast_channel *chan, void *data)
482 {
483         ast_indicate(control->channel, AST_CONTROL_RINGING);
484
485         return 0;
486 }
487
488 int stasis_app_control_ring(struct stasis_app_control *control)
489 {
490         stasis_app_send_command_async(control, app_control_ring, NULL, NULL);
491
492         return 0;
493 }
494
495 static int app_control_ring_stop(struct stasis_app_control *control,
496         struct ast_channel *chan, void *data)
497 {
498         ast_indicate(control->channel, -1);
499
500         return 0;
501 }
502
503 int stasis_app_control_ring_stop(struct stasis_app_control *control)
504 {
505         stasis_app_send_command_async(control, app_control_ring_stop, NULL, NULL);
506
507         return 0;
508 }
509
510 struct stasis_app_control_mute_data {
511         enum ast_frame_type frametype;
512         unsigned int direction;
513 };
514
515 static int app_control_mute(struct stasis_app_control *control,
516         struct ast_channel *chan, void *data)
517 {
518         struct stasis_app_control_mute_data *mute_data = data;
519         SCOPED_CHANNELLOCK(lockvar, chan);
520
521         ast_channel_suppress(control->channel, mute_data->direction, mute_data->frametype);
522
523         return 0;
524 }
525
526 int stasis_app_control_mute(struct stasis_app_control *control, unsigned int direction, enum ast_frame_type frametype)
527 {
528         struct stasis_app_control_mute_data *mute_data;
529
530         if (!(mute_data = ast_calloc(1, sizeof(*mute_data)))) {
531                 return -1;
532         }
533
534         mute_data->direction = direction;
535         mute_data->frametype = frametype;
536
537         stasis_app_send_command_async(control, app_control_mute, mute_data, ast_free_ptr);
538
539         return 0;
540 }
541
542 static int app_control_unmute(struct stasis_app_control *control,
543         struct ast_channel *chan, void *data)
544 {
545         struct stasis_app_control_mute_data *mute_data = data;
546         SCOPED_CHANNELLOCK(lockvar, chan);
547
548         ast_channel_unsuppress(control->channel, mute_data->direction, mute_data->frametype);
549
550         return 0;
551 }
552
553 int stasis_app_control_unmute(struct stasis_app_control *control, unsigned int direction, enum ast_frame_type frametype)
554 {
555         struct stasis_app_control_mute_data *mute_data;
556
557         if (!(mute_data = ast_calloc(1, sizeof(*mute_data)))) {
558                 return -1;
559         }
560
561         mute_data->direction = direction;
562         mute_data->frametype = frametype;
563
564         stasis_app_send_command_async(control, app_control_unmute, mute_data, ast_free_ptr);
565
566         return 0;
567 }
568
569 int stasis_app_control_set_channel_var(struct stasis_app_control *control, const char *variable, const char *value)
570 {
571         return pbx_builtin_setvar_helper(control->channel, variable, value);
572 }
573
574 static int app_control_hold(struct stasis_app_control *control,
575         struct ast_channel *chan, void *data)
576 {
577         ast_indicate(control->channel, AST_CONTROL_HOLD);
578
579         return 0;
580 }
581
582 void stasis_app_control_hold(struct stasis_app_control *control)
583 {
584         stasis_app_send_command_async(control, app_control_hold, NULL, NULL);
585 }
586
587 static int app_control_unhold(struct stasis_app_control *control,
588         struct ast_channel *chan, void *data)
589 {
590         ast_indicate(control->channel, AST_CONTROL_UNHOLD);
591
592         return 0;
593 }
594
595 void stasis_app_control_unhold(struct stasis_app_control *control)
596 {
597         stasis_app_send_command_async(control, app_control_unhold, NULL, NULL);
598 }
599
600 static int app_control_moh_start(struct stasis_app_control *control,
601         struct ast_channel *chan, void *data)
602 {
603         char *moh_class = data;
604
605         if (ast_channel_state(chan) != AST_STATE_UP) {
606                 ast_indicate(chan, AST_CONTROL_PROGRESS);
607         }
608
609         ast_moh_start(chan, moh_class, NULL);
610
611         return 0;
612 }
613
614 void stasis_app_control_moh_start(struct stasis_app_control *control, const char *moh_class)
615 {
616         char *data = NULL;
617
618         if (!ast_strlen_zero(moh_class)) {
619                 data = ast_strdup(moh_class);
620         }
621
622         stasis_app_send_command_async(control, app_control_moh_start, data, ast_free_ptr);
623 }
624
625 static int app_control_moh_stop(struct stasis_app_control *control,
626         struct ast_channel *chan, void *data)
627 {
628         ast_moh_stop(chan);
629         return 0;
630 }
631
632 void stasis_app_control_moh_stop(struct stasis_app_control *control)
633 {
634         stasis_app_send_command_async(control, app_control_moh_stop, NULL, NULL);
635 }
636
637 static int app_control_silence_start(struct stasis_app_control *control,
638         struct ast_channel *chan, void *data)
639 {
640         if (ast_channel_state(chan) != AST_STATE_UP) {
641                 ast_indicate(chan, AST_CONTROL_PROGRESS);
642         }
643
644         if (control->silgen) {
645                 /* We have a silence generator, but it may have been implicitly
646                  * disabled by media actions (music on hold, playing media,
647                  * etc.) Just stop it and restart a new one.
648                  */
649                 ast_channel_stop_silence_generator(
650                         control->channel, control->silgen);
651         }
652
653         ast_debug(3, "%s: Starting silence generator\n",
654                 stasis_app_control_get_channel_id(control));
655         control->silgen = ast_channel_start_silence_generator(control->channel);
656
657         if (!control->silgen) {
658                 ast_log(LOG_WARNING,
659                         "%s: Failed to start silence generator.\n",
660                         stasis_app_control_get_channel_id(control));
661         }
662
663         return 0;
664 }
665
666 void stasis_app_control_silence_start(struct stasis_app_control *control)
667 {
668         stasis_app_send_command_async(control, app_control_silence_start, NULL, NULL);
669 }
670
671 static int app_control_silence_stop(struct stasis_app_control *control,
672         struct ast_channel *chan, void *data)
673 {
674         if (control->silgen) {
675                 ast_debug(3, "%s: Stopping silence generator\n",
676                         stasis_app_control_get_channel_id(control));
677                 ast_channel_stop_silence_generator(
678                         control->channel, control->silgen);
679                 control->silgen = NULL;
680         }
681
682         return 0;
683 }
684
685 void stasis_app_control_silence_stop(struct stasis_app_control *control)
686 {
687         stasis_app_send_command_async(control, app_control_silence_stop, NULL, NULL);
688 }
689
690 struct ast_channel_snapshot *stasis_app_control_get_snapshot(
691         const struct stasis_app_control *control)
692 {
693         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
694         struct ast_channel_snapshot *snapshot;
695
696         msg = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(),
697                 stasis_app_control_get_channel_id(control));
698         if (!msg) {
699                 return NULL;
700         }
701
702         snapshot = stasis_message_data(msg);
703         ast_assert(snapshot != NULL);
704
705         ao2_ref(snapshot, +1);
706         return snapshot;
707 }
708
709 static int app_send_command_on_condition(struct stasis_app_control *control,
710                                          stasis_app_command_cb command_fn, void *data,
711                                          command_data_destructor_fn data_destructor,
712                                          app_command_can_exec_cb can_exec_fn)
713 {
714         RAII_VAR(struct stasis_app_command *, command, NULL, ao2_cleanup);
715
716         if (control == NULL) {
717                 return -1;
718         }
719
720         command = exec_command_on_condition(
721                 control, command_fn, data, data_destructor, can_exec_fn);
722         if (!command) {
723                 return -1;
724         }
725
726         return command_join(command);
727 }
728
729 int stasis_app_send_command(struct stasis_app_control *control,
730         stasis_app_command_cb command_fn, void *data, command_data_destructor_fn data_destructor)
731 {
732         return app_send_command_on_condition(control, command_fn, data, data_destructor, NULL);
733 }
734
735 int stasis_app_send_command_async(struct stasis_app_control *control,
736         stasis_app_command_cb command_fn, void *data,
737         command_data_destructor_fn data_destructor)
738 {
739         RAII_VAR(struct stasis_app_command *, command, NULL, ao2_cleanup);
740
741         if (control == NULL) {
742                 return -1;
743         }
744
745         command = exec_command(control, command_fn, data, data_destructor);
746         if (!command) {
747                 return -1;
748         }
749
750         return 0;
751 }
752
753 struct ast_bridge *stasis_app_get_bridge(struct stasis_app_control *control)
754 {
755         if (!control) {
756                 return NULL;
757         } else {
758                 SCOPED_AO2LOCK(lock, control);
759                 return control->bridge;
760         }
761 }
762
763 static int bridge_channel_depart(struct stasis_app_control *control,
764         struct ast_channel *chan, void *data)
765 {
766         struct ast_bridge_channel *bridge_channel = data;
767
768         {
769                 SCOPED_CHANNELLOCK(lock, chan);
770
771                 if (bridge_channel != ast_channel_internal_bridge_channel(chan)) {
772                         ast_debug(3, "%s: Channel is no longer in departable state\n",
773                                 ast_channel_uniqueid(chan));
774                         return -1;
775                 }
776         }
777
778         ast_debug(3, "%s: Channel departing bridge\n",
779                 ast_channel_uniqueid(chan));
780
781         ast_bridge_depart(chan);
782
783         return 0;
784 }
785
786 static void bridge_after_cb(struct ast_channel *chan, void *data)
787 {
788         struct stasis_app_control *control = data;
789         SCOPED_AO2LOCK(lock, control);
790         struct ast_bridge_channel *bridge_channel;
791
792         ast_debug(3, "%s, %s: Channel leaving bridge\n",
793                 ast_channel_uniqueid(chan), control->bridge->uniqueid);
794
795         ast_assert(chan == control->channel);
796
797         /* Restore the channel's PBX */
798         ast_channel_pbx_set(control->channel, control->pbx);
799         control->pbx = NULL;
800
801         app_unsubscribe_bridge(control->app, control->bridge);
802
803         /* No longer in the bridge */
804         control->bridge = NULL;
805
806         /* Get the bridge channel so we don't depart from the wrong bridge */
807         ast_channel_lock(chan);
808         bridge_channel = ast_channel_get_bridge_channel(chan);
809         ast_channel_unlock(chan);
810
811         /* Depart this channel from the bridge using the command queue if possible */
812         stasis_app_send_command_async(control, bridge_channel_depart, bridge_channel, __ao2_cleanup);
813         if (stasis_app_channel_is_stasis_end_published(chan)) {
814                 /* The channel has had a StasisEnd published on it, but until now had remained in
815                  * the bridging system. This means that the channel moved from a Stasis bridge to a
816                  * non-Stasis bridge and is now exiting the bridging system. Because of this, the
817                  * channel needs to exit the Stasis application and go to wherever the non-Stasis
818                  * bridge has directed it to go. If the non-Stasis bridge has not set up an after
819                  * bridge destination, then the channel should be hung up.
820                  */
821                 int hangup_flag;
822
823                 hangup_flag = ast_bridge_setup_after_goto(chan) ? AST_SOFTHANGUP_DEV : AST_SOFTHANGUP_ASYNCGOTO;
824                 ast_channel_lock(chan);
825                 ast_softhangup_nolock(chan, hangup_flag);
826                 ast_channel_unlock(chan);
827         }
828 }
829
830 static void bridge_after_cb_failed(enum ast_bridge_after_cb_reason reason,
831         void *data)
832 {
833         struct stasis_app_control *control = data;
834
835         bridge_after_cb(control->channel, data);
836
837         ast_debug(3, "  reason: %s\n",
838                 ast_bridge_after_cb_reason_string(reason));
839 }
840
841 int control_add_channel_to_bridge(
842         struct stasis_app_control *control,
843         struct ast_channel *chan, void *data)
844 {
845         struct ast_bridge *bridge = data;
846         int res;
847
848         if (!control || !bridge) {
849                 return -1;
850         }
851
852         ast_debug(3, "%s: Adding to bridge %s\n",
853                 stasis_app_control_get_channel_id(control),
854                 bridge->uniqueid);
855
856         ast_assert(chan != NULL);
857
858         /* Depart whatever Stasis bridge we're currently in. */
859         if (stasis_app_get_bridge(control)) {
860                 /* Note that it looks like there's a race condition here, since
861                  * we don't have control locked. But this happens from the
862                  * control callback thread, so there won't be any other
863                  * concurrent attempts to bridge.
864                  */
865                 ast_bridge_depart(chan);
866         }
867
868
869         res = ast_bridge_set_after_callback(chan, bridge_after_cb,
870                 bridge_after_cb_failed, control);
871         if (res != 0) {
872                 ast_log(LOG_ERROR, "Error setting after-bridge callback\n");
873                 return -1;
874         }
875
876         {
877                 /* pbx and bridge are modified by the bridging impart thread.
878                  * It shouldn't happen concurrently, but we still need to lock
879                  * for the memory fence.
880                  */
881                 SCOPED_AO2LOCK(lock, control);
882
883                 /* Ensure the controlling application is subscribed early enough
884                  * to receive the ChannelEnteredBridge message. This works in concert
885                  * with the subscription handled in the Stasis application execution
886                  * loop */
887                 app_subscribe_bridge(control->app, bridge);
888
889                 /* Save off the channel's PBX */
890                 ast_assert(control->pbx == NULL);
891                 if (!control->pbx) {
892                         control->pbx = ast_channel_pbx(chan);
893                         ast_channel_pbx_set(chan, NULL);
894                 }
895
896                 res = ast_bridge_impart(bridge,
897                         chan,
898                         NULL, /* swap channel */
899                         NULL, /* features */
900                         AST_BRIDGE_IMPART_CHAN_DEPARTABLE);
901                 if (res != 0) {
902                         ast_log(LOG_ERROR, "Error adding channel to bridge\n");
903                         ast_channel_pbx_set(chan, control->pbx);
904                         control->pbx = NULL;
905                         return -1;
906                 }
907
908                 ast_assert(stasis_app_get_bridge(control) == NULL);
909                 control->bridge = bridge;
910         }
911         return 0;
912 }
913
914 int stasis_app_control_add_channel_to_bridge(
915         struct stasis_app_control *control, struct ast_bridge *bridge)
916 {
917         ast_debug(3, "%s: Sending channel add_to_bridge command\n",
918                         stasis_app_control_get_channel_id(control));
919
920         return app_send_command_on_condition(
921                 control, control_add_channel_to_bridge, bridge, NULL,
922                 app_control_can_add_channel_to_bridge);
923 }
924
925 static int app_control_remove_channel_from_bridge(
926         struct stasis_app_control *control,
927         struct ast_channel *chan, void *data)
928 {
929         struct ast_bridge *bridge = data;
930
931         if (!control) {
932                 return -1;
933         }
934
935         /* We should only depart from our own bridge */
936         ast_debug(3, "%s: Departing bridge %s\n",
937                 stasis_app_control_get_channel_id(control),
938                 bridge->uniqueid);
939
940         if (bridge != stasis_app_get_bridge(control)) {
941                 ast_log(LOG_WARNING, "%s: Not in bridge %s; not removing\n",
942                         stasis_app_control_get_channel_id(control),
943                         bridge->uniqueid);
944                 return -1;
945         }
946
947         ast_bridge_depart(chan);
948         return 0;
949 }
950
951 int stasis_app_control_remove_channel_from_bridge(
952         struct stasis_app_control *control, struct ast_bridge *bridge)
953 {
954         ast_debug(3, "%s: Sending channel remove_from_bridge command\n",
955                         stasis_app_control_get_channel_id(control));
956         return app_send_command_on_condition(
957                 control, app_control_remove_channel_from_bridge, bridge, NULL,
958                 app_control_can_remove_channel_from_bridge);
959 }
960
961 const char *stasis_app_control_get_channel_id(
962         const struct stasis_app_control *control)
963 {
964         return ast_channel_uniqueid(control->channel);
965 }
966
967 void stasis_app_control_publish(
968         struct stasis_app_control *control, struct stasis_message *message)
969 {
970         if (!control || !control->channel || !message) {
971                 return;
972         }
973         stasis_publish(ast_channel_topic(control->channel), message);
974 }
975
976 int stasis_app_control_queue_control(struct stasis_app_control *control,
977         enum ast_control_frame_type frame_type)
978 {
979         return ast_queue_control(control->channel, frame_type);
980 }
981
982 int control_dispatch_all(struct stasis_app_control *control,
983         struct ast_channel *chan)
984 {
985         int count = 0;
986         struct ao2_iterator i;
987         void *obj;
988
989         ast_assert(control->channel == chan);
990
991         i = ao2_iterator_init(control->command_queue, AO2_ITERATOR_UNLINK);
992
993         while ((obj = ao2_iterator_next(&i))) {
994                 RAII_VAR(struct stasis_app_command *, command, obj, ao2_cleanup);
995                 command_invoke(command, control, chan);
996                 ++count;
997         }
998
999         ao2_iterator_destroy(&i);
1000         return count;
1001 }
1002
1003 void control_wait(struct stasis_app_control *control)
1004 {
1005         if (!control) {
1006                 return;
1007         }
1008
1009         ast_assert(control->command_queue != NULL);
1010
1011         ao2_lock(control->command_queue);
1012         while (ao2_container_count(control->command_queue) == 0) {
1013                 int res = ast_cond_wait(&control->wait_cond,
1014                         ao2_object_get_lockaddr(control->command_queue));
1015                 if (res < 0) {
1016                         ast_log(LOG_ERROR, "Error waiting on command queue\n");
1017                         break;
1018                 }
1019         }
1020         ao2_unlock(control->command_queue);
1021 }
1022
1023 int control_prestart_dispatch_all(struct stasis_app_control *control,
1024         struct ast_channel *chan)
1025 {
1026         struct ao2_container *command_queue;
1027         int count = 0;
1028         struct ao2_iterator iter;
1029         struct stasis_app_command *command;
1030
1031         ast_channel_lock(chan);
1032         command_queue = command_prestart_get_container(chan);
1033         ast_channel_unlock(chan);
1034         if (!command_queue) {
1035                 return 0;
1036         }
1037
1038         iter = ao2_iterator_init(command_queue, AO2_ITERATOR_UNLINK);
1039
1040         while ((command = ao2_iterator_next(&iter))) {
1041                 command_invoke(command, control, chan);
1042                 ao2_cleanup(command);
1043                 ++count;
1044         }
1045
1046         ao2_iterator_destroy(&iter);
1047         ao2_cleanup(command_queue);
1048         return count;
1049 }
1050
1051 struct stasis_app *control_app(struct stasis_app_control *control)
1052 {
1053         return control->app;
1054 }