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