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