CI: Various updates to buildAsterisk.sh
[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 #include <signal.h>
36
37 #include "asterisk/heap.h"
38 #include "asterisk/alertpipe.h"
39 #include "asterisk/astobj2.h"
40 #include "asterisk/stringfields.h"
41 #include "asterisk/app.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/timing.h"
45 #include "asterisk/bridge.h"
46 #include "asterisk/bridge_channel.h"
47 #include "asterisk/bridge_after.h"
48 #include "asterisk/bridge_channel_internal.h"
49 #include "asterisk/bridge_internal.h"
50 #include "asterisk/stasis_bridges.h"
51 #include "asterisk/stasis_channels.h"
52 #include "asterisk/musiconhold.h"
53 #include "asterisk/features_config.h"
54 #include "asterisk/parking.h"
55 #include "asterisk/causes.h"
56 #include "asterisk/test.h"
57 #include "asterisk/sem.h"
58 #include "asterisk/stream.h"
59 #include "asterisk/message.h"
60
61 /*!
62  * \brief Used to queue an action frame onto a bridge channel and write an action frame into a bridge.
63  * \since 12.0.0
64  *
65  * \param bridge_channel Which channel work with.
66  * \param action Type of bridge action frame.
67  * \param data Frame payload data to pass.
68  * \param datalen Frame payload data length to pass.
69  *
70  * \retval 0 on success.
71  * \retval -1 on error.
72  */
73 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);
74
75 /*!
76  * \brief Counter used for assigning synchronous bridge action IDs
77  */
78 static int sync_ids;
79
80 /*!
81  * \brief Frame payload for synchronous bridge actions.
82  *
83  * The payload serves as a wrapper around the actual payload of the
84  * frame, with the addition of an id used to find the associated
85  * bridge_sync object.
86  */
87 struct sync_payload {
88         /*! Unique ID for this synchronous action */
89         unsigned int id;
90         /*! Actual frame data to process */
91         unsigned char data[0];
92 };
93
94 /*!
95  * \brief Synchronous bridge action object.
96  *
97  * Synchronous bridge actions require the ability for one thread to wait
98  * and for another thread to indicate that the action has completed. This
99  * structure facilitates that goal by providing synchronization structures.
100  */
101 struct bridge_sync {
102         /*! Unique ID of this synchronization object. Corresponds with ID in synchronous frame payload */
103         unsigned int id;
104         /*! Semaphore used for synchronization */
105         struct ast_sem sem;
106         /*! Pointer to next entry in the list */
107         AST_LIST_ENTRY(bridge_sync) list;
108 };
109
110 /*!
111  * \brief List holding active synchronous action objects.
112  */
113 static AST_RWLIST_HEAD_STATIC(sync_structs, bridge_sync);
114
115 /*!
116  * \brief initialize a synchronous bridge object.
117  *
118  * This both initializes the structure and adds it to the list of
119  * synchronization structures.
120  *
121  * \param sync_struct The synchronization object to initialize.
122  * \param id ID to assign to the synchronization object.
123  */
124 static void bridge_sync_init(struct bridge_sync *sync_struct, unsigned int id)
125 {
126         memset(sync_struct, 0, sizeof(*sync_struct));
127         sync_struct->id = id;
128         ast_sem_init(&sync_struct->sem, 0, 0);
129
130         AST_RWLIST_WRLOCK(&sync_structs);
131         AST_RWLIST_INSERT_TAIL(&sync_structs, sync_struct, list);
132         AST_RWLIST_UNLOCK(&sync_structs);
133 }
134
135 /*!
136  * \brief Clean up a syncrhonization bridge object.
137  *
138  * This frees fields within the synchronization object and removes
139  * it from the list of active synchronization objects.
140  *
141  * Since synchronization objects are stack-allocated, it is vital
142  * that this is called before the synchronization object goes
143  * out of scope.
144  *
145  * \param sync_struct Synchronization object to clean up.
146  */
147 static void bridge_sync_cleanup(struct bridge_sync *sync_struct)
148 {
149         struct bridge_sync *iter;
150
151         AST_RWLIST_WRLOCK(&sync_structs);
152         AST_LIST_TRAVERSE_SAFE_BEGIN(&sync_structs, iter, list) {
153                 if (iter->id == sync_struct->id) {
154                         AST_LIST_REMOVE_CURRENT(list);
155                         break;
156                 }
157         }
158         AST_LIST_TRAVERSE_SAFE_END;
159         AST_RWLIST_UNLOCK(&sync_structs);
160
161         ast_sem_destroy(&sync_struct->sem);
162 }
163
164 /*!
165  * \brief Failsafe for synchronous bridge action waiting.
166  *
167  * When waiting for a synchronous bridge action to complete,
168  * if there is a frame resource leak somewhere, it is possible
169  * that we will never get notified that the synchronous action
170  * completed.
171  *
172  * If a significant amount of time passes, then we will abandon
173  * waiting for the synchrnous bridge action to complete.
174  *
175  * This constant represents the number of milliseconds we will
176  * wait for the bridge action to complete.
177  */
178 #define PLAYBACK_TIMEOUT (600 * 1000)
179
180 /*!
181  * \brief Wait for a synchronous bridge action to complete.
182  *
183  * \param sync_struct Synchronization object corresponding to the bridge action.
184  */
185 static void bridge_sync_wait(struct bridge_sync *sync_struct)
186 {
187         struct timeval timeout_val = ast_tvadd(ast_tvnow(), ast_samp2tv(PLAYBACK_TIMEOUT, 1000));
188         struct timespec timeout_spec = {
189                 .tv_sec = timeout_val.tv_sec,
190                 .tv_nsec = timeout_val.tv_usec * 1000,
191         };
192
193         ast_sem_timedwait(&sync_struct->sem, &timeout_spec);
194 }
195
196 /*!
197  * \brief Signal that waiting for a synchronous bridge action is no longer necessary.
198  *
199  * This may occur for several reasons
200  * \li The synchronous bridge action has completed.
201  * \li The bridge channel has been removed from the bridge.
202  * \li The synchronous bridge action could not be queued.
203  *
204  * \param sync_struct Synchronization object corresponding to the bridge action.
205  */
206 static void bridge_sync_signal(struct bridge_sync *sync_struct)
207 {
208         ast_sem_post(&sync_struct->sem);
209 }
210
211 void ast_bridge_channel_lock_bridge(struct ast_bridge_channel *bridge_channel)
212 {
213         struct ast_bridge *bridge;
214
215         for (;;) {
216                 /* Safely get the bridge pointer */
217                 ast_bridge_channel_lock(bridge_channel);
218                 bridge = bridge_channel->bridge;
219                 ao2_ref(bridge, +1);
220                 ast_bridge_channel_unlock(bridge_channel);
221
222                 /* Lock the bridge and see if it is still the bridge we need to lock. */
223                 ast_bridge_lock(bridge);
224                 if (bridge == bridge_channel->bridge) {
225                         ao2_ref(bridge, -1);
226                         return;
227                 }
228                 ast_bridge_unlock(bridge);
229                 ao2_ref(bridge, -1);
230         }
231 }
232
233 int ast_bridge_channel_notify_talking(struct ast_bridge_channel *bridge_channel, int started_talking)
234 {
235         struct ast_frame action = {
236                 .frametype = AST_FRAME_BRIDGE_ACTION,
237                 .subclass.integer = started_talking
238                         ? BRIDGE_CHANNEL_ACTION_TALKING_START : BRIDGE_CHANNEL_ACTION_TALKING_STOP,
239         };
240
241         return ast_bridge_channel_queue_frame(bridge_channel, &action);
242 }
243
244 /*!
245  * \internal
246  * \brief Poke the bridge_channel thread
247  */
248 static void bridge_channel_poke(struct ast_bridge_channel *bridge_channel)
249 {
250         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
251                 /* Wake up the bridge channel thread. */
252                 ast_queue_frame(bridge_channel->chan, &ast_null_frame);
253         }
254 }
255
256 /*!
257  * \internal
258  * \brief Set actual cause on channel.
259  * \since 12.0.0
260  *
261  * \param chan Channel to set cause.
262  * \param cause Cause to set on channel.
263  *   If cause <= 0 then use cause on channel if cause still <= 0 use AST_CAUSE_NORMAL_CLEARING.
264  *
265  * \return Actual cause set on channel.
266  */
267 static int channel_set_cause(struct ast_channel *chan, int cause)
268 {
269         ast_channel_lock(chan);
270         if (cause <= 0) {
271                 cause = ast_channel_hangupcause(chan);
272                 if (cause <= 0) {
273                         cause = AST_CAUSE_NORMAL_CLEARING;
274                 }
275         }
276         ast_channel_hangupcause_set(chan, cause);
277         ast_channel_unlock(chan);
278         return cause;
279 }
280
281 void ast_bridge_channel_leave_bridge_nolock(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
282 {
283         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
284                 return;
285         }
286
287         ast_debug(1, "Setting %p(%s) state from:%u to:%u\n",
288                 bridge_channel, ast_channel_name(bridge_channel->chan), bridge_channel->state,
289                 new_state);
290
291         channel_set_cause(bridge_channel->chan, cause);
292
293         ast_channel_lock(bridge_channel->chan);
294         ast_bridge_vars_set(bridge_channel->chan, NULL, NULL);
295         ast_channel_unlock(bridge_channel->chan);
296
297         /* Change the state on the bridge channel */
298         bridge_channel->state = new_state;
299
300         bridge_channel_poke(bridge_channel);
301 }
302
303 void ast_bridge_channel_leave_bridge(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
304 {
305         ast_bridge_channel_lock(bridge_channel);
306         ast_bridge_channel_leave_bridge_nolock(bridge_channel, new_state, cause);
307         ast_bridge_channel_unlock(bridge_channel);
308 }
309
310 struct ast_bridge_channel *ast_bridge_channel_peer(struct ast_bridge_channel *bridge_channel)
311 {
312         struct ast_bridge *bridge = bridge_channel->bridge;
313         struct ast_bridge_channel *other = NULL;
314
315         if (bridge_channel->in_bridge && bridge->num_channels == 2) {
316                 AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
317                         if (other != bridge_channel) {
318                                 break;
319                         }
320                 }
321         }
322
323         return other;
324 }
325
326 void ast_bridge_channel_restore_formats(struct ast_bridge_channel *bridge_channel)
327 {
328         ast_assert(bridge_channel->read_format != NULL);
329         ast_assert(bridge_channel->write_format != NULL);
330
331         ast_channel_lock(bridge_channel->chan);
332
333         /* Restore original formats of the channel as they came in */
334         if (ast_format_cmp(ast_channel_readformat(bridge_channel->chan), bridge_channel->read_format) == AST_FORMAT_CMP_NOT_EQUAL) {
335                 ast_debug(1, "Bridge is returning %p(%s) to read format %s\n",
336                         bridge_channel, ast_channel_name(bridge_channel->chan),
337                         ast_format_get_name(bridge_channel->read_format));
338                 if (ast_set_read_format(bridge_channel->chan, bridge_channel->read_format)) {
339                         ast_debug(1, "Bridge failed to return %p(%s) to read format %s\n",
340                                 bridge_channel, ast_channel_name(bridge_channel->chan),
341                                 ast_format_get_name(bridge_channel->read_format));
342                 }
343         }
344         if (ast_format_cmp(ast_channel_writeformat(bridge_channel->chan), bridge_channel->write_format) == AST_FORMAT_CMP_NOT_EQUAL) {
345                 ast_debug(1, "Bridge is returning %p(%s) to write format %s\n",
346                         bridge_channel, ast_channel_name(bridge_channel->chan),
347                         ast_format_get_name(bridge_channel->write_format));
348                 if (ast_set_write_format(bridge_channel->chan, bridge_channel->write_format)) {
349                         ast_debug(1, "Bridge failed to return %p(%s) to write format %s\n",
350                                 bridge_channel, ast_channel_name(bridge_channel->chan),
351                                 ast_format_get_name(bridge_channel->write_format));
352                 }
353         }
354
355         ast_channel_unlock(bridge_channel->chan);
356 }
357
358 struct ast_bridge *ast_bridge_channel_merge_inhibit(struct ast_bridge_channel *bridge_channel, int request)
359 {
360         struct ast_bridge *bridge;
361
362         ast_bridge_channel_lock_bridge(bridge_channel);
363         bridge = bridge_channel->bridge;
364         ao2_ref(bridge, +1);
365         bridge_merge_inhibit_nolock(bridge, request);
366         ast_bridge_unlock(bridge);
367         return bridge;
368 }
369
370 void ast_bridge_channel_update_linkedids(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
371 {
372         struct ast_bridge_channel *other;
373         struct ast_bridge *bridge = bridge_channel->bridge;
374         struct ast_channel *oldest_linkedid_chan = bridge_channel->chan;
375
376         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
377                 if (other == swap) {
378                         continue;
379                 }
380                 oldest_linkedid_chan = ast_channel_internal_oldest_linkedid(
381                         oldest_linkedid_chan, other->chan);
382         }
383
384         ast_channel_lock(bridge_channel->chan);
385         ast_channel_internal_copy_linkedid(bridge_channel->chan, oldest_linkedid_chan);
386         ast_channel_unlock(bridge_channel->chan);
387         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
388                 if (other == swap) {
389                         continue;
390                 }
391                 ast_channel_lock(other->chan);
392                 ast_channel_internal_copy_linkedid(other->chan, oldest_linkedid_chan);
393                 ast_channel_unlock(other->chan);
394         }
395 }
396
397 /*!
398  * \internal
399  * \brief Set dest's empty peeraccount with the src's non-empty accountcode.
400  * \since 12.5.0
401  *
402  * \param dest Channel to update peeraccount.
403  * \param src Channel to get accountcode from.
404  *
405  * \note Both channels are already locked.
406  *
407  * \return Nothing
408  */
409 static void channel_fill_empty_peeraccount(struct ast_channel *dest, struct ast_channel *src)
410 {
411         if (ast_strlen_zero(ast_channel_peeraccount(dest))
412                 && !ast_strlen_zero(ast_channel_accountcode(src))) {
413                 ast_debug(1, "Setting channel %s peeraccount with channel %s accountcode '%s'.\n",
414                         ast_channel_name(dest),
415                         ast_channel_name(src), ast_channel_accountcode(src));
416                 ast_channel_peeraccount_set(dest, ast_channel_accountcode(src));
417         }
418 }
419
420 /*!
421  * \internal
422  * \brief Set dest's empty accountcode with the src's non-empty peeraccount.
423  * \since 12.5.0
424  *
425  * \param dest Channel to update accountcode.
426  * \param src Channel to get peeraccount from.
427  *
428  * \note Both channels are already locked.
429  *
430  * \return Nothing
431  */
432 static void channel_fill_empty_accountcode(struct ast_channel *dest, struct ast_channel *src)
433 {
434         if (ast_strlen_zero(ast_channel_accountcode(dest))
435                 && !ast_strlen_zero(ast_channel_peeraccount(src))) {
436                 ast_debug(1, "Setting channel %s accountcode with channel %s peeraccount '%s'.\n",
437                         ast_channel_name(dest),
438                         ast_channel_name(src), ast_channel_peeraccount(src));
439                 ast_channel_accountcode_set(dest, ast_channel_peeraccount(src));
440         }
441 }
442
443 /*!
444  * \internal
445  * \brief Set empty peeraccount and accountcode in a channel from the other channel.
446  * \since 12.5.0
447  *
448  * \param c0 First bridge channel to update.
449  * \param c1 Second bridge channel to update.
450  *
451  * \note Both channels are already locked.
452  *
453  * \return Nothing
454  */
455 static void channel_set_empty_accountcodes(struct ast_channel *c0, struct ast_channel *c1)
456 {
457         /* Set empty peeraccount from the other channel's accountcode. */
458         channel_fill_empty_peeraccount(c0, c1);
459         channel_fill_empty_peeraccount(c1, c0);
460
461         /* Set empty accountcode from the other channel's peeraccount. */
462         channel_fill_empty_accountcode(c0, c1);
463         channel_fill_empty_accountcode(c1, c0);
464 }
465
466 /*!
467  * \internal
468  * \brief Update dest's peeraccount with the src's different accountcode.
469  * \since 12.5.0
470  *
471  * \param dest Channel to update peeraccount.
472  * \param src Channel to get accountcode from.
473  *
474  * \note Both channels are already locked.
475  *
476  * \return Nothing
477  */
478 static void channel_update_peeraccount(struct ast_channel *dest, struct ast_channel *src)
479 {
480         if (strcmp(ast_channel_accountcode(src), ast_channel_peeraccount(dest))) {
481                 ast_debug(1, "Changing channel %s peeraccount '%s' to match channel %s accountcode '%s'.\n",
482                         ast_channel_name(dest), ast_channel_peeraccount(dest),
483                         ast_channel_name(src), ast_channel_accountcode(src));
484                 ast_channel_peeraccount_set(dest, ast_channel_accountcode(src));
485         }
486 }
487
488 /*!
489  * \internal
490  * \brief Update peeraccounts to match the other channel's accountcode.
491  * \since 12.5.0
492  *
493  * \param c0 First channel to update.
494  * \param c1 Second channel to update.
495  *
496  * \note Both channels are already locked.
497  *
498  * \return Nothing
499  */
500 static void channel_update_peeraccounts(struct ast_channel *c0, struct ast_channel *c1)
501 {
502         channel_update_peeraccount(c0, c1);
503         channel_update_peeraccount(c1, c0);
504 }
505
506 /*!
507  * \internal
508  * \brief Update channel accountcodes because a channel is joining a bridge.
509  * \since 12.5.0
510  *
511  * \param joining Channel joining the bridge.
512  * \param swap Channel being replaced by the joining channel.  May be NULL.
513  *
514  * \note The bridge must be locked prior to calling this function.
515  *
516  * \return Nothing
517  */
518 static void bridge_channel_update_accountcodes_joining(struct ast_bridge_channel *joining, struct ast_bridge_channel *swap)
519 {
520         struct ast_bridge *bridge = joining->bridge;
521         struct ast_bridge_channel *other;
522         unsigned int swap_in_bridge = 0;
523         unsigned int will_be_two_party;
524
525         /*
526          * Only update the peeraccount to match if the joining channel
527          * will make it a two party bridge.
528          */
529         if (bridge->num_channels <= 2 && swap) {
530                 AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
531                         if (other == swap) {
532                                 swap_in_bridge = 1;
533                                 break;
534                         }
535                 }
536         }
537         will_be_two_party = (1 == bridge->num_channels - swap_in_bridge);
538
539         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
540                 if (other == swap) {
541                         continue;
542                 }
543                 ast_assert(joining != other);
544                 ast_channel_lock_both(joining->chan, other->chan);
545                 channel_set_empty_accountcodes(joining->chan, other->chan);
546                 if (will_be_two_party) {
547                         channel_update_peeraccounts(joining->chan, other->chan);
548                 }
549                 ast_channel_unlock(joining->chan);
550                 ast_channel_unlock(other->chan);
551         }
552 }
553
554 /*!
555  * \internal
556  * \brief Update channel peeraccount codes because a channel has left a bridge.
557  * \since 12.5.0
558  *
559  * \param leaving Channel leaving the bridge. (Has already been removed actually)
560  *
561  * \note The bridge must be locked prior to calling this function.
562  *
563  * \return Nothing
564  */
565 static void bridge_channel_update_accountcodes_leaving(struct ast_bridge_channel *leaving)
566 {
567         struct ast_bridge *bridge = leaving->bridge;
568         struct ast_bridge_channel *first;
569         struct ast_bridge_channel *second;
570
571         if (bridge->num_channels != 2 || bridge->dissolved) {
572                 return;
573         }
574
575         first = AST_LIST_FIRST(&bridge->channels);
576         second = AST_LIST_LAST(&bridge->channels);
577         ast_assert(first && first != second);
578         ast_channel_lock_both(first->chan, second->chan);
579         channel_set_empty_accountcodes(first->chan, second->chan);
580         channel_update_peeraccounts(first->chan, second->chan);
581         ast_channel_unlock(second->chan);
582         ast_channel_unlock(first->chan);
583 }
584
585 void ast_bridge_channel_update_accountcodes(struct ast_bridge_channel *joining, struct ast_bridge_channel *leaving)
586 {
587         if (joining) {
588                 bridge_channel_update_accountcodes_joining(joining, leaving);
589         } else {
590                 bridge_channel_update_accountcodes_leaving(leaving);
591         }
592 }
593
594 void ast_bridge_channel_kick(struct ast_bridge_channel *bridge_channel, int cause)
595 {
596         struct ast_bridge_features *features = bridge_channel->features;
597         struct ast_bridge_hook *hook;
598         struct ao2_iterator iter;
599
600         ast_bridge_channel_lock(bridge_channel);
601         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
602                 channel_set_cause(bridge_channel->chan, cause);
603                 cause = 0;
604         }
605         ast_bridge_channel_unlock(bridge_channel);
606
607         /* Run any hangup hooks. */
608         iter = ao2_iterator_init(features->other_hooks, 0);
609         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
610                 int remove_me;
611
612                 if (hook->type != AST_BRIDGE_HOOK_TYPE_HANGUP) {
613                         continue;
614                 }
615                 remove_me = hook->callback(bridge_channel, hook->hook_pvt);
616                 if (remove_me) {
617                         ast_debug(1, "Hangup hook %p is being removed from %p(%s)\n",
618                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
619                         ao2_unlink(features->other_hooks, hook);
620                 }
621         }
622         ao2_iterator_destroy(&iter);
623
624         /* Default hangup action. */
625         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END, cause);
626 }
627
628 /*!
629  * \internal
630  * \brief Write an \ref ast_frame into the bridge
631  * \since 12.0.0
632  *
633  * \param bridge_channel Which channel is queueing the frame.
634  * \param frame The frame to write into the bridge
635  *
636  * \retval 0 on success.
637  * \retval -1 on error.
638  */
639 static int bridge_channel_write_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
640 {
641         const struct ast_control_t38_parameters *t38_parameters;
642         int unmapped_stream_num;
643         int deferred;
644
645         ast_assert(frame->frametype != AST_FRAME_BRIDGE_ACTION_SYNC);
646
647         ast_bridge_channel_lock_bridge(bridge_channel);
648
649         /* Map the frame to the bridge. */
650         if (ast_channel_is_multistream(bridge_channel->chan)) {
651                 unmapped_stream_num = frame->stream_num;
652                 switch (frame->frametype) {
653                 case AST_FRAME_VOICE:
654                 case AST_FRAME_VIDEO:
655                 case AST_FRAME_TEXT:
656                 case AST_FRAME_IMAGE:
657                 case AST_FRAME_RTCP:
658                         /* These frames need to be mapped to an appropriate write stream */
659                         if (frame->stream_num < 0) {
660                                 /* Map to default stream */
661                                 frame->stream_num = -1;
662                                 break;
663                         }
664                         ast_bridge_channel_lock(bridge_channel);
665                         if (frame->stream_num < (int)AST_VECTOR_SIZE(&bridge_channel->stream_map.to_bridge)) {
666                                 frame->stream_num = AST_VECTOR_GET(
667                                         &bridge_channel->stream_map.to_bridge, frame->stream_num);
668                                 if (0 <= frame->stream_num) {
669                                         ast_bridge_channel_unlock(bridge_channel);
670                                         break;
671                                 }
672                         }
673                         ast_bridge_channel_unlock(bridge_channel);
674                         ast_bridge_unlock(bridge_channel->bridge);
675                         /*
676                          * Ignore frame because we don't know how to map the frame
677                          * or the bridge is not expecting any media from that
678                          * stream.
679                          */
680                         return 0;
681                 case AST_FRAME_DTMF_BEGIN:
682                 case AST_FRAME_DTMF_END:
683                         /*
684                          * XXX It makes sense that DTMF could be on any audio stream.
685                          * For now we will only put it on the default audio stream.
686                          */
687                 default:
688                         frame->stream_num = -1;
689                         break;
690                 }
691         } else {
692                 unmapped_stream_num = -1;
693                 frame->stream_num = -1;
694         }
695
696         deferred = bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
697         if (deferred) {
698                 struct ast_frame *dup;
699
700                 dup = ast_frdup(frame);
701                 if (dup) {
702                         /*
703                          * We have to unmap the deferred frame so it comes back
704                          * in like a new frame.
705                          */
706                         dup->stream_num = unmapped_stream_num;
707                         ast_bridge_channel_lock(bridge_channel);
708                         AST_LIST_INSERT_HEAD(&bridge_channel->deferred_queue, dup, frame_list);
709                         ast_bridge_channel_unlock(bridge_channel);
710                 }
711         }
712
713         /* Remember any owed events to the bridge. */
714         switch (frame->frametype) {
715         case AST_FRAME_DTMF_BEGIN:
716                 bridge_channel->owed.dtmf_tv = ast_tvnow();
717                 bridge_channel->owed.dtmf_digit = frame->subclass.integer;
718                 break;
719         case AST_FRAME_DTMF_END:
720                 bridge_channel->owed.dtmf_digit = '\0';
721                 break;
722         case AST_FRAME_CONTROL:
723                 /*
724                  * We explicitly will not remember HOLD/UNHOLD frames because
725                  * things like attended transfers will handle them.
726                  */
727                 switch (frame->subclass.integer) {
728                 case AST_CONTROL_T38_PARAMETERS:
729                         t38_parameters = frame->data.ptr;
730                         switch (t38_parameters->request_response) {
731                         case AST_T38_REQUEST_NEGOTIATE:
732                         case AST_T38_NEGOTIATED:
733                                 bridge_channel->owed.t38_terminate = 1;
734                                 break;
735                         case AST_T38_REQUEST_TERMINATE:
736                         case AST_T38_TERMINATED:
737                         case AST_T38_REFUSED:
738                                 bridge_channel->owed.t38_terminate = 0;
739                                 break;
740                         default:
741                                 break;
742                         }
743                         break;
744                 default:
745                         break;
746                 }
747                 break;
748         default:
749                 break;
750         }
751         ast_bridge_unlock(bridge_channel->bridge);
752
753         /*
754          * Claim successful write to bridge.  If deferred frame
755          * support is added, claim successfully deferred.
756          */
757         return 0;
758 }
759
760 /*!
761  * \internal
762  * \brief Cancel owed events by the channel to the bridge.
763  * \since 13.8.0
764  *
765  * \param bridge_channel Channel that owes events to the bridge.
766  *
767  * \note On entry, the bridge_channel->bridge is already locked.
768  *
769  * \return Nothing
770  */
771 static void bridge_channel_cancel_owed_events(struct ast_bridge_channel *bridge_channel)
772 {
773         bridge_channel->owed.dtmf_digit = '\0';
774         bridge_channel->owed.t38_terminate = 0;
775 }
776
777 void bridge_channel_settle_owed_events(struct ast_bridge *orig_bridge, struct ast_bridge_channel *bridge_channel)
778 {
779         if (bridge_channel->owed.dtmf_digit) {
780                 struct ast_frame frame = {
781                         .frametype = AST_FRAME_DTMF_END,
782                         .subclass.integer = bridge_channel->owed.dtmf_digit,
783                         .src = "Bridge channel owed DTMF",
784                 };
785
786                 frame.len = ast_tvdiff_ms(ast_tvnow(), bridge_channel->owed.dtmf_tv);
787                 if (frame.len < option_dtmfminduration) {
788                         frame.len = option_dtmfminduration;
789                 }
790                 ast_log(LOG_DTMF, "DTMF end '%c' simulated to bridge %s because %s left.  Duration %ld ms.\n",
791                         bridge_channel->owed.dtmf_digit, orig_bridge->uniqueid,
792                         ast_channel_name(bridge_channel->chan), frame.len);
793                 bridge_channel->owed.dtmf_digit = '\0';
794                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
795         }
796         if (bridge_channel->owed.t38_terminate) {
797                 struct ast_control_t38_parameters t38_parameters = {
798                         .request_response = AST_T38_TERMINATED,
799                 };
800                 struct ast_frame frame = {
801                         .frametype = AST_FRAME_CONTROL,
802                         .subclass.integer = AST_CONTROL_T38_PARAMETERS,
803                         .data.ptr = &t38_parameters,
804                         .datalen = sizeof(t38_parameters),
805                         .src = "Bridge channel owed T.38 terminate",
806                 };
807
808                 ast_debug(1, "T.38 terminate simulated to bridge %s because %s left.\n",
809                         orig_bridge->uniqueid, ast_channel_name(bridge_channel->chan));
810                 bridge_channel->owed.t38_terminate = 0;
811                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
812         }
813 }
814
815 void bridge_channel_queue_deferred_frames(struct ast_bridge_channel *bridge_channel)
816 {
817         struct ast_frame *frame;
818
819         ast_bridge_channel_lock(bridge_channel);
820         ast_channel_lock(bridge_channel->chan);
821         while ((frame = AST_LIST_REMOVE_HEAD(&bridge_channel->deferred_queue, frame_list))) {
822                 ast_queue_frame_head(bridge_channel->chan, frame);
823                 ast_frfree(frame);
824         }
825         ast_channel_unlock(bridge_channel->chan);
826         ast_bridge_channel_unlock(bridge_channel);
827 }
828
829 /*!
830  * \internal
831  * \brief Suspend a channel from a bridge.
832  *
833  * \param bridge_channel Channel to suspend.
834  *
835  * \note This function assumes bridge_channel->bridge is locked.
836  *
837  * \return Nothing
838  */
839 void bridge_channel_internal_suspend_nolock(struct ast_bridge_channel *bridge_channel)
840 {
841         bridge_channel->suspended = 1;
842         if (bridge_channel->in_bridge) {
843                 --bridge_channel->bridge->num_active;
844         }
845
846         /* Get technology bridge threads off of the channel. */
847         if (bridge_channel->bridge->technology->suspend) {
848                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
849         }
850 }
851
852 /*!
853  * \internal
854  * \brief Suspend a channel from a bridge.
855  *
856  * \param bridge_channel Channel to suspend.
857  *
858  * \return Nothing
859  */
860 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
861 {
862         ast_bridge_channel_lock_bridge(bridge_channel);
863         bridge_channel_internal_suspend_nolock(bridge_channel);
864         ast_bridge_unlock(bridge_channel->bridge);
865 }
866
867 /*!
868  * \internal
869  * \brief Unsuspend a channel from a bridge.
870  *
871  * \param bridge_channel Channel to unsuspend.
872  *
873  * \note This function assumes bridge_channel->bridge is locked.
874  *
875  * \return Nothing
876  */
877 void bridge_channel_internal_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
878 {
879         bridge_channel->suspended = 0;
880         if (bridge_channel->in_bridge) {
881                 ++bridge_channel->bridge->num_active;
882         }
883
884         /* Wake technology bridge threads to take care of channel again. */
885         if (bridge_channel->bridge->technology->unsuspend) {
886                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
887         }
888
889         /* Wake suspended channel. */
890         ast_bridge_channel_lock(bridge_channel);
891         ast_cond_signal(&bridge_channel->cond);
892         ast_bridge_channel_unlock(bridge_channel);
893 }
894
895 /*!
896  * \internal
897  * \brief Unsuspend a channel from a bridge.
898  *
899  * \param bridge_channel Channel to unsuspend.
900  *
901  * \return Nothing
902  */
903 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
904 {
905         ast_bridge_channel_lock_bridge(bridge_channel);
906         bridge_channel_internal_unsuspend_nolock(bridge_channel);
907         ast_bridge_unlock(bridge_channel->bridge);
908 }
909
910 /*!
911  * \internal
912  * \brief Queue an action frame onto the bridge channel with data.
913  * \since 12.0.0
914  *
915  * \param bridge_channel Which channel to queue the frame onto.
916  * \param action Type of bridge action frame.
917  * \param data Frame payload data to pass.
918  * \param datalen Frame payload data length to pass.
919  *
920  * \retval 0 on success.
921  * \retval -1 on error.
922  */
923 static int bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel,
924         enum bridge_channel_action_type action, const void *data, size_t datalen)
925 {
926         struct ast_frame frame = {
927                 .frametype = AST_FRAME_BRIDGE_ACTION,
928                 .subclass.integer = action,
929                 .datalen = datalen,
930                 .data.ptr = (void *) data,
931         };
932
933         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
934 }
935
936 /*!
937  * \internal
938  * \brief Queue an action frame onto the bridge channel with data synchronously.
939  * \since 12.2.0
940  *
941  * The function will not return until the queued frame is freed.
942  *
943  * \param bridge_channel Which channel to queue the frame onto.
944  * \param action Type of bridge action frame.
945  * \param data Frame payload data to pass.
946  * \param datalen Frame payload data length to pass.
947  *
948  * \retval 0 on success.
949  * \retval -1 on error.
950  */
951 static int bridge_channel_queue_action_data_sync(struct ast_bridge_channel *bridge_channel,
952         enum bridge_channel_action_type action, const void *data, size_t datalen)
953 {
954         struct sync_payload *sync_payload;
955         int sync_payload_len = sizeof(*sync_payload) + datalen;
956         struct bridge_sync sync_struct;
957         struct ast_frame frame = {
958                 .frametype = AST_FRAME_BRIDGE_ACTION_SYNC,
959                 .subclass.integer = action,
960         };
961
962         /* Make sure we don't end up trying to wait on ourself to deliver the frame */
963         ast_assert(!pthread_equal(pthread_self(), bridge_channel->thread));
964
965         sync_payload = ast_alloca(sync_payload_len);
966         sync_payload->id = ast_atomic_fetchadd_int(&sync_ids, +1);
967         memcpy(sync_payload->data, data, datalen);
968
969         frame.datalen = sync_payload_len;
970         frame.data.ptr = sync_payload;
971
972         bridge_sync_init(&sync_struct, sync_payload->id);
973         if (ast_bridge_channel_queue_frame(bridge_channel, &frame)) {
974                 bridge_sync_cleanup(&sync_struct);
975                 return -1;
976         }
977
978         bridge_sync_wait(&sync_struct);
979         bridge_sync_cleanup(&sync_struct);
980         return 0;
981 }
982 /*!
983  * \internal
984  * \brief Write an action frame onto the bridge channel with data.
985  * \since 12.0.0
986  *
987  * \param bridge_channel Which channel to queue the frame onto.
988  * \param action Type of bridge action frame.
989  * \param data Frame payload data to pass.
990  * \param datalen Frame payload data length to pass.
991  *
992  * \retval 0 on success.
993  * \retval -1 on error.
994  */
995 static int bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel,
996         enum bridge_channel_action_type action, const void *data, size_t datalen)
997 {
998         struct ast_frame frame = {
999                 .frametype = AST_FRAME_BRIDGE_ACTION,
1000                 .subclass.integer = action,
1001                 .datalen = datalen,
1002                 .data.ptr = (void *) data,
1003         };
1004
1005         return bridge_channel_write_frame(bridge_channel, &frame);
1006 }
1007
1008 static void bridge_frame_free(struct ast_frame *frame)
1009 {
1010         if (frame->frametype == AST_FRAME_BRIDGE_ACTION_SYNC) {
1011                 struct sync_payload *sync_payload = frame->data.ptr;
1012                 struct bridge_sync *sync;
1013
1014                 AST_RWLIST_RDLOCK(&sync_structs);
1015                 AST_RWLIST_TRAVERSE(&sync_structs, sync, list) {
1016                         if (sync->id == sync_payload->id) {
1017                                 break;
1018                         }
1019                 }
1020                 if (sync) {
1021                         bridge_sync_signal(sync);
1022                 }
1023                 AST_RWLIST_UNLOCK(&sync_structs);
1024         }
1025
1026         ast_frfree(frame);
1027 }
1028
1029 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1030 {
1031         struct ast_frame *dup;
1032
1033         if (bridge_channel->suspended
1034                 /* Also defer DTMF frames. */
1035                 && fr->frametype != AST_FRAME_DTMF_BEGIN
1036                 && fr->frametype != AST_FRAME_DTMF_END
1037                 && !ast_is_deferrable_frame(fr)) {
1038                 /* Drop non-deferable frames when suspended. */
1039                 return 0;
1040         }
1041         if (fr->frametype == AST_FRAME_NULL) {
1042                 /* "Accept" the frame and discard it. */
1043                 return 0;
1044         }
1045
1046         dup = ast_frdup(fr);
1047         if (!dup) {
1048                 return -1;
1049         }
1050
1051         ast_bridge_channel_lock(bridge_channel);
1052         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1053                 /* Drop frames on channels leaving the bridge. */
1054                 ast_bridge_channel_unlock(bridge_channel);
1055                 bridge_frame_free(dup);
1056                 return 0;
1057         }
1058
1059         if (DEBUG_ATLEAST(1)) {
1060                 if (fr->frametype == AST_FRAME_TEXT) {
1061                         ast_log(LOG_DEBUG, "Queuing TEXT frame to '%s': %*.s\n", ast_channel_name(bridge_channel->chan),
1062                                 fr->datalen, (char *)fr->data.ptr);
1063                 } else if (fr->frametype == AST_FRAME_TEXT_DATA) {
1064                         struct ast_msg_data *msg = fr->data.ptr;
1065                         ast_log(LOG_DEBUG, "Queueing TEXT_DATA frame from '%s' to '%s:%s': %s\n",
1066                                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_FROM),
1067                                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_TO),
1068                                 ast_channel_name(bridge_channel->chan),
1069                                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_BODY));
1070                 }
1071         }
1072
1073         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
1074         if (ast_alertpipe_write(bridge_channel->alert_pipe)) {
1075                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
1076                         bridge_channel, ast_channel_name(bridge_channel->chan));
1077         }
1078         ast_bridge_channel_unlock(bridge_channel);
1079         return 0;
1080 }
1081
1082 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1083 {
1084         struct ast_bridge_channel *cur;
1085         int not_written = -1;
1086
1087         if (frame->frametype == AST_FRAME_NULL) {
1088                 /* "Accept" the frame and discard it. */
1089                 return 0;
1090         }
1091
1092         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
1093                 if (cur == bridge_channel) {
1094                         continue;
1095                 }
1096                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
1097                         not_written = 0;
1098                 }
1099         }
1100         return not_written;
1101 }
1102
1103 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)
1104 {
1105         struct ast_frame frame = {
1106                 .frametype = AST_FRAME_CONTROL,
1107                 .subclass.integer = control,
1108                 .datalen = datalen,
1109                 .data.ptr = (void *) data,
1110         };
1111
1112         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
1113 }
1114
1115 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)
1116 {
1117         struct ast_frame frame = {
1118                 .frametype = AST_FRAME_CONTROL,
1119                 .subclass.integer = control,
1120                 .datalen = datalen,
1121                 .data.ptr = (void *) data,
1122         };
1123
1124         return bridge_channel_write_frame(bridge_channel, &frame);
1125 }
1126
1127 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
1128 {
1129         struct ast_json *blob;
1130         int res;
1131         size_t datalen;
1132
1133         if (!ast_strlen_zero(moh_class)) {
1134                 datalen = strlen(moh_class) + 1;
1135
1136                 blob = ast_json_pack("{s: s}",
1137                         "musicclass", moh_class);
1138         } else {
1139                 moh_class = NULL;
1140                 datalen = 0;
1141                 blob = NULL;
1142         }
1143
1144         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
1145
1146         res = ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
1147                 moh_class, datalen);
1148
1149         ast_json_unref(blob);
1150         return res;
1151 }
1152
1153 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
1154 {
1155         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
1156
1157         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
1158 }
1159
1160 /*!
1161  * \internal
1162  * \brief Helper function to kick off a PBX app on a bridge_channel
1163  */
1164 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
1165 {
1166         int res = 0;
1167
1168         if (!strcasecmp("Gosub", app_name)) {
1169                 ast_app_exec_sub(NULL, chan, app_args, 0);
1170         } else if (!strcasecmp("Macro", app_name)) {
1171                 ast_app_exec_macro(NULL, chan, app_args);
1172         } else {
1173                 struct ast_app *app;
1174
1175                 app = pbx_findapp(app_name);
1176                 if (!app) {
1177                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
1178                 } else {
1179                         struct ast_str *substituted_args = ast_str_create(16);
1180
1181                         if (substituted_args) {
1182                                 ast_str_substitute_variables(&substituted_args, 0, chan, app_args);
1183                                 res = pbx_exec(chan, app, ast_str_buffer(substituted_args));
1184                                 ast_free(substituted_args);
1185                         } else {
1186                                 ast_log(LOG_WARNING, "Could not substitute application argument variables for %s\n", app_name);
1187                                 res = pbx_exec(chan, app, app_args);
1188                         }
1189                 }
1190         }
1191         return res;
1192 }
1193
1194 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1195 {
1196         if (moh_class) {
1197                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1198         }
1199         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
1200                 /* Break the bridge if the app returns non-zero. */
1201                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1202         }
1203         if (moh_class) {
1204                 ast_bridge_channel_write_unhold(bridge_channel);
1205         }
1206 }
1207
1208 struct bridge_run_app {
1209         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
1210         int moh_offset;
1211         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
1212         int app_args_offset;
1213         /*! Application name to run. */
1214         char app_name[0];
1215 };
1216
1217 /*!
1218  * \internal
1219  * \brief Handle the run application bridge action.
1220  * \since 12.0.0
1221  *
1222  * \param bridge_channel Which channel to run the application on.
1223  * \param data Action frame data to run the application.
1224  *
1225  * \return Nothing
1226  */
1227 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
1228 {
1229         ast_bridge_channel_run_app(bridge_channel, data->app_name,
1230                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
1231                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
1232 }
1233
1234 /*!
1235  * \internal
1236  * \brief Marshal an application to be executed on a bridge_channel
1237  */
1238 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
1239         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1240 {
1241         struct bridge_run_app *app_data;
1242         size_t len_name = strlen(app_name) + 1;
1243         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
1244         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1245         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
1246
1247         /* Fill in application run frame data. */
1248         app_data = alloca(len_data);
1249         app_data->app_args_offset = len_args ? len_name : 0;
1250         app_data->moh_offset = len_moh ? len_name + len_args : 0;
1251         strcpy(app_data->app_name, app_name);/* Safe */
1252         if (len_args) {
1253                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
1254         }
1255         if (moh_class) {
1256                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
1257         }
1258
1259         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
1260 }
1261
1262 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1263 {
1264         return payload_helper_app(bridge_channel_write_action_data,
1265                 bridge_channel, app_name, app_args, moh_class);
1266 }
1267
1268 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1269 {
1270         return payload_helper_app(bridge_channel_queue_action_data,
1271                 bridge_channel, app_name, app_args, moh_class);
1272 }
1273
1274 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)
1275 {
1276         if (moh_class) {
1277                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1278         }
1279         if (custom_play) {
1280                 custom_play(bridge_channel, playfile);
1281         } else {
1282                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
1283         }
1284         if (moh_class) {
1285                 ast_bridge_channel_write_unhold(bridge_channel);
1286         }
1287
1288         /*
1289          * It may be necessary to resume music on hold after we finish
1290          * playing the announcment.
1291          */
1292         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
1293                 const char *latest_musicclass;
1294
1295                 ast_channel_lock(bridge_channel->chan);
1296                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
1297                 ast_channel_unlock(bridge_channel->chan);
1298                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
1299         }
1300 }
1301
1302 struct bridge_playfile {
1303         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
1304         ast_bridge_custom_play_fn custom_play;
1305         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
1306         int moh_offset;
1307         /*! Filename to play. */
1308         char playfile[0];
1309 };
1310
1311 /*!
1312  * \internal
1313  * \brief Handle the playfile bridge action.
1314  * \since 12.0.0
1315  *
1316  * \param bridge_channel Which channel to play a file on.
1317  * \param payload Action frame payload to play a file.
1318  *
1319  * \return Nothing
1320  */
1321 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
1322 {
1323         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
1324                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
1325 }
1326
1327 /*!
1328  * \internal
1329  * \brief Marshal a file to be played on a bridge_channel
1330  */
1331 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
1332         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1333 {
1334         struct bridge_playfile *payload;
1335         size_t len_name = strlen(playfile) + 1;
1336         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1337         size_t len_payload = sizeof(*payload) + len_name + len_moh;
1338
1339         /* Fill in play file frame data. */
1340         payload = ast_alloca(len_payload);
1341         payload->custom_play = custom_play;
1342         payload->moh_offset = len_moh ? len_name : 0;
1343         strcpy(payload->playfile, playfile);/* Safe */
1344         if (moh_class) {
1345                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
1346         }
1347
1348         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
1349 }
1350
1351 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)
1352 {
1353         return payload_helper_playfile(bridge_channel_write_action_data,
1354                 bridge_channel, custom_play, playfile, moh_class);
1355 }
1356
1357 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)
1358 {
1359         return payload_helper_playfile(bridge_channel_queue_action_data,
1360                 bridge_channel, custom_play, playfile, moh_class);
1361 }
1362
1363 int ast_bridge_channel_queue_playfile_sync(struct ast_bridge_channel *bridge_channel,
1364                 ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1365 {
1366         return payload_helper_playfile(bridge_channel_queue_action_data_sync,
1367                 bridge_channel, custom_play, playfile, moh_class);
1368 }
1369
1370 struct bridge_custom_callback {
1371         /*! Call this function on the bridge channel thread. */
1372         ast_bridge_custom_callback_fn callback;
1373         /*! Size of the payload if it exists.  A number otherwise. */
1374         size_t payload_size;
1375         /*! Option flags determining how callback is called. */
1376         unsigned int flags;
1377         /*! Nonzero if the payload exists. */
1378         char payload_exists;
1379         /*! Payload to give to callback. */
1380         char payload[0];
1381 };
1382
1383 /*!
1384  * \internal
1385  * \brief Handle the do custom callback bridge action.
1386  * \since 12.0.0
1387  *
1388  * \param bridge_channel Which channel to call the callback on.
1389  * \param data Action frame data to call the callback.
1390  *
1391  * \return Nothing
1392  */
1393 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
1394 {
1395         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1396                 bridge_channel_suspend(bridge_channel);
1397                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1398         }
1399         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
1400         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1401                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1402                 bridge_channel_unsuspend(bridge_channel);
1403         }
1404 }
1405
1406 /*!
1407  * \internal
1408  * \brief Marshal a custom callback function to be called on a bridge_channel
1409  */
1410 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
1411         struct ast_bridge_channel *bridge_channel,
1412         enum ast_bridge_channel_custom_callback_option flags,
1413         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1414 {
1415         struct bridge_custom_callback *cb_data;
1416         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
1417
1418         /* Sanity check. */
1419         if (!callback) {
1420                 ast_assert(0);
1421                 return -1;
1422         }
1423
1424         /* Fill in custom callback frame data. */
1425         cb_data = alloca(len_data);
1426         cb_data->callback = callback;
1427         cb_data->payload_size = payload_size;
1428         cb_data->flags = flags;
1429         cb_data->payload_exists = payload && payload_size;
1430         if (cb_data->payload_exists) {
1431                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
1432         }
1433
1434         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
1435 }
1436
1437 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
1438         enum ast_bridge_channel_custom_callback_option flags,
1439         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1440 {
1441         return payload_helper_cb(bridge_channel_write_action_data,
1442                 bridge_channel, flags, callback, payload, payload_size);
1443 }
1444
1445 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
1446         enum ast_bridge_channel_custom_callback_option flags,
1447         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1448 {
1449         return payload_helper_cb(bridge_channel_queue_action_data,
1450                 bridge_channel, flags, callback, payload, payload_size);
1451 }
1452
1453 struct bridge_park {
1454         int parker_uuid_offset;
1455         int app_data_offset;
1456         /* buffer used for holding those strings */
1457         char parkee_uuid[0];
1458 };
1459
1460 /*!
1461  * \internal
1462  * \brief Park a bridge_cahnnel
1463  */
1464 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
1465 {
1466         if (!ast_parking_provider_registered()) {
1467                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
1468                         ast_channel_name(bridge_channel->chan));
1469                 return;
1470         }
1471
1472         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
1473                 &payload->parkee_uuid[payload->parker_uuid_offset],
1474                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
1475                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
1476                         ast_channel_name(bridge_channel->chan));
1477         }
1478 }
1479
1480 /*!
1481  * \internal
1482  * \brief Marshal a park action onto a bridge_channel
1483  */
1484 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
1485         struct ast_bridge_channel *bridge_channel,
1486         const char *parkee_uuid,
1487         const char *parker_uuid,
1488         const char *app_data)
1489 {
1490         struct bridge_park *payload;
1491         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1492         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1493         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1494         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1495
1496         payload = alloca(len_payload);
1497         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1498         payload->parker_uuid_offset = len_parkee_uuid;
1499         strcpy(payload->parkee_uuid, parkee_uuid);
1500         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1501         if (app_data) {
1502                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1503         }
1504
1505         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
1506 }
1507
1508 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1509 {
1510         return payload_helper_park(bridge_channel_write_action_data,
1511                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1512 }
1513
1514 /*!
1515  * \internal
1516  * \brief Handle bridge channel interval expiration.
1517  * \since 12.0.0
1518  *
1519  * \param bridge_channel Channel to run expired intervals on.
1520  *
1521  * \return Nothing
1522  */
1523 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
1524 {
1525         struct ast_heap *interval_hooks;
1526         struct ast_bridge_hook_timer *hook;
1527         struct timeval start;
1528         int chan_suspended = 0;
1529
1530         interval_hooks = bridge_channel->features->interval_hooks;
1531         ast_heap_wrlock(interval_hooks);
1532         start = ast_tvnow();
1533         while ((hook = ast_heap_peek(interval_hooks, 1))) {
1534                 int interval;
1535                 unsigned int execution_time;
1536
1537                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1538                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1539                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1540                         break;
1541                 }
1542                 ao2_ref(hook, +1);
1543                 ast_heap_unlock(interval_hooks);
1544
1545                 if (!chan_suspended
1546                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1547                         chan_suspended = 1;
1548                         bridge_channel_suspend(bridge_channel);
1549                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1550                 }
1551
1552                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1553                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1554                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1555
1556                 ast_heap_wrlock(interval_hooks);
1557                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1558                         || !ast_heap_remove(interval_hooks, hook)) {
1559                         /* Interval hook is already removed from the bridge_channel. */
1560                         ao2_ref(hook, -1);
1561                         continue;
1562                 }
1563                 ao2_ref(hook, -1);
1564
1565                 if (interval < 0) {
1566                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1567                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1568                         ao2_ref(hook, -1);
1569                         continue;
1570                 }
1571                 if (interval) {
1572                         /* Set new interval for the hook. */
1573                         hook->timer.interval = interval;
1574                 }
1575
1576                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1577                         hook, hook->timer.interval, bridge_channel,
1578                         ast_channel_name(bridge_channel->chan));
1579
1580                 /* resetting start */
1581                 start = ast_tvnow();
1582
1583                 /*
1584                  * Resetup the interval hook for the next interval.  We may need
1585                  * to skip over any missed intervals because the hook was
1586                  * delayed or took too long.
1587                  */
1588                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1589                 while (hook->timer.interval < execution_time) {
1590                         execution_time -= hook->timer.interval;
1591                 }
1592                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1593                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1594
1595                 if (ast_heap_push(interval_hooks, hook)) {
1596                         /* Could not push the hook back onto the heap. */
1597                         ao2_ref(hook, -1);
1598                 }
1599         }
1600         ast_heap_unlock(interval_hooks);
1601
1602         if (chan_suspended) {
1603                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1604                 bridge_channel_unsuspend(bridge_channel);
1605         }
1606 }
1607
1608 /*!
1609  * \internal
1610  * \brief Write a DTMF stream out to a channel
1611  */
1612 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1613 {
1614         return bridge_channel_write_action_data(bridge_channel,
1615                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1616 }
1617
1618 /*!
1619  * \internal
1620  * \brief Indicate to the testsuite a feature was successfully detected.
1621  *
1622  * Currently, this function only will relay built-in features to the testsuite,
1623  * but it could be modified to detect applicationmap items should the need arise.
1624  *
1625  * \param chan The channel that activated the feature
1626  * \param dtmf The DTMF sequence entered to activate the feature
1627  */
1628 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1629 {
1630 #ifdef TEST_FRAMEWORK
1631         char *feature = "unknown";
1632         struct ast_featuremap_config *featuremap;
1633         struct ast_features_xfer_config *xfer;
1634
1635         ast_channel_lock(chan);
1636         featuremap = ast_get_chan_featuremap_config(chan);
1637         xfer = ast_get_chan_features_xfer_config(chan);
1638         ast_channel_unlock(chan);
1639
1640         if (featuremap) {
1641                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1642                         feature = "blindxfer";
1643                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1644                         feature = "atxfer";
1645                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1646                         feature = "disconnect";
1647                 } else if (!strcmp(dtmf, featuremap->automon)) {
1648                         feature = "automon";
1649                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1650                         feature = "automixmon";
1651                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1652                         feature = "parkcall";
1653                 }
1654         }
1655         if (xfer) {
1656                 if (!strcmp(dtmf, xfer->atxferthreeway)) {
1657                         feature = "atxferthreeway";
1658                 }
1659         }
1660
1661         ao2_cleanup(featuremap);
1662         ao2_cleanup(xfer);
1663
1664         ast_test_suite_event_notify("FEATURE_DETECTION",
1665                         "Result: success\r\n"
1666                         "Feature: %s", feature);
1667 #endif /* TEST_FRAMEWORK */
1668 }
1669
1670 static int bridge_channel_feature_digit_add(
1671         struct ast_bridge_channel *bridge_channel, int digit, size_t dtmf_len)
1672 {
1673         if (dtmf_len < ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) - 1) {
1674                 /* Add the new digit to the DTMF string so we can do our matching */
1675                 bridge_channel->dtmf_hook_state.collected[dtmf_len++] = digit;
1676                 bridge_channel->dtmf_hook_state.collected[dtmf_len] = '\0';
1677
1678                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1679                           bridge_channel, ast_channel_name(bridge_channel->chan),
1680                           bridge_channel->dtmf_hook_state.collected);
1681         }
1682
1683         return dtmf_len;
1684 }
1685
1686 static unsigned int bridge_channel_feature_digit_timeout(struct ast_bridge_channel *bridge_channel)
1687 {
1688         unsigned int digit_timeout;
1689         struct ast_features_general_config *gen_cfg;
1690
1691         /* Determine interdigit timeout */
1692         ast_channel_lock(bridge_channel->chan);
1693         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1694         ast_channel_unlock(bridge_channel->chan);
1695
1696         if (!gen_cfg) {
1697                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1698                 return 3000; /* Pick a reasonable failsafe timeout in ms */
1699         }
1700
1701         digit_timeout = gen_cfg->featuredigittimeout;
1702         ao2_ref(gen_cfg, -1);
1703
1704         return digit_timeout;
1705 }
1706
1707 void ast_bridge_channel_feature_digit_add(struct ast_bridge_channel *bridge_channel, int digit)
1708 {
1709         if (digit) {
1710                 bridge_channel_feature_digit_add(
1711                         bridge_channel, digit, strlen(bridge_channel->dtmf_hook_state.collected));
1712         }
1713 }
1714
1715 void ast_bridge_channel_feature_digit(struct ast_bridge_channel *bridge_channel, int digit)
1716 {
1717         struct ast_bridge_features *features = bridge_channel->features;
1718         struct ast_bridge_hook_dtmf *hook = NULL;
1719         size_t dtmf_len;
1720
1721         struct sanity_check_of_dtmf_size {
1722                 char check[1 / (ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) == ARRAY_LEN(hook->dtmf.code))];
1723         };
1724
1725         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1726         if (!dtmf_len && !digit) {
1727                 /* Nothing to do */
1728                 return;
1729         }
1730
1731         if (digit) {
1732                 dtmf_len = bridge_channel_feature_digit_add(bridge_channel, digit, dtmf_len);
1733         }
1734
1735         while (digit) {
1736                 /* See if a DTMF feature hook matches or can match */
1737                 hook = ao2_find(features->dtmf_hooks, bridge_channel->dtmf_hook_state.collected,
1738                         OBJ_SEARCH_PARTIAL_KEY);
1739                 if (!hook) {
1740                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1741                                 bridge_channel, ast_channel_name(bridge_channel->chan),
1742                                 bridge_channel->dtmf_hook_state.collected);
1743                         break;
1744                 } else if (dtmf_len != strlen(hook->dtmf.code)) {
1745                         unsigned int digit_timeout;
1746                         /* Need more digits to match */
1747                         ao2_ref(hook, -1);
1748                         digit_timeout = bridge_channel_feature_digit_timeout(bridge_channel);
1749                         bridge_channel->dtmf_hook_state.interdigit_timeout =
1750                                 ast_tvadd(ast_tvnow(), ast_samp2tv(digit_timeout, 1000));
1751                         return;
1752                 } else {
1753                         int remove_me;
1754                         int already_suspended;
1755
1756                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1757                                 hook, bridge_channel->dtmf_hook_state.collected, bridge_channel,
1758                                 ast_channel_name(bridge_channel->chan));
1759
1760                         /*
1761                          * Clear the collected digits before executing the hook
1762                          * in case the hook starts another sequence.
1763                          */
1764                         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1765
1766                         ast_bridge_channel_lock_bridge(bridge_channel);
1767                         already_suspended = bridge_channel->suspended;
1768                         if (!already_suspended) {
1769                                 bridge_channel_internal_suspend_nolock(bridge_channel);
1770                         }
1771                         ast_bridge_unlock(bridge_channel->bridge);
1772                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1773
1774                         /* Execute the matched hook on this channel. */
1775                         remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1776                         if (remove_me) {
1777                                 ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1778                                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1779                                 ao2_unlink(features->dtmf_hooks, hook);
1780                         }
1781                         testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1782                         ao2_ref(hook, -1);
1783
1784                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1785                         if (!already_suspended) {
1786                                 bridge_channel_unsuspend(bridge_channel);
1787                         }
1788
1789                         /*
1790                          * If we are handing the channel off to an external hook for
1791                          * ownership, we are not guaranteed what kind of state it will
1792                          * come back in.  If the channel hungup, we need to detect that
1793                          * here if the hook did not already change the state.
1794                          */
1795                         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1796                                 ast_bridge_channel_kick(bridge_channel, 0);
1797                                 bridge_channel->dtmf_hook_state.collected[0] = '\0';
1798                                 return;
1799                         }
1800
1801                         /* if there is dtmf that has been collected then loop back through,
1802                            but set digit to -1 so it doesn't try to do an add since the dtmf
1803                            is already in the buffer */
1804                         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1805                         if (!dtmf_len) {
1806                                 return;
1807                         }
1808                 }
1809         }
1810
1811         if (!digit) {
1812                 ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1813                         bridge_channel, ast_channel_name(bridge_channel->chan));
1814         }
1815
1816         /* Timeout or DTMF digit didn't allow a match with any hooks. */
1817         if (features->dtmf_passthrough) {
1818                 /* Stream the collected DTMF to the other channels. */
1819                 bridge_channel_write_dtmf_stream(bridge_channel,
1820                         bridge_channel->dtmf_hook_state.collected);
1821         }
1822         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1823
1824         ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1825 }
1826
1827 /*!
1828  * \internal
1829  * \brief Handle bridge channel DTMF feature timeout expiration.
1830  * \since 12.8.0
1831  *
1832  * \param bridge_channel Channel to check expired interdigit timer on.
1833  *
1834  * \return Nothing
1835  */
1836 static void bridge_channel_handle_feature_timeout(struct ast_bridge_channel *bridge_channel)
1837 {
1838         if (!bridge_channel->dtmf_hook_state.collected[0]
1839                 || 0 < ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
1840                         ast_tvnow())) {
1841                 /* Not within a sequence or not timed out. */
1842                 return;
1843         }
1844
1845         ast_bridge_channel_feature_digit(bridge_channel, 0);
1846 }
1847
1848 /*!
1849  * \internal
1850  * \brief Indicate that a bridge_channel is talking
1851  */
1852 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1853 {
1854         struct ast_bridge_features *features = bridge_channel->features;
1855         struct ast_bridge_hook *hook;
1856         struct ao2_iterator iter;
1857
1858         /* Run any talk detection hooks. */
1859         iter = ao2_iterator_init(features->other_hooks, 0);
1860         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1861                 int remove_me;
1862                 ast_bridge_talking_indicate_callback talk_cb;
1863
1864                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1865                         continue;
1866                 }
1867                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1868                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1869                 if (remove_me) {
1870                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1871                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1872                         ao2_unlink(features->other_hooks, hook);
1873                 }
1874         }
1875         ao2_iterator_destroy(&iter);
1876 }
1877
1878 /*! \brief Internal function that plays back DTMF on a bridge channel */
1879 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1880 {
1881         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1882                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1883         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1884 }
1885
1886 /*! \brief Data specifying where a blind transfer is going to */
1887 struct blind_transfer_data {
1888         char exten[AST_MAX_EXTENSION];
1889         char context[AST_MAX_CONTEXT];
1890 };
1891
1892 /*!
1893  * \internal
1894  * \brief Execute after bridge actions on a channel when it leaves a bridge
1895  */
1896 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1897 {
1898         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1899         struct ast_party_connected_line connected_target;
1900         unsigned char connected_line_data[1024];
1901         int payload_size;
1902
1903         ast_party_connected_line_init(&connected_target);
1904
1905         ast_channel_lock(chan_target);
1906         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1907         ast_channel_unlock(chan_target);
1908         ast_party_id_reset(&connected_target.priv);
1909
1910         if (ast_channel_move(chan_target, chan_bridged)) {
1911                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1912                 ast_party_connected_line_free(&connected_target);
1913                 return;
1914         }
1915
1916         /* The ast_channel_move function will end up updating the connected line information
1917          * on chan_target to the value we have here, but will not inform it. To ensure that
1918          * AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO is executed we wipe it away here. If
1919          * we don't do this then the change will be considered redundant, since the connected
1920          * line information is already there (despite the channel not being told).
1921          */
1922         ast_channel_lock(chan_target);
1923         ast_party_connected_line_free(ast_channel_connected_indicated(chan_target));
1924         ast_party_connected_line_init(ast_channel_connected_indicated(chan_target));
1925         ast_channel_unlock(chan_target);
1926
1927         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1928                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1929                 struct ast_control_read_action_payload *frame_payload;
1930                 int frame_size;
1931
1932                 frame_size = payload_size + sizeof(*frame_payload);
1933                 frame_payload = ast_alloca(frame_size);
1934                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1935                 frame_payload->payload_size = payload_size;
1936                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1937                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1938         }
1939
1940         /* A connected line update is queued so that if chan_target is remotely involved with
1941          * anything (such as dialing a channel) the other channel(s) will be informed of the
1942          * new channel they are involved with.
1943          */
1944         ast_channel_lock(chan_target);
1945         ast_connected_line_copy_from_caller(&connected_target, ast_channel_caller(chan_target));
1946         ast_channel_queue_connected_line_update(chan_target, &connected_target, NULL);
1947         ast_channel_unlock(chan_target);
1948
1949         ast_party_connected_line_free(&connected_target);
1950 }
1951
1952 /*!
1953  * \internal
1954  * \brief Execute logic to cleanup when after bridge fails
1955  */
1956 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1957 {
1958         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1959
1960         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1961                 ast_bridge_after_cb_reason_string(reason));
1962         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1963 }
1964
1965 /*!
1966  * \internal
1967  * \brief Perform a blind transfer on a channel in a bridge
1968  */
1969 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1970                 struct blind_transfer_data *blind_data)
1971 {
1972         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1973         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1974 }
1975
1976 /*!
1977  * \internal
1978  * \brief Perform an attended transfer on a channel in a bridge
1979  */
1980 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1981                 const char *target_chan_name)
1982 {
1983         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1984         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1985
1986         chan_target = ast_channel_get_by_name(target_chan_name);
1987         if (!chan_target) {
1988                 /* Dang, it disappeared somehow */
1989                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1990                 return;
1991         }
1992
1993         ast_bridge_channel_lock(bridge_channel);
1994         chan_bridged = bridge_channel->chan;
1995         ast_assert(chan_bridged != NULL);
1996         ao2_ref(chan_bridged, +1);
1997         ast_bridge_channel_unlock(bridge_channel);
1998
1999         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
2000                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
2001                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2002
2003                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
2004                 ast_channel_unref(chan_target);
2005         }
2006         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
2007 }
2008
2009 /*!
2010  * \internal
2011  * \brief Handle bridge channel bridge action frame.
2012  * \since 12.0.0
2013  *
2014  * \param bridge_channel Channel to execute the action on.
2015  * \param action What to do.
2016  * \param data data from the action.
2017  *
2018  * \return Nothing
2019  */
2020 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel,
2021         enum bridge_channel_action_type action, void *data)
2022 {
2023         switch (action) {
2024         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
2025                 bridge_channel_suspend(bridge_channel);
2026                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2027                 bridge_channel_dtmf_stream(bridge_channel, data);
2028                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2029                 bridge_channel_unsuspend(bridge_channel);
2030                 break;
2031         case BRIDGE_CHANNEL_ACTION_TALKING_START:
2032         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
2033                 bridge_channel_talking(bridge_channel,
2034                         action == BRIDGE_CHANNEL_ACTION_TALKING_START);
2035                 break;
2036         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
2037                 bridge_channel_suspend(bridge_channel);
2038                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2039                 bridge_channel_playfile(bridge_channel, data);
2040                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2041                 bridge_channel_unsuspend(bridge_channel);
2042                 break;
2043         case BRIDGE_CHANNEL_ACTION_RUN_APP:
2044                 bridge_channel_suspend(bridge_channel);
2045                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2046                 bridge_channel_run_app(bridge_channel, data);
2047                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2048                 bridge_channel_unsuspend(bridge_channel);
2049                 break;
2050         case BRIDGE_CHANNEL_ACTION_CALLBACK:
2051                 bridge_channel_do_callback(bridge_channel, data);
2052                 break;
2053         case BRIDGE_CHANNEL_ACTION_PARK:
2054                 bridge_channel_suspend(bridge_channel);
2055                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2056                 bridge_channel_park(bridge_channel, data);
2057                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2058                 bridge_channel_unsuspend(bridge_channel);
2059                 break;
2060         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
2061                 bridge_channel_blind_transfer(bridge_channel, data);
2062                 break;
2063         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
2064                 bridge_channel_attended_transfer(bridge_channel, data);
2065                 break;
2066         default:
2067                 break;
2068         }
2069
2070         /* While invoking an action it is possible for the channel to be hung up. So
2071          * that the bridge respects this we check here and if hung up kick it out.
2072          */
2073         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
2074                 ast_bridge_channel_kick(bridge_channel, 0);
2075         }
2076 }
2077
2078 /*!
2079  * \internal
2080  * \brief Check if a bridge should dissolve and do it.
2081  * \since 12.0.0
2082  *
2083  * \param bridge_channel Channel causing the check.
2084  *
2085  * \note On entry, bridge_channel->bridge is already locked.
2086  *
2087  * \return Nothing
2088  */
2089 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
2090 {
2091         struct ast_bridge *bridge = bridge_channel->bridge;
2092
2093         if (bridge->dissolved) {
2094                 return;
2095         }
2096
2097         if (!bridge->num_channels
2098                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
2099                 /* Last channel leaving the bridge turns off the lights. */
2100                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2101                 return;
2102         }
2103
2104         switch (bridge_channel->state) {
2105         case BRIDGE_CHANNEL_STATE_END:
2106                 /* Do we need to dissolve the bridge because this channel hung up? */
2107                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
2108                         || (bridge_channel->features->usable
2109                                 && ast_test_flag(&bridge_channel->features->feature_flags,
2110                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
2111                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2112                         return;
2113                 }
2114                 break;
2115         default:
2116                 break;
2117         }
2118
2119         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
2120                 /*
2121                  * This will start a chain reaction where each channel leaving
2122                  * enters this function and causes the next to leave as long as
2123                  * there aren't non-lonely channels in the bridge.
2124                  */
2125                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
2126                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
2127                         ast_channel_hangupcause(bridge_channel->chan));
2128         }
2129 }
2130
2131 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
2132 {
2133         struct ast_bridge *bridge = bridge_channel->bridge;
2134
2135         if (!bridge_channel->in_bridge) {
2136                 return;
2137         }
2138         bridge_channel->in_bridge = 0;
2139
2140         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
2141                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2142
2143         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
2144                 ast_channel_name(bridge_channel->chan),
2145                 bridge->technology->name,
2146                 bridge->v_table->name,
2147                 bridge->uniqueid);
2148
2149         if (!bridge_channel->just_joined) {
2150                 /* Tell the bridge technology we are leaving so they tear us down */
2151                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
2152                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2153                         bridge->technology->name);
2154                 if (bridge->technology->leave) {
2155                         bridge->technology->leave(bridge, bridge_channel);
2156                 }
2157         }
2158
2159         /* Remove channel from the bridge */
2160         if (!bridge_channel->suspended) {
2161                 --bridge->num_active;
2162         }
2163         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2164                 --bridge->num_lonely;
2165         }
2166         --bridge->num_channels;
2167         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
2168
2169         bridge_channel_dissolve_check(bridge_channel);
2170         bridge->v_table->pull(bridge, bridge_channel);
2171
2172         ast_bridge_channel_clear_roles(bridge_channel);
2173
2174         /* If we are not going to be hung up after leaving a bridge, and we were an
2175          * outgoing channel, clear the outgoing flag.
2176          */
2177         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
2178             && (ast_channel_is_leaving_bridge(bridge_channel->chan)
2179                 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
2180                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
2181                 ast_channel_clear_flag(bridge_channel->chan, AST_FLAG_OUTGOING);
2182         }
2183
2184         bridge->reconfigured = 1;
2185         ast_bridge_publish_leave(bridge, bridge_channel->chan);
2186 }
2187
2188 int bridge_channel_internal_push_full(struct ast_bridge_channel *bridge_channel, int optimized)
2189 {
2190         struct ast_bridge *bridge = bridge_channel->bridge;
2191         struct ast_bridge_channel *swap;
2192
2193         ast_assert(!bridge_channel->in_bridge);
2194
2195         swap = bridge_find_channel(bridge, bridge_channel->swap);
2196         bridge_channel->swap = NULL;
2197
2198         if (swap) {
2199                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
2200                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2201                         swap, ast_channel_name(swap->chan));
2202         } else {
2203                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
2204                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2205         }
2206
2207         /* Add channel to the bridge */
2208         if (bridge->dissolved
2209                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2210                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
2211                 || bridge->v_table->push(bridge, bridge_channel, swap)) {
2212                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
2213                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2214                 return -1;
2215         }
2216
2217         ast_bridge_channel_establish_roles(bridge_channel);
2218
2219         if (swap) {
2220                 int dissolve = ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2221
2222                 /* This flag is cleared so the act of this channel leaving does not cause it to dissolve if need be */
2223                 ast_clear_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2224
2225                 if (optimized) {
2226                         bridge_channel_cancel_owed_events(swap);
2227                 }
2228                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
2229                 bridge_channel_internal_pull(swap);
2230
2231                 ast_set2_flag(&bridge->feature_flags, dissolve, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2232         }
2233
2234         bridge_channel->in_bridge = 1;
2235         bridge_channel->just_joined = 1;
2236         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
2237         ++bridge->num_channels;
2238         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2239                 ++bridge->num_lonely;
2240         }
2241         if (!bridge_channel->suspended) {
2242                 ++bridge->num_active;
2243         }
2244
2245         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
2246                 ast_channel_name(bridge_channel->chan),
2247                 swap ? "swapped with " : "joined",
2248                 swap ? ast_channel_name(swap->chan) : "",
2249                 swap ? " into" : "",
2250                 bridge->technology->name,
2251                 bridge->v_table->name,
2252                 bridge->uniqueid);
2253
2254         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
2255
2256         /* Clear any BLINDTRANSFER,ATTENDEDTRANSFER and FORWARDERNAME since the transfer has completed. */
2257         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
2258         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
2259         pbx_builtin_setvar_helper(bridge_channel->chan, "FORWARDERNAME", NULL);
2260
2261         /* Wake up the bridge channel thread to reevaluate any interval timers. */
2262         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
2263
2264         bridge->reconfigured = 1;
2265         return 0;
2266 }
2267
2268 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
2269 {
2270         return bridge_channel_internal_push_full(bridge_channel, 0);
2271 }
2272
2273 /*!
2274  * \internal
2275  * \brief Handle bridge channel control frame action.
2276  * \since 12.0.0
2277  *
2278  * \param bridge_channel Channel to execute the control frame action on.
2279  * \param fr Control frame to handle.
2280  *
2281  * \return Nothing
2282  */
2283 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2284 {
2285         struct ast_channel *chan;
2286         struct ast_option_header *aoh;
2287         int is_caller;
2288
2289         chan = bridge_channel->chan;
2290         switch (fr->subclass.integer) {
2291         case AST_CONTROL_REDIRECTING:
2292                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2293                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
2294                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
2295                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2296                 }
2297                 break;
2298         case AST_CONTROL_CONNECTED_LINE:
2299                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2300                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
2301                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
2302                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2303                 }
2304                 break;
2305         case AST_CONTROL_OPTION:
2306                 /*
2307                  * Forward option Requests, but only ones we know are safe These
2308                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2309                  * are useful. I haven't deleted them entirely because I just am
2310                  * not sure of the ramifications of removing them.
2311                  */
2312                 aoh = fr->data.ptr;
2313                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2314                         switch (ntohs(aoh->option)) {
2315                         case AST_OPTION_TONE_VERIFY:
2316                         case AST_OPTION_TDD:
2317                         case AST_OPTION_RELAXDTMF:
2318                         case AST_OPTION_AUDIO_MODE:
2319                         case AST_OPTION_DIGIT_DETECT:
2320                         case AST_OPTION_FAX_DETECT:
2321                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2322                                         fr->datalen - sizeof(*aoh), 0);
2323                                 break;
2324                         default:
2325                                 break;
2326                         }
2327                 }
2328                 break;
2329         case AST_CONTROL_ANSWER:
2330                 if (ast_channel_state(chan) != AST_STATE_UP) {
2331                         ast_answer(chan);
2332                         ast_bridge_channel_lock_bridge(bridge_channel);
2333                         bridge_channel->bridge->reconfigured = 1;
2334                         bridge_reconfigured(bridge_channel->bridge, 0);
2335                         ast_bridge_unlock(bridge_channel->bridge);
2336                 } else {
2337                         ast_indicate(chan, -1);
2338                 }
2339                 break;
2340         case AST_CONTROL_MASQUERADE_NOTIFY:
2341                 /* Should never happen. */
2342                 ast_assert(0);
2343                 break;
2344         case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2345                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2346                 break;
2347         default:
2348                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2349                 break;
2350         }
2351 }
2352
2353 /*!
2354  * \internal
2355  * \brief Handle bridge channel write frame to channel.
2356  * \since 12.0.0
2357  *
2358  * \param bridge_channel Channel to write outgoing frame.
2359  *
2360  * \return Nothing
2361  */
2362 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2363 {
2364         struct ast_frame *fr;
2365         struct sync_payload *sync_payload;
2366         int num;
2367         struct ast_msg_data *msg;
2368
2369         ast_bridge_channel_lock(bridge_channel);
2370
2371         /* It's not good to have unbalanced frames and alert_pipe alerts. */
2372         ast_assert(!AST_LIST_EMPTY(&bridge_channel->wr_queue));
2373         if (AST_LIST_EMPTY(&bridge_channel->wr_queue)) {
2374                 /* No frame, flush the alert pipe of excess alerts. */
2375                 ast_log(LOG_WARNING, "Weird.  No frame from bridge for %s to process?\n",
2376                         ast_channel_name(bridge_channel->chan));
2377                 ast_alertpipe_read(bridge_channel->alert_pipe);
2378                 ast_bridge_channel_unlock(bridge_channel);
2379                 return;
2380         }
2381
2382         AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge_channel->wr_queue, fr, frame_list) {
2383                 if (bridge_channel->dtmf_hook_state.collected[0]) {
2384                         switch (fr->frametype) {
2385                         case AST_FRAME_BRIDGE_ACTION:
2386                         case AST_FRAME_BRIDGE_ACTION_SYNC:
2387                                 /* Defer processing these frames while DTMF is collected. */
2388                                 continue;
2389                         default:
2390                                 break;
2391                         }
2392                 }
2393                 ast_alertpipe_read(bridge_channel->alert_pipe);
2394                 AST_LIST_REMOVE_CURRENT(frame_list);
2395                 break;
2396         }
2397         AST_LIST_TRAVERSE_SAFE_END;
2398
2399         ast_bridge_channel_unlock(bridge_channel);
2400
2401         if (!fr) {
2402                 /*
2403                  * Wait some to reduce CPU usage from a tight loop
2404                  * without any wait because we only have deferred
2405                  * frames in the wr_queue.
2406                  */
2407                 usleep(1);
2408                 return;
2409         }
2410
2411         switch (fr->frametype) {
2412         case AST_FRAME_BRIDGE_ACTION:
2413                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, fr->data.ptr);
2414                 break;
2415         case AST_FRAME_BRIDGE_ACTION_SYNC:
2416                 sync_payload = fr->data.ptr;
2417                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, sync_payload->data);
2418                 break;
2419         case AST_FRAME_CONTROL:
2420                 bridge_channel_handle_control(bridge_channel, fr);
2421                 break;
2422         case AST_FRAME_NULL:
2423                 break;
2424         case AST_FRAME_TEXT:
2425                 ast_debug(1, "Sending TEXT frame to '%s': %*.s\n",
2426                         ast_channel_name(bridge_channel->chan), fr->datalen, (char *)fr->data.ptr);
2427                 ast_sendtext(bridge_channel->chan, fr->data.ptr);
2428                 break;
2429         case AST_FRAME_TEXT_DATA:
2430                 msg = (struct ast_msg_data *)fr->data.ptr;
2431                 ast_debug(1, "Sending TEXT_DATA frame from '%s' to '%s:%s': %s\n",
2432                         ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_FROM),
2433                         ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_TO),
2434                         ast_channel_name(bridge_channel->chan),
2435                         ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_BODY));
2436                 ast_sendtext_data(bridge_channel->chan, msg);
2437                 break;
2438         default:
2439                 /* Assume that there is no mapped stream for this */
2440                 num = -1;
2441
2442                 if (fr->stream_num > -1) {
2443                         ast_bridge_channel_lock(bridge_channel);
2444                         if (fr->stream_num < (int)AST_VECTOR_SIZE(&bridge_channel->stream_map.to_channel)) {
2445                                 num = AST_VECTOR_GET(&bridge_channel->stream_map.to_channel, fr->stream_num);
2446                         }
2447                         ast_bridge_channel_unlock(bridge_channel);
2448
2449                         /* If there is no mapped stream after checking the mapping then there is nowhere
2450                          * to write this frame to, so drop it.
2451                          */
2452                         if (num == -1) {
2453                                 break;
2454                         }
2455                 }
2456
2457                 /* Write the frame to the channel. */
2458                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
2459                 ast_write_stream(bridge_channel->chan, num, fr);
2460                 break;
2461         }
2462         bridge_frame_free(fr);
2463 }
2464
2465 /*! \brief Internal function to handle DTMF from a channel */
2466 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
2467 {
2468         struct ast_bridge_features *features = bridge_channel->features;
2469         struct ast_bridge_hook_dtmf *hook = NULL;
2470         char dtmf[2];
2471
2472         /*
2473          * See if we are already matching a DTMF feature hook sequence or
2474          * if this DTMF matches the beginning of any DTMF feature hooks.
2475          */
2476         dtmf[0] = frame->subclass.integer;
2477         dtmf[1] = '\0';
2478         if (bridge_channel->dtmf_hook_state.collected[0]
2479                 || (hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_SEARCH_PARTIAL_KEY))) {
2480                 enum ast_frame_type frametype = frame->frametype;
2481
2482                 bridge_frame_free(frame);
2483                 frame = NULL;
2484
2485                 ao2_cleanup(hook);
2486
2487                 switch (frametype) {
2488                 case AST_FRAME_DTMF_BEGIN:
2489                         /* Just eat the frame. */
2490                         break;
2491                 case AST_FRAME_DTMF_END:
2492                         ast_bridge_channel_feature_digit(bridge_channel, dtmf[0]);
2493                         break;
2494                 default:
2495                         /* Unexpected frame type. */
2496                         ast_assert(0);
2497                         break;
2498                 }
2499 #ifdef TEST_FRAMEWORK
2500         } else if (frame->frametype == AST_FRAME_DTMF_END) {
2501                 /* Only transmit this event on DTMF end or else every DTMF
2502                  * press will result in the event being broadcast twice
2503                  */
2504                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
2505 #endif
2506         }
2507
2508         return frame;
2509 }
2510
2511 static const char *controls[] = {
2512         [AST_CONTROL_RINGING] = "RINGING",
2513         [AST_CONTROL_PROCEEDING] = "PROCEEDING",
2514         [AST_CONTROL_PROGRESS] = "PROGRESS",
2515         [AST_CONTROL_BUSY] = "BUSY",
2516         [AST_CONTROL_CONGESTION] = "CONGESTION",
2517         [AST_CONTROL_ANSWER] = "ANSWER",
2518 };
2519
2520 /*!
2521  * \internal
2522  * \brief Feed notification that a frame is waiting on a channel into the bridging core
2523  *
2524  * \param bridge_channel Bridge channel the notification was received on
2525  */
2526 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
2527 {
2528         struct ast_frame *frame;
2529         int blocked;
2530
2531         if (!ast_strlen_zero(ast_channel_call_forward(bridge_channel->chan))) {
2532                 /* TODO If early bridging is ever used by anything other than ARI,
2533                  * it's important that we actually attempt to handle the call forward
2534                  * attempt, as well as expand features on a bridge channel to allow/disallow
2535                  * call forwarding. For now, all we do is raise an event, showing that
2536                  * a call forward is being attempted.
2537                  */
2538                 ast_channel_publish_dial_forward(NULL, bridge_channel->chan, NULL, NULL, "CANCEL",
2539                         ast_channel_call_forward(bridge_channel->chan));
2540         }
2541
2542         if (bridge_channel->features->mute) {
2543                 frame = ast_read_stream_noaudio(bridge_channel->chan);
2544         } else {
2545                 frame = ast_read_stream(bridge_channel->chan);
2546         }
2547
2548         if (!frame) {
2549                 ast_bridge_channel_kick(bridge_channel, 0);
2550                 return;
2551         }
2552
2553         if (!ast_channel_is_multistream(bridge_channel->chan)) {
2554                 /* This may not be initialized by non-multistream channel drivers */
2555                 frame->stream_num = -1;
2556         }
2557
2558         switch (frame->frametype) {
2559         case AST_FRAME_CONTROL:
2560                 switch (frame->subclass.integer) {
2561                 case AST_CONTROL_CONGESTION:
2562                 case AST_CONTROL_BUSY:
2563                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2564                         break;
2565                 case AST_CONTROL_HANGUP:
2566                         ast_bridge_channel_kick(bridge_channel, 0);
2567                         bridge_frame_free(frame);
2568                         return;
2569                 case AST_CONTROL_RINGING:
2570                 case AST_CONTROL_PROGRESS:
2571                 case AST_CONTROL_PROCEEDING:
2572                 case AST_CONTROL_ANSWER:
2573                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2574                         break;
2575                 case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
2576                         ast_bridge_channel_lock_bridge(bridge_channel);
2577                         blocked = bridge_channel->bridge->technology->stream_topology_request_change
2578                                 && bridge_channel->bridge->technology->stream_topology_request_change(
2579                                         bridge_channel->bridge, bridge_channel);
2580                         ast_bridge_unlock(bridge_channel->bridge);
2581                         if (blocked) {
2582                                 /*
2583                                  * Topology change was intercepted by the bridge technology
2584                                  * so drop frame.
2585                                  */
2586                                 bridge_frame_free(frame);
2587                                 return;
2588                         }
2589                         break;
2590                 case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2591                         /*
2592                          * If a stream topology has changed then the bridge_channel's
2593                          * media mapping needs to be updated.
2594                          */
2595                         ast_bridge_channel_lock_bridge(bridge_channel);
2596                         if (bridge_channel->bridge->technology->stream_topology_changed) {
2597                                 bridge_channel->bridge->technology->stream_topology_changed(
2598                                         bridge_channel->bridge, bridge_channel);
2599                         } else {
2600                                 ast_bridge_channel_stream_map(bridge_channel);
2601                         }
2602                         ast_bridge_unlock(bridge_channel->bridge);
2603                         break;
2604                 default:
2605                         break;
2606                 }
2607                 break;
2608         case AST_FRAME_DTMF_BEGIN:
2609         case AST_FRAME_DTMF_END:
2610                 frame = bridge_handle_dtmf(bridge_channel, frame);
2611                 if (!frame) {
2612                         return;
2613                 }
2614                 if (!bridge_channel->features->dtmf_passthrough) {
2615                         bridge_frame_free(frame);
2616                         return;
2617                 }
2618                 break;
2619         default:
2620                 break;
2621         }
2622
2623         /* Simply write the frame out to the bridge technology. */
2624         bridge_channel_write_frame(bridge_channel, frame);
2625         bridge_frame_free(frame);
2626 }
2627
2628 /*!
2629  * \internal
2630  * \brief Determine how long till the next timer interval.
2631  * \since 12.0.0
2632  *
2633  * \param bridge_channel Channel to determine how long can wait.
2634  *
2635  * \retval ms Number of milliseconds to wait.
2636  * \retval -1 to wait forever.
2637  */
2638 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
2639 {
2640         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
2641         struct ast_bridge_hook_timer *hook;
2642         int ms;
2643
2644         ast_heap_wrlock(interval_hooks);
2645         hook = ast_heap_peek(interval_hooks, 1);
2646         if (hook) {
2647                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
2648                 if (ms < 0) {
2649                         /* Expire immediately.  An interval hook is ready to run. */
2650                         ms = 0;
2651                 }
2652         } else {
2653                 /* No hook so wait forever. */
2654                 ms = -1;
2655         }
2656         ast_heap_unlock(interval_hooks);
2657
2658         return ms;
2659 }
2660
2661 /*!
2662  * \internal
2663  * \brief Determine how long till the DTMF interdigit timeout.
2664  * \since 12.8.0
2665  *
2666  * \param bridge_channel Channel to determine how long can wait.
2667  *
2668  * \retval ms Number of milliseconds to wait.
2669  * \retval -1 to wait forever.
2670  */
2671 static int bridge_channel_feature_timeout(struct ast_bridge_channel *bridge_channel)
2672 {
2673         int ms;
2674
2675         if (bridge_channel->dtmf_hook_state.collected[0]) {
2676                 ms = ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
2677                         ast_tvnow());
2678                 if (ms < 0) {
2679                         /* Expire immediately. */
2680                         ms = 0;
2681                 }
2682         } else {
2683                 /* Timer is not active so wait forever. */
2684                 ms = -1;
2685         }
2686
2687         return ms;
2688 }
2689
2690 /*!
2691  * \internal
2692  * \brief Determine how long till a timeout.
2693  * \since 12.8.0
2694  *
2695  * \param bridge_channel Channel to determine how long can wait.
2696  *
2697  * \retval ms Number of milliseconds to wait.
2698  * \retval -1 to wait forever.
2699  */
2700 static int bridge_channel_next_timeout(struct ast_bridge_channel *bridge_channel)
2701 {
2702         int ms_interval;
2703         int ms;
2704
2705         ms_interval = bridge_channel_next_interval(bridge_channel);
2706         ms = bridge_channel_feature_timeout(bridge_channel);
2707         if (ms < 0 || (0 <= ms_interval && ms_interval < ms)) {
2708                 /* Interval hook timeout is next. */
2709                 ms = ms_interval;
2710         }
2711
2712         return ms;
2713 }
2714
2715 /*!
2716  * \internal
2717  * \brief Wait for something to happen on the bridge channel and handle it.
2718  * \since 12.0.0
2719  *
2720  * \param bridge_channel Channel to wait.
2721  *
2722  * \note Each channel does writing/reading in their own thread.
2723  *
2724  * \return Nothing
2725  */
2726 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2727 {
2728         int ms;
2729         int outfd;
2730         struct ast_channel *chan;
2731
2732         /* Wait for data to either come from the channel or us to be signaled */
2733         ast_bridge_channel_lock(bridge_channel);
2734         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2735         } else if (bridge_channel->suspended) {
2736 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
2737                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2738                         bridge_channel->bridge->uniqueid, bridge_channel,
2739                         ast_channel_name(bridge_channel->chan));
2740                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2741         } else {
2742                 ast_bridge_channel_unlock(bridge_channel);
2743                 outfd = -1;
2744                 ms = bridge_channel_next_timeout(bridge_channel);
2745                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2746                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2747                 if (ast_channel_unbridged(bridge_channel->chan)) {
2748                         ast_channel_set_unbridged(bridge_channel->chan, 0);
2749                         ast_bridge_channel_lock_bridge(bridge_channel);
2750                         bridge_channel->bridge->reconfigured = 1;
2751                         bridge_reconfigured(bridge_channel->bridge, 0);
2752                         ast_bridge_unlock(bridge_channel->bridge);
2753                 }
2754                 ast_bridge_channel_lock(bridge_channel);
2755                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
2756                 ast_bridge_channel_unlock(bridge_channel);
2757                 if (!bridge_channel->suspended
2758                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2759                         if (chan) {
2760                                 bridge_handle_trip(bridge_channel);
2761                         } else if (ms == 0) {
2762                                 /* An interdigit timeout or interval expired. */
2763                                 bridge_channel_handle_feature_timeout(bridge_channel);
2764                                 bridge_channel_handle_interval(bridge_channel);
2765                         } else if (-1 < outfd) {
2766                                 /*
2767                                  * Must do this after checking timeouts or may have
2768                                  * an infinite loop due to deferring write queue
2769                                  * actions while trying to match DTMF feature hooks.
2770                                  */
2771                                 bridge_channel_handle_write(bridge_channel);
2772                         }
2773                 }
2774                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
2775                 return;
2776         }
2777         ast_bridge_channel_unlock(bridge_channel);
2778 }
2779
2780 /*!
2781  * \internal
2782  * \brief Handle bridge channel join/leave event.
2783  * \since 12.0.0
2784  *
2785  * \param bridge_channel Which channel is involved.
2786  * \param type Specified join/leave event.
2787  *
2788  * \return Nothing
2789  */
2790 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
2791 {
2792         struct ast_bridge_features *features = bridge_channel->features;
2793         struct ast_bridge_hook *hook;
2794         struct ao2_iterator iter;
2795
2796         /* Run the specified hooks. */
2797         iter = ao2_iterator_init(features->other_hooks, 0);
2798         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2799                 if (hook->type == type) {
2800                         break;
2801                 }
2802         }
2803         if (hook) {
2804                 /* Found the first specified hook to run. */
2805                 bridge_channel_suspend(bridge_channel);
2806                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2807                 do {
2808                         if (hook->type == type) {
2809                                 hook->callback(bridge_channel, hook->hook_pvt);
2810                                 ao2_unlink(features->other_hooks, hook);
2811                         }
2812                         ao2_ref(hook, -1);
2813                 } while ((hook = ao2_iterator_next(&iter)));
2814                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2815                 bridge_channel_unsuspend(bridge_channel);
2816         }
2817         ao2_iterator_destroy(&iter);
2818 }
2819
2820 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
2821 {
2822         int res = 0;
2823         uint8_t indicate_src_change = 0;
2824         struct ast_bridge_features *channel_features;
2825         struct ast_channel *swap;
2826
2827         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2828                 bridge_channel->bridge->uniqueid,
2829                 bridge_channel, ast_channel_name(bridge_channel->chan));
2830
2831         /*
2832          * Directly locking the bridge is safe here because nobody else
2833          * knows about this bridge_channel yet.
2834          */
2835         ast_bridge_lock(bridge_channel->bridge);
2836
2837         ast_channel_lock(bridge_channel->chan);
2838
2839         bridge_channel->read_format = ao2_bump(ast_channel_readformat(bridge_channel->chan));
2840         bridge_channel->write_format = ao2_bump(ast_channel_writeformat(bridge_channel->chan));
2841
2842         /* Make sure we're still good to be put into a bridge */
2843         if (ast_channel_internal_bridge(bridge_channel->chan)
2844                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
2845                 ast_channel_unlock(bridge_channel->chan);
2846                 ast_bridge_unlock(bridge_channel->bridge);
2847                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
2848                         bridge_channel->bridge->uniqueid,
2849                         bridge_channel,
2850                         ast_channel_name(bridge_channel->chan));
2851                 return -1;
2852         }
2853         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2854
2855         /* Attach features requested by the channel */
2856         channel_features = ast_channel_feature_hooks_get(bridge_channel->chan);
2857         if (channel_features) {
2858                 ast_bridge_features_merge(bridge_channel->features, channel_features);
2859         }
2860         ast_channel_unlock(bridge_channel->chan);
2861
2862         /* Add the jitterbuffer if the channel requires it */
2863         ast_jb_enable_for_channel(bridge_channel->chan);
2864
2865         if (!bridge_channel->bridge->callid) {
2866                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2867         }
2868
2869         /* Take the swap channel ref from the bridge_channel struct. */
2870         swap = bridge_channel->swap;
2871
2872         if (bridge_channel_internal_push(bridge_channel)) {
2873                 int cause = bridge_channel->bridge->cause;
2874
2875                 ast_bridge_unlock(bridge_channel->bridge);
2876                 ast_bridge_channel_kick(bridge_channel, cause);
2877                 ast_bridge_channel_lock_bridge(bridge_channel);
2878                 ast_bridge_features_remove(bridge_channel->features,
2879                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2880                 bridge_channel_dissolve_check(bridge_channel);
2881                 res = -1;
2882         }
2883         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2884
2885         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2886                 /*
2887                  * Indicate a source change since this channel is entering the
2888                  * bridge system only if the bridge technology is not MULTIMIX
2889                  * capable.  The MULTIMIX technology has already done it.
2890                  */
2891                 if (!(bridge_channel->bridge->technology->capabilities
2892                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2893                         indicate_src_change = 1;
2894                 }
2895
2896                 bridge_channel_impart_signal(bridge_channel->chan);
2897                 ast_bridge_unlock(bridge_channel->bridge);
2898
2899                 /* Must release any swap ref after unlocking the bridge. */
2900                 ao2_t_cleanup(swap, "Bridge push with swap successful");
2901                 swap = NULL;
2902
2903                 if (indicate_src_change) {
2904                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2905                 }
2906
2907                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2908
2909                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2910                         /* Wait for something to do. */
2911                         bridge_channel_wait(bridge_channel);
2912                 }
2913
2914                 /* Force a timeout on any accumulated DTMF hook digits. */
2915                 ast_bridge_channel_feature_digit(bridge_channel, 0);
2916
2917                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2918                 ast_bridge_channel_lock_bridge(bridge_channel);
2919         }
2920
2921         bridge_channel_internal_pull(bridge_channel);
2922         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2923         bridge_reconfigured(bridge_channel->bridge, 1);
2924
2925         /* Remove ourselves if we are the video source */
2926         ast_bridge_remove_video_src(bridge_channel->bridge, bridge_channel->chan);
2927
2928         ast_bridge_unlock(bridge_channel->bridge);
2929
2930         /* Must release any swap ref after unlocking the bridge. */
2931         ao2_t_cleanup(swap, "Bridge push with swap failed or exited immediately");
2932
2933         /* Complete any active hold before exiting the bridge. */
2934         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2935                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2936                         ast_channel_name(bridge_channel->chan));
2937                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2938         }
2939
2940         /* Complete any partial DTMF digit before exiting the bridge. */
2941         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2942                 ast_channel_end_dtmf(bridge_channel->chan,
2943                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2944                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2945         }
2946
2947         /* Complete any T.38 session before exiting the bridge. */
2948         if (ast_channel_is_t38_active(bridge_channel->chan)) {
2949                 struct ast_control_t38_parameters t38_parameters = {
2950                         .request_response = AST_T38_TERMINATED,
2951                 };
2952
2953                 ast_debug(1, "Channel %s simulating T.38 terminate for bridge end.\n",
2954                         ast_channel_name(bridge_channel->chan));
2955                 ast_indicate_data(bridge_channel->chan, AST_CONTROL_T38_PARAMETERS,
2956                         &t38_parameters, sizeof(t38_parameters));
2957         }
2958
2959         /* Indicate a source change since this channel is leaving the bridge system. */
2960         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2961
2962         /*
2963          * Wait for any dual redirect to complete.
2964          *
2965          * Must be done while "still in the bridge" for ast_async_goto()
2966          * to work right.
2967          */
2968         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2969                 sched_yield();
2970         }
2971         ast_channel_lock(bridge_channel->chan);
2972         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2973         ast_channel_unlock(bridge_channel->chan);
2974
2975         ast_bridge_channel_restore_formats(bridge_channel);
2976
2977         return res;
2978 }
2979
2980 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2981                 const char *exten, const char *context,
2982                 transfer_channel_cb new_channel_cb, void *user_data)
2983 {
2984         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2985         struct blind_transfer_data blind_data;
2986
2987         ast_channel_lock(transferee);
2988         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2989         ast_channel_unlock(transferee);
2990
2991         if (!transferee_bridge_channel) {
2992                 return -1;
2993         }
2994
2995         if (new_channel_cb) {
2996                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2997         }
2998
2999         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
3000         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
3001
3002         return bridge_channel_queue_action_data(transferee_bridge_channel,
3003                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
3004 }
3005
3006 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
3007                 struct ast_channel *unbridged_chan)
3008 {
3009         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
3010         char unbridged_chan_name[AST_CHANNEL_NAME];
3011
3012         ast_channel_lock(transferee);
3013         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
3014         ast_channel_unlock(transferee);
3015
3016         if (!transferee_bridge_channel) {
3017                 return -1;
3018         }
3019
3020         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
3021                 sizeof(unbridged_chan_name));
3022
3023         return bridge_channel_queue_action_data(transferee_bridge_channel,
3024                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
3025                 sizeof(unbridged_chan_name));
3026 }
3027
3028 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
3029 {
3030         return bridge_channel->in_bridge
3031                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
3032 }
3033
3034 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
3035 static void bridge_channel_destroy(void *obj)
3036 {
3037         struct ast_bridge_channel *bridge_channel = obj;
3038         struct ast_frame *fr;
3039
3040         if (bridge_channel->callid) {
3041                 bridge_channel->callid = 0;
3042         }
3043
3044         if (bridge_channel->bridge) {
3045                 ao2_ref(bridge_channel->bridge, -1);
3046                 bridge_channel->bridge = NULL;
3047         }
3048
3049         /* Flush any unhandled wr_queue frames. */
3050         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
3051                 bridge_frame_free(fr);
3052         }
3053         ast_alertpipe_close(bridge_channel->alert_pipe);
3054
3055         /* Flush any unhandled deferred_queue frames. */
3056         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->deferred_queue, frame_list))) {
3057                 ast_frfree(fr);
3058         }
3059
3060         ast_cond_destroy(&bridge_channel->cond);
3061
3062         ao2_cleanup(bridge_channel->write_format);
3063         ao2_cleanup(bridge_channel->read_format);
3064
3065         AST_VECTOR_FREE(&bridge_channel->stream_map.to_bridge);
3066         AST_VECTOR_FREE(&bridge_channel->stream_map.to_channel);
3067 }
3068
3069 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
3070 {
3071         struct ast_bridge_channel *bridge_channel;
3072
3073         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
3074         if (!bridge_channel) {
3075                 return NULL;
3076         }
3077         ast_cond_init(&bridge_channel->cond, NULL);
3078         if (ast_alertpipe_init(bridge_channel->alert_pipe)) {
3079                 ao2_ref(bridge_channel, -1);
3080                 return NULL;
3081         }
3082         if (bridge) {
3083                 bridge_channel->bridge = bridge;
3084                 ao2_ref(bridge_channel->bridge, +1);
3085         }
3086
3087         /* The stream_map is initialized later - see ast_bridge_channel_stream_map */
3088
3089         return bridge_channel;
3090 }
3091
3092 void ast_bridge_channel_stream_map(struct ast_bridge_channel *bridge_channel)
3093 {
3094         ast_bridge_channel_lock(bridge_channel);
3095         ast_channel_lock(bridge_channel->chan);
3096         ast_stream_topology_map(ast_channel_get_stream_topology(bridge_channel->chan),
3097                 &bridge_channel->bridge->media_types, &bridge_channel->stream_map.to_bridge,
3098                 &bridge_channel->stream_map.to_channel);
3099         ast_channel_unlock(bridge_channel->chan);
3100         ast_bridge_channel_unlock(bridge_channel);
3101 }