96bfb209a352693b7132b6e236e98ca924c439da
[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         struct ast_features_xfer_config *xfer = ast_get_chan_features_xfer_config(chan);
1096
1097         if (featuremap) {
1098                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1099                         feature = "blindxfer";
1100                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1101                         feature = "atxfer";
1102                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1103                         feature = "disconnect";
1104                 } else if (!strcmp(dtmf, featuremap->automon)) {
1105                         feature = "automon";
1106                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1107                         feature = "automixmon";
1108                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1109                         feature = "parkcall";
1110                 } else if (!strcmp(dtmf, xfer->atxferthreeway)) {
1111                         feature = "atxferthreeway";
1112                 }
1113         }
1114
1115         ast_test_suite_event_notify("FEATURE_DETECTION",
1116                         "Result: success\r\n"
1117                         "Feature: %s", feature);
1118 #endif /* TEST_FRAMEWORK */
1119 }
1120
1121 /*!
1122  * \internal
1123  * \brief Internal function that executes a feature on a bridge channel
1124  * \note Neither the bridge nor the bridge_channel locks should be held when entering
1125  * this function.
1126  */
1127 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel, const char *starting_dtmf)
1128 {
1129         struct ast_bridge_features *features = bridge_channel->features;
1130         struct ast_bridge_hook_dtmf *hook = NULL;
1131         char dtmf[MAXIMUM_DTMF_FEATURE_STRING];
1132         size_t dtmf_len;
1133         unsigned int digit_timeout;
1134         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
1135
1136         ast_channel_lock(bridge_channel->chan);
1137         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1138         if (!gen_cfg) {
1139                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1140                 ast_channel_unlock(bridge_channel->chan);
1141                 return;
1142         }
1143         digit_timeout = gen_cfg->featuredigittimeout;
1144         ast_channel_unlock(bridge_channel->chan);
1145
1146         if (ast_strlen_zero(starting_dtmf)) {
1147                 dtmf[0] = '\0';
1148                 dtmf_len = 0;
1149         } else {
1150                 ast_copy_string(dtmf, starting_dtmf, sizeof(dtmf));
1151                 dtmf_len = strlen(dtmf);
1152         }
1153
1154         /*
1155          * Check if any feature DTMF hooks match or could match and
1156          * try to collect more DTMF digits.
1157          */
1158         for (;;) {
1159                 int res;
1160
1161                 if (dtmf_len) {
1162                         ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1163                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1164
1165                         /* See if a DTMF feature hook matches or can match */
1166                         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1167                         if (!hook) {
1168                                 ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1169                                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1170                                 break;
1171                         }
1172                         if (strlen(hook->dtmf.code) == dtmf_len) {
1173                                 ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1174                                         hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1175                                 break;
1176                         }
1177                         ao2_ref(hook, -1);
1178                         hook = NULL;
1179
1180                         if (ARRAY_LEN(dtmf) - 1 <= dtmf_len) {
1181                                 /* We have reached the maximum length of a DTMF feature string. */
1182                                 break;
1183                         }
1184                 }
1185
1186                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
1187                 if (!res) {
1188                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1189                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1190                         break;
1191                 }
1192                 if (res < 0) {
1193                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
1194                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1195                         break;
1196                 }
1197
1198                 /* Add the new DTMF into the DTMF string so we can do our matching */
1199                 dtmf[dtmf_len] = res;
1200                 dtmf[++dtmf_len] = '\0';
1201         }
1202
1203         if (hook) {
1204                 int remove_me;
1205
1206                 /* Execute the matched hook on this channel. */
1207                 remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1208                 if (remove_me) {
1209                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1210                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1211                         ao2_unlink(features->dtmf_hooks, hook);
1212                 }
1213                 testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1214                 ao2_ref(hook, -1);
1215
1216                 /*
1217                  * If we are handing the channel off to an external hook for
1218                  * ownership, we are not guaranteed what kind of state it will
1219                  * come back in.  If the channel hungup, we need to detect that
1220                  * here if the hook did not already change the state.
1221                  */
1222                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1223                         ast_bridge_channel_kick(bridge_channel, 0);
1224                 }
1225         } else {
1226                 if (features->dtmf_passthrough) {
1227                         /* Stream any collected DTMF to the other channels. */
1228                         bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
1229                 }
1230                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1231         }
1232 }
1233
1234 /*!
1235  * \internal
1236  * \brief Indicate that a bridge_channel is talking
1237  */
1238 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1239 {
1240         struct ast_bridge_features *features = bridge_channel->features;
1241         struct ast_bridge_hook *hook;
1242         struct ao2_iterator iter;
1243
1244         /* Run any talk detection hooks. */
1245         iter = ao2_iterator_init(features->other_hooks, 0);
1246         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1247                 int remove_me;
1248                 ast_bridge_talking_indicate_callback talk_cb;
1249
1250                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1251                         continue;
1252                 }
1253                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1254                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1255                 if (remove_me) {
1256                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1257                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1258                         ao2_unlink(features->other_hooks, hook);
1259                 }
1260         }
1261         ao2_iterator_destroy(&iter);
1262 }
1263
1264 /*! \brief Internal function that plays back DTMF on a bridge channel */
1265 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1266 {
1267         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1268                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1269         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1270 }
1271
1272 /*! \brief Data specifying where a blind transfer is going to */
1273 struct blind_transfer_data {
1274         char exten[AST_MAX_EXTENSION];
1275         char context[AST_MAX_CONTEXT];
1276 };
1277
1278 /*!
1279  * \internal
1280  * \brief Execute after bridge actions on a channel when it leaves a bridge
1281  */
1282 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1283 {
1284         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1285         struct ast_party_connected_line connected_target;
1286         unsigned char connected_line_data[1024];
1287         int payload_size;
1288
1289         ast_party_connected_line_init(&connected_target);
1290
1291         ast_channel_lock(chan_target);
1292         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1293         ast_channel_unlock(chan_target);
1294         ast_party_id_reset(&connected_target.priv);
1295
1296         if (ast_channel_move(chan_target, chan_bridged)) {
1297                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1298                 ast_party_connected_line_free(&connected_target);
1299                 return;
1300         }
1301
1302         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1303                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1304                 struct ast_control_read_action_payload *frame_payload;
1305                 int frame_size;
1306
1307                 frame_size = payload_size + sizeof(*frame_payload);
1308                 frame_payload = ast_alloca(frame_size);
1309                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1310                 frame_payload->payload_size = payload_size;
1311                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1312                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1313         }
1314
1315         ast_party_connected_line_free(&connected_target);
1316 }
1317
1318 /*!
1319  * \internal
1320  * \brief Execute logic to cleanup when after bridge fails
1321  */
1322 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1323 {
1324         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1325
1326         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1327                 ast_bridge_after_cb_reason_string(reason));
1328         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1329 }
1330
1331 /*!
1332  * \internal
1333  * \brief Perform a blind transfer on a channel in a bridge
1334  */
1335 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1336                 struct blind_transfer_data *blind_data)
1337 {
1338         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1339         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1340 }
1341
1342 /*!
1343  * \internal
1344  * \brief Perform an attended transfer on a channel in a bridge
1345  */
1346 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1347                 const char *target_chan_name)
1348 {
1349         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1350         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1351
1352         chan_target = ast_channel_get_by_name(target_chan_name);
1353         if (!chan_target) {
1354                 /* Dang, it disappeared somehow */
1355                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1356                 return;
1357         }
1358
1359         ast_bridge_channel_lock(bridge_channel);
1360         chan_bridged = bridge_channel->chan;
1361         ast_assert(chan_bridged != NULL);
1362         ao2_ref(chan_bridged, +1);
1363         ast_bridge_channel_unlock(bridge_channel);
1364
1365         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1366                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1367                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1368
1369                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1370                 ast_channel_unref(chan_target);
1371         }
1372         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1373 }
1374
1375 /*!
1376  * \internal
1377  * \brief Handle bridge channel bridge action frame.
1378  * \since 12.0.0
1379  *
1380  * \param bridge_channel Channel to execute the action on.
1381  * \param action What to do.
1382  *
1383  * \return Nothing
1384  */
1385 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
1386 {
1387         switch (action->subclass.integer) {
1388         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1389                 bridge_channel_suspend(bridge_channel);
1390                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1391                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
1392                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1393                 bridge_channel_unsuspend(bridge_channel);
1394                 break;
1395         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1396         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1397                 bridge_channel_talking(bridge_channel,
1398                         action->subclass.integer == BRIDGE_CHANNEL_ACTION_TALKING_START);
1399                 break;
1400         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1401                 bridge_channel_suspend(bridge_channel);
1402                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1403                 bridge_channel_playfile(bridge_channel, action->data.ptr);
1404                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1405                 bridge_channel_unsuspend(bridge_channel);
1406                 break;
1407         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1408                 bridge_channel_suspend(bridge_channel);
1409                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1410                 bridge_channel_run_app(bridge_channel, action->data.ptr);
1411                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1412                 bridge_channel_unsuspend(bridge_channel);
1413                 break;
1414         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1415                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
1416                 break;
1417         case BRIDGE_CHANNEL_ACTION_PARK:
1418                 bridge_channel_suspend(bridge_channel);
1419                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1420                 bridge_channel_park(bridge_channel, action->data.ptr);
1421                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1422                 bridge_channel_unsuspend(bridge_channel);
1423                 break;
1424         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1425                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
1426                 break;
1427         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1428                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
1429                 break;
1430         default:
1431                 break;
1432         }
1433 }
1434
1435 /*!
1436  * \internal
1437  * \brief Check if a bridge should dissolve and do it.
1438  * \since 12.0.0
1439  *
1440  * \param bridge_channel Channel causing the check.
1441  *
1442  * \note On entry, bridge_channel->bridge is already locked.
1443  *
1444  * \return Nothing
1445  */
1446 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1447 {
1448         struct ast_bridge *bridge = bridge_channel->bridge;
1449
1450         if (bridge->dissolved) {
1451                 return;
1452         }
1453
1454         if (!bridge->num_channels
1455                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1456                 /* Last channel leaving the bridge turns off the lights. */
1457                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1458                 return;
1459         }
1460
1461         switch (bridge_channel->state) {
1462         case BRIDGE_CHANNEL_STATE_END:
1463                 /* Do we need to dissolve the bridge because this channel hung up? */
1464                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1465                         || (bridge_channel->features->usable
1466                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1467                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1468                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1469                         return;
1470                 }
1471                 break;
1472         default:
1473                 break;
1474         }
1475
1476         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1477                 /*
1478                  * This will start a chain reaction where each channel leaving
1479                  * enters this function and causes the next to leave as long as
1480                  * there aren't non-lonely channels in the bridge.
1481                  */
1482                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
1483                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
1484                         ast_channel_hangupcause(bridge_channel->chan));
1485         }
1486 }
1487
1488 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1489 {
1490         struct ast_bridge *bridge = bridge_channel->bridge;
1491
1492         if (!bridge_channel->in_bridge) {
1493                 return;
1494         }
1495         bridge_channel->in_bridge = 0;
1496
1497         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1498                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1499
1500         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1501                 ast_channel_name(bridge_channel->chan),
1502                 bridge->technology->name,
1503                 bridge->v_table->name,
1504                 bridge->uniqueid);
1505
1506         if (!bridge_channel->just_joined) {
1507                 /* Tell the bridge technology we are leaving so they tear us down */
1508                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
1509                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1510                         bridge->technology->name);
1511                 if (bridge->technology->leave) {
1512                         bridge->technology->leave(bridge, bridge_channel);
1513                 }
1514         }
1515
1516         /* Remove channel from the bridge */
1517         if (!bridge_channel->suspended) {
1518                 --bridge->num_active;
1519         }
1520         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1521                 --bridge->num_lonely;
1522         }
1523         --bridge->num_channels;
1524         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
1525         bridge->v_table->pull(bridge, bridge_channel);
1526
1527         ast_bridge_channel_clear_roles(bridge_channel);
1528
1529         /* If we are not going to be hung up after leaving a bridge, and we were an
1530          * outgoing channel, clear the outgoing flag.
1531          */
1532         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
1533                         && (ast_channel_softhangup_internal_flag(bridge_channel->chan) & (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE)
1534                             || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
1535                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
1536                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
1537         }
1538
1539         bridge_channel_dissolve_check(bridge_channel);
1540
1541         bridge->reconfigured = 1;
1542         ast_bridge_publish_leave(bridge, bridge_channel->chan);
1543 }
1544
1545 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
1546 {
1547         struct ast_bridge *bridge = bridge_channel->bridge;
1548         struct ast_bridge_channel *swap;
1549
1550         ast_assert(!bridge_channel->in_bridge);
1551
1552         swap = bridge_find_channel(bridge, bridge_channel->swap);
1553         bridge_channel->swap = NULL;
1554
1555         if (swap) {
1556                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
1557                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1558                         swap, ast_channel_name(swap->chan));
1559         } else {
1560                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
1561                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1562         }
1563
1564         /* Add channel to the bridge */
1565         if (bridge->dissolved
1566                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
1567                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
1568                 || bridge->v_table->push(bridge, bridge_channel, swap)
1569                 || ast_bridge_channel_establish_roles(bridge_channel)) {
1570                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
1571                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1572                 return -1;
1573         }
1574         bridge_channel->in_bridge = 1;
1575         bridge_channel->just_joined = 1;
1576         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1577         ++bridge->num_channels;
1578         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1579                 ++bridge->num_lonely;
1580         }
1581         if (!bridge_channel->suspended) {
1582                 ++bridge->num_active;
1583         }
1584
1585         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
1586                 ast_channel_name(bridge_channel->chan),
1587                 swap ? "swapped with " : "joined",
1588                 swap ? ast_channel_name(swap->chan) : "",
1589                 swap ? " into" : "",
1590                 bridge->technology->name,
1591                 bridge->v_table->name,
1592                 bridge->uniqueid);
1593
1594         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
1595         if (swap) {
1596                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
1597                 bridge_channel_internal_pull(swap);
1598         }
1599
1600         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
1601         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
1602         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
1603
1604         /* Wake up the bridge channel thread to reevaluate any interval timers. */
1605         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
1606
1607         bridge->reconfigured = 1;
1608         return 0;
1609 }
1610
1611 /*!
1612  * \internal
1613  * \brief Handle bridge channel control frame action.
1614  * \since 12.0.0
1615  *
1616  * \param bridge_channel Channel to execute the control frame action on.
1617  * \param fr Control frame to handle.
1618  *
1619  * \return Nothing
1620  */
1621 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1622 {
1623         struct ast_channel *chan;
1624         struct ast_option_header *aoh;
1625         int is_caller;
1626
1627         chan = bridge_channel->chan;
1628         switch (fr->subclass.integer) {
1629         case AST_CONTROL_REDIRECTING:
1630                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1631                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
1632                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
1633                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1634                 }
1635                 break;
1636         case AST_CONTROL_CONNECTED_LINE:
1637                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1638                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
1639                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
1640                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1641                 }
1642                 break;
1643         case AST_CONTROL_OPTION:
1644                 /*
1645                  * Forward option Requests, but only ones we know are safe These
1646                  * are ONLY sent by chan_iax2 and I'm not convinced that they
1647                  * are useful. I haven't deleted them entirely because I just am
1648                  * not sure of the ramifications of removing them.
1649                  */
1650                 aoh = fr->data.ptr;
1651                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
1652                         switch (ntohs(aoh->option)) {
1653                         case AST_OPTION_TONE_VERIFY:
1654                         case AST_OPTION_TDD:
1655                         case AST_OPTION_RELAXDTMF:
1656                         case AST_OPTION_AUDIO_MODE:
1657                         case AST_OPTION_DIGIT_DETECT:
1658                         case AST_OPTION_FAX_DETECT:
1659                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
1660                                         fr->datalen - sizeof(*aoh), 0);
1661                                 break;
1662                         default:
1663                                 break;
1664                         }
1665                 }
1666                 break;
1667         case AST_CONTROL_ANSWER:
1668                 if (ast_channel_state(chan) != AST_STATE_UP) {
1669                         ast_answer(chan);
1670                 } else {
1671                         ast_indicate(chan, -1);
1672                 }
1673                 break;
1674         default:
1675                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1676                 break;
1677         }
1678 }
1679
1680 /*!
1681  * \internal
1682  * \brief Handle bridge channel write frame to channel.
1683  * \since 12.0.0
1684  *
1685  * \param bridge_channel Channel to write outgoing frame.
1686  *
1687  * \return Nothing
1688  */
1689 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
1690 {
1691         struct ast_frame *fr;
1692         char nudge;
1693
1694         ast_bridge_channel_lock(bridge_channel);
1695         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
1696                 if (errno != EINTR && errno != EAGAIN) {
1697                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
1698                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
1699                 }
1700         }
1701         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
1702         ast_bridge_channel_unlock(bridge_channel);
1703         if (!fr) {
1704                 return;
1705         }
1706         switch (fr->frametype) {
1707         case AST_FRAME_BRIDGE_ACTION:
1708                 bridge_channel_handle_action(bridge_channel, fr);
1709                 break;
1710         case AST_FRAME_CONTROL:
1711                 bridge_channel_handle_control(bridge_channel, fr);
1712                 break;
1713         case AST_FRAME_NULL:
1714                 break;
1715         default:
1716                 /* Write the frame to the channel. */
1717                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
1718                 ast_write(bridge_channel->chan, fr);
1719                 break;
1720         }
1721         ast_frfree(fr);
1722 }
1723
1724 /*! \brief Internal function to handle DTMF from a channel */
1725 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1726 {
1727         struct ast_bridge_features *features = bridge_channel->features;
1728         struct ast_bridge_hook_dtmf *hook;
1729         char dtmf[2];
1730
1731         /* See if this DTMF matches the beginning of any feature hooks. */
1732         dtmf[0] = frame->subclass.integer;
1733         dtmf[1] = '\0';
1734         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1735         if (hook) {
1736                 enum ast_frame_type frametype = frame->frametype;
1737
1738                 ast_frfree(frame);
1739                 frame = NULL;
1740
1741                 ao2_ref(hook, -1);
1742
1743                 /* Collect any more needed DTMF to execute a hook. */
1744                 bridge_channel_suspend(bridge_channel);
1745                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1746                 switch (frametype) {
1747                 case AST_FRAME_DTMF_BEGIN:
1748                         bridge_channel_feature(bridge_channel, NULL);
1749                         break;
1750                 case AST_FRAME_DTMF_END:
1751                         bridge_channel_feature(bridge_channel, dtmf);
1752                         break;
1753                 default:
1754                         /* Unexpected frame type. */
1755                         ast_assert(0);
1756                         break;
1757                 }
1758                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1759                 bridge_channel_unsuspend(bridge_channel);
1760 #ifdef TEST_FRAMEWORK
1761         } else if (frame->frametype == AST_FRAME_DTMF_END) {
1762                 /* Only transmit this event on DTMF end or else every DTMF
1763                  * press will result in the event being broadcast twice
1764                  */
1765                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1766 #endif
1767         }
1768
1769         return frame;
1770 }
1771
1772
1773 /*!
1774  * \internal
1775  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1776  *
1777  * \param bridge_channel Bridge channel the notification was received on
1778  */
1779 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1780 {
1781         struct ast_frame *frame;
1782
1783         if (bridge_channel->features->mute) {
1784                 frame = ast_read_noaudio(bridge_channel->chan);
1785         } else {
1786                 frame = ast_read(bridge_channel->chan);
1787         }
1788
1789         if (!frame) {
1790                 ast_bridge_channel_kick(bridge_channel, 0);
1791                 return;
1792         }
1793         switch (frame->frametype) {
1794         case AST_FRAME_CONTROL:
1795                 switch (frame->subclass.integer) {
1796                 case AST_CONTROL_HANGUP:
1797                         ast_bridge_channel_kick(bridge_channel, 0);
1798                         ast_frfree(frame);
1799                         return;
1800                 default:
1801                         break;
1802                 }
1803                 break;
1804         case AST_FRAME_DTMF_BEGIN:
1805         case AST_FRAME_DTMF_END:
1806                 frame = bridge_handle_dtmf(bridge_channel, frame);
1807                 if (!frame) {
1808                         return;
1809                 }
1810                 if (!bridge_channel->features->dtmf_passthrough) {
1811                         ast_frfree(frame);
1812                         return;
1813                 }
1814                 break;
1815         default:
1816                 break;
1817         }
1818
1819         /* Simply write the frame out to the bridge technology. */
1820         bridge_channel_write_frame(bridge_channel, frame);
1821         ast_frfree(frame);
1822 }
1823
1824 /*!
1825  * \internal
1826  * \brief Determine how long till the next timer interval.
1827  * \since 12.0.0
1828  *
1829  * \param bridge_channel Channel to determine how long can wait.
1830  *
1831  * \retval ms Number of milliseconds to wait.
1832  * \retval -1 to wait forever.
1833  */
1834 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
1835 {
1836         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
1837         struct ast_bridge_hook_timer *hook;
1838         int ms;
1839
1840         ast_heap_wrlock(interval_hooks);
1841         hook = ast_heap_peek(interval_hooks, 1);
1842         if (hook) {
1843                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
1844                 if (ms < 0) {
1845                         /* Expire immediately.  An interval hook is ready to run. */
1846                         ms = 0;
1847                 }
1848         } else {
1849                 /* No hook so wait forever. */
1850                 ms = -1;
1851         }
1852         ast_heap_unlock(interval_hooks);
1853
1854         return ms;
1855 }
1856
1857 /*!
1858  * \internal
1859  * \brief Wait for something to happen on the bridge channel and handle it.
1860  * \since 12.0.0
1861  *
1862  * \param bridge_channel Channel to wait.
1863  *
1864  * \note Each channel does writing/reading in their own thread.
1865  *
1866  * \return Nothing
1867  */
1868 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
1869 {
1870         int ms;
1871         int outfd;
1872         struct ast_channel *chan;
1873
1874         /* Wait for data to either come from the channel or us to be signaled */
1875         ast_bridge_channel_lock(bridge_channel);
1876         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1877         } else if (bridge_channel->suspended) {
1878 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
1879                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
1880                         bridge_channel->bridge->uniqueid, bridge_channel,
1881                         ast_channel_name(bridge_channel->chan));
1882                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
1883         } else {
1884                 ast_bridge_channel_unlock(bridge_channel);
1885                 outfd = -1;
1886                 ms = bridge_channel_next_interval(bridge_channel);
1887                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
1888                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
1889                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
1890                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
1891                         ast_bridge_channel_lock_bridge(bridge_channel);
1892                         bridge_channel->bridge->reconfigured = 1;
1893                         bridge_reconfigured(bridge_channel->bridge, 0);
1894                         ast_bridge_unlock(bridge_channel->bridge);
1895                 }
1896                 ast_bridge_channel_lock(bridge_channel);
1897                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
1898                 ast_bridge_channel_unlock(bridge_channel);
1899                 if (!bridge_channel->suspended
1900                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1901                         if (chan) {
1902                                 bridge_handle_trip(bridge_channel);
1903                         } else if (-1 < outfd) {
1904                                 bridge_channel_handle_write(bridge_channel);
1905                         } else if (ms == 0) {
1906                                 /* An interval expired. */
1907                                 bridge_channel_handle_interval(bridge_channel);
1908                         }
1909                 }
1910                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
1911                 return;
1912         }
1913         ast_bridge_channel_unlock(bridge_channel);
1914 }
1915
1916 /*!
1917  * \internal
1918  * \brief Handle bridge channel join/leave event.
1919  * \since 12.0.0
1920  *
1921  * \param bridge_channel Which channel is involved.
1922  * \param type Specified join/leave event.
1923  *
1924  * \return Nothing
1925  */
1926 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
1927 {
1928         struct ast_bridge_features *features = bridge_channel->features;
1929         struct ast_bridge_hook *hook;
1930         struct ao2_iterator iter;
1931
1932         /* Run the specified hooks. */
1933         iter = ao2_iterator_init(features->other_hooks, 0);
1934         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1935                 if (hook->type == type) {
1936                         break;
1937                 }
1938         }
1939         if (hook) {
1940                 /* Found the first specified hook to run. */
1941                 bridge_channel_suspend(bridge_channel);
1942                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1943                 do {
1944                         if (hook->type == type) {
1945                                 hook->callback(bridge_channel, hook->hook_pvt);
1946                                 ao2_unlink(features->other_hooks, hook);
1947                         }
1948                         ao2_ref(hook, -1);
1949                 } while ((hook = ao2_iterator_next(&iter)));
1950                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1951                 bridge_channel_unsuspend(bridge_channel);
1952         }
1953         ao2_iterator_destroy(&iter);
1954 }
1955
1956 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
1957 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
1958 {
1959         int res = 0;
1960
1961         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
1962         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
1963
1964         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
1965                 bridge_channel->bridge->uniqueid,
1966                 bridge_channel, ast_channel_name(bridge_channel->chan));
1967
1968         /*
1969          * Directly locking the bridge is safe here because nobody else
1970          * knows about this bridge_channel yet.
1971          */
1972         ast_bridge_lock(bridge_channel->bridge);
1973
1974         /* Make sure we're still good to be put into a bridge */
1975         ast_channel_lock(bridge_channel->chan);
1976         if (ast_channel_internal_bridge(bridge_channel->chan)
1977                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
1978                 ast_channel_unlock(bridge_channel->chan);
1979                 ast_bridge_unlock(bridge_channel->bridge);
1980                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
1981                         bridge_channel->bridge->uniqueid,
1982                         bridge_channel,
1983                         ast_channel_name(bridge_channel->chan));
1984                 return -1;
1985         }
1986         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
1987         ast_channel_unlock(bridge_channel->chan);
1988
1989         /* Add the jitterbuffer if the channel requires it */
1990         ast_jb_enable_for_channel(bridge_channel->chan);
1991
1992         if (!bridge_channel->bridge->callid) {
1993                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
1994         }
1995
1996         if (bridge_channel_internal_push(bridge_channel)) {
1997                 int cause = bridge_channel->bridge->cause;
1998
1999                 ast_bridge_unlock(bridge_channel->bridge);
2000                 ast_bridge_channel_kick(bridge_channel, cause);
2001                 ast_bridge_channel_lock_bridge(bridge_channel);
2002                 ast_bridge_features_remove(bridge_channel->features,
2003                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2004                 bridge_channel_dissolve_check(bridge_channel);
2005                 res = -1;
2006         }
2007         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2008
2009         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2010                 /*
2011                  * Indicate a source change since this channel is entering the
2012                  * bridge system only if the bridge technology is not MULTIMIX
2013                  * capable.  The MULTIMIX technology has already done it.
2014                  */
2015                 if (!(bridge_channel->bridge->technology->capabilities
2016                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2017                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2018                 }
2019
2020                 ast_bridge_unlock(bridge_channel->bridge);
2021                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2022                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2023                         /* Wait for something to do. */
2024                         bridge_channel_wait(bridge_channel);
2025                 }
2026                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2027                 ast_bridge_channel_lock_bridge(bridge_channel);
2028         }
2029
2030         bridge_channel_internal_pull(bridge_channel);
2031         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2032         bridge_reconfigured(bridge_channel->bridge, 1);
2033
2034         ast_bridge_unlock(bridge_channel->bridge);
2035
2036         /* Complete any active hold before exiting the bridge. */
2037         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2038                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2039                         ast_channel_name(bridge_channel->chan));
2040                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2041         }
2042
2043         /* Complete any partial DTMF digit before exiting the bridge. */
2044         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2045                 ast_channel_end_dtmf(bridge_channel->chan,
2046                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2047                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2048         }
2049
2050         /* Indicate a source change since this channel is leaving the bridge system. */
2051         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2052
2053         /*
2054          * Wait for any dual redirect to complete.
2055          *
2056          * Must be done while "still in the bridge" for ast_async_goto()
2057          * to work right.
2058          */
2059         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2060                 sched_yield();
2061         }
2062         ast_channel_lock(bridge_channel->chan);
2063         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2064         ast_channel_unlock(bridge_channel->chan);
2065
2066         ast_bridge_channel_restore_formats(bridge_channel);
2067
2068         return res;
2069 }
2070
2071 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2072                 const char *exten, const char *context,
2073                 transfer_channel_cb new_channel_cb, void *user_data)
2074 {
2075         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2076         struct blind_transfer_data blind_data;
2077
2078         ast_channel_lock(transferee);
2079         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2080         ast_channel_unlock(transferee);
2081
2082         if (!transferee_bridge_channel) {
2083                 return -1;
2084         }
2085
2086         if (new_channel_cb) {
2087                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2088         }
2089
2090         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2091         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2092
2093         return bridge_channel_queue_action_data(transferee_bridge_channel,
2094                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2095 }
2096
2097 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2098                 struct ast_channel *unbridged_chan)
2099 {
2100         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2101         char unbridged_chan_name[AST_CHANNEL_NAME];
2102
2103         ast_channel_lock(transferee);
2104         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2105         ast_channel_unlock(transferee);
2106
2107         if (!transferee_bridge_channel) {
2108                 return -1;
2109         }
2110
2111         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2112                 sizeof(unbridged_chan_name));
2113
2114         return bridge_channel_queue_action_data(transferee_bridge_channel,
2115                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2116                 sizeof(unbridged_chan_name));
2117 }
2118
2119 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2120 {
2121         return bridge_channel->in_bridge
2122                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2123 }
2124
2125 /*!
2126  * \internal
2127  * \brief Close a pipe.
2128  * \since 12.0.0
2129  *
2130  * \param my_pipe What to close.
2131  *
2132  * \return Nothing
2133  */
2134 static void pipe_close(int *my_pipe)
2135 {
2136         if (my_pipe[0] > -1) {
2137                 close(my_pipe[0]);
2138                 my_pipe[0] = -1;
2139         }
2140         if (my_pipe[1] > -1) {
2141                 close(my_pipe[1]);
2142                 my_pipe[1] = -1;
2143         }
2144 }
2145
2146 /*!
2147  * \internal
2148  * \brief Initialize a pipe as non-blocking.
2149  * \since 12.0.0
2150  *
2151  * \param my_pipe What to initialize.
2152  *
2153  * \retval 0 on success.
2154  * \retval -1 on error.
2155  */
2156 static int pipe_init_nonblock(int *my_pipe)
2157 {
2158         int flags;
2159
2160         my_pipe[0] = -1;
2161         my_pipe[1] = -1;
2162         if (pipe(my_pipe)) {
2163                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2164                 return -1;
2165         }
2166         flags = fcntl(my_pipe[0], F_GETFL);
2167         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2168                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2169                         errno, strerror(errno));
2170                 return -1;
2171         }
2172         flags = fcntl(my_pipe[1], F_GETFL);
2173         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2174                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2175                         errno, strerror(errno));
2176                 return -1;
2177         }
2178         return 0;
2179 }
2180
2181 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2182 static void bridge_channel_destroy(void *obj)
2183 {
2184         struct ast_bridge_channel *bridge_channel = obj;
2185         struct ast_frame *fr;
2186
2187         if (bridge_channel->callid) {
2188                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2189         }
2190
2191         if (bridge_channel->bridge) {
2192                 ao2_ref(bridge_channel->bridge, -1);
2193                 bridge_channel->bridge = NULL;
2194         }
2195
2196         /* Flush any unhandled wr_queue frames. */
2197         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2198                 ast_frfree(fr);
2199         }
2200         pipe_close(bridge_channel->alert_pipe);
2201
2202         ast_cond_destroy(&bridge_channel->cond);
2203 }
2204
2205 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2206 {
2207         struct ast_bridge_channel *bridge_channel;
2208
2209         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2210         if (!bridge_channel) {
2211                 return NULL;
2212         }
2213         ast_cond_init(&bridge_channel->cond, NULL);
2214         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2215                 ao2_ref(bridge_channel, -1);
2216                 return NULL;
2217         }
2218         if (bridge) {
2219                 bridge_channel->bridge = bridge;
2220                 ao2_ref(bridge_channel->bridge, +1);
2221         }
2222
2223         return bridge_channel;
2224 }