Bridge API: Set a cause code on a channel when it is ejected from a bridge.
[asterisk/asterisk.git] / main / bridge_channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2009, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Bridging Channel API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  * \author Richard Mudgett <rmudgett@digium.com>
25  * \author Matt Jordan <mjordan@digium.com>
26  *
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <signal.h>
38
39 #include "asterisk/heap.h"
40 #include "asterisk/astobj2.h"
41 #include "asterisk/stringfields.h"
42 #include "asterisk/app.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/timing.h"
46 #include "asterisk/bridge.h"
47 #include "asterisk/bridge_channel.h"
48 #include "asterisk/bridge_after.h"
49 #include "asterisk/bridge_channel_internal.h"
50 #include "asterisk/bridge_internal.h"
51 #include "asterisk/stasis_bridges.h"
52 #include "asterisk/stasis_channels.h"
53 #include "asterisk/musiconhold.h"
54 #include "asterisk/features_config.h"
55 #include "asterisk/parking.h"
56 #include "asterisk/causes.h"
57
58 /*!
59  * \brief Used to queue an action frame onto a bridge channel and write an action frame into a bridge.
60  * \since 12.0.0
61  *
62  * \param bridge_channel Which channel work with.
63  * \param action Type of bridge action frame.
64  * \param data Frame payload data to pass.
65  * \param datalen Frame payload data length to pass.
66  *
67  * \retval 0 on success.
68  * \retval -1 on error.
69  */
70 typedef int (*ast_bridge_channel_post_action_data)(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen);
71
72 void ast_bridge_channel_lock_bridge(struct ast_bridge_channel *bridge_channel)
73 {
74         struct ast_bridge *bridge;
75
76         for (;;) {
77                 /* Safely get the bridge pointer */
78                 ast_bridge_channel_lock(bridge_channel);
79                 bridge = bridge_channel->bridge;
80                 ao2_ref(bridge, +1);
81                 ast_bridge_channel_unlock(bridge_channel);
82
83                 /* Lock the bridge and see if it is still the bridge we need to lock. */
84                 ast_bridge_lock(bridge);
85                 if (bridge == bridge_channel->bridge) {
86                         ao2_ref(bridge, -1);
87                         return;
88                 }
89                 ast_bridge_unlock(bridge);
90                 ao2_ref(bridge, -1);
91         }
92 }
93
94 int ast_bridge_channel_notify_talking(struct ast_bridge_channel *bridge_channel, int started_talking)
95 {
96         struct ast_frame action = {
97                 .frametype = AST_FRAME_BRIDGE_ACTION,
98                 .subclass.integer = started_talking
99                         ? BRIDGE_CHANNEL_ACTION_TALKING_START : BRIDGE_CHANNEL_ACTION_TALKING_STOP,
100         };
101
102         return ast_bridge_channel_queue_frame(bridge_channel, &action);
103 }
104
105 /*!
106  * \internal
107  * \brief Poke the bridge_channel thread
108  */
109 static void bridge_channel_poke(struct ast_bridge_channel *bridge_channel)
110 {
111         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
112                 while (bridge_channel->waiting) {
113                         pthread_kill(bridge_channel->thread, SIGURG);
114                         sched_yield();
115                 }
116         }
117 }
118
119 /*!
120  * \internal
121  * \brief Set actual cause on channel.
122  * \since 12.0.0
123  *
124  * \param chan Channel to set cause.
125  * \param cause Cause to set on channel.
126  *   If cause <= 0 then use cause on channel if cause still <= 0 use AST_CAUSE_NORMAL_CLEARING.
127  *
128  * \return Actual cause set on channel.
129  */
130 static int channel_set_cause(struct ast_channel *chan, int cause)
131 {
132         ast_channel_lock(chan);
133         if (cause <= 0) {
134                 cause = ast_channel_hangupcause(chan);
135                 if (cause <= 0) {
136                         cause = AST_CAUSE_NORMAL_CLEARING;
137                 }
138         }
139         ast_channel_hangupcause_set(chan, cause);
140         ast_channel_unlock(chan);
141         return cause;
142 }
143
144 void ast_bridge_channel_leave_bridge_nolock(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
145 {
146         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
147                 return;
148         }
149
150         ast_debug(1, "Setting %p(%s) state from:%d to:%d\n",
151                 bridge_channel, ast_channel_name(bridge_channel->chan), bridge_channel->state,
152                 new_state);
153
154         channel_set_cause(bridge_channel->chan, cause);
155
156         /* Change the state on the bridge channel */
157         bridge_channel->state = new_state;
158
159         bridge_channel_poke(bridge_channel);
160 }
161
162 void ast_bridge_channel_leave_bridge(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
163 {
164         ast_bridge_channel_lock(bridge_channel);
165         ast_bridge_channel_leave_bridge_nolock(bridge_channel, new_state, cause);
166         ast_bridge_channel_unlock(bridge_channel);
167 }
168
169 struct ast_bridge_channel *ast_bridge_channel_peer(struct ast_bridge_channel *bridge_channel)
170 {
171         struct ast_bridge *bridge = bridge_channel->bridge;
172         struct ast_bridge_channel *other = NULL;
173
174         if (bridge_channel->in_bridge && bridge->num_channels == 2) {
175                 AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
176                         if (other != bridge_channel) {
177                                 break;
178                         }
179                 }
180         }
181
182         return other;
183 }
184
185 void ast_bridge_channel_restore_formats(struct ast_bridge_channel *bridge_channel)
186 {
187         /* Restore original formats of the channel as they came in */
188         if (ast_format_cmp(ast_channel_readformat(bridge_channel->chan), &bridge_channel->read_format) == AST_FORMAT_CMP_NOT_EQUAL) {
189                 ast_debug(1, "Bridge is returning %p(%s) to read format %s\n",
190                         bridge_channel, ast_channel_name(bridge_channel->chan),
191                         ast_getformatname(&bridge_channel->read_format));
192                 if (ast_set_read_format(bridge_channel->chan, &bridge_channel->read_format)) {
193                         ast_debug(1, "Bridge failed to return %p(%s) to read format %s\n",
194                                 bridge_channel, ast_channel_name(bridge_channel->chan),
195                                 ast_getformatname(&bridge_channel->read_format));
196                 }
197         }
198         if (ast_format_cmp(ast_channel_writeformat(bridge_channel->chan), &bridge_channel->write_format) == AST_FORMAT_CMP_NOT_EQUAL) {
199                 ast_debug(1, "Bridge is returning %p(%s) to write format %s\n",
200                         bridge_channel, ast_channel_name(bridge_channel->chan),
201                         ast_getformatname(&bridge_channel->write_format));
202                 if (ast_set_write_format(bridge_channel->chan, &bridge_channel->write_format)) {
203                         ast_debug(1, "Bridge failed to return %p(%s) to write format %s\n",
204                                 bridge_channel, ast_channel_name(bridge_channel->chan),
205                                 ast_getformatname(&bridge_channel->write_format));
206                 }
207         }
208 }
209
210 struct ast_bridge *ast_bridge_channel_merge_inhibit(struct ast_bridge_channel *bridge_channel, int request)
211 {
212         struct ast_bridge *bridge;
213
214         ast_bridge_channel_lock_bridge(bridge_channel);
215         bridge = bridge_channel->bridge;
216         ao2_ref(bridge, +1);
217         bridge_merge_inhibit_nolock(bridge, request);
218         ast_bridge_unlock(bridge);
219         return bridge;
220 }
221
222 void ast_bridge_channel_update_linkedids(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
223 {
224         struct ast_bridge_channel *other = NULL;
225         struct ast_bridge *bridge = bridge_channel->bridge;
226         const char *oldest_linkedid = ast_channel_linkedid(bridge_channel->chan);
227
228         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
229                 if (other == swap) {
230                         continue;
231                 }
232                 oldest_linkedid = ast_channel_oldest_linkedid(oldest_linkedid, ast_channel_linkedid(other->chan));
233         }
234
235         if (ast_strlen_zero(oldest_linkedid)) {
236                 return;
237         }
238
239         ast_channel_linkedid_set(bridge_channel->chan, oldest_linkedid);
240         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
241                 if (other == swap) {
242                         continue;
243                 }
244                 ast_channel_linkedid_set(other->chan, oldest_linkedid);
245         }
246 }
247
248 void ast_bridge_channel_update_accountcodes(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
249 {
250         struct ast_bridge *bridge = bridge_channel->bridge;
251         struct ast_bridge_channel *other = NULL;
252
253         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
254                 if (other == swap) {
255                         continue;
256                 }
257
258                 if (!ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan)) && ast_strlen_zero(ast_channel_peeraccount(other->chan))) {
259                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
260                                         ast_channel_accountcode(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
261                         ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
262                 }
263                 if (!ast_strlen_zero(ast_channel_accountcode(other->chan)) && ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan))) {
264                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
265                                         ast_channel_accountcode(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
266                         ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
267                 }
268                 if (!ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan)) && ast_strlen_zero(ast_channel_accountcode(other->chan))) {
269                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
270                                         ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
271                         ast_channel_accountcode_set(other->chan, ast_channel_peeraccount(bridge_channel->chan));
272                 }
273                 if (!ast_strlen_zero(ast_channel_peeraccount(other->chan)) && ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan))) {
274                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
275                                         ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
276                         ast_channel_accountcode_set(bridge_channel->chan, ast_channel_peeraccount(other->chan));
277                 }
278                 if (bridge->num_channels == 2) {
279                         if (strcmp(ast_channel_accountcode(bridge_channel->chan), ast_channel_peeraccount(other->chan))) {
280                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
281                                                 ast_channel_peeraccount(other->chan), ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
282                                 ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
283                         }
284                         if (strcmp(ast_channel_accountcode(other->chan), ast_channel_peeraccount(bridge_channel->chan))) {
285                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
286                                                 ast_channel_peeraccount(bridge_channel->chan), ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
287                                 ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
288                         }
289                 }
290         }
291 }
292
293 void ast_bridge_channel_kick(struct ast_bridge_channel *bridge_channel, int cause)
294 {
295         struct ast_bridge_features *features = bridge_channel->features;
296         struct ast_bridge_hook *hook;
297         struct ao2_iterator iter;
298
299         ast_bridge_channel_lock(bridge_channel);
300         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
301                 channel_set_cause(bridge_channel->chan, cause);
302                 cause = 0;
303         }
304         ast_bridge_channel_unlock(bridge_channel);
305
306         /* Run any hangup hooks. */
307         iter = ao2_iterator_init(features->other_hooks, 0);
308         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
309                 int remove_me;
310
311                 if (hook->type != AST_BRIDGE_HOOK_TYPE_HANGUP) {
312                         continue;
313                 }
314                 remove_me = hook->callback(bridge_channel, hook->hook_pvt);
315                 if (remove_me) {
316                         ast_debug(1, "Hangup hook %p is being removed from %p(%s)\n",
317                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
318                         ao2_unlink(features->other_hooks, hook);
319                 }
320         }
321         ao2_iterator_destroy(&iter);
322
323         /* Default hangup action. */
324         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END, cause);
325 }
326
327 /*!
328  * \internal
329  * \brief Write an \ref ast_frame onto the bridge channel
330  * \since 12.0.0
331  *
332  * \param bridge_channel Which channel to queue the frame onto.
333  * \param frame The frame to write onto the bridge_channel
334  *
335  * \retval 0 on success.
336  * \retval -1 on error.
337  */
338 static int bridge_channel_write_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
339 {
340         ast_bridge_channel_lock_bridge(bridge_channel);
341 /*
342  * XXX need to implement a deferred write queue for when there
343  * is no peer channel in the bridge (yet or it was kicked).
344  *
345  * The tech decides if a frame needs to be pushed back for deferral.
346  * simple_bridge/native_bridge are likely the only techs that will do this.
347  */
348         bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
349         ast_bridge_unlock(bridge_channel->bridge);
350
351         /*
352          * Claim successful write to bridge.  If deferred frame
353          * support is added, claim successfully deferred.
354          */
355         return 0;
356 }
357
358 /*!
359  * \internal
360  * \brief Suspend a channel from a bridge.
361  *
362  * \param bridge_channel Channel to suspend.
363  *
364  * \note This function assumes bridge_channel->bridge is locked.
365  *
366  * \return Nothing
367  */
368 void bridge_channel_internal_suspend_nolock(struct ast_bridge_channel *bridge_channel)
369 {
370         bridge_channel->suspended = 1;
371         if (bridge_channel->in_bridge) {
372                 --bridge_channel->bridge->num_active;
373         }
374
375         /* Get technology bridge threads off of the channel. */
376         if (bridge_channel->bridge->technology->suspend) {
377                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
378         }
379 }
380
381 /*!
382  * \internal
383  * \brief Suspend a channel from a bridge.
384  *
385  * \param bridge_channel Channel to suspend.
386  *
387  * \return Nothing
388  */
389 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
390 {
391         ast_bridge_channel_lock_bridge(bridge_channel);
392         bridge_channel_internal_suspend_nolock(bridge_channel);
393         ast_bridge_unlock(bridge_channel->bridge);
394 }
395
396 /*!
397  * \internal
398  * \brief Unsuspend a channel from a bridge.
399  *
400  * \param bridge_channel Channel to unsuspend.
401  *
402  * \note This function assumes bridge_channel->bridge is locked.
403  *
404  * \return Nothing
405  */
406 void bridge_channel_internal_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
407 {
408         bridge_channel->suspended = 0;
409         if (bridge_channel->in_bridge) {
410                 ++bridge_channel->bridge->num_active;
411         }
412
413         /* Wake technology bridge threads to take care of channel again. */
414         if (bridge_channel->bridge->technology->unsuspend) {
415                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
416         }
417
418         /* Wake suspended channel. */
419         ast_bridge_channel_lock(bridge_channel);
420         ast_cond_signal(&bridge_channel->cond);
421         ast_bridge_channel_unlock(bridge_channel);
422 }
423
424 /*!
425  * \internal
426  * \brief Unsuspend a channel from a bridge.
427  *
428  * \param bridge_channel Channel to unsuspend.
429  *
430  * \return Nothing
431  */
432 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
433 {
434         ast_bridge_channel_lock_bridge(bridge_channel);
435         bridge_channel_internal_unsuspend_nolock(bridge_channel);
436         ast_bridge_unlock(bridge_channel->bridge);
437 }
438
439 /*!
440  * \internal
441  * \brief Queue an action frame onto the bridge channel with data.
442  * \since 12.0.0
443  *
444  * \param bridge_channel Which channel to queue the frame onto.
445  * \param action Type of bridge action frame.
446  * \param data Frame payload data to pass.
447  * \param datalen Frame payload data length to pass.
448  *
449  * \retval 0 on success.
450  * \retval -1 on error.
451  */
452 static int bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen)
453 {
454         struct ast_frame frame = {
455                 .frametype = AST_FRAME_BRIDGE_ACTION,
456                 .subclass.integer = action,
457                 .datalen = datalen,
458                 .data.ptr = (void *) data,
459         };
460
461         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
462 }
463
464 /*!
465  * \internal
466  * \brief Write an action frame onto the bridge channel with data.
467  * \since 12.0.0
468  *
469  * \param bridge_channel Which channel to queue the frame onto.
470  * \param action Type of bridge action frame.
471  * \param data Frame payload data to pass.
472  * \param datalen Frame payload data length to pass.
473  *
474  * \retval 0 on success.
475  * \retval -1 on error.
476  */
477 static int bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen)
478 {
479         struct ast_frame frame = {
480                 .frametype = AST_FRAME_BRIDGE_ACTION,
481                 .subclass.integer = action,
482                 .datalen = datalen,
483                 .data.ptr = (void *) data,
484         };
485
486         return bridge_channel_write_frame(bridge_channel, &frame);
487 }
488
489 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
490 {
491         struct ast_frame *dup;
492         char nudge = 0;
493
494         if (bridge_channel->suspended
495                 /* Also defer DTMF frames. */
496                 && fr->frametype != AST_FRAME_DTMF_BEGIN
497                 && fr->frametype != AST_FRAME_DTMF_END
498                 && !ast_is_deferrable_frame(fr)) {
499                 /* Drop non-deferable frames when suspended. */
500                 return 0;
501         }
502         if (fr->frametype == AST_FRAME_NULL) {
503                 /* "Accept" the frame and discard it. */
504                 return 0;
505         }
506
507         dup = ast_frdup(fr);
508         if (!dup) {
509                 return -1;
510         }
511
512         ast_bridge_channel_lock(bridge_channel);
513         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
514                 /* Drop frames on channels leaving the bridge. */
515                 ast_bridge_channel_unlock(bridge_channel);
516                 ast_frfree(dup);
517                 return 0;
518         }
519
520         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
521         if (write(bridge_channel->alert_pipe[1], &nudge, sizeof(nudge)) != sizeof(nudge)) {
522                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
523                         bridge_channel, ast_channel_name(bridge_channel->chan));
524         }
525         ast_bridge_channel_unlock(bridge_channel);
526         return 0;
527 }
528
529 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
530 {
531         struct ast_bridge_channel *cur;
532         int not_written = -1;
533
534         if (frame->frametype == AST_FRAME_NULL) {
535                 /* "Accept" the frame and discard it. */
536                 return 0;
537         }
538
539         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
540                 if (cur == bridge_channel) {
541                         continue;
542                 }
543                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
544                         not_written = 0;
545                 }
546         }
547         return not_written;
548 }
549
550 int ast_bridge_channel_queue_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
551 {
552         struct ast_frame frame = {
553                 .frametype = AST_FRAME_CONTROL,
554                 .subclass.integer = control,
555                 .datalen = datalen,
556                 .data.ptr = (void *) data,
557         };
558
559         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
560 }
561
562 int ast_bridge_channel_write_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
563 {
564         struct ast_frame frame = {
565                 .frametype = AST_FRAME_CONTROL,
566                 .subclass.integer = control,
567                 .datalen = datalen,
568                 .data.ptr = (void *) data,
569         };
570
571         return bridge_channel_write_frame(bridge_channel, &frame);
572 }
573
574 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
575 {
576         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
577         size_t datalen;
578
579         if (!ast_strlen_zero(moh_class)) {
580                 datalen = strlen(moh_class) + 1;
581
582                 blob = ast_json_pack("{s: s}",
583                         "musicclass", moh_class);
584         } else {
585                 moh_class = NULL;
586                 datalen = 0;
587         }
588
589         ast_channel_publish_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
590         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
591                 moh_class, datalen);
592 }
593
594 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
595 {
596         ast_channel_publish_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
597         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
598 }
599
600 /*!
601  * \internal
602  * \brief Helper function to kick off a PBX app on a bridge_channel
603  */
604 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
605 {
606         int res = 0;
607
608         if (!strcasecmp("Gosub", app_name)) {
609                 ast_app_exec_sub(NULL, chan, app_args, 0);
610         } else if (!strcasecmp("Macro", app_name)) {
611                 ast_app_exec_macro(NULL, chan, app_args);
612         } else {
613                 struct ast_app *app;
614
615                 app = pbx_findapp(app_name);
616                 if (!app) {
617                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
618                 } else {
619                         res = pbx_exec(chan, app, app_args);
620                 }
621         }
622         return res;
623 }
624
625 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
626 {
627         if (moh_class) {
628                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
629         }
630         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
631                 /* Break the bridge if the app returns non-zero. */
632                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
633         }
634         if (moh_class) {
635                 ast_bridge_channel_write_unhold(bridge_channel);
636         }
637 }
638
639 struct bridge_run_app {
640         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
641         int moh_offset;
642         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
643         int app_args_offset;
644         /*! Application name to run. */
645         char app_name[0];
646 };
647
648 /*!
649  * \internal
650  * \brief Handle the run application bridge action.
651  * \since 12.0.0
652  *
653  * \param bridge_channel Which channel to run the application on.
654  * \param data Action frame data to run the application.
655  *
656  * \return Nothing
657  */
658 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
659 {
660         ast_bridge_channel_run_app(bridge_channel, data->app_name,
661                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
662                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
663 }
664
665 /*!
666  * \internal
667  * \brief Marshal an application to be executed on a bridge_channel
668  */
669 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
670         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
671 {
672         struct bridge_run_app *app_data;
673         size_t len_name = strlen(app_name) + 1;
674         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
675         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
676         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
677
678         /* Fill in application run frame data. */
679         app_data = alloca(len_data);
680         app_data->app_args_offset = len_args ? len_name : 0;
681         app_data->moh_offset = len_moh ? len_name + len_args : 0;
682         strcpy(app_data->app_name, app_name);/* Safe */
683         if (len_args) {
684                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
685         }
686         if (moh_class) {
687                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
688         }
689
690         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
691 }
692
693 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
694 {
695         return payload_helper_app(bridge_channel_write_action_data,
696                 bridge_channel, app_name, app_args, moh_class);
697 }
698
699 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
700 {
701         return payload_helper_app(bridge_channel_queue_action_data,
702                 bridge_channel, app_name, app_args, moh_class);
703 }
704
705 void ast_bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
706 {
707         if (moh_class) {
708                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
709         }
710         if (custom_play) {
711                 custom_play(bridge_channel, playfile);
712         } else {
713                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
714         }
715         if (moh_class) {
716                 ast_bridge_channel_write_unhold(bridge_channel);
717         }
718
719         /*
720          * It may be necessary to resume music on hold after we finish
721          * playing the announcment.
722          *
723          * XXX We have no idea what MOH class was in use before playing
724          * the file. This method also fails to restore ringing indications.
725          * the proposed solution is to create a resume_entertainment callback
726          * for the bridge technology and execute it here.
727          */
728         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
729                 ast_moh_start(bridge_channel->chan, NULL, NULL);
730         }
731 }
732
733 struct bridge_playfile {
734         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
735         ast_bridge_custom_play_fn custom_play;
736         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
737         int moh_offset;
738         /*! Filename to play. */
739         char playfile[0];
740 };
741
742 /*!
743  * \internal
744  * \brief Handle the playfile bridge action.
745  * \since 12.0.0
746  *
747  * \param bridge_channel Which channel to play a file on.
748  * \param payload Action frame payload to play a file.
749  *
750  * \return Nothing
751  */
752 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
753 {
754         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
755                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
756 }
757
758 /*!
759  * \internal
760  * \brief Marshal a file to be played on a bridge_channel
761  */
762 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
763         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
764 {
765         struct bridge_playfile *payload;
766         size_t len_name = strlen(playfile) + 1;
767         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
768         size_t len_payload = sizeof(*payload) + len_name + len_moh;
769
770         /* Fill in play file frame data. */
771         payload = alloca(len_payload);
772         payload->custom_play = custom_play;
773         payload->moh_offset = len_moh ? len_name : 0;
774         strcpy(payload->playfile, playfile);/* Safe */
775         if (moh_class) {
776                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
777         }
778
779         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
780 }
781
782 int ast_bridge_channel_write_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
783 {
784         return payload_helper_playfile(bridge_channel_write_action_data,
785                 bridge_channel, custom_play, playfile, moh_class);
786 }
787
788 int ast_bridge_channel_queue_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
789 {
790         return payload_helper_playfile(bridge_channel_queue_action_data,
791                 bridge_channel, custom_play, playfile, moh_class);
792 }
793
794 struct bridge_custom_callback {
795         /*! Call this function on the bridge channel thread. */
796         ast_bridge_custom_callback_fn callback;
797         /*! Size of the payload if it exists.  A number otherwise. */
798         size_t payload_size;
799         /*! Option flags determining how callback is called. */
800         unsigned int flags;
801         /*! Nonzero if the payload exists. */
802         char payload_exists;
803         /*! Payload to give to callback. */
804         char payload[0];
805 };
806
807 /*!
808  * \internal
809  * \brief Handle the do custom callback bridge action.
810  * \since 12.0.0
811  *
812  * \param bridge_channel Which channel to call the callback on.
813  * \param data Action frame data to call the callback.
814  *
815  * \return Nothing
816  */
817 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
818 {
819         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
820                 bridge_channel_suspend(bridge_channel);
821                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
822         }
823         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
824         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
825                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
826                 bridge_channel_unsuspend(bridge_channel);
827         }
828 }
829
830 /*!
831  * \internal
832  * \brief Marshal a custom callback function to be called on a bridge_channel
833  */
834 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
835         struct ast_bridge_channel *bridge_channel,
836         enum ast_bridge_channel_custom_callback_option flags,
837         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
838 {
839         struct bridge_custom_callback *cb_data;
840         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
841
842         /* Sanity check. */
843         if (!callback) {
844                 ast_assert(0);
845                 return -1;
846         }
847
848         /* Fill in custom callback frame data. */
849         cb_data = alloca(len_data);
850         cb_data->callback = callback;
851         cb_data->payload_size = payload_size;
852         cb_data->flags = flags;
853         cb_data->payload_exists = payload && payload_size;
854         if (cb_data->payload_exists) {
855                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
856         }
857
858         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
859 }
860
861 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
862         enum ast_bridge_channel_custom_callback_option flags,
863         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
864 {
865         return payload_helper_cb(bridge_channel_write_action_data,
866                 bridge_channel, flags, callback, payload, payload_size);
867 }
868
869 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
870         enum ast_bridge_channel_custom_callback_option flags,
871         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
872 {
873         return payload_helper_cb(bridge_channel_queue_action_data,
874                 bridge_channel, flags, callback, payload, payload_size);
875 }
876
877 struct bridge_park {
878         int parker_uuid_offset;
879         int app_data_offset;
880         /* buffer used for holding those strings */
881         char parkee_uuid[0];
882 };
883
884 /*!
885  * \internal
886  * \brief Park a bridge_cahnnel
887  */
888 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
889 {
890         if (!ast_parking_provider_registered()) {
891                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
892                         ast_channel_name(bridge_channel->chan));
893                 return;
894         }
895
896         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
897                 &payload->parkee_uuid[payload->parker_uuid_offset],
898                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
899                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
900                         ast_channel_name(bridge_channel->chan));
901         }
902 }
903
904 /*!
905  * \internal
906  * \brief Marshal a park action onto a bridge_channel
907  */
908 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
909         struct ast_bridge_channel *bridge_channel,
910         const char *parkee_uuid,
911         const char *parker_uuid,
912         const char *app_data)
913 {
914         struct bridge_park *payload;
915         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
916         size_t len_parker_uuid = strlen(parker_uuid) + 1;
917         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
918         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
919
920         payload = alloca(len_payload);
921         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
922         payload->parker_uuid_offset = len_parkee_uuid;
923         strcpy(payload->parkee_uuid, parkee_uuid);
924         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
925         if (app_data) {
926                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
927         }
928
929         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
930 }
931
932 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
933 {
934         return payload_helper_park(bridge_channel_write_action_data,
935                 bridge_channel, parkee_uuid, parker_uuid, app_data);
936 }
937
938 /*!
939  * \internal
940  * \brief Handle bridge channel interval expiration.
941  * \since 12.0.0
942  *
943  * \param bridge_channel Channel to run expired intervals on.
944  *
945  * \return Nothing
946  */
947 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
948 {
949         struct ast_heap *interval_hooks;
950         struct ast_bridge_hook_timer *hook;
951         struct timeval start;
952         int chan_suspended = 0;
953
954         interval_hooks = bridge_channel->features->interval_hooks;
955         ast_heap_wrlock(interval_hooks);
956         start = ast_tvnow();
957         while ((hook = ast_heap_peek(interval_hooks, 1))) {
958                 int interval;
959                 unsigned int execution_time;
960
961                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
962                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
963                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
964                         break;
965                 }
966                 ao2_ref(hook, +1);
967                 ast_heap_unlock(interval_hooks);
968
969                 if (!chan_suspended
970                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
971                         chan_suspended = 1;
972                         bridge_channel_suspend(bridge_channel);
973                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
974                 }
975
976                 ast_debug(1, "Executing hook %p on %p(%s)\n",
977                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
978                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
979
980                 ast_heap_wrlock(interval_hooks);
981                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
982                         || !ast_heap_remove(interval_hooks, hook)) {
983                         /* Interval hook is already removed from the bridge_channel. */
984                         ao2_ref(hook, -1);
985                         continue;
986                 }
987                 ao2_ref(hook, -1);
988
989                 if (interval < 0) {
990                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
991                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
992                         ao2_ref(hook, -1);
993                         continue;
994                 }
995                 if (interval) {
996                         /* Set new interval for the hook. */
997                         hook->timer.interval = interval;
998                 }
999
1000                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1001                         hook, hook->timer.interval, bridge_channel,
1002                         ast_channel_name(bridge_channel->chan));
1003
1004                 /* resetting start */
1005                 start = ast_tvnow();
1006
1007                 /*
1008                  * Resetup the interval hook for the next interval.  We may need
1009                  * to skip over any missed intervals because the hook was
1010                  * delayed or took too long.
1011                  */
1012                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1013                 while (hook->timer.interval < execution_time) {
1014                         execution_time -= hook->timer.interval;
1015                 }
1016                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1017                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1018
1019                 if (ast_heap_push(interval_hooks, hook)) {
1020                         /* Could not push the hook back onto the heap. */
1021                         ao2_ref(hook, -1);
1022                 }
1023         }
1024         ast_heap_unlock(interval_hooks);
1025
1026         if (chan_suspended) {
1027                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1028                 bridge_channel_unsuspend(bridge_channel);
1029         }
1030 }
1031
1032 /*!
1033  * \internal
1034  * \brief Write a DTMF stream out to a channel
1035  */
1036 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1037 {
1038         return bridge_channel_write_action_data(bridge_channel,
1039                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1040 }
1041
1042 /*!
1043  * \internal
1044  * \brief Internal function that executes a feature on a bridge channel
1045  * \note Neither the bridge nor the bridge_channel locks should be held when entering
1046  * this function.
1047  */
1048 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel, const char *starting_dtmf)
1049 {
1050         struct ast_bridge_features *features = bridge_channel->features;
1051         struct ast_bridge_hook_dtmf *hook = NULL;
1052         char dtmf[MAXIMUM_DTMF_FEATURE_STRING];
1053         size_t dtmf_len;
1054         unsigned int digit_timeout;
1055         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
1056
1057         ast_channel_lock(bridge_channel->chan);
1058         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1059         if (!gen_cfg) {
1060                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1061                 ast_channel_unlock(bridge_channel->chan);
1062                 return;
1063         }
1064         digit_timeout = gen_cfg->featuredigittimeout;
1065         ast_channel_unlock(bridge_channel->chan);
1066
1067         if (ast_strlen_zero(starting_dtmf)) {
1068                 dtmf[0] = '\0';
1069                 dtmf_len = 0;
1070         } else {
1071                 ast_copy_string(dtmf, starting_dtmf, sizeof(dtmf));
1072                 dtmf_len = strlen(dtmf);
1073         }
1074
1075         /*
1076          * Check if any feature DTMF hooks match or could match and
1077          * try to collect more DTMF digits.
1078          */
1079         for (;;) {
1080                 int res;
1081
1082                 if (dtmf_len) {
1083                         ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1084                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1085
1086                         /* See if a DTMF feature hook matches or can match */
1087                         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1088                         if (!hook) {
1089                                 ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1090                                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1091                                 break;
1092                         }
1093                         if (strlen(hook->dtmf.code) == dtmf_len) {
1094                                 ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1095                                         hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1096                                 break;
1097                         }
1098                         ao2_ref(hook, -1);
1099                         hook = NULL;
1100
1101                         if (ARRAY_LEN(dtmf) - 1 <= dtmf_len) {
1102                                 /* We have reached the maximum length of a DTMF feature string. */
1103                                 break;
1104                         }
1105                 }
1106
1107                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
1108                 if (!res) {
1109                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1110                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1111                         break;
1112                 }
1113                 if (res < 0) {
1114                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
1115                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1116                         break;
1117                 }
1118
1119                 /* Add the new DTMF into the DTMF string so we can do our matching */
1120                 dtmf[dtmf_len] = res;
1121                 dtmf[++dtmf_len] = '\0';
1122         }
1123
1124         if (hook) {
1125                 int remove_me;
1126
1127                 /* Execute the matched hook on this channel. */
1128                 remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1129                 if (remove_me) {
1130                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1131                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1132                         ao2_unlink(features->dtmf_hooks, hook);
1133                 }
1134                 ao2_ref(hook, -1);
1135
1136                 /*
1137                  * If we are handing the channel off to an external hook for
1138                  * ownership, we are not guaranteed what kind of state it will
1139                  * come back in.  If the channel hungup, we need to detect that
1140                  * here if the hook did not already change the state.
1141                  */
1142                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1143                         ast_bridge_channel_kick(bridge_channel, 0);
1144                 }
1145         } else if (features->dtmf_passthrough) {
1146                 /* Stream any collected DTMF to the other channels. */
1147                 bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
1148         }
1149 }
1150
1151 /*!
1152  * \internal
1153  * \brief Indicate that a bridge_channel is talking
1154  */
1155 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1156 {
1157         struct ast_bridge_features *features = bridge_channel->features;
1158         struct ast_bridge_hook *hook;
1159         struct ao2_iterator iter;
1160
1161         /* Run any talk detection hooks. */
1162         iter = ao2_iterator_init(features->other_hooks, 0);
1163         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1164                 int remove_me;
1165                 ast_bridge_talking_indicate_callback talk_cb;
1166
1167                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1168                         continue;
1169                 }
1170                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1171                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1172                 if (remove_me) {
1173                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1174                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1175                         ao2_unlink(features->other_hooks, hook);
1176                 }
1177         }
1178         ao2_iterator_destroy(&iter);
1179 }
1180
1181 /*! \brief Internal function that plays back DTMF on a bridge channel */
1182 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1183 {
1184         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1185                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1186         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1187 }
1188
1189 /*! \brief Data specifying where a blind transfer is going to */
1190 struct blind_transfer_data {
1191         char exten[AST_MAX_EXTENSION];
1192         char context[AST_MAX_CONTEXT];
1193 };
1194
1195 /*!
1196  * \internal
1197  * \brief Execute after bridge actions on a channel when it leaves a bridge
1198  */
1199 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1200 {
1201         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1202         struct ast_party_connected_line connected_target;
1203         unsigned char connected_line_data[1024];
1204         int payload_size;
1205
1206         ast_party_connected_line_init(&connected_target);
1207
1208         ast_channel_lock(chan_target);
1209         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1210         ast_channel_unlock(chan_target);
1211         ast_party_id_reset(&connected_target.priv);
1212
1213         if (ast_channel_move(chan_target, chan_bridged)) {
1214                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1215                 ast_party_connected_line_free(&connected_target);
1216                 return;
1217         }
1218
1219         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1220                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1221                 struct ast_control_read_action_payload *frame_payload;
1222                 int frame_size;
1223
1224                 frame_size = payload_size + sizeof(*frame_payload);
1225                 frame_payload = ast_alloca(frame_size);
1226                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1227                 frame_payload->payload_size = payload_size;
1228                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1229                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1230         }
1231
1232         ast_party_connected_line_free(&connected_target);
1233 }
1234
1235 /*!
1236  * \internal
1237  * \brief Execute logic to cleanup when after bridge fails
1238  */
1239 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1240 {
1241         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1242
1243         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1244                 ast_bridge_after_cb_reason_string(reason));
1245         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1246 }
1247
1248 /*!
1249  * \internal
1250  * \brief Perform a blind transfer on a channel in a bridge
1251  */
1252 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1253                 struct blind_transfer_data *blind_data)
1254 {
1255         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1256         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1257 }
1258
1259 /*!
1260  * \internal
1261  * \brief Perform an attended transfer on a channel in a bridge
1262  */
1263 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1264                 const char *target_chan_name)
1265 {
1266         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1267         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1268
1269         chan_target = ast_channel_get_by_name(target_chan_name);
1270         if (!chan_target) {
1271                 /* Dang, it disappeared somehow */
1272                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1273                 return;
1274         }
1275
1276         ast_bridge_channel_lock(bridge_channel);
1277         chan_bridged = bridge_channel->chan;
1278         ast_assert(chan_bridged != NULL);
1279         ao2_ref(chan_bridged, +1);
1280         ast_bridge_channel_unlock(bridge_channel);
1281
1282         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1283                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1284                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1285
1286                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1287                 ast_channel_unref(chan_target);
1288         }
1289         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1290 }
1291
1292 /*!
1293  * \internal
1294  * \brief Handle bridge channel bridge action frame.
1295  * \since 12.0.0
1296  *
1297  * \param bridge_channel Channel to execute the action on.
1298  * \param action What to do.
1299  *
1300  * \return Nothing
1301  */
1302 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
1303 {
1304         switch (action->subclass.integer) {
1305         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1306                 bridge_channel_suspend(bridge_channel);
1307                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1308                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
1309                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1310                 bridge_channel_unsuspend(bridge_channel);
1311                 break;
1312         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1313         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1314                 bridge_channel_talking(bridge_channel,
1315                         action->subclass.integer == BRIDGE_CHANNEL_ACTION_TALKING_START);
1316                 break;
1317         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1318                 bridge_channel_suspend(bridge_channel);
1319                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1320                 bridge_channel_playfile(bridge_channel, action->data.ptr);
1321                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1322                 bridge_channel_unsuspend(bridge_channel);
1323                 break;
1324         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1325                 bridge_channel_suspend(bridge_channel);
1326                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1327                 bridge_channel_run_app(bridge_channel, action->data.ptr);
1328                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1329                 bridge_channel_unsuspend(bridge_channel);
1330                 break;
1331         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1332                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
1333                 break;
1334         case BRIDGE_CHANNEL_ACTION_PARK:
1335                 bridge_channel_suspend(bridge_channel);
1336                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1337                 bridge_channel_park(bridge_channel, action->data.ptr);
1338                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1339                 bridge_channel_unsuspend(bridge_channel);
1340                 break;
1341         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1342                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
1343                 break;
1344         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1345                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
1346                 break;
1347         default:
1348                 break;
1349         }
1350 }
1351
1352 /*!
1353  * \internal
1354  * \brief Check if a bridge should dissolve and do it.
1355  * \since 12.0.0
1356  *
1357  * \param bridge_channel Channel causing the check.
1358  *
1359  * \note On entry, bridge_channel->bridge is already locked.
1360  *
1361  * \return Nothing
1362  */
1363 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1364 {
1365         struct ast_bridge *bridge = bridge_channel->bridge;
1366
1367         if (bridge->dissolved) {
1368                 return;
1369         }
1370
1371         if (!bridge->num_channels
1372                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1373                 /* Last channel leaving the bridge turns off the lights. */
1374                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1375                 return;
1376         }
1377
1378         switch (bridge_channel->state) {
1379         case BRIDGE_CHANNEL_STATE_END:
1380                 /* Do we need to dissolve the bridge because this channel hung up? */
1381                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1382                         || (bridge_channel->features->usable
1383                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1384                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1385                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1386                         return;
1387                 }
1388                 break;
1389         default:
1390                 break;
1391         }
1392
1393         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1394                 /*
1395                  * This will start a chain reaction where each channel leaving
1396                  * enters this function and causes the next to leave as long as
1397                  * there aren't non-lonely channels in the bridge.
1398                  */
1399                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
1400                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
1401                         ast_channel_hangupcause(bridge_channel->chan));
1402         }
1403 }
1404
1405 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1406 {
1407         struct ast_bridge *bridge = bridge_channel->bridge;
1408
1409         if (!bridge_channel->in_bridge) {
1410                 return;
1411         }
1412         bridge_channel->in_bridge = 0;
1413
1414         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1415                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1416
1417         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1418                 ast_channel_name(bridge_channel->chan),
1419                 bridge->technology->name,
1420                 bridge->v_table->name,
1421                 bridge->uniqueid);
1422
1423 /* BUGBUG This is where incoming HOLD/UNHOLD memory should write UNHOLD into bridge. (if not local optimizing) */
1424 /* BUGBUG This is where incoming DTMF begin/end memory should write DTMF end into bridge. (if not local optimizing) */
1425         if (!bridge_channel->just_joined) {
1426                 /* Tell the bridge technology we are leaving so they tear us down */
1427                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
1428                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1429                         bridge->technology->name);
1430                 if (bridge->technology->leave) {
1431                         bridge->technology->leave(bridge, bridge_channel);
1432                 }
1433         }
1434
1435         /* Remove channel from the bridge */
1436         if (!bridge_channel->suspended) {
1437                 --bridge->num_active;
1438         }
1439         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1440                 --bridge->num_lonely;
1441         }
1442         --bridge->num_channels;
1443         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
1444         bridge->v_table->pull(bridge, bridge_channel);
1445
1446         ast_bridge_channel_clear_roles(bridge_channel);
1447
1448         /* If we are not going to be hung up after leaving a bridge, and we were an
1449          * outgoing channel, clear the outgoing flag.
1450          */
1451         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
1452                         && (ast_channel_softhangup_internal_flag(bridge_channel->chan) &
1453                                 (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE))) {
1454                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
1455         }
1456
1457         bridge_channel_dissolve_check(bridge_channel);
1458
1459         bridge->reconfigured = 1;
1460         ast_bridge_publish_leave(bridge, bridge_channel->chan);
1461 }
1462
1463 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
1464 {
1465         struct ast_bridge *bridge = bridge_channel->bridge;
1466         struct ast_bridge_channel *swap;
1467
1468         ast_assert(!bridge_channel->in_bridge);
1469
1470         swap = bridge_find_channel(bridge, bridge_channel->swap);
1471         bridge_channel->swap = NULL;
1472
1473         if (swap) {
1474                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
1475                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1476                         swap, ast_channel_name(swap->chan));
1477         } else {
1478                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
1479                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1480         }
1481
1482         /* Add channel to the bridge */
1483         if (bridge->dissolved
1484                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
1485                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
1486                 || bridge->v_table->push(bridge, bridge_channel, swap)
1487                 || ast_bridge_channel_establish_roles(bridge_channel)) {
1488                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
1489                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1490                 ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1491                 return -1;
1492         }
1493         bridge_channel->in_bridge = 1;
1494         bridge_channel->just_joined = 1;
1495         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1496         ++bridge->num_channels;
1497         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1498                 ++bridge->num_lonely;
1499         }
1500         if (!bridge_channel->suspended) {
1501                 ++bridge->num_active;
1502         }
1503
1504         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
1505                 ast_channel_name(bridge_channel->chan),
1506                 swap ? "swapped with " : "joined",
1507                 swap ? ast_channel_name(swap->chan) : "",
1508                 swap ? " into" : "",
1509                 bridge->technology->name,
1510                 bridge->v_table->name,
1511                 bridge->uniqueid);
1512
1513         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
1514         if (swap) {
1515                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
1516                 bridge_channel_internal_pull(swap);
1517         }
1518
1519         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
1520         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
1521         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
1522
1523         /* Wake up the bridge channel thread to reevaluate any interval timers. */
1524         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
1525
1526         bridge->reconfigured = 1;
1527         return 0;
1528 }
1529
1530 /*!
1531  * \internal
1532  * \brief Handle bridge channel control frame action.
1533  * \since 12.0.0
1534  *
1535  * \param bridge_channel Channel to execute the control frame action on.
1536  * \param fr Control frame to handle.
1537  *
1538  * \return Nothing
1539  */
1540 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1541 {
1542         struct ast_channel *chan;
1543         struct ast_option_header *aoh;
1544         int is_caller;
1545
1546         chan = bridge_channel->chan;
1547         switch (fr->subclass.integer) {
1548         case AST_CONTROL_REDIRECTING:
1549                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1550                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
1551                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
1552                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1553                 }
1554                 break;
1555         case AST_CONTROL_CONNECTED_LINE:
1556                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1557                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
1558                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
1559                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1560                 }
1561                 break;
1562         case AST_CONTROL_HOLD:
1563         case AST_CONTROL_UNHOLD:
1564 /*
1565  * BUGBUG bridge_channels should remember sending/receiving an outstanding HOLD to/from the bridge
1566  *
1567  * When the sending channel is pulled from the bridge it needs to write into the bridge an UNHOLD before being pulled.
1568  * When the receiving channel is pulled from the bridge it needs to generate its own UNHOLD.
1569  * Something similar needs to be done for DTMF begin/end.
1570  */
1571                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1572                 break;
1573         case AST_CONTROL_OPTION:
1574                 /*
1575                  * Forward option Requests, but only ones we know are safe These
1576                  * are ONLY sent by chan_iax2 and I'm not convinced that they
1577                  * are useful. I haven't deleted them entirely because I just am
1578                  * not sure of the ramifications of removing them.
1579                  */
1580                 aoh = fr->data.ptr;
1581                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
1582                         switch (ntohs(aoh->option)) {
1583                         case AST_OPTION_TONE_VERIFY:
1584                         case AST_OPTION_TDD:
1585                         case AST_OPTION_RELAXDTMF:
1586                         case AST_OPTION_AUDIO_MODE:
1587                         case AST_OPTION_DIGIT_DETECT:
1588                         case AST_OPTION_FAX_DETECT:
1589                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
1590                                         fr->datalen - sizeof(*aoh), 0);
1591                                 break;
1592                         default:
1593                                 break;
1594                         }
1595                 }
1596                 break;
1597         case AST_CONTROL_ANSWER:
1598                 if (ast_channel_state(chan) != AST_STATE_UP) {
1599                         ast_answer(chan);
1600                 } else {
1601                         ast_indicate(chan, -1);
1602                 }
1603                 break;
1604         default:
1605                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1606                 break;
1607         }
1608 }
1609
1610 /*!
1611  * \internal
1612  * \brief Handle bridge channel write frame to channel.
1613  * \since 12.0.0
1614  *
1615  * \param bridge_channel Channel to write outgoing frame.
1616  *
1617  * \return Nothing
1618  */
1619 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
1620 {
1621         struct ast_frame *fr;
1622         char nudge;
1623
1624         ast_bridge_channel_lock(bridge_channel);
1625         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
1626                 if (errno != EINTR && errno != EAGAIN) {
1627                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
1628                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
1629                 }
1630         }
1631         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
1632         ast_bridge_channel_unlock(bridge_channel);
1633         if (!fr) {
1634                 return;
1635         }
1636         switch (fr->frametype) {
1637         case AST_FRAME_BRIDGE_ACTION:
1638                 bridge_channel_handle_action(bridge_channel, fr);
1639                 break;
1640         case AST_FRAME_CONTROL:
1641                 bridge_channel_handle_control(bridge_channel, fr);
1642                 break;
1643         case AST_FRAME_NULL:
1644                 break;
1645         default:
1646                 /* Write the frame to the channel. */
1647                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
1648                 ast_write(bridge_channel->chan, fr);
1649                 break;
1650         }
1651         ast_frfree(fr);
1652 }
1653
1654 /*! \brief Internal function to handle DTMF from a channel */
1655 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1656 {
1657         struct ast_bridge_features *features = bridge_channel->features;
1658         struct ast_bridge_hook_dtmf *hook;
1659         char dtmf[2];
1660
1661         /* See if this DTMF matches the beginning of any feature hooks. */
1662         dtmf[0] = frame->subclass.integer;
1663         dtmf[1] = '\0';
1664         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1665         if (hook) {
1666                 enum ast_frame_type frametype = frame->frametype;
1667
1668                 ast_frfree(frame);
1669                 frame = NULL;
1670
1671                 ao2_ref(hook, -1);
1672
1673                 /* Collect any more needed DTMF to execute a hook. */
1674                 bridge_channel_suspend(bridge_channel);
1675                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1676                 switch (frametype) {
1677                 case AST_FRAME_DTMF_BEGIN:
1678                         bridge_channel_feature(bridge_channel, NULL);
1679                         break;
1680                 case AST_FRAME_DTMF_END:
1681                         bridge_channel_feature(bridge_channel, dtmf);
1682                         break;
1683                 default:
1684                         /* Unexpected frame type. */
1685                         ast_assert(0);
1686                         break;
1687                 }
1688                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1689                 bridge_channel_unsuspend(bridge_channel);
1690         }
1691
1692         return frame;
1693 }
1694
1695
1696 /*!
1697  * \internal
1698  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1699  *
1700  * \param bridge_channel Bridge channel the notification was received on
1701  */
1702 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1703 {
1704         struct ast_frame *frame;
1705
1706         if (bridge_channel->features->mute) {
1707                 frame = ast_read_noaudio(bridge_channel->chan);
1708         } else {
1709                 frame = ast_read(bridge_channel->chan);
1710         }
1711
1712         if (!frame) {
1713                 ast_bridge_channel_kick(bridge_channel, 0);
1714                 return;
1715         }
1716         switch (frame->frametype) {
1717         case AST_FRAME_CONTROL:
1718                 switch (frame->subclass.integer) {
1719                 case AST_CONTROL_HANGUP:
1720                         ast_bridge_channel_kick(bridge_channel, 0);
1721                         ast_frfree(frame);
1722                         return;
1723 /* BUGBUG This is where incoming HOLD/UNHOLD memory should register.  Write UNHOLD into bridge when this channel is pulled. */
1724                 default:
1725                         break;
1726                 }
1727                 break;
1728         case AST_FRAME_DTMF_BEGIN:
1729         case AST_FRAME_DTMF_END:
1730                 frame = bridge_handle_dtmf(bridge_channel, frame);
1731                 if (!frame) {
1732                         return;
1733                 }
1734                 if (!bridge_channel->features->dtmf_passthrough) {
1735                         ast_frfree(frame);
1736                         return;
1737                 }
1738 /* BUGBUG This is where incoming DTMF begin/end memory should register.  Write DTMF end into bridge when this channel is pulled. */
1739                 break;
1740         default:
1741                 break;
1742         }
1743
1744         /* Simply write the frame out to the bridge technology. */
1745         bridge_channel_write_frame(bridge_channel, frame);
1746         ast_frfree(frame);
1747 }
1748
1749 /*!
1750  * \internal
1751  * \brief Determine how long till the next timer interval.
1752  * \since 12.0.0
1753  *
1754  * \param bridge_channel Channel to determine how long can wait.
1755  *
1756  * \retval ms Number of milliseconds to wait.
1757  * \retval -1 to wait forever.
1758  */
1759 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
1760 {
1761         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
1762         struct ast_bridge_hook_timer *hook;
1763         int ms;
1764
1765         ast_heap_wrlock(interval_hooks);
1766         hook = ast_heap_peek(interval_hooks, 1);
1767         if (hook) {
1768                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
1769                 if (ms < 0) {
1770                         /* Expire immediately.  An interval hook is ready to run. */
1771                         ms = 0;
1772                 }
1773         } else {
1774                 /* No hook so wait forever. */
1775                 ms = -1;
1776         }
1777         ast_heap_unlock(interval_hooks);
1778
1779         return ms;
1780 }
1781
1782 /*!
1783  * \internal
1784  * \brief Wait for something to happen on the bridge channel and handle it.
1785  * \since 12.0.0
1786  *
1787  * \param bridge_channel Channel to wait.
1788  *
1789  * \note Each channel does writing/reading in their own thread.
1790  *
1791  * \return Nothing
1792  */
1793 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
1794 {
1795         int ms;
1796         int outfd;
1797         struct ast_channel *chan;
1798
1799         /* Wait for data to either come from the channel or us to be signaled */
1800         ast_bridge_channel_lock(bridge_channel);
1801         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1802         } else if (bridge_channel->suspended) {
1803 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
1804                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
1805                         bridge_channel->bridge->uniqueid, bridge_channel,
1806                         ast_channel_name(bridge_channel->chan));
1807                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
1808         } else {
1809                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
1810                         bridge_channel->bridge->uniqueid, bridge_channel,
1811                         ast_channel_name(bridge_channel->chan));
1812                 bridge_channel->waiting = 1;
1813                 ast_bridge_channel_unlock(bridge_channel);
1814                 outfd = -1;
1815                 ms = bridge_channel_next_interval(bridge_channel);
1816                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
1817                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
1818                 bridge_channel->waiting = 0;
1819                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
1820                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
1821                         ast_bridge_channel_lock_bridge(bridge_channel);
1822                         bridge_channel->bridge->reconfigured = 1;
1823                         bridge_reconfigured(bridge_channel->bridge, 0);
1824                         ast_bridge_unlock(bridge_channel->bridge);
1825                 }
1826                 ast_bridge_channel_lock(bridge_channel);
1827                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
1828                 ast_bridge_channel_unlock(bridge_channel);
1829                 if (!bridge_channel->suspended
1830                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1831                         if (chan) {
1832                                 bridge_handle_trip(bridge_channel);
1833                         } else if (-1 < outfd) {
1834                                 bridge_channel_handle_write(bridge_channel);
1835                         } else if (ms == 0) {
1836                                 /* An interval expired. */
1837                                 bridge_channel_handle_interval(bridge_channel);
1838                         }
1839                 }
1840                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
1841                 return;
1842         }
1843         ast_bridge_channel_unlock(bridge_channel);
1844 }
1845
1846 /*!
1847  * \internal
1848  * \brief Handle bridge channel join/leave event.
1849  * \since 12.0.0
1850  *
1851  * \param bridge_channel Which channel is involved.
1852  * \param type Specified join/leave event.
1853  *
1854  * \return Nothing
1855  */
1856 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
1857 {
1858         struct ast_bridge_features *features = bridge_channel->features;
1859         struct ast_bridge_hook *hook;
1860         struct ao2_iterator iter;
1861
1862         /* Run the specified hooks. */
1863         iter = ao2_iterator_init(features->other_hooks, 0);
1864         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1865                 if (hook->type == type) {
1866                         break;
1867                 }
1868         }
1869         if (hook) {
1870                 /* Found the first specified hook to run. */
1871                 bridge_channel_suspend(bridge_channel);
1872                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1873                 do {
1874                         if (hook->type == type) {
1875                                 hook->callback(bridge_channel, hook->hook_pvt);
1876                                 ao2_unlink(features->other_hooks, hook);
1877                         }
1878                         ao2_ref(hook, -1);
1879                 } while ((hook = ao2_iterator_next(&iter)));
1880                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1881                 bridge_channel_unsuspend(bridge_channel);
1882         }
1883         ao2_iterator_destroy(&iter);
1884 }
1885
1886 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
1887 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
1888 {
1889         int res = 0;
1890         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
1891         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
1892
1893         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
1894                 bridge_channel->bridge->uniqueid,
1895                 bridge_channel, ast_channel_name(bridge_channel->chan));
1896
1897         /*
1898          * Directly locking the bridge is safe here because nobody else
1899          * knows about this bridge_channel yet.
1900          */
1901         ast_bridge_lock(bridge_channel->bridge);
1902
1903         /* Make sure we're still good to be put into a bridge
1904          */
1905         ast_channel_lock(bridge_channel->chan);
1906         if (ast_channel_internal_bridge(bridge_channel->chan)
1907                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
1908                 ast_channel_unlock(bridge_channel->chan);
1909                 ast_bridge_unlock(bridge_channel->bridge);
1910                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
1911                         bridge_channel->bridge->uniqueid,
1912                         bridge_channel,
1913                         ast_channel_name(bridge_channel->chan));
1914                 return -1;
1915         }
1916         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
1917         ast_channel_unlock(bridge_channel->chan);
1918
1919         /* Add the jitterbuffer if the channel requires it */
1920         ast_jb_enable_for_channel(bridge_channel->chan);
1921
1922         if (!bridge_channel->bridge->callid) {
1923                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
1924         }
1925
1926         if (bridge_channel_internal_push(bridge_channel)) {
1927                 ast_bridge_channel_leave_bridge(bridge_channel,
1928                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
1929                 res = -1;
1930         }
1931         bridge_reconfigured(bridge_channel->bridge, 1);
1932
1933         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1934                 /*
1935                  * Indicate a source change since this channel is entering the
1936                  * bridge system only if the bridge technology is not MULTIMIX
1937                  * capable.  The MULTIMIX technology has already done it.
1938                  */
1939                 if (!(bridge_channel->bridge->technology->capabilities
1940                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
1941                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
1942                 }
1943
1944                 ast_bridge_unlock(bridge_channel->bridge);
1945                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
1946                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1947                         /* Wait for something to do. */
1948                         bridge_channel_wait(bridge_channel);
1949                 }
1950                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
1951                 ast_bridge_channel_lock_bridge(bridge_channel);
1952         }
1953
1954         bridge_channel_internal_pull(bridge_channel);
1955         bridge_reconfigured(bridge_channel->bridge, 1);
1956
1957         ast_bridge_unlock(bridge_channel->bridge);
1958
1959         /* Indicate a source change since this channel is leaving the bridge system. */
1960         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
1961
1962 /* BUGBUG Revisit in regards to moving channels between bridges and local channel optimization. */
1963 /* BUGBUG This is where outgoing HOLD/UNHOLD memory should write UNHOLD to channel. */
1964         /* Complete any partial DTMF digit before exiting the bridge. */
1965         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
1966                 ast_channel_end_dtmf(bridge_channel->chan,
1967                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
1968                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
1969         }
1970
1971         /*
1972          * Wait for any dual redirect to complete.
1973          *
1974          * Must be done while "still in the bridge" for ast_async_goto()
1975          * to work right.
1976          */
1977         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
1978                 sched_yield();
1979         }
1980         ast_channel_lock(bridge_channel->chan);
1981         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
1982         ast_channel_unlock(bridge_channel->chan);
1983
1984         ast_bridge_channel_restore_formats(bridge_channel);
1985
1986         return res;
1987 }
1988
1989 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
1990                 const char *exten, const char *context,
1991                 transfer_channel_cb new_channel_cb, void *user_data)
1992 {
1993         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
1994         struct blind_transfer_data blind_data;
1995
1996         ast_channel_lock(transferee);
1997         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
1998         ast_channel_unlock(transferee);
1999
2000         if (!transferee_bridge_channel) {
2001                 return -1;
2002         }
2003
2004         if (new_channel_cb) {
2005                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2006         }
2007
2008         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2009         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2010
2011         return bridge_channel_queue_action_data(transferee_bridge_channel,
2012                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2013 }
2014
2015 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2016                 struct ast_channel *unbridged_chan)
2017 {
2018         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2019         char unbridged_chan_name[AST_CHANNEL_NAME];
2020
2021         ast_channel_lock(transferee);
2022         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2023         ast_channel_unlock(transferee);
2024
2025         if (!transferee_bridge_channel) {
2026                 return -1;
2027         }
2028
2029         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2030                 sizeof(unbridged_chan_name));
2031
2032         return bridge_channel_queue_action_data(transferee_bridge_channel,
2033                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2034                 sizeof(unbridged_chan_name));
2035 }
2036
2037 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2038 {
2039         return bridge_channel->in_bridge
2040                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2041 }
2042
2043 /*!
2044  * \internal
2045  * \brief Close a pipe.
2046  * \since 12.0.0
2047  *
2048  * \param my_pipe What to close.
2049  *
2050  * \return Nothing
2051  */
2052 static void pipe_close(int *my_pipe)
2053 {
2054         if (my_pipe[0] > -1) {
2055                 close(my_pipe[0]);
2056                 my_pipe[0] = -1;
2057         }
2058         if (my_pipe[1] > -1) {
2059                 close(my_pipe[1]);
2060                 my_pipe[1] = -1;
2061         }
2062 }
2063
2064 /*!
2065  * \internal
2066  * \brief Initialize a pipe as non-blocking.
2067  * \since 12.0.0
2068  *
2069  * \param my_pipe What to initialize.
2070  *
2071  * \retval 0 on success.
2072  * \retval -1 on error.
2073  */
2074 static int pipe_init_nonblock(int *my_pipe)
2075 {
2076         int flags;
2077
2078         my_pipe[0] = -1;
2079         my_pipe[1] = -1;
2080         if (pipe(my_pipe)) {
2081                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2082                 return -1;
2083         }
2084         flags = fcntl(my_pipe[0], F_GETFL);
2085         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2086                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2087                         errno, strerror(errno));
2088                 return -1;
2089         }
2090         flags = fcntl(my_pipe[1], F_GETFL);
2091         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2092                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2093                         errno, strerror(errno));
2094                 return -1;
2095         }
2096         return 0;
2097 }
2098
2099 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2100 static void bridge_channel_destroy(void *obj)
2101 {
2102         struct ast_bridge_channel *bridge_channel = obj;
2103         struct ast_frame *fr;
2104
2105         if (bridge_channel->callid) {
2106                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2107         }
2108
2109         if (bridge_channel->bridge) {
2110                 ao2_ref(bridge_channel->bridge, -1);
2111                 bridge_channel->bridge = NULL;
2112         }
2113
2114         /* Flush any unhandled wr_queue frames. */
2115         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2116                 ast_frfree(fr);
2117         }
2118         pipe_close(bridge_channel->alert_pipe);
2119
2120         ast_cond_destroy(&bridge_channel->cond);
2121 }
2122
2123 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2124 {
2125         struct ast_bridge_channel *bridge_channel;
2126
2127         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2128         if (!bridge_channel) {
2129                 return NULL;
2130         }
2131         ast_cond_init(&bridge_channel->cond, NULL);
2132         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2133                 ao2_ref(bridge_channel, -1);
2134                 return NULL;
2135         }
2136         if (bridge) {
2137                 bridge_channel->bridge = bridge;
2138                 ao2_ref(bridge_channel->bridge, +1);
2139         }
2140
2141         return bridge_channel;
2142 }