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