Improve call forwarding reporting, especially with regards to ARI.
[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, app_command_can_exec_cb can_exec_fn)
242 {
243         int retval;
244         struct stasis_app_command *command;
245
246         command_fn = command_fn ? : noop_cb;
247
248         command = command_create(command_fn, data);
249         if (!command) {
250                 return NULL;
251         }
252
253         ao2_lock(control->command_queue);
254         if (can_exec_fn && (retval = can_exec_fn(control))) {
255                 ao2_unlock(control->command_queue);
256                 command_complete(command, retval);
257                 return command;
258         }
259
260         ao2_link_flags(control->command_queue, command, OBJ_NOLOCK);
261         ast_cond_signal(&control->wait_cond);
262         ao2_unlock(control->command_queue);
263
264         return command;
265 }
266
267 static struct stasis_app_command *exec_command(
268         struct stasis_app_control *control, stasis_app_command_cb command_fn,
269         void *data)
270 {
271         return exec_command_on_condition(control, command_fn, data, NULL);
272 }
273
274 struct stasis_app_control_dial_data {
275         char endpoint[AST_CHANNEL_NAME];
276         int timeout;
277 };
278
279 static int app_control_dial(struct stasis_app_control *control,
280         struct ast_channel *chan, void *data)
281 {
282         RAII_VAR(struct ast_dial *, dial, ast_dial_create(), ast_dial_destroy);
283         RAII_VAR(struct stasis_app_control_dial_data *, dial_data, data, ast_free);
284         enum ast_dial_result res;
285         char *tech, *resource;
286         struct ast_channel *new_chan;
287         RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
288
289         tech = dial_data->endpoint;
290         if (!(resource = strchr(tech, '/'))) {
291                 return -1;
292         }
293         *resource++ = '\0';
294
295         if (!dial) {
296                 ast_log(LOG_ERROR, "Failed to create dialing structure.\n");
297                 return -1;
298         }
299
300         if (ast_dial_append(dial, tech, resource, NULL) < 0) {
301                 ast_log(LOG_ERROR, "Failed to add %s/%s to dialing structure.\n", tech, resource);
302                 return -1;
303         }
304
305         ast_dial_set_global_timeout(dial, dial_data->timeout);
306
307         res = ast_dial_run(dial, NULL, 0);
308         if (res != AST_DIAL_RESULT_ANSWERED || !(new_chan = ast_dial_answered_steal(dial))) {
309                 return -1;
310         }
311
312         if (!(bridge = ast_bridge_basic_new())) {
313                 ast_log(LOG_ERROR, "Failed to create basic bridge.\n");
314                 return -1;
315         }
316
317         if (ast_bridge_impart(bridge, new_chan, NULL, NULL,
318                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
319                 ast_hangup(new_chan);
320         } else {
321                 control_add_channel_to_bridge(control, chan, bridge);
322         }
323
324         return 0;
325 }
326
327 int stasis_app_control_dial(struct stasis_app_control *control, const char *endpoint, const char *exten, const char *context,
328                             int timeout)
329 {
330         struct stasis_app_control_dial_data *dial_data;
331
332         if (!(dial_data = ast_calloc(1, sizeof(*dial_data)))) {
333                 return -1;
334         }
335
336         if (!ast_strlen_zero(endpoint)) {
337                 ast_copy_string(dial_data->endpoint, endpoint, sizeof(dial_data->endpoint));
338         } else if (!ast_strlen_zero(exten) && !ast_strlen_zero(context)) {
339                 snprintf(dial_data->endpoint, sizeof(dial_data->endpoint), "Local/%s@%s", exten, context);
340         } else {
341                 return -1;
342         }
343
344         if (timeout > 0) {
345                 dial_data->timeout = timeout * 1000;
346         } else if (timeout == -1) {
347                 dial_data->timeout = -1;
348         } else {
349                 dial_data->timeout = 30000;
350         }
351
352         stasis_app_send_command_async(control, app_control_dial, dial_data);
353
354         return 0;
355 }
356
357 int stasis_app_control_add_role(struct stasis_app_control *control, const char *role)
358 {
359         return ast_channel_add_bridge_role(control->channel, role);
360 }
361
362 void stasis_app_control_clear_roles(struct stasis_app_control *control)
363 {
364         ast_channel_clear_bridge_roles(control->channel);
365 }
366
367 int control_command_count(struct stasis_app_control *control)
368 {
369         return ao2_container_count(control->command_queue);
370 }
371
372 int control_is_done(struct stasis_app_control *control)
373 {
374         /* Called from stasis_app_exec thread; no lock needed */
375         return control->is_done;
376 }
377
378 void control_mark_done(struct stasis_app_control *control)
379 {
380         control->is_done = 1;
381 }
382
383 struct stasis_app_control_continue_data {
384         char context[AST_MAX_CONTEXT];
385         char extension[AST_MAX_EXTENSION];
386         int priority;
387 };
388
389 static int app_control_continue(struct stasis_app_control *control,
390         struct ast_channel *chan, void *data)
391 {
392         RAII_VAR(struct stasis_app_control_continue_data *, continue_data, data, ast_free);
393
394         ast_assert(control->channel != NULL);
395
396         /* If we're in a Stasis bridge, depart it before going back to the
397          * dialplan */
398         if (stasis_app_get_bridge(control)) {
399                 ast_bridge_depart(control->channel);
400         }
401
402         /* Called from stasis_app_exec thread; no lock needed */
403         ast_explicit_goto(control->channel, continue_data->context, continue_data->extension, continue_data->priority);
404
405         control->is_done = 1;
406
407         return 0;
408 }
409
410 int stasis_app_control_continue(struct stasis_app_control *control, const char *context, const char *extension, int priority)
411 {
412         struct stasis_app_control_continue_data *continue_data;
413
414         if (!(continue_data = ast_calloc(1, sizeof(*continue_data)))) {
415                 return -1;
416         }
417         ast_copy_string(continue_data->context, S_OR(context, ""), sizeof(continue_data->context));
418         ast_copy_string(continue_data->extension, S_OR(extension, ""), sizeof(continue_data->extension));
419         if (priority > 0) {
420                 continue_data->priority = priority;
421         } else {
422                 continue_data->priority = -1;
423         }
424
425         stasis_app_send_command_async(control, app_control_continue, continue_data);
426
427         return 0;
428 }
429
430 struct stasis_app_control_dtmf_data {
431         int before;
432         int between;
433         unsigned int duration;
434         int after;
435         char dtmf[];
436 };
437
438 static int app_control_dtmf(struct stasis_app_control *control,
439         struct ast_channel *chan, void *data)
440 {
441         RAII_VAR(struct stasis_app_control_dtmf_data *, dtmf_data, data, ast_free);
442
443         if (ast_channel_state(chan) != AST_STATE_UP) {
444                 ast_indicate(chan, AST_CONTROL_PROGRESS);
445         }
446
447         if (dtmf_data->before) {
448                 ast_safe_sleep(chan, dtmf_data->before);
449         }
450
451         ast_dtmf_stream(chan, NULL, dtmf_data->dtmf, dtmf_data->between, dtmf_data->duration);
452
453         if (dtmf_data->after) {
454                 ast_safe_sleep(chan, dtmf_data->after);
455         }
456
457         return 0;
458 }
459
460 int stasis_app_control_dtmf(struct stasis_app_control *control, const char *dtmf, int before, int between, unsigned int duration, int after)
461 {
462         struct stasis_app_control_dtmf_data *dtmf_data;
463
464         if (!(dtmf_data = ast_calloc(1, sizeof(*dtmf_data) + strlen(dtmf) + 1))) {
465                 return -1;
466         }
467
468         dtmf_data->before = before;
469         dtmf_data->between = between;
470         dtmf_data->duration = duration;
471         dtmf_data->after = after;
472         strcpy(dtmf_data->dtmf, dtmf);
473
474         stasis_app_send_command_async(control, app_control_dtmf, dtmf_data);
475
476         return 0;
477 }
478
479 static int app_control_ring(struct stasis_app_control *control,
480         struct ast_channel *chan, void *data)
481 {
482         ast_indicate(control->channel, AST_CONTROL_RINGING);
483
484         return 0;
485 }
486
487 int stasis_app_control_ring(struct stasis_app_control *control)
488 {
489         stasis_app_send_command_async(control, app_control_ring, NULL);
490
491         return 0;
492 }
493
494 static int app_control_ring_stop(struct stasis_app_control *control,
495         struct ast_channel *chan, void *data)
496 {
497         ast_indicate(control->channel, -1);
498
499         return 0;
500 }
501
502 int stasis_app_control_ring_stop(struct stasis_app_control *control)
503 {
504         stasis_app_send_command_async(control, app_control_ring_stop, NULL);
505
506         return 0;
507 }
508
509 struct stasis_app_control_mute_data {
510         enum ast_frame_type frametype;
511         unsigned int direction;
512 };
513
514 static int app_control_mute(struct stasis_app_control *control,
515         struct ast_channel *chan, void *data)
516 {
517         RAII_VAR(struct stasis_app_control_mute_data *, mute_data, data, ast_free);
518         SCOPED_CHANNELLOCK(lockvar, chan);
519
520         ast_channel_suppress(control->channel, mute_data->direction, mute_data->frametype);
521
522         return 0;
523 }
524
525 int stasis_app_control_mute(struct stasis_app_control *control, unsigned int direction, enum ast_frame_type frametype)
526 {
527         struct stasis_app_control_mute_data *mute_data;
528
529         if (!(mute_data = ast_calloc(1, sizeof(*mute_data)))) {
530                 return -1;
531         }
532
533         mute_data->direction = direction;
534         mute_data->frametype = frametype;
535
536         stasis_app_send_command_async(control, app_control_mute, mute_data);
537
538         return 0;
539 }
540
541 static int app_control_unmute(struct stasis_app_control *control,
542         struct ast_channel *chan, void *data)
543 {
544         RAII_VAR(struct stasis_app_control_mute_data *, mute_data, data, ast_free);
545         SCOPED_CHANNELLOCK(lockvar, chan);
546
547         ast_channel_unsuppress(control->channel, mute_data->direction, mute_data->frametype);
548
549         return 0;
550 }
551
552 int stasis_app_control_unmute(struct stasis_app_control *control, unsigned int direction, enum ast_frame_type frametype)
553 {
554         struct stasis_app_control_mute_data *mute_data;
555
556         if (!(mute_data = ast_calloc(1, sizeof(*mute_data)))) {
557                 return -1;
558         }
559
560         mute_data->direction = direction;
561         mute_data->frametype = frametype;
562
563         stasis_app_send_command_async(control, app_control_unmute, mute_data);
564
565         return 0;
566 }
567
568 int stasis_app_control_set_channel_var(struct stasis_app_control *control, const char *variable, const char *value)
569 {
570         return pbx_builtin_setvar_helper(control->channel, variable, value);
571 }
572
573 static int app_control_hold(struct stasis_app_control *control,
574         struct ast_channel *chan, void *data)
575 {
576         ast_indicate(control->channel, AST_CONTROL_HOLD);
577
578         return 0;
579 }
580
581 void stasis_app_control_hold(struct stasis_app_control *control)
582 {
583         stasis_app_send_command_async(control, app_control_hold, NULL);
584 }
585
586 static int app_control_unhold(struct stasis_app_control *control,
587         struct ast_channel *chan, void *data)
588 {
589         ast_indicate(control->channel, AST_CONTROL_UNHOLD);
590
591         return 0;
592 }
593
594 void stasis_app_control_unhold(struct stasis_app_control *control)
595 {
596         stasis_app_send_command_async(control, app_control_unhold, NULL);
597 }
598
599 static int app_control_moh_start(struct stasis_app_control *control,
600         struct ast_channel *chan, void *data)
601 {
602         char *moh_class = data;
603
604         if (ast_channel_state(chan) != AST_STATE_UP) {
605                 ast_indicate(chan, AST_CONTROL_PROGRESS);
606         }
607
608         ast_moh_start(chan, moh_class, NULL);
609
610         ast_free(moh_class);
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);
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);
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);
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);
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                                          app_command_can_exec_cb can_exec_fn)
712 {
713         RAII_VAR(struct stasis_app_command *, command, NULL, ao2_cleanup);
714
715         if (control == NULL) {
716                 return -1;
717         }
718
719         command = exec_command_on_condition(
720                 control, command_fn, data, can_exec_fn);
721         if (!command) {
722                 return -1;
723         }
724
725         return command_join(command);
726 }
727
728 int stasis_app_send_command(struct stasis_app_control *control,
729         stasis_app_command_cb command_fn, void *data)
730 {
731         return app_send_command_on_condition(control, command_fn, data, NULL);
732 }
733
734 int stasis_app_send_command_async(struct stasis_app_control *control,
735         stasis_app_command_cb command_fn, void *data)
736 {
737         RAII_VAR(struct stasis_app_command *, command, NULL, ao2_cleanup);
738
739         if (control == NULL) {
740                 return -1;
741         }
742
743         command = exec_command(control, command_fn, data);
744         if (!command) {
745                 return -1;
746         }
747
748         return 0;
749 }
750
751 struct ast_bridge *stasis_app_get_bridge(struct stasis_app_control *control)
752 {
753         if (!control) {
754                 return NULL;
755         } else {
756                 SCOPED_AO2LOCK(lock, control);
757                 return control->bridge;
758         }
759 }
760
761 static int bridge_channel_depart(struct stasis_app_control *control,
762         struct ast_channel *chan, void *data)
763 {
764         RAII_VAR(struct ast_bridge_channel *, bridge_channel, data, ao2_cleanup);
765
766         {
767                 SCOPED_CHANNELLOCK(lock, chan);
768
769                 if (bridge_channel != ast_channel_internal_bridge_channel(chan)) {
770                         ast_debug(3, "%s: Channel is no longer in departable state\n",
771                                 ast_channel_uniqueid(chan));
772                         return -1;
773                 }
774         }
775
776         ast_debug(3, "%s: Channel departing bridge\n",
777                 ast_channel_uniqueid(chan));
778
779         ast_bridge_depart(chan);
780
781         return 0;
782 }
783
784 static void bridge_after_cb(struct ast_channel *chan, void *data)
785 {
786         struct stasis_app_control *control = data;
787         SCOPED_AO2LOCK(lock, control);
788         struct ast_bridge_channel *bridge_channel;
789
790         ast_debug(3, "%s, %s: Channel leaving bridge\n",
791                 ast_channel_uniqueid(chan), control->bridge->uniqueid);
792
793         ast_assert(chan == control->channel);
794
795         /* Restore the channel's PBX */
796         ast_channel_pbx_set(control->channel, control->pbx);
797         control->pbx = NULL;
798
799         app_unsubscribe_bridge(control->app, control->bridge);
800
801         /* No longer in the bridge */
802         control->bridge = NULL;
803
804         /* Get the bridge channel so we don't depart from the wrong bridge */
805         ast_channel_lock(chan);
806         bridge_channel = ast_channel_get_bridge_channel(chan);
807         ast_channel_unlock(chan);
808
809         /* Depart this channel from the bridge using the command queue if possible */
810         if (stasis_app_send_command_async(control, bridge_channel_depart, bridge_channel)) {
811                 ao2_cleanup(bridge_channel);
812         }
813 }
814
815 static void bridge_after_cb_failed(enum ast_bridge_after_cb_reason reason,
816         void *data)
817 {
818         struct stasis_app_control *control = data;
819
820         bridge_after_cb(control->channel, data);
821
822         ast_debug(3, "  reason: %s\n",
823                 ast_bridge_after_cb_reason_string(reason));
824 }
825
826 int control_add_channel_to_bridge(
827         struct stasis_app_control *control,
828         struct ast_channel *chan, void *data)
829 {
830         struct ast_bridge *bridge = data;
831         int res;
832
833         if (!control || !bridge) {
834                 return -1;
835         }
836
837         ast_debug(3, "%s: Adding to bridge %s\n",
838                 stasis_app_control_get_channel_id(control),
839                 bridge->uniqueid);
840
841         ast_assert(chan != NULL);
842
843         /* Depart whatever Stasis bridge we're currently in. */
844         if (stasis_app_get_bridge(control)) {
845                 /* Note that it looks like there's a race condition here, since
846                  * we don't have control locked. But this happens from the
847                  * control callback thread, so there won't be any other
848                  * concurrent attempts to bridge.
849                  */
850                 ast_bridge_depart(chan);
851         }
852
853
854         res = ast_bridge_set_after_callback(chan, bridge_after_cb,
855                 bridge_after_cb_failed, control);
856         if (res != 0) {
857                 ast_log(LOG_ERROR, "Error setting after-bridge callback\n");
858                 return -1;
859         }
860
861         {
862                 /* pbx and bridge are modified by the bridging impart thread.
863                  * It shouldn't happen concurrently, but we still need to lock
864                  * for the memory fence.
865                  */
866                 SCOPED_AO2LOCK(lock, control);
867
868                 /* Ensure the controlling application is subscribed early enough
869                  * to receive the ChannelEnteredBridge message. This works in concert
870                  * with the subscription handled in the Stasis application execution
871                  * loop */
872                 app_subscribe_bridge(control->app, bridge);
873
874                 /* Save off the channel's PBX */
875                 ast_assert(control->pbx == NULL);
876                 if (!control->pbx) {
877                         control->pbx = ast_channel_pbx(chan);
878                         ast_channel_pbx_set(chan, NULL);
879                 }
880
881                 res = ast_bridge_impart(bridge,
882                         chan,
883                         NULL, /* swap channel */
884                         NULL, /* features */
885                         AST_BRIDGE_IMPART_CHAN_DEPARTABLE);
886                 if (res != 0) {
887                         ast_log(LOG_ERROR, "Error adding channel to bridge\n");
888                         ast_channel_pbx_set(chan, control->pbx);
889                         control->pbx = NULL;
890                         return -1;
891                 }
892
893                 ast_assert(stasis_app_get_bridge(control) == NULL);
894                 control->bridge = bridge;
895         }
896         return 0;
897 }
898
899 int stasis_app_control_add_channel_to_bridge(
900         struct stasis_app_control *control, struct ast_bridge *bridge)
901 {
902         ast_debug(3, "%s: Sending channel add_to_bridge command\n",
903                         stasis_app_control_get_channel_id(control));
904
905         return app_send_command_on_condition(
906                 control, control_add_channel_to_bridge, bridge,
907                 app_control_can_add_channel_to_bridge);
908 }
909
910 static int app_control_remove_channel_from_bridge(
911         struct stasis_app_control *control,
912         struct ast_channel *chan, void *data)
913 {
914         struct ast_bridge *bridge = data;
915
916         if (!control) {
917                 return -1;
918         }
919
920         /* We should only depart from our own bridge */
921         ast_debug(3, "%s: Departing bridge %s\n",
922                 stasis_app_control_get_channel_id(control),
923                 bridge->uniqueid);
924
925         if (bridge != stasis_app_get_bridge(control)) {
926                 ast_log(LOG_WARNING, "%s: Not in bridge %s; not removing\n",
927                         stasis_app_control_get_channel_id(control),
928                         bridge->uniqueid);
929                 return -1;
930         }
931
932         ast_bridge_depart(chan);
933         return 0;
934 }
935
936 int stasis_app_control_remove_channel_from_bridge(
937         struct stasis_app_control *control, struct ast_bridge *bridge)
938 {
939         ast_debug(3, "%s: Sending channel remove_from_bridge command\n",
940                         stasis_app_control_get_channel_id(control));
941         return app_send_command_on_condition(
942                 control, app_control_remove_channel_from_bridge, bridge,
943                 app_control_can_remove_channel_from_bridge);
944 }
945
946 const char *stasis_app_control_get_channel_id(
947         const struct stasis_app_control *control)
948 {
949         return ast_channel_uniqueid(control->channel);
950 }
951
952 void stasis_app_control_publish(
953         struct stasis_app_control *control, struct stasis_message *message)
954 {
955         if (!control || !control->channel || !message) {
956                 return;
957         }
958         stasis_publish(ast_channel_topic(control->channel), message);
959 }
960
961 int stasis_app_control_queue_control(struct stasis_app_control *control,
962         enum ast_control_frame_type frame_type)
963 {
964         return ast_queue_control(control->channel, frame_type);
965 }
966
967 int control_dispatch_all(struct stasis_app_control *control,
968         struct ast_channel *chan)
969 {
970         int count = 0;
971         struct ao2_iterator i;
972         void *obj;
973
974         ast_assert(control->channel == chan);
975
976         i = ao2_iterator_init(control->command_queue, AO2_ITERATOR_UNLINK);
977
978         while ((obj = ao2_iterator_next(&i))) {
979                 RAII_VAR(struct stasis_app_command *, command, obj, ao2_cleanup);
980                 command_invoke(command, control, chan);
981                 ++count;
982         }
983
984         ao2_iterator_destroy(&i);
985         return count;
986 }
987
988 void control_wait(struct stasis_app_control *control)
989 {
990         if (!control) {
991                 return;
992         }
993
994         ast_assert(control->command_queue != NULL);
995
996         ao2_lock(control->command_queue);
997         while (ao2_container_count(control->command_queue) == 0) {
998                 int res = ast_cond_wait(&control->wait_cond,
999                         ao2_object_get_lockaddr(control->command_queue));
1000                 if (res < 0) {
1001                         ast_log(LOG_ERROR, "Error waiting on command queue\n");
1002                         break;
1003                 }
1004         }
1005         ao2_unlock(control->command_queue);
1006 }
1007
1008 int control_prestart_dispatch_all(struct stasis_app_control *control,
1009         struct ast_channel *chan)
1010 {
1011         struct ao2_container *command_queue;
1012         int count = 0;
1013         struct ao2_iterator iter;
1014         struct stasis_app_command *command;
1015
1016         ast_channel_lock(chan);
1017         command_queue = command_prestart_get_container(chan);
1018         ast_channel_unlock(chan);
1019         if (!command_queue) {
1020                 return 0;
1021         }
1022
1023         iter = ao2_iterator_init(command_queue, AO2_ITERATOR_UNLINK);
1024
1025         while ((command = ao2_iterator_next(&iter))) {
1026                 command_invoke(command, control, chan);
1027                 ao2_cleanup(command);
1028                 ++count;
1029         }
1030
1031         ao2_iterator_destroy(&iter);
1032         ao2_cleanup(command_queue);
1033         return count;
1034 }
1035
1036 struct stasis_app *control_app(struct stasis_app_control *control)
1037 {
1038         return control->app;
1039 }