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