Bridging: Allow channels to define bridging hooks
[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_publish_cached_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
842
843         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
844                 moh_class, datalen);
845 }
846
847 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
848 {
849         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
850
851         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
852 }
853
854 /*!
855  * \internal
856  * \brief Helper function to kick off a PBX app on a bridge_channel
857  */
858 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
859 {
860         int res = 0;
861
862         if (!strcasecmp("Gosub", app_name)) {
863                 ast_app_exec_sub(NULL, chan, app_args, 0);
864         } else if (!strcasecmp("Macro", app_name)) {
865                 ast_app_exec_macro(NULL, chan, app_args);
866         } else {
867                 struct ast_app *app;
868
869                 app = pbx_findapp(app_name);
870                 if (!app) {
871                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
872                 } else {
873                         res = pbx_exec(chan, app, app_args);
874                 }
875         }
876         return res;
877 }
878
879 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
880 {
881         if (moh_class) {
882                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
883         }
884         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
885                 /* Break the bridge if the app returns non-zero. */
886                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
887         }
888         if (moh_class) {
889                 ast_bridge_channel_write_unhold(bridge_channel);
890         }
891 }
892
893 struct bridge_run_app {
894         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
895         int moh_offset;
896         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
897         int app_args_offset;
898         /*! Application name to run. */
899         char app_name[0];
900 };
901
902 /*!
903  * \internal
904  * \brief Handle the run application bridge action.
905  * \since 12.0.0
906  *
907  * \param bridge_channel Which channel to run the application on.
908  * \param data Action frame data to run the application.
909  *
910  * \return Nothing
911  */
912 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
913 {
914         ast_bridge_channel_run_app(bridge_channel, data->app_name,
915                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
916                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
917 }
918
919 /*!
920  * \internal
921  * \brief Marshal an application to be executed on a bridge_channel
922  */
923 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
924         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
925 {
926         struct bridge_run_app *app_data;
927         size_t len_name = strlen(app_name) + 1;
928         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
929         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
930         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
931
932         /* Fill in application run frame data. */
933         app_data = alloca(len_data);
934         app_data->app_args_offset = len_args ? len_name : 0;
935         app_data->moh_offset = len_moh ? len_name + len_args : 0;
936         strcpy(app_data->app_name, app_name);/* Safe */
937         if (len_args) {
938                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
939         }
940         if (moh_class) {
941                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
942         }
943
944         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
945 }
946
947 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
948 {
949         return payload_helper_app(bridge_channel_write_action_data,
950                 bridge_channel, app_name, app_args, moh_class);
951 }
952
953 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
954 {
955         return payload_helper_app(bridge_channel_queue_action_data,
956                 bridge_channel, app_name, app_args, moh_class);
957 }
958
959 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)
960 {
961         if (moh_class) {
962                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
963         }
964         if (custom_play) {
965                 custom_play(bridge_channel, playfile);
966         } else {
967                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
968         }
969         if (moh_class) {
970                 ast_bridge_channel_write_unhold(bridge_channel);
971         }
972
973         /*
974          * It may be necessary to resume music on hold after we finish
975          * playing the announcment.
976          */
977         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
978                 const char *latest_musicclass;
979
980                 ast_channel_lock(bridge_channel->chan);
981                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
982                 ast_channel_unlock(bridge_channel->chan);
983                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
984         }
985 }
986
987 struct bridge_playfile {
988         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
989         ast_bridge_custom_play_fn custom_play;
990         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
991         int moh_offset;
992         /*! Filename to play. */
993         char playfile[0];
994 };
995
996 /*!
997  * \internal
998  * \brief Handle the playfile bridge action.
999  * \since 12.0.0
1000  *
1001  * \param bridge_channel Which channel to play a file on.
1002  * \param payload Action frame payload to play a file.
1003  *
1004  * \return Nothing
1005  */
1006 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
1007 {
1008         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
1009                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
1010 }
1011
1012 /*!
1013  * \internal
1014  * \brief Marshal a file to be played on a bridge_channel
1015  */
1016 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
1017         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1018 {
1019         struct bridge_playfile *payload;
1020         size_t len_name = strlen(playfile) + 1;
1021         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1022         size_t len_payload = sizeof(*payload) + len_name + len_moh;
1023
1024         /* Fill in play file frame data. */
1025         payload = ast_alloca(len_payload);
1026         payload->custom_play = custom_play;
1027         payload->moh_offset = len_moh ? len_name : 0;
1028         strcpy(payload->playfile, playfile);/* Safe */
1029         if (moh_class) {
1030                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
1031         }
1032
1033         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
1034 }
1035
1036 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)
1037 {
1038         return payload_helper_playfile(bridge_channel_write_action_data,
1039                 bridge_channel, custom_play, playfile, moh_class);
1040 }
1041
1042 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)
1043 {
1044         return payload_helper_playfile(bridge_channel_queue_action_data,
1045                 bridge_channel, custom_play, playfile, moh_class);
1046 }
1047
1048 int ast_bridge_channel_queue_playfile_sync(struct ast_bridge_channel *bridge_channel,
1049                 ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1050 {
1051         return payload_helper_playfile(bridge_channel_queue_action_data_sync,
1052                 bridge_channel, custom_play, playfile, moh_class);
1053 }
1054
1055 struct bridge_custom_callback {
1056         /*! Call this function on the bridge channel thread. */
1057         ast_bridge_custom_callback_fn callback;
1058         /*! Size of the payload if it exists.  A number otherwise. */
1059         size_t payload_size;
1060         /*! Option flags determining how callback is called. */
1061         unsigned int flags;
1062         /*! Nonzero if the payload exists. */
1063         char payload_exists;
1064         /*! Payload to give to callback. */
1065         char payload[0];
1066 };
1067
1068 /*!
1069  * \internal
1070  * \brief Handle the do custom callback bridge action.
1071  * \since 12.0.0
1072  *
1073  * \param bridge_channel Which channel to call the callback on.
1074  * \param data Action frame data to call the callback.
1075  *
1076  * \return Nothing
1077  */
1078 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
1079 {
1080         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1081                 bridge_channel_suspend(bridge_channel);
1082                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1083         }
1084         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
1085         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1086                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1087                 bridge_channel_unsuspend(bridge_channel);
1088         }
1089 }
1090
1091 /*!
1092  * \internal
1093  * \brief Marshal a custom callback function to be called on a bridge_channel
1094  */
1095 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
1096         struct ast_bridge_channel *bridge_channel,
1097         enum ast_bridge_channel_custom_callback_option flags,
1098         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1099 {
1100         struct bridge_custom_callback *cb_data;
1101         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
1102
1103         /* Sanity check. */
1104         if (!callback) {
1105                 ast_assert(0);
1106                 return -1;
1107         }
1108
1109         /* Fill in custom callback frame data. */
1110         cb_data = alloca(len_data);
1111         cb_data->callback = callback;
1112         cb_data->payload_size = payload_size;
1113         cb_data->flags = flags;
1114         cb_data->payload_exists = payload && payload_size;
1115         if (cb_data->payload_exists) {
1116                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
1117         }
1118
1119         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
1120 }
1121
1122 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
1123         enum ast_bridge_channel_custom_callback_option flags,
1124         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1125 {
1126         return payload_helper_cb(bridge_channel_write_action_data,
1127                 bridge_channel, flags, callback, payload, payload_size);
1128 }
1129
1130 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
1131         enum ast_bridge_channel_custom_callback_option flags,
1132         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1133 {
1134         return payload_helper_cb(bridge_channel_queue_action_data,
1135                 bridge_channel, flags, callback, payload, payload_size);
1136 }
1137
1138 struct bridge_park {
1139         int parker_uuid_offset;
1140         int app_data_offset;
1141         /* buffer used for holding those strings */
1142         char parkee_uuid[0];
1143 };
1144
1145 /*!
1146  * \internal
1147  * \brief Park a bridge_cahnnel
1148  */
1149 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
1150 {
1151         if (!ast_parking_provider_registered()) {
1152                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
1153                         ast_channel_name(bridge_channel->chan));
1154                 return;
1155         }
1156
1157         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
1158                 &payload->parkee_uuid[payload->parker_uuid_offset],
1159                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
1160                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
1161                         ast_channel_name(bridge_channel->chan));
1162         }
1163 }
1164
1165 /*!
1166  * \internal
1167  * \brief Marshal a park action onto a bridge_channel
1168  */
1169 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
1170         struct ast_bridge_channel *bridge_channel,
1171         const char *parkee_uuid,
1172         const char *parker_uuid,
1173         const char *app_data)
1174 {
1175         struct bridge_park *payload;
1176         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1177         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1178         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1179         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1180
1181         payload = alloca(len_payload);
1182         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1183         payload->parker_uuid_offset = len_parkee_uuid;
1184         strcpy(payload->parkee_uuid, parkee_uuid);
1185         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1186         if (app_data) {
1187                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1188         }
1189
1190         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
1191 }
1192
1193 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1194 {
1195         return payload_helper_park(bridge_channel_write_action_data,
1196                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1197 }
1198
1199 /*!
1200  * \internal
1201  * \brief Handle bridge channel interval expiration.
1202  * \since 12.0.0
1203  *
1204  * \param bridge_channel Channel to run expired intervals on.
1205  *
1206  * \return Nothing
1207  */
1208 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
1209 {
1210         struct ast_heap *interval_hooks;
1211         struct ast_bridge_hook_timer *hook;
1212         struct timeval start;
1213         int chan_suspended = 0;
1214
1215         interval_hooks = bridge_channel->features->interval_hooks;
1216         ast_heap_wrlock(interval_hooks);
1217         start = ast_tvnow();
1218         while ((hook = ast_heap_peek(interval_hooks, 1))) {
1219                 int interval;
1220                 unsigned int execution_time;
1221
1222                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1223                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1224                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1225                         break;
1226                 }
1227                 ao2_ref(hook, +1);
1228                 ast_heap_unlock(interval_hooks);
1229
1230                 if (!chan_suspended
1231                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1232                         chan_suspended = 1;
1233                         bridge_channel_suspend(bridge_channel);
1234                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1235                 }
1236
1237                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1238                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1239                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1240
1241                 ast_heap_wrlock(interval_hooks);
1242                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1243                         || !ast_heap_remove(interval_hooks, hook)) {
1244                         /* Interval hook is already removed from the bridge_channel. */
1245                         ao2_ref(hook, -1);
1246                         continue;
1247                 }
1248                 ao2_ref(hook, -1);
1249
1250                 if (interval < 0) {
1251                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1252                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1253                         ao2_ref(hook, -1);
1254                         continue;
1255                 }
1256                 if (interval) {
1257                         /* Set new interval for the hook. */
1258                         hook->timer.interval = interval;
1259                 }
1260
1261                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1262                         hook, hook->timer.interval, bridge_channel,
1263                         ast_channel_name(bridge_channel->chan));
1264
1265                 /* resetting start */
1266                 start = ast_tvnow();
1267
1268                 /*
1269                  * Resetup the interval hook for the next interval.  We may need
1270                  * to skip over any missed intervals because the hook was
1271                  * delayed or took too long.
1272                  */
1273                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1274                 while (hook->timer.interval < execution_time) {
1275                         execution_time -= hook->timer.interval;
1276                 }
1277                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1278                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1279
1280                 if (ast_heap_push(interval_hooks, hook)) {
1281                         /* Could not push the hook back onto the heap. */
1282                         ao2_ref(hook, -1);
1283                 }
1284         }
1285         ast_heap_unlock(interval_hooks);
1286
1287         if (chan_suspended) {
1288                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1289                 bridge_channel_unsuspend(bridge_channel);
1290         }
1291 }
1292
1293 /*!
1294  * \internal
1295  * \brief Write a DTMF stream out to a channel
1296  */
1297 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1298 {
1299         return bridge_channel_write_action_data(bridge_channel,
1300                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1301 }
1302
1303 /*!
1304  * \internal
1305  * \brief Indicate to the testsuite a feature was successfully detected.
1306  *
1307  * Currently, this function only will relay built-in features to the testsuite,
1308  * but it could be modified to detect applicationmap items should the need arise.
1309  *
1310  * \param chan The channel that activated the feature
1311  * \param dtmf The DTMF sequence entered to activate the feature
1312  */
1313 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1314 {
1315 #ifdef TEST_FRAMEWORK
1316         char *feature = "unknown";
1317         struct ast_featuremap_config *featuremap = ast_get_chan_featuremap_config(chan);
1318         struct ast_features_xfer_config *xfer = ast_get_chan_features_xfer_config(chan);
1319
1320         if (featuremap) {
1321                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1322                         feature = "blindxfer";
1323                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1324                         feature = "atxfer";
1325                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1326                         feature = "disconnect";
1327                 } else if (!strcmp(dtmf, featuremap->automon)) {
1328                         feature = "automon";
1329                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1330                         feature = "automixmon";
1331                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1332                         feature = "parkcall";
1333                 } else if (!strcmp(dtmf, xfer->atxferthreeway)) {
1334                         feature = "atxferthreeway";
1335                 }
1336         }
1337
1338         ast_test_suite_event_notify("FEATURE_DETECTION",
1339                         "Result: success\r\n"
1340                         "Feature: %s", feature);
1341 #endif /* TEST_FRAMEWORK */
1342 }
1343
1344 /*!
1345  * \internal
1346  * \brief Internal function that executes a feature on a bridge channel
1347  * \note Neither the bridge nor the bridge_channel locks should be held when entering
1348  * this function.
1349  */
1350 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel, const char *starting_dtmf)
1351 {
1352         struct ast_bridge_features *features = bridge_channel->features;
1353         struct ast_bridge_hook_dtmf *hook = NULL;
1354         char dtmf[MAXIMUM_DTMF_FEATURE_STRING];
1355         size_t dtmf_len;
1356         unsigned int digit_timeout;
1357         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
1358
1359         ast_channel_lock(bridge_channel->chan);
1360         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1361         if (!gen_cfg) {
1362                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1363                 ast_channel_unlock(bridge_channel->chan);
1364                 return;
1365         }
1366         digit_timeout = gen_cfg->featuredigittimeout;
1367         ast_channel_unlock(bridge_channel->chan);
1368
1369         if (ast_strlen_zero(starting_dtmf)) {
1370                 dtmf[0] = '\0';
1371                 dtmf_len = 0;
1372         } else {
1373                 ast_copy_string(dtmf, starting_dtmf, sizeof(dtmf));
1374                 dtmf_len = strlen(dtmf);
1375         }
1376
1377         /*
1378          * Check if any feature DTMF hooks match or could match and
1379          * try to collect more DTMF digits.
1380          */
1381         for (;;) {
1382                 int res;
1383
1384                 if (dtmf_len) {
1385                         ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1386                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1387
1388                         /* See if a DTMF feature hook matches or can match */
1389                         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1390                         if (!hook) {
1391                                 ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1392                                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1393                                 break;
1394                         }
1395                         if (strlen(hook->dtmf.code) == dtmf_len) {
1396                                 ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1397                                         hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1398                                 break;
1399                         }
1400                         ao2_ref(hook, -1);
1401                         hook = NULL;
1402
1403                         if (ARRAY_LEN(dtmf) - 1 <= dtmf_len) {
1404                                 /* We have reached the maximum length of a DTMF feature string. */
1405                                 break;
1406                         }
1407                 }
1408
1409                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
1410                 if (!res) {
1411                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1412                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1413                         break;
1414                 }
1415                 if (res < 0) {
1416                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
1417                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1418                         break;
1419                 }
1420
1421                 /* Add the new DTMF into the DTMF string so we can do our matching */
1422                 dtmf[dtmf_len] = res;
1423                 dtmf[++dtmf_len] = '\0';
1424         }
1425
1426         if (hook) {
1427                 int remove_me;
1428
1429                 /* Execute the matched hook on this channel. */
1430                 remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1431                 if (remove_me) {
1432                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1433                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1434                         ao2_unlink(features->dtmf_hooks, hook);
1435                 }
1436                 testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1437                 ao2_ref(hook, -1);
1438
1439                 /*
1440                  * If we are handing the channel off to an external hook for
1441                  * ownership, we are not guaranteed what kind of state it will
1442                  * come back in.  If the channel hungup, we need to detect that
1443                  * here if the hook did not already change the state.
1444                  */
1445                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1446                         ast_bridge_channel_kick(bridge_channel, 0);
1447                 }
1448         } else {
1449                 if (features->dtmf_passthrough) {
1450                         /* Stream any collected DTMF to the other channels. */
1451                         bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
1452                 }
1453                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1454         }
1455 }
1456
1457 /*!
1458  * \internal
1459  * \brief Indicate that a bridge_channel is talking
1460  */
1461 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1462 {
1463         struct ast_bridge_features *features = bridge_channel->features;
1464         struct ast_bridge_hook *hook;
1465         struct ao2_iterator iter;
1466
1467         /* Run any talk detection hooks. */
1468         iter = ao2_iterator_init(features->other_hooks, 0);
1469         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1470                 int remove_me;
1471                 ast_bridge_talking_indicate_callback talk_cb;
1472
1473                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1474                         continue;
1475                 }
1476                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1477                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1478                 if (remove_me) {
1479                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1480                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1481                         ao2_unlink(features->other_hooks, hook);
1482                 }
1483         }
1484         ao2_iterator_destroy(&iter);
1485 }
1486
1487 /*! \brief Internal function that plays back DTMF on a bridge channel */
1488 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1489 {
1490         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1491                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1492         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1493 }
1494
1495 /*! \brief Data specifying where a blind transfer is going to */
1496 struct blind_transfer_data {
1497         char exten[AST_MAX_EXTENSION];
1498         char context[AST_MAX_CONTEXT];
1499 };
1500
1501 /*!
1502  * \internal
1503  * \brief Execute after bridge actions on a channel when it leaves a bridge
1504  */
1505 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1506 {
1507         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1508         struct ast_party_connected_line connected_target;
1509         unsigned char connected_line_data[1024];
1510         int payload_size;
1511
1512         ast_party_connected_line_init(&connected_target);
1513
1514         ast_channel_lock(chan_target);
1515         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1516         ast_channel_unlock(chan_target);
1517         ast_party_id_reset(&connected_target.priv);
1518
1519         if (ast_channel_move(chan_target, chan_bridged)) {
1520                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1521                 ast_party_connected_line_free(&connected_target);
1522                 return;
1523         }
1524
1525         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1526                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1527                 struct ast_control_read_action_payload *frame_payload;
1528                 int frame_size;
1529
1530                 frame_size = payload_size + sizeof(*frame_payload);
1531                 frame_payload = ast_alloca(frame_size);
1532                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1533                 frame_payload->payload_size = payload_size;
1534                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1535                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1536         }
1537
1538         ast_party_connected_line_free(&connected_target);
1539 }
1540
1541 /*!
1542  * \internal
1543  * \brief Execute logic to cleanup when after bridge fails
1544  */
1545 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1546 {
1547         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1548
1549         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1550                 ast_bridge_after_cb_reason_string(reason));
1551         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1552 }
1553
1554 /*!
1555  * \internal
1556  * \brief Perform a blind transfer on a channel in a bridge
1557  */
1558 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1559                 struct blind_transfer_data *blind_data)
1560 {
1561         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1562         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1563 }
1564
1565 /*!
1566  * \internal
1567  * \brief Perform an attended transfer on a channel in a bridge
1568  */
1569 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1570                 const char *target_chan_name)
1571 {
1572         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1573         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1574
1575         chan_target = ast_channel_get_by_name(target_chan_name);
1576         if (!chan_target) {
1577                 /* Dang, it disappeared somehow */
1578                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1579                 return;
1580         }
1581
1582         ast_bridge_channel_lock(bridge_channel);
1583         chan_bridged = bridge_channel->chan;
1584         ast_assert(chan_bridged != NULL);
1585         ao2_ref(chan_bridged, +1);
1586         ast_bridge_channel_unlock(bridge_channel);
1587
1588         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1589                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1590                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1591
1592                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1593                 ast_channel_unref(chan_target);
1594         }
1595         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1596 }
1597
1598 /*!
1599  * \internal
1600  * \brief Handle bridge channel bridge action frame.
1601  * \since 12.0.0
1602  *
1603  * \param bridge_channel Channel to execute the action on.
1604  * \param action What to do.
1605  * \param data data from the action.
1606  *
1607  * \return Nothing
1608  */
1609 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel,
1610         enum bridge_channel_action_type action, void *data)
1611 {
1612         switch (action) {
1613         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1614                 bridge_channel_suspend(bridge_channel);
1615                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1616                 bridge_channel_dtmf_stream(bridge_channel, data);
1617                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1618                 bridge_channel_unsuspend(bridge_channel);
1619                 break;
1620         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1621         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1622                 bridge_channel_talking(bridge_channel,
1623                         action == BRIDGE_CHANNEL_ACTION_TALKING_START);
1624                 break;
1625         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1626                 bridge_channel_suspend(bridge_channel);
1627                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1628                 bridge_channel_playfile(bridge_channel, data);
1629                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1630                 bridge_channel_unsuspend(bridge_channel);
1631                 break;
1632         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1633                 bridge_channel_suspend(bridge_channel);
1634                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1635                 bridge_channel_run_app(bridge_channel, data);
1636                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1637                 bridge_channel_unsuspend(bridge_channel);
1638                 break;
1639         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1640                 bridge_channel_do_callback(bridge_channel, data);
1641                 break;
1642         case BRIDGE_CHANNEL_ACTION_PARK:
1643                 bridge_channel_suspend(bridge_channel);
1644                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1645                 bridge_channel_park(bridge_channel, data);
1646                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1647                 bridge_channel_unsuspend(bridge_channel);
1648                 break;
1649         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1650                 bridge_channel_blind_transfer(bridge_channel, data);
1651                 break;
1652         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1653                 bridge_channel_attended_transfer(bridge_channel, data);
1654                 break;
1655         default:
1656                 break;
1657         }
1658 }
1659
1660 /*!
1661  * \internal
1662  * \brief Check if a bridge should dissolve and do it.
1663  * \since 12.0.0
1664  *
1665  * \param bridge_channel Channel causing the check.
1666  *
1667  * \note On entry, bridge_channel->bridge is already locked.
1668  *
1669  * \return Nothing
1670  */
1671 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1672 {
1673         struct ast_bridge *bridge = bridge_channel->bridge;
1674
1675         if (bridge->dissolved) {
1676                 return;
1677         }
1678
1679         if (!bridge->num_channels
1680                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1681                 /* Last channel leaving the bridge turns off the lights. */
1682                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1683                 return;
1684         }
1685
1686         switch (bridge_channel->state) {
1687         case BRIDGE_CHANNEL_STATE_END:
1688                 /* Do we need to dissolve the bridge because this channel hung up? */
1689                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1690                         || (bridge_channel->features->usable
1691                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1692                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1693                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1694                         return;
1695                 }
1696                 break;
1697         default:
1698                 break;
1699         }
1700
1701         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1702                 /*
1703                  * This will start a chain reaction where each channel leaving
1704                  * enters this function and causes the next to leave as long as
1705                  * there aren't non-lonely channels in the bridge.
1706                  */
1707                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
1708                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
1709                         ast_channel_hangupcause(bridge_channel->chan));
1710         }
1711 }
1712
1713 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1714 {
1715         struct ast_bridge *bridge = bridge_channel->bridge;
1716
1717         if (!bridge_channel->in_bridge) {
1718                 return;
1719         }
1720         bridge_channel->in_bridge = 0;
1721
1722         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1723                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1724
1725         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1726                 ast_channel_name(bridge_channel->chan),
1727                 bridge->technology->name,
1728                 bridge->v_table->name,
1729                 bridge->uniqueid);
1730
1731         if (!bridge_channel->just_joined) {
1732                 /* Tell the bridge technology we are leaving so they tear us down */
1733                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
1734                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1735                         bridge->technology->name);
1736                 if (bridge->technology->leave) {
1737                         bridge->technology->leave(bridge, bridge_channel);
1738                 }
1739         }
1740
1741         /* Remove channel from the bridge */
1742         if (!bridge_channel->suspended) {
1743                 --bridge->num_active;
1744         }
1745         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1746                 --bridge->num_lonely;
1747         }
1748         --bridge->num_channels;
1749         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
1750         bridge->v_table->pull(bridge, bridge_channel);
1751
1752         ast_bridge_channel_clear_roles(bridge_channel);
1753
1754         /* If we are not going to be hung up after leaving a bridge, and we were an
1755          * outgoing channel, clear the outgoing flag.
1756          */
1757         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
1758             && (ast_channel_is_leaving_bridge(bridge_channel->chan)
1759                 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
1760                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
1761                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
1762         }
1763
1764         bridge_channel_dissolve_check(bridge_channel);
1765
1766         bridge->reconfigured = 1;
1767         ast_bridge_publish_leave(bridge, bridge_channel->chan);
1768 }
1769
1770 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
1771 {
1772         struct ast_bridge *bridge = bridge_channel->bridge;
1773         struct ast_bridge_channel *swap;
1774
1775         ast_assert(!bridge_channel->in_bridge);
1776
1777         swap = bridge_find_channel(bridge, bridge_channel->swap);
1778         bridge_channel->swap = NULL;
1779
1780         if (swap) {
1781                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
1782                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1783                         swap, ast_channel_name(swap->chan));
1784         } else {
1785                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
1786                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1787         }
1788
1789         /* Add channel to the bridge */
1790         if (bridge->dissolved
1791                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
1792                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
1793                 || bridge->v_table->push(bridge, bridge_channel, swap)
1794                 || ast_bridge_channel_establish_roles(bridge_channel)) {
1795                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
1796                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1797                 return -1;
1798         }
1799         bridge_channel->in_bridge = 1;
1800         bridge_channel->just_joined = 1;
1801         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1802         ++bridge->num_channels;
1803         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1804                 ++bridge->num_lonely;
1805         }
1806         if (!bridge_channel->suspended) {
1807                 ++bridge->num_active;
1808         }
1809
1810         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
1811                 ast_channel_name(bridge_channel->chan),
1812                 swap ? "swapped with " : "joined",
1813                 swap ? ast_channel_name(swap->chan) : "",
1814                 swap ? " into" : "",
1815                 bridge->technology->name,
1816                 bridge->v_table->name,
1817                 bridge->uniqueid);
1818
1819         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
1820         if (swap) {
1821                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
1822                 bridge_channel_internal_pull(swap);
1823         }
1824
1825         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
1826         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
1827         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
1828
1829         /* Wake up the bridge channel thread to reevaluate any interval timers. */
1830         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
1831
1832         bridge->reconfigured = 1;
1833         return 0;
1834 }
1835
1836 /*!
1837  * \internal
1838  * \brief Handle bridge channel control frame action.
1839  * \since 12.0.0
1840  *
1841  * \param bridge_channel Channel to execute the control frame action on.
1842  * \param fr Control frame to handle.
1843  *
1844  * \return Nothing
1845  */
1846 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1847 {
1848         struct ast_channel *chan;
1849         struct ast_option_header *aoh;
1850         int is_caller;
1851
1852         chan = bridge_channel->chan;
1853         switch (fr->subclass.integer) {
1854         case AST_CONTROL_REDIRECTING:
1855                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1856                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
1857                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
1858                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1859                 }
1860                 break;
1861         case AST_CONTROL_CONNECTED_LINE:
1862                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1863                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
1864                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
1865                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1866                 }
1867                 break;
1868         case AST_CONTROL_OPTION:
1869                 /*
1870                  * Forward option Requests, but only ones we know are safe These
1871                  * are ONLY sent by chan_iax2 and I'm not convinced that they
1872                  * are useful. I haven't deleted them entirely because I just am
1873                  * not sure of the ramifications of removing them.
1874                  */
1875                 aoh = fr->data.ptr;
1876                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
1877                         switch (ntohs(aoh->option)) {
1878                         case AST_OPTION_TONE_VERIFY:
1879                         case AST_OPTION_TDD:
1880                         case AST_OPTION_RELAXDTMF:
1881                         case AST_OPTION_AUDIO_MODE:
1882                         case AST_OPTION_DIGIT_DETECT:
1883                         case AST_OPTION_FAX_DETECT:
1884                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
1885                                         fr->datalen - sizeof(*aoh), 0);
1886                                 break;
1887                         default:
1888                                 break;
1889                         }
1890                 }
1891                 break;
1892         case AST_CONTROL_ANSWER:
1893                 if (ast_channel_state(chan) != AST_STATE_UP) {
1894                         ast_answer(chan);
1895                 } else {
1896                         ast_indicate(chan, -1);
1897                 }
1898                 break;
1899         default:
1900                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1901                 break;
1902         }
1903 }
1904
1905 /*!
1906  * \internal
1907  * \brief Handle bridge channel write frame to channel.
1908  * \since 12.0.0
1909  *
1910  * \param bridge_channel Channel to write outgoing frame.
1911  *
1912  * \return Nothing
1913  */
1914 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
1915 {
1916         struct ast_frame *fr;
1917         char nudge;
1918         struct sync_payload *sync_payload;
1919
1920         ast_bridge_channel_lock(bridge_channel);
1921         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
1922                 if (errno != EINTR && errno != EAGAIN) {
1923                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
1924                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
1925                 }
1926         }
1927         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
1928         ast_bridge_channel_unlock(bridge_channel);
1929         if (!fr) {
1930                 return;
1931         }
1932         switch (fr->frametype) {
1933         case AST_FRAME_BRIDGE_ACTION:
1934                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, fr->data.ptr);
1935                 break;
1936         case AST_FRAME_BRIDGE_ACTION_SYNC:
1937                 sync_payload = fr->data.ptr;
1938                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, sync_payload->data);
1939                 break;
1940         case AST_FRAME_CONTROL:
1941                 bridge_channel_handle_control(bridge_channel, fr);
1942                 break;
1943         case AST_FRAME_NULL:
1944                 break;
1945         default:
1946                 /* Write the frame to the channel. */
1947                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
1948                 ast_write(bridge_channel->chan, fr);
1949                 break;
1950         }
1951         bridge_frame_free(fr);
1952 }
1953
1954 /*! \brief Internal function to handle DTMF from a channel */
1955 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1956 {
1957         struct ast_bridge_features *features = bridge_channel->features;
1958         struct ast_bridge_hook_dtmf *hook;
1959         char dtmf[2];
1960
1961         /* See if this DTMF matches the beginning of any feature hooks. */
1962         dtmf[0] = frame->subclass.integer;
1963         dtmf[1] = '\0';
1964         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1965         if (hook) {
1966                 enum ast_frame_type frametype = frame->frametype;
1967
1968                 bridge_frame_free(frame);
1969                 frame = NULL;
1970
1971                 ao2_ref(hook, -1);
1972
1973                 /* Collect any more needed DTMF to execute a hook. */
1974                 bridge_channel_suspend(bridge_channel);
1975                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1976                 switch (frametype) {
1977                 case AST_FRAME_DTMF_BEGIN:
1978                         bridge_channel_feature(bridge_channel, NULL);
1979                         break;
1980                 case AST_FRAME_DTMF_END:
1981                         bridge_channel_feature(bridge_channel, dtmf);
1982                         break;
1983                 default:
1984                         /* Unexpected frame type. */
1985                         ast_assert(0);
1986                         break;
1987                 }
1988                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1989                 bridge_channel_unsuspend(bridge_channel);
1990 #ifdef TEST_FRAMEWORK
1991         } else if (frame->frametype == AST_FRAME_DTMF_END) {
1992                 /* Only transmit this event on DTMF end or else every DTMF
1993                  * press will result in the event being broadcast twice
1994                  */
1995                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1996 #endif
1997         }
1998
1999         return frame;
2000 }
2001
2002
2003 /*!
2004  * \internal
2005  * \brief Feed notification that a frame is waiting on a channel into the bridging core
2006  *
2007  * \param bridge_channel Bridge channel the notification was received on
2008  */
2009 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
2010 {
2011         struct ast_frame *frame;
2012
2013         if (bridge_channel->features->mute) {
2014                 frame = ast_read_noaudio(bridge_channel->chan);
2015         } else {
2016                 frame = ast_read(bridge_channel->chan);
2017         }
2018
2019         if (!frame) {
2020                 ast_bridge_channel_kick(bridge_channel, 0);
2021                 return;
2022         }
2023         switch (frame->frametype) {
2024         case AST_FRAME_CONTROL:
2025                 switch (frame->subclass.integer) {
2026                 case AST_CONTROL_HANGUP:
2027                         ast_bridge_channel_kick(bridge_channel, 0);
2028                         bridge_frame_free(frame);
2029                         return;
2030                 default:
2031                         break;
2032                 }
2033                 break;
2034         case AST_FRAME_DTMF_BEGIN:
2035         case AST_FRAME_DTMF_END:
2036                 frame = bridge_handle_dtmf(bridge_channel, frame);
2037                 if (!frame) {
2038                         return;
2039                 }
2040                 if (!bridge_channel->features->dtmf_passthrough) {
2041                         bridge_frame_free(frame);
2042                         return;
2043                 }
2044                 break;
2045         default:
2046                 break;
2047         }
2048
2049         /* Simply write the frame out to the bridge technology. */
2050         bridge_channel_write_frame(bridge_channel, frame);
2051         bridge_frame_free(frame);
2052 }
2053
2054 /*!
2055  * \internal
2056  * \brief Determine how long till the next timer interval.
2057  * \since 12.0.0
2058  *
2059  * \param bridge_channel Channel to determine how long can wait.
2060  *
2061  * \retval ms Number of milliseconds to wait.
2062  * \retval -1 to wait forever.
2063  */
2064 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
2065 {
2066         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
2067         struct ast_bridge_hook_timer *hook;
2068         int ms;
2069
2070         ast_heap_wrlock(interval_hooks);
2071         hook = ast_heap_peek(interval_hooks, 1);
2072         if (hook) {
2073                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
2074                 if (ms < 0) {
2075                         /* Expire immediately.  An interval hook is ready to run. */
2076                         ms = 0;
2077                 }
2078         } else {
2079                 /* No hook so wait forever. */
2080                 ms = -1;
2081         }
2082         ast_heap_unlock(interval_hooks);
2083
2084         return ms;
2085 }
2086
2087 /*!
2088  * \internal
2089  * \brief Wait for something to happen on the bridge channel and handle it.
2090  * \since 12.0.0
2091  *
2092  * \param bridge_channel Channel to wait.
2093  *
2094  * \note Each channel does writing/reading in their own thread.
2095  *
2096  * \return Nothing
2097  */
2098 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2099 {
2100         int ms;
2101         int outfd;
2102         struct ast_channel *chan;
2103
2104         /* Wait for data to either come from the channel or us to be signaled */
2105         ast_bridge_channel_lock(bridge_channel);
2106         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2107         } else if (bridge_channel->suspended) {
2108 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
2109                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2110                         bridge_channel->bridge->uniqueid, bridge_channel,
2111                         ast_channel_name(bridge_channel->chan));
2112                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2113         } else {
2114                 ast_bridge_channel_unlock(bridge_channel);
2115                 outfd = -1;
2116                 ms = bridge_channel_next_interval(bridge_channel);
2117                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2118                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2119                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
2120                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
2121                         ast_bridge_channel_lock_bridge(bridge_channel);
2122                         bridge_channel->bridge->reconfigured = 1;
2123                         bridge_reconfigured(bridge_channel->bridge, 0);
2124                         ast_bridge_unlock(bridge_channel->bridge);
2125                 }
2126                 ast_bridge_channel_lock(bridge_channel);
2127                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
2128                 ast_bridge_channel_unlock(bridge_channel);
2129                 if (!bridge_channel->suspended
2130                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2131                         if (chan) {
2132                                 bridge_handle_trip(bridge_channel);
2133                         } else if (-1 < outfd) {
2134                                 bridge_channel_handle_write(bridge_channel);
2135                         } else if (ms == 0) {
2136                                 /* An interval expired. */
2137                                 bridge_channel_handle_interval(bridge_channel);
2138                         }
2139                 }
2140                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
2141                 return;
2142         }
2143         ast_bridge_channel_unlock(bridge_channel);
2144 }
2145
2146 /*!
2147  * \internal
2148  * \brief Handle bridge channel join/leave event.
2149  * \since 12.0.0
2150  *
2151  * \param bridge_channel Which channel is involved.
2152  * \param type Specified join/leave event.
2153  *
2154  * \return Nothing
2155  */
2156 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
2157 {
2158         struct ast_bridge_features *features = bridge_channel->features;
2159         struct ast_bridge_hook *hook;
2160         struct ao2_iterator iter;
2161
2162         /* Run the specified hooks. */
2163         iter = ao2_iterator_init(features->other_hooks, 0);
2164         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2165                 if (hook->type == type) {
2166                         break;
2167                 }
2168         }
2169         if (hook) {
2170                 /* Found the first specified hook to run. */
2171                 bridge_channel_suspend(bridge_channel);
2172                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2173                 do {
2174                         if (hook->type == type) {
2175                                 hook->callback(bridge_channel, hook->hook_pvt);
2176                                 ao2_unlink(features->other_hooks, hook);
2177                         }
2178                         ao2_ref(hook, -1);
2179                 } while ((hook = ao2_iterator_next(&iter)));
2180                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2181                 bridge_channel_unsuspend(bridge_channel);
2182         }
2183         ao2_iterator_destroy(&iter);
2184 }
2185
2186 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
2187 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
2188 {
2189         int res = 0;
2190         struct ast_bridge_features *channel_features;
2191
2192         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
2193         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
2194
2195         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2196                 bridge_channel->bridge->uniqueid,
2197                 bridge_channel, ast_channel_name(bridge_channel->chan));
2198
2199         /*
2200          * Directly locking the bridge is safe here because nobody else
2201          * knows about this bridge_channel yet.
2202          */
2203         ast_bridge_lock(bridge_channel->bridge);
2204
2205         ast_channel_lock(bridge_channel->chan);
2206         /* Make sure we're still good to be put into a bridge */
2207         if (ast_channel_internal_bridge(bridge_channel->chan)
2208                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
2209                 ast_channel_unlock(bridge_channel->chan);
2210                 ast_bridge_unlock(bridge_channel->bridge);
2211                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
2212                         bridge_channel->bridge->uniqueid,
2213                         bridge_channel,
2214                         ast_channel_name(bridge_channel->chan));
2215                 return -1;
2216         }
2217         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2218
2219         /* Attach features requested by the channel */
2220         channel_features = ast_channel_feature_hooks_get(bridge_channel->chan);
2221         if (channel_features) {
2222                 ast_bridge_features_merge(bridge_channel->features, channel_features);
2223         }
2224         ast_channel_unlock(bridge_channel->chan);
2225
2226         /* Add the jitterbuffer if the channel requires it */
2227         ast_jb_enable_for_channel(bridge_channel->chan);
2228
2229         if (!bridge_channel->bridge->callid) {
2230                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2231         }
2232
2233         if (bridge_channel_internal_push(bridge_channel)) {
2234                 int cause = bridge_channel->bridge->cause;
2235
2236                 ast_bridge_unlock(bridge_channel->bridge);
2237                 ast_bridge_channel_kick(bridge_channel, cause);
2238                 ast_bridge_channel_lock_bridge(bridge_channel);
2239                 ast_bridge_features_remove(bridge_channel->features,
2240                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2241                 bridge_channel_dissolve_check(bridge_channel);
2242                 res = -1;
2243         }
2244         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2245
2246         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2247                 /*
2248                  * Indicate a source change since this channel is entering the
2249                  * bridge system only if the bridge technology is not MULTIMIX
2250                  * capable.  The MULTIMIX technology has already done it.
2251                  */
2252                 if (!(bridge_channel->bridge->technology->capabilities
2253                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2254                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2255                 }
2256
2257                 ast_bridge_unlock(bridge_channel->bridge);
2258                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2259                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2260                         /* Wait for something to do. */
2261                         bridge_channel_wait(bridge_channel);
2262                 }
2263                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2264                 ast_bridge_channel_lock_bridge(bridge_channel);
2265         }
2266
2267         bridge_channel_internal_pull(bridge_channel);
2268         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2269         bridge_reconfigured(bridge_channel->bridge, 1);
2270
2271         ast_bridge_unlock(bridge_channel->bridge);
2272
2273         /* Complete any active hold before exiting the bridge. */
2274         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2275                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2276                         ast_channel_name(bridge_channel->chan));
2277                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2278         }
2279
2280         /* Complete any partial DTMF digit before exiting the bridge. */
2281         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2282                 ast_channel_end_dtmf(bridge_channel->chan,
2283                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2284                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2285         }
2286
2287         /* Indicate a source change since this channel is leaving the bridge system. */
2288         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2289
2290         /*
2291          * Wait for any dual redirect to complete.
2292          *
2293          * Must be done while "still in the bridge" for ast_async_goto()
2294          * to work right.
2295          */
2296         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2297                 sched_yield();
2298         }
2299         ast_channel_lock(bridge_channel->chan);
2300         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2301         ast_channel_unlock(bridge_channel->chan);
2302
2303         ast_bridge_channel_restore_formats(bridge_channel);
2304
2305         return res;
2306 }
2307
2308 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2309                 const char *exten, const char *context,
2310                 transfer_channel_cb new_channel_cb, void *user_data)
2311 {
2312         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2313         struct blind_transfer_data blind_data;
2314
2315         ast_channel_lock(transferee);
2316         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2317         ast_channel_unlock(transferee);
2318
2319         if (!transferee_bridge_channel) {
2320                 return -1;
2321         }
2322
2323         if (new_channel_cb) {
2324                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2325         }
2326
2327         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2328         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2329
2330         return bridge_channel_queue_action_data(transferee_bridge_channel,
2331                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2332 }
2333
2334 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2335                 struct ast_channel *unbridged_chan)
2336 {
2337         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2338         char unbridged_chan_name[AST_CHANNEL_NAME];
2339
2340         ast_channel_lock(transferee);
2341         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2342         ast_channel_unlock(transferee);
2343
2344         if (!transferee_bridge_channel) {
2345                 return -1;
2346         }
2347
2348         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2349                 sizeof(unbridged_chan_name));
2350
2351         return bridge_channel_queue_action_data(transferee_bridge_channel,
2352                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2353                 sizeof(unbridged_chan_name));
2354 }
2355
2356 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2357 {
2358         return bridge_channel->in_bridge
2359                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2360 }
2361
2362 /*!
2363  * \internal
2364  * \brief Close a pipe.
2365  * \since 12.0.0
2366  *
2367  * \param my_pipe What to close.
2368  *
2369  * \return Nothing
2370  */
2371 static void pipe_close(int *my_pipe)
2372 {
2373         if (my_pipe[0] > -1) {
2374                 close(my_pipe[0]);
2375                 my_pipe[0] = -1;
2376         }
2377         if (my_pipe[1] > -1) {
2378                 close(my_pipe[1]);
2379                 my_pipe[1] = -1;
2380         }
2381 }
2382
2383 /*!
2384  * \internal
2385  * \brief Initialize a pipe as non-blocking.
2386  * \since 12.0.0
2387  *
2388  * \param my_pipe What to initialize.
2389  *
2390  * \retval 0 on success.
2391  * \retval -1 on error.
2392  */
2393 static int pipe_init_nonblock(int *my_pipe)
2394 {
2395         int flags;
2396
2397         my_pipe[0] = -1;
2398         my_pipe[1] = -1;
2399         if (pipe(my_pipe)) {
2400                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2401                 return -1;
2402         }
2403         flags = fcntl(my_pipe[0], F_GETFL);
2404         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2405                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2406                         errno, strerror(errno));
2407                 return -1;
2408         }
2409         flags = fcntl(my_pipe[1], F_GETFL);
2410         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2411                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2412                         errno, strerror(errno));
2413                 return -1;
2414         }
2415         return 0;
2416 }
2417
2418 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2419 static void bridge_channel_destroy(void *obj)
2420 {
2421         struct ast_bridge_channel *bridge_channel = obj;
2422         struct ast_frame *fr;
2423
2424         if (bridge_channel->callid) {
2425                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2426         }
2427
2428         if (bridge_channel->bridge) {
2429                 ao2_ref(bridge_channel->bridge, -1);
2430                 bridge_channel->bridge = NULL;
2431         }
2432
2433         /* Flush any unhandled wr_queue frames. */
2434         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2435                 bridge_frame_free(fr);
2436         }
2437         pipe_close(bridge_channel->alert_pipe);
2438
2439         ast_cond_destroy(&bridge_channel->cond);
2440 }
2441
2442 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2443 {
2444         struct ast_bridge_channel *bridge_channel;
2445
2446         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2447         if (!bridge_channel) {
2448                 return NULL;
2449         }
2450         ast_cond_init(&bridge_channel->cond, NULL);
2451         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2452                 ao2_ref(bridge_channel, -1);
2453                 return NULL;
2454         }
2455         if (bridge) {
2456                 bridge_channel->bridge = bridge;
2457                 ao2_ref(bridge_channel->bridge, +1);
2458         }
2459
2460         return bridge_channel;
2461 }