confbridge: Add support for disabling text messaging.
[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 ((fr->frametype == AST_FRAME_TEXT || fr->frametype == AST_FRAME_TEXT_DATA) &&
1060                 !bridge_channel->features->text_messaging) {
1061                 /* This channel is not accepting text messages. */
1062                 ast_bridge_channel_unlock(bridge_channel);
1063                 bridge_frame_free(dup);
1064                 return 0;
1065         }
1066
1067         if (DEBUG_ATLEAST(1)) {
1068                 if (fr->frametype == AST_FRAME_TEXT) {
1069                         ast_log(LOG_DEBUG, "Queuing TEXT frame to '%s': %*.s\n", ast_channel_name(bridge_channel->chan),
1070                                 fr->datalen, (char *)fr->data.ptr);
1071                 } else if (fr->frametype == AST_FRAME_TEXT_DATA) {
1072                         struct ast_msg_data *msg = fr->data.ptr;
1073                         ast_log(LOG_DEBUG, "Queueing TEXT_DATA frame from '%s' to '%s:%s': %s\n",
1074                                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_FROM),
1075                                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_TO),
1076                                 ast_channel_name(bridge_channel->chan),
1077                                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_BODY));
1078                 }
1079         }
1080
1081         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
1082         if (ast_alertpipe_write(bridge_channel->alert_pipe)) {
1083                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
1084                         bridge_channel, ast_channel_name(bridge_channel->chan));
1085         }
1086         ast_bridge_channel_unlock(bridge_channel);
1087         return 0;
1088 }
1089
1090 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1091 {
1092         struct ast_bridge_channel *cur;
1093         int not_written = -1;
1094
1095         if (frame->frametype == AST_FRAME_NULL) {
1096                 /* "Accept" the frame and discard it. */
1097                 return 0;
1098         }
1099
1100         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
1101                 if (cur == bridge_channel) {
1102                         continue;
1103                 }
1104                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
1105                         not_written = 0;
1106                 }
1107         }
1108         return not_written;
1109 }
1110
1111 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)
1112 {
1113         struct ast_frame frame = {
1114                 .frametype = AST_FRAME_CONTROL,
1115                 .subclass.integer = control,
1116                 .datalen = datalen,
1117                 .data.ptr = (void *) data,
1118         };
1119
1120         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
1121 }
1122
1123 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)
1124 {
1125         struct ast_frame frame = {
1126                 .frametype = AST_FRAME_CONTROL,
1127                 .subclass.integer = control,
1128                 .datalen = datalen,
1129                 .data.ptr = (void *) data,
1130         };
1131
1132         return bridge_channel_write_frame(bridge_channel, &frame);
1133 }
1134
1135 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
1136 {
1137         struct ast_json *blob;
1138         int res;
1139         size_t datalen;
1140
1141         if (!ast_strlen_zero(moh_class)) {
1142                 datalen = strlen(moh_class) + 1;
1143
1144                 blob = ast_json_pack("{s: s}",
1145                         "musicclass", moh_class);
1146         } else {
1147                 moh_class = NULL;
1148                 datalen = 0;
1149                 blob = NULL;
1150         }
1151
1152         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
1153
1154         res = ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
1155                 moh_class, datalen);
1156
1157         ast_json_unref(blob);
1158         return res;
1159 }
1160
1161 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
1162 {
1163         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
1164
1165         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
1166 }
1167
1168 /*!
1169  * \internal
1170  * \brief Helper function to kick off a PBX app on a bridge_channel
1171  */
1172 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
1173 {
1174         int res = 0;
1175
1176         if (!strcasecmp("Gosub", app_name)) {
1177                 ast_app_exec_sub(NULL, chan, app_args, 0);
1178         } else if (!strcasecmp("Macro", app_name)) {
1179                 ast_app_exec_macro(NULL, chan, app_args);
1180         } else {
1181                 struct ast_app *app;
1182
1183                 app = pbx_findapp(app_name);
1184                 if (!app) {
1185                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
1186                 } else {
1187                         struct ast_str *substituted_args = ast_str_create(16);
1188
1189                         if (substituted_args) {
1190                                 ast_str_substitute_variables(&substituted_args, 0, chan, app_args);
1191                                 res = pbx_exec(chan, app, ast_str_buffer(substituted_args));
1192                                 ast_free(substituted_args);
1193                         } else {
1194                                 ast_log(LOG_WARNING, "Could not substitute application argument variables for %s\n", app_name);
1195                                 res = pbx_exec(chan, app, app_args);
1196                         }
1197                 }
1198         }
1199         return res;
1200 }
1201
1202 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1203 {
1204         if (moh_class) {
1205                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1206         }
1207         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
1208                 /* Break the bridge if the app returns non-zero. */
1209                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1210         }
1211         if (moh_class) {
1212                 ast_bridge_channel_write_unhold(bridge_channel);
1213         }
1214 }
1215
1216 struct bridge_run_app {
1217         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
1218         int moh_offset;
1219         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
1220         int app_args_offset;
1221         /*! Application name to run. */
1222         char app_name[0];
1223 };
1224
1225 /*!
1226  * \internal
1227  * \brief Handle the run application bridge action.
1228  * \since 12.0.0
1229  *
1230  * \param bridge_channel Which channel to run the application on.
1231  * \param data Action frame data to run the application.
1232  *
1233  * \return Nothing
1234  */
1235 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
1236 {
1237         ast_bridge_channel_run_app(bridge_channel, data->app_name,
1238                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
1239                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
1240 }
1241
1242 /*!
1243  * \internal
1244  * \brief Marshal an application to be executed on a bridge_channel
1245  */
1246 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
1247         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1248 {
1249         struct bridge_run_app *app_data;
1250         size_t len_name = strlen(app_name) + 1;
1251         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
1252         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1253         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
1254
1255         /* Fill in application run frame data. */
1256         app_data = alloca(len_data);
1257         app_data->app_args_offset = len_args ? len_name : 0;
1258         app_data->moh_offset = len_moh ? len_name + len_args : 0;
1259         strcpy(app_data->app_name, app_name);/* Safe */
1260         if (len_args) {
1261                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
1262         }
1263         if (moh_class) {
1264                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
1265         }
1266
1267         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
1268 }
1269
1270 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1271 {
1272         return payload_helper_app(bridge_channel_write_action_data,
1273                 bridge_channel, app_name, app_args, moh_class);
1274 }
1275
1276 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1277 {
1278         return payload_helper_app(bridge_channel_queue_action_data,
1279                 bridge_channel, app_name, app_args, moh_class);
1280 }
1281
1282 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)
1283 {
1284         if (moh_class) {
1285                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1286         }
1287         if (custom_play) {
1288                 custom_play(bridge_channel, playfile);
1289         } else {
1290                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
1291         }
1292         if (moh_class) {
1293                 ast_bridge_channel_write_unhold(bridge_channel);
1294         }
1295
1296         /*
1297          * It may be necessary to resume music on hold after we finish
1298          * playing the announcment.
1299          */
1300         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
1301                 const char *latest_musicclass;
1302
1303                 ast_channel_lock(bridge_channel->chan);
1304                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
1305                 ast_channel_unlock(bridge_channel->chan);
1306                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
1307         }
1308 }
1309
1310 struct bridge_playfile {
1311         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
1312         ast_bridge_custom_play_fn custom_play;
1313         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
1314         int moh_offset;
1315         /*! Filename to play. */
1316         char playfile[0];
1317 };
1318
1319 /*!
1320  * \internal
1321  * \brief Handle the playfile bridge action.
1322  * \since 12.0.0
1323  *
1324  * \param bridge_channel Which channel to play a file on.
1325  * \param payload Action frame payload to play a file.
1326  *
1327  * \return Nothing
1328  */
1329 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
1330 {
1331         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
1332                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
1333 }
1334
1335 /*!
1336  * \internal
1337  * \brief Marshal a file to be played on a bridge_channel
1338  */
1339 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
1340         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1341 {
1342         struct bridge_playfile *payload;
1343         size_t len_name = strlen(playfile) + 1;
1344         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1345         size_t len_payload = sizeof(*payload) + len_name + len_moh;
1346
1347         /* Fill in play file frame data. */
1348         payload = ast_alloca(len_payload);
1349         payload->custom_play = custom_play;
1350         payload->moh_offset = len_moh ? len_name : 0;
1351         strcpy(payload->playfile, playfile);/* Safe */
1352         if (moh_class) {
1353                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
1354         }
1355
1356         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
1357 }
1358
1359 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)
1360 {
1361         return payload_helper_playfile(bridge_channel_write_action_data,
1362                 bridge_channel, custom_play, playfile, moh_class);
1363 }
1364
1365 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)
1366 {
1367         return payload_helper_playfile(bridge_channel_queue_action_data,
1368                 bridge_channel, custom_play, playfile, moh_class);
1369 }
1370
1371 int ast_bridge_channel_queue_playfile_sync(struct ast_bridge_channel *bridge_channel,
1372                 ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1373 {
1374         return payload_helper_playfile(bridge_channel_queue_action_data_sync,
1375                 bridge_channel, custom_play, playfile, moh_class);
1376 }
1377
1378 struct bridge_custom_callback {
1379         /*! Call this function on the bridge channel thread. */
1380         ast_bridge_custom_callback_fn callback;
1381         /*! Size of the payload if it exists.  A number otherwise. */
1382         size_t payload_size;
1383         /*! Option flags determining how callback is called. */
1384         unsigned int flags;
1385         /*! Nonzero if the payload exists. */
1386         char payload_exists;
1387         /*! Payload to give to callback. */
1388         char payload[0];
1389 };
1390
1391 /*!
1392  * \internal
1393  * \brief Handle the do custom callback bridge action.
1394  * \since 12.0.0
1395  *
1396  * \param bridge_channel Which channel to call the callback on.
1397  * \param data Action frame data to call the callback.
1398  *
1399  * \return Nothing
1400  */
1401 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
1402 {
1403         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1404                 bridge_channel_suspend(bridge_channel);
1405                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1406         }
1407         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
1408         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1409                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1410                 bridge_channel_unsuspend(bridge_channel);
1411         }
1412 }
1413
1414 /*!
1415  * \internal
1416  * \brief Marshal a custom callback function to be called on a bridge_channel
1417  */
1418 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
1419         struct ast_bridge_channel *bridge_channel,
1420         enum ast_bridge_channel_custom_callback_option flags,
1421         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1422 {
1423         struct bridge_custom_callback *cb_data;
1424         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
1425
1426         /* Sanity check. */
1427         if (!callback) {
1428                 ast_assert(0);
1429                 return -1;
1430         }
1431
1432         /* Fill in custom callback frame data. */
1433         cb_data = alloca(len_data);
1434         cb_data->callback = callback;
1435         cb_data->payload_size = payload_size;
1436         cb_data->flags = flags;
1437         cb_data->payload_exists = payload && payload_size;
1438         if (cb_data->payload_exists) {
1439                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
1440         }
1441
1442         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
1443 }
1444
1445 int ast_bridge_channel_write_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_write_action_data,
1450                 bridge_channel, flags, callback, payload, payload_size);
1451 }
1452
1453 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
1454         enum ast_bridge_channel_custom_callback_option flags,
1455         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1456 {
1457         return payload_helper_cb(bridge_channel_queue_action_data,
1458                 bridge_channel, flags, callback, payload, payload_size);
1459 }
1460
1461 struct bridge_park {
1462         int parker_uuid_offset;
1463         int app_data_offset;
1464         /* buffer used for holding those strings */
1465         char parkee_uuid[0];
1466 };
1467
1468 /*!
1469  * \internal
1470  * \brief Park a bridge_cahnnel
1471  */
1472 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
1473 {
1474         if (!ast_parking_provider_registered()) {
1475                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
1476                         ast_channel_name(bridge_channel->chan));
1477                 return;
1478         }
1479
1480         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
1481                 &payload->parkee_uuid[payload->parker_uuid_offset],
1482                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
1483                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
1484                         ast_channel_name(bridge_channel->chan));
1485         }
1486 }
1487
1488 /*!
1489  * \internal
1490  * \brief Marshal a park action onto a bridge_channel
1491  */
1492 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
1493         struct ast_bridge_channel *bridge_channel,
1494         const char *parkee_uuid,
1495         const char *parker_uuid,
1496         const char *app_data)
1497 {
1498         struct bridge_park *payload;
1499         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1500         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1501         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1502         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1503
1504         payload = alloca(len_payload);
1505         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1506         payload->parker_uuid_offset = len_parkee_uuid;
1507         strcpy(payload->parkee_uuid, parkee_uuid);
1508         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1509         if (app_data) {
1510                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1511         }
1512
1513         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
1514 }
1515
1516 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1517 {
1518         return payload_helper_park(bridge_channel_write_action_data,
1519                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1520 }
1521
1522 /*!
1523  * \internal
1524  * \brief Handle bridge channel interval expiration.
1525  * \since 12.0.0
1526  *
1527  * \param bridge_channel Channel to run expired intervals on.
1528  *
1529  * \return Nothing
1530  */
1531 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
1532 {
1533         struct ast_heap *interval_hooks;
1534         struct ast_bridge_hook_timer *hook;
1535         struct timeval start;
1536         int chan_suspended = 0;
1537
1538         interval_hooks = bridge_channel->features->interval_hooks;
1539         ast_heap_wrlock(interval_hooks);
1540         start = ast_tvnow();
1541         while ((hook = ast_heap_peek(interval_hooks, 1))) {
1542                 int interval;
1543                 unsigned int execution_time;
1544
1545                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1546                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1547                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1548                         break;
1549                 }
1550                 ao2_ref(hook, +1);
1551                 ast_heap_unlock(interval_hooks);
1552
1553                 if (!chan_suspended
1554                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1555                         chan_suspended = 1;
1556                         bridge_channel_suspend(bridge_channel);
1557                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1558                 }
1559
1560                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1561                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1562                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1563
1564                 ast_heap_wrlock(interval_hooks);
1565                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1566                         || !ast_heap_remove(interval_hooks, hook)) {
1567                         /* Interval hook is already removed from the bridge_channel. */
1568                         ao2_ref(hook, -1);
1569                         continue;
1570                 }
1571                 ao2_ref(hook, -1);
1572
1573                 if (interval < 0) {
1574                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1575                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1576                         ao2_ref(hook, -1);
1577                         continue;
1578                 }
1579                 if (interval) {
1580                         /* Set new interval for the hook. */
1581                         hook->timer.interval = interval;
1582                 }
1583
1584                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1585                         hook, hook->timer.interval, bridge_channel,
1586                         ast_channel_name(bridge_channel->chan));
1587
1588                 /* resetting start */
1589                 start = ast_tvnow();
1590
1591                 /*
1592                  * Resetup the interval hook for the next interval.  We may need
1593                  * to skip over any missed intervals because the hook was
1594                  * delayed or took too long.
1595                  */
1596                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1597                 while (hook->timer.interval < execution_time) {
1598                         execution_time -= hook->timer.interval;
1599                 }
1600                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1601                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1602
1603                 if (ast_heap_push(interval_hooks, hook)) {
1604                         /* Could not push the hook back onto the heap. */
1605                         ao2_ref(hook, -1);
1606                 }
1607         }
1608         ast_heap_unlock(interval_hooks);
1609
1610         if (chan_suspended) {
1611                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1612                 bridge_channel_unsuspend(bridge_channel);
1613         }
1614 }
1615
1616 /*!
1617  * \internal
1618  * \brief Write a DTMF stream out to a channel
1619  */
1620 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1621 {
1622         return bridge_channel_write_action_data(bridge_channel,
1623                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1624 }
1625
1626 /*!
1627  * \internal
1628  * \brief Indicate to the testsuite a feature was successfully detected.
1629  *
1630  * Currently, this function only will relay built-in features to the testsuite,
1631  * but it could be modified to detect applicationmap items should the need arise.
1632  *
1633  * \param chan The channel that activated the feature
1634  * \param dtmf The DTMF sequence entered to activate the feature
1635  */
1636 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1637 {
1638 #ifdef TEST_FRAMEWORK
1639         char *feature = "unknown";
1640         struct ast_featuremap_config *featuremap;
1641         struct ast_features_xfer_config *xfer;
1642
1643         ast_channel_lock(chan);
1644         featuremap = ast_get_chan_featuremap_config(chan);
1645         xfer = ast_get_chan_features_xfer_config(chan);
1646         ast_channel_unlock(chan);
1647
1648         if (featuremap) {
1649                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1650                         feature = "blindxfer";
1651                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1652                         feature = "atxfer";
1653                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1654                         feature = "disconnect";
1655                 } else if (!strcmp(dtmf, featuremap->automon)) {
1656                         feature = "automon";
1657                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1658                         feature = "automixmon";
1659                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1660                         feature = "parkcall";
1661                 }
1662         }
1663         if (xfer) {
1664                 if (!strcmp(dtmf, xfer->atxferthreeway)) {
1665                         feature = "atxferthreeway";
1666                 }
1667         }
1668
1669         ao2_cleanup(featuremap);
1670         ao2_cleanup(xfer);
1671
1672         ast_test_suite_event_notify("FEATURE_DETECTION",
1673                         "Result: success\r\n"
1674                         "Feature: %s", feature);
1675 #endif /* TEST_FRAMEWORK */
1676 }
1677
1678 static int bridge_channel_feature_digit_add(
1679         struct ast_bridge_channel *bridge_channel, int digit, size_t dtmf_len)
1680 {
1681         if (dtmf_len < ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) - 1) {
1682                 /* Add the new digit to the DTMF string so we can do our matching */
1683                 bridge_channel->dtmf_hook_state.collected[dtmf_len++] = digit;
1684                 bridge_channel->dtmf_hook_state.collected[dtmf_len] = '\0';
1685
1686                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1687                           bridge_channel, ast_channel_name(bridge_channel->chan),
1688                           bridge_channel->dtmf_hook_state.collected);
1689         }
1690
1691         return dtmf_len;
1692 }
1693
1694 static unsigned int bridge_channel_feature_digit_timeout(struct ast_bridge_channel *bridge_channel)
1695 {
1696         unsigned int digit_timeout;
1697         struct ast_features_general_config *gen_cfg;
1698
1699         /* Determine interdigit timeout */
1700         ast_channel_lock(bridge_channel->chan);
1701         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1702         ast_channel_unlock(bridge_channel->chan);
1703
1704         if (!gen_cfg) {
1705                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1706                 return 3000; /* Pick a reasonable failsafe timeout in ms */
1707         }
1708
1709         digit_timeout = gen_cfg->featuredigittimeout;
1710         ao2_ref(gen_cfg, -1);
1711
1712         return digit_timeout;
1713 }
1714
1715 void ast_bridge_channel_feature_digit_add(struct ast_bridge_channel *bridge_channel, int digit)
1716 {
1717         if (digit) {
1718                 bridge_channel_feature_digit_add(
1719                         bridge_channel, digit, strlen(bridge_channel->dtmf_hook_state.collected));
1720         }
1721 }
1722
1723 void ast_bridge_channel_feature_digit(struct ast_bridge_channel *bridge_channel, int digit)
1724 {
1725         struct ast_bridge_features *features = bridge_channel->features;
1726         struct ast_bridge_hook_dtmf *hook = NULL;
1727         size_t dtmf_len;
1728
1729         struct sanity_check_of_dtmf_size {
1730                 char check[1 / (ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) == ARRAY_LEN(hook->dtmf.code))];
1731         };
1732
1733         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1734         if (!dtmf_len && !digit) {
1735                 /* Nothing to do */
1736                 return;
1737         }
1738
1739         if (digit) {
1740                 dtmf_len = bridge_channel_feature_digit_add(bridge_channel, digit, dtmf_len);
1741         }
1742
1743         while (digit) {
1744                 /* See if a DTMF feature hook matches or can match */
1745                 hook = ao2_find(features->dtmf_hooks, bridge_channel->dtmf_hook_state.collected,
1746                         OBJ_SEARCH_PARTIAL_KEY);
1747                 if (!hook) {
1748                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1749                                 bridge_channel, ast_channel_name(bridge_channel->chan),
1750                                 bridge_channel->dtmf_hook_state.collected);
1751                         break;
1752                 } else if (dtmf_len != strlen(hook->dtmf.code)) {
1753                         unsigned int digit_timeout;
1754                         /* Need more digits to match */
1755                         ao2_ref(hook, -1);
1756                         digit_timeout = bridge_channel_feature_digit_timeout(bridge_channel);
1757                         bridge_channel->dtmf_hook_state.interdigit_timeout =
1758                                 ast_tvadd(ast_tvnow(), ast_samp2tv(digit_timeout, 1000));
1759                         return;
1760                 } else {
1761                         int remove_me;
1762                         int already_suspended;
1763
1764                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1765                                 hook, bridge_channel->dtmf_hook_state.collected, bridge_channel,
1766                                 ast_channel_name(bridge_channel->chan));
1767
1768                         /*
1769                          * Clear the collected digits before executing the hook
1770                          * in case the hook starts another sequence.
1771                          */
1772                         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1773
1774                         ast_bridge_channel_lock_bridge(bridge_channel);
1775                         already_suspended = bridge_channel->suspended;
1776                         if (!already_suspended) {
1777                                 bridge_channel_internal_suspend_nolock(bridge_channel);
1778                         }
1779                         ast_bridge_unlock(bridge_channel->bridge);
1780                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1781
1782                         /* Execute the matched hook on this channel. */
1783                         remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1784                         if (remove_me) {
1785                                 ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1786                                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1787                                 ao2_unlink(features->dtmf_hooks, hook);
1788                         }
1789                         testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1790                         ao2_ref(hook, -1);
1791
1792                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1793                         if (!already_suspended) {
1794                                 bridge_channel_unsuspend(bridge_channel);
1795                         }
1796
1797                         /*
1798                          * If we are handing the channel off to an external hook for
1799                          * ownership, we are not guaranteed what kind of state it will
1800                          * come back in.  If the channel hungup, we need to detect that
1801                          * here if the hook did not already change the state.
1802                          */
1803                         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1804                                 ast_bridge_channel_kick(bridge_channel, 0);
1805                                 bridge_channel->dtmf_hook_state.collected[0] = '\0';
1806                                 return;
1807                         }
1808
1809                         /* if there is dtmf that has been collected then loop back through,
1810                            but set digit to -1 so it doesn't try to do an add since the dtmf
1811                            is already in the buffer */
1812                         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1813                         if (!dtmf_len) {
1814                                 return;
1815                         }
1816                 }
1817         }
1818
1819         if (!digit) {
1820                 ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1821                         bridge_channel, ast_channel_name(bridge_channel->chan));
1822         }
1823
1824         /* Timeout or DTMF digit didn't allow a match with any hooks. */
1825         if (features->dtmf_passthrough) {
1826                 /* Stream the collected DTMF to the other channels. */
1827                 bridge_channel_write_dtmf_stream(bridge_channel,
1828                         bridge_channel->dtmf_hook_state.collected);
1829         }
1830         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1831
1832         ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1833 }
1834
1835 /*!
1836  * \internal
1837  * \brief Handle bridge channel DTMF feature timeout expiration.
1838  * \since 12.8.0
1839  *
1840  * \param bridge_channel Channel to check expired interdigit timer on.
1841  *
1842  * \return Nothing
1843  */
1844 static void bridge_channel_handle_feature_timeout(struct ast_bridge_channel *bridge_channel)
1845 {
1846         if (!bridge_channel->dtmf_hook_state.collected[0]
1847                 || 0 < ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
1848                         ast_tvnow())) {
1849                 /* Not within a sequence or not timed out. */
1850                 return;
1851         }
1852
1853         ast_bridge_channel_feature_digit(bridge_channel, 0);
1854 }
1855
1856 /*!
1857  * \internal
1858  * \brief Indicate that a bridge_channel is talking
1859  */
1860 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1861 {
1862         struct ast_bridge_features *features = bridge_channel->features;
1863         struct ast_bridge_hook *hook;
1864         struct ao2_iterator iter;
1865
1866         /* Run any talk detection hooks. */
1867         iter = ao2_iterator_init(features->other_hooks, 0);
1868         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1869                 int remove_me;
1870                 ast_bridge_talking_indicate_callback talk_cb;
1871
1872                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1873                         continue;
1874                 }
1875                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1876                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1877                 if (remove_me) {
1878                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1879                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1880                         ao2_unlink(features->other_hooks, hook);
1881                 }
1882         }
1883         ao2_iterator_destroy(&iter);
1884 }
1885
1886 /*! \brief Internal function that plays back DTMF on a bridge channel */
1887 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1888 {
1889         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1890                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1891         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1892 }
1893
1894 /*! \brief Data specifying where a blind transfer is going to */
1895 struct blind_transfer_data {
1896         char exten[AST_MAX_EXTENSION];
1897         char context[AST_MAX_CONTEXT];
1898 };
1899
1900 /*!
1901  * \internal
1902  * \brief Execute after bridge actions on a channel when it leaves a bridge
1903  */
1904 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1905 {
1906         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1907         struct ast_party_connected_line connected_target;
1908         unsigned char connected_line_data[1024];
1909         int payload_size;
1910
1911         ast_party_connected_line_init(&connected_target);
1912
1913         ast_channel_lock(chan_target);
1914         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1915         ast_channel_unlock(chan_target);
1916         ast_party_id_reset(&connected_target.priv);
1917
1918         if (ast_channel_move(chan_target, chan_bridged)) {
1919                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1920                 ast_party_connected_line_free(&connected_target);
1921                 return;
1922         }
1923
1924         /* The ast_channel_move function will end up updating the connected line information
1925          * on chan_target to the value we have here, but will not inform it. To ensure that
1926          * AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO is executed we wipe it away here. If
1927          * we don't do this then the change will be considered redundant, since the connected
1928          * line information is already there (despite the channel not being told).
1929          */
1930         ast_channel_lock(chan_target);
1931         ast_party_connected_line_free(ast_channel_connected_indicated(chan_target));
1932         ast_party_connected_line_init(ast_channel_connected_indicated(chan_target));
1933         ast_channel_unlock(chan_target);
1934
1935         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1936                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1937                 struct ast_control_read_action_payload *frame_payload;
1938                 int frame_size;
1939
1940                 frame_size = payload_size + sizeof(*frame_payload);
1941                 frame_payload = ast_alloca(frame_size);
1942                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1943                 frame_payload->payload_size = payload_size;
1944                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1945                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1946         }
1947
1948         /* A connected line update is queued so that if chan_target is remotely involved with
1949          * anything (such as dialing a channel) the other channel(s) will be informed of the
1950          * new channel they are involved with.
1951          */
1952         ast_channel_lock(chan_target);
1953         ast_connected_line_copy_from_caller(&connected_target, ast_channel_caller(chan_target));
1954         ast_channel_queue_connected_line_update(chan_target, &connected_target, NULL);
1955         ast_channel_unlock(chan_target);
1956
1957         ast_party_connected_line_free(&connected_target);
1958 }
1959
1960 /*!
1961  * \internal
1962  * \brief Execute logic to cleanup when after bridge fails
1963  */
1964 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1965 {
1966         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1967
1968         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1969                 ast_bridge_after_cb_reason_string(reason));
1970         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1971 }
1972
1973 /*!
1974  * \internal
1975  * \brief Perform a blind transfer on a channel in a bridge
1976  */
1977 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1978                 struct blind_transfer_data *blind_data)
1979 {
1980         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1981         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1982 }
1983
1984 /*!
1985  * \internal
1986  * \brief Perform an attended transfer on a channel in a bridge
1987  */
1988 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1989                 const char *target_chan_name)
1990 {
1991         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1992         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1993
1994         chan_target = ast_channel_get_by_name(target_chan_name);
1995         if (!chan_target) {
1996                 /* Dang, it disappeared somehow */
1997                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1998                 return;
1999         }
2000
2001         ast_bridge_channel_lock(bridge_channel);
2002         chan_bridged = bridge_channel->chan;
2003         ast_assert(chan_bridged != NULL);
2004         ao2_ref(chan_bridged, +1);
2005         ast_bridge_channel_unlock(bridge_channel);
2006
2007         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
2008                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
2009                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2010
2011                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
2012                 ast_channel_unref(chan_target);
2013         }
2014         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
2015 }
2016
2017 /*!
2018  * \internal
2019  * \brief Handle bridge channel bridge action frame.
2020  * \since 12.0.0
2021  *
2022  * \param bridge_channel Channel to execute the action on.
2023  * \param action What to do.
2024  * \param data data from the action.
2025  *
2026  * \return Nothing
2027  */
2028 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel,
2029         enum bridge_channel_action_type action, void *data)
2030 {
2031         switch (action) {
2032         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
2033                 bridge_channel_suspend(bridge_channel);
2034                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2035                 bridge_channel_dtmf_stream(bridge_channel, data);
2036                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2037                 bridge_channel_unsuspend(bridge_channel);
2038                 break;
2039         case BRIDGE_CHANNEL_ACTION_TALKING_START:
2040         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
2041                 bridge_channel_talking(bridge_channel,
2042                         action == BRIDGE_CHANNEL_ACTION_TALKING_START);
2043                 break;
2044         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
2045                 bridge_channel_suspend(bridge_channel);
2046                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2047                 bridge_channel_playfile(bridge_channel, data);
2048                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2049                 bridge_channel_unsuspend(bridge_channel);
2050                 break;
2051         case BRIDGE_CHANNEL_ACTION_RUN_APP:
2052                 bridge_channel_suspend(bridge_channel);
2053                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2054                 bridge_channel_run_app(bridge_channel, data);
2055                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2056                 bridge_channel_unsuspend(bridge_channel);
2057                 break;
2058         case BRIDGE_CHANNEL_ACTION_CALLBACK:
2059                 bridge_channel_do_callback(bridge_channel, data);
2060                 break;
2061         case BRIDGE_CHANNEL_ACTION_PARK:
2062                 bridge_channel_suspend(bridge_channel);
2063                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2064                 bridge_channel_park(bridge_channel, data);
2065                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2066                 bridge_channel_unsuspend(bridge_channel);
2067                 break;
2068         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
2069                 bridge_channel_blind_transfer(bridge_channel, data);
2070                 break;
2071         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
2072                 bridge_channel_attended_transfer(bridge_channel, data);
2073                 break;
2074         default:
2075                 break;
2076         }
2077
2078         /* While invoking an action it is possible for the channel to be hung up. So
2079          * that the bridge respects this we check here and if hung up kick it out.
2080          */
2081         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
2082                 ast_bridge_channel_kick(bridge_channel, 0);
2083         }
2084 }
2085
2086 /*!
2087  * \internal
2088  * \brief Check if a bridge should dissolve and do it.
2089  * \since 12.0.0
2090  *
2091  * \param bridge_channel Channel causing the check.
2092  *
2093  * \note On entry, bridge_channel->bridge is already locked.
2094  *
2095  * \return Nothing
2096  */
2097 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
2098 {
2099         struct ast_bridge *bridge = bridge_channel->bridge;
2100
2101         if (bridge->dissolved) {
2102                 return;
2103         }
2104
2105         if (!bridge->num_channels
2106                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
2107                 /* Last channel leaving the bridge turns off the lights. */
2108                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2109                 return;
2110         }
2111
2112         switch (bridge_channel->state) {
2113         case BRIDGE_CHANNEL_STATE_END:
2114                 /* Do we need to dissolve the bridge because this channel hung up? */
2115                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
2116                         || (bridge_channel->features->usable
2117                                 && ast_test_flag(&bridge_channel->features->feature_flags,
2118                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
2119                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
2120                         return;
2121                 }
2122                 break;
2123         default:
2124                 break;
2125         }
2126
2127         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
2128                 /*
2129                  * This will start a chain reaction where each channel leaving
2130                  * enters this function and causes the next to leave as long as
2131                  * there aren't non-lonely channels in the bridge.
2132                  */
2133                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
2134                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
2135                         ast_channel_hangupcause(bridge_channel->chan));
2136         }
2137 }
2138
2139 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
2140 {
2141         struct ast_bridge *bridge = bridge_channel->bridge;
2142
2143         if (!bridge_channel->in_bridge) {
2144                 return;
2145         }
2146         bridge_channel->in_bridge = 0;
2147
2148         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
2149                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2150
2151         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
2152                 ast_channel_name(bridge_channel->chan),
2153                 bridge->technology->name,
2154                 bridge->v_table->name,
2155                 bridge->uniqueid);
2156
2157         if (!bridge_channel->just_joined) {
2158                 /* Tell the bridge technology we are leaving so they tear us down */
2159                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
2160                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2161                         bridge->technology->name);
2162                 if (bridge->technology->leave) {
2163                         bridge->technology->leave(bridge, bridge_channel);
2164                 }
2165         }
2166
2167         /* Remove channel from the bridge */
2168         if (!bridge_channel->suspended) {
2169                 --bridge->num_active;
2170         }
2171         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2172                 --bridge->num_lonely;
2173         }
2174         --bridge->num_channels;
2175         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
2176
2177         bridge_channel_dissolve_check(bridge_channel);
2178         bridge->v_table->pull(bridge, bridge_channel);
2179
2180         ast_bridge_channel_clear_roles(bridge_channel);
2181
2182         /* If we are not going to be hung up after leaving a bridge, and we were an
2183          * outgoing channel, clear the outgoing flag.
2184          */
2185         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
2186             && (ast_channel_is_leaving_bridge(bridge_channel->chan)
2187                 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
2188                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
2189                 ast_channel_clear_flag(bridge_channel->chan, AST_FLAG_OUTGOING);
2190         }
2191
2192         bridge->reconfigured = 1;
2193         ast_bridge_publish_leave(bridge, bridge_channel->chan);
2194 }
2195
2196 int bridge_channel_internal_push_full(struct ast_bridge_channel *bridge_channel, int optimized)
2197 {
2198         struct ast_bridge *bridge = bridge_channel->bridge;
2199         struct ast_bridge_channel *swap;
2200
2201         ast_assert(!bridge_channel->in_bridge);
2202
2203         swap = bridge_find_channel(bridge, bridge_channel->swap);
2204         bridge_channel->swap = NULL;
2205
2206         if (swap) {
2207                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
2208                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2209                         swap, ast_channel_name(swap->chan));
2210         } else {
2211                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
2212                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2213         }
2214
2215         /* Add channel to the bridge */
2216         if (bridge->dissolved
2217                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2218                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
2219                 || bridge->v_table->push(bridge, bridge_channel, swap)) {
2220                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
2221                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2222                 return -1;
2223         }
2224
2225         ast_bridge_channel_establish_roles(bridge_channel);
2226
2227         if (swap) {
2228                 int dissolve = ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2229
2230                 /* This flag is cleared so the act of this channel leaving does not cause it to dissolve if need be */
2231                 ast_clear_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2232
2233                 if (optimized) {
2234                         bridge_channel_cancel_owed_events(swap);
2235                 }
2236                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
2237                 bridge_channel_internal_pull(swap);
2238
2239                 ast_set2_flag(&bridge->feature_flags, dissolve, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2240         }
2241
2242         bridge_channel->in_bridge = 1;
2243         bridge_channel->just_joined = 1;
2244         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
2245         ++bridge->num_channels;
2246         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2247                 ++bridge->num_lonely;
2248         }
2249         if (!bridge_channel->suspended) {
2250                 ++bridge->num_active;
2251         }
2252
2253         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
2254                 ast_channel_name(bridge_channel->chan),
2255                 swap ? "swapped with " : "joined",
2256                 swap ? ast_channel_name(swap->chan) : "",
2257                 swap ? " into" : "",
2258                 bridge->technology->name,
2259                 bridge->v_table->name,
2260                 bridge->uniqueid);
2261
2262         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
2263
2264         /* Clear any BLINDTRANSFER,ATTENDEDTRANSFER and FORWARDERNAME since the transfer has completed. */
2265         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
2266         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
2267         pbx_builtin_setvar_helper(bridge_channel->chan, "FORWARDERNAME", NULL);
2268
2269         /* Wake up the bridge channel thread to reevaluate any interval timers. */
2270         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
2271
2272         bridge->reconfigured = 1;
2273         return 0;
2274 }
2275
2276 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
2277 {
2278         return bridge_channel_internal_push_full(bridge_channel, 0);
2279 }
2280
2281 /*!
2282  * \internal
2283  * \brief Handle bridge channel control frame action.
2284  * \since 12.0.0
2285  *
2286  * \param bridge_channel Channel to execute the control frame action on.
2287  * \param fr Control frame to handle.
2288  *
2289  * \return Nothing
2290  */
2291 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2292 {
2293         struct ast_channel *chan;
2294         struct ast_option_header *aoh;
2295         int is_caller;
2296
2297         chan = bridge_channel->chan;
2298         switch (fr->subclass.integer) {
2299         case AST_CONTROL_REDIRECTING:
2300                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2301                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
2302                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
2303                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2304                 }
2305                 break;
2306         case AST_CONTROL_CONNECTED_LINE:
2307                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2308                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
2309                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
2310                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2311                 }
2312                 break;
2313         case AST_CONTROL_OPTION:
2314                 /*
2315                  * Forward option Requests, but only ones we know are safe These
2316                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2317                  * are useful. I haven't deleted them entirely because I just am
2318                  * not sure of the ramifications of removing them.
2319                  */
2320                 aoh = fr->data.ptr;
2321                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2322                         switch (ntohs(aoh->option)) {
2323                         case AST_OPTION_TONE_VERIFY:
2324                         case AST_OPTION_TDD:
2325                         case AST_OPTION_RELAXDTMF:
2326                         case AST_OPTION_AUDIO_MODE:
2327                         case AST_OPTION_DIGIT_DETECT:
2328                         case AST_OPTION_FAX_DETECT:
2329                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2330                                         fr->datalen - sizeof(*aoh), 0);
2331                                 break;
2332                         default:
2333                                 break;
2334                         }
2335                 }
2336                 break;
2337         case AST_CONTROL_ANSWER:
2338                 if (ast_channel_state(chan) != AST_STATE_UP) {
2339                         ast_answer(chan);
2340                         ast_bridge_channel_lock_bridge(bridge_channel);
2341                         bridge_channel->bridge->reconfigured = 1;
2342                         bridge_reconfigured(bridge_channel->bridge, 0);
2343                         ast_bridge_unlock(bridge_channel->bridge);
2344                 } else {
2345                         ast_indicate(chan, -1);
2346                 }
2347                 break;
2348         case AST_CONTROL_MASQUERADE_NOTIFY:
2349                 /* Should never happen. */
2350                 ast_assert(0);
2351                 break;
2352         case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2353                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2354                 break;
2355         default:
2356                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2357                 break;
2358         }
2359 }
2360
2361 /*!
2362  * \internal
2363  * \brief Handle bridge channel write frame to channel.
2364  * \since 12.0.0
2365  *
2366  * \param bridge_channel Channel to write outgoing frame.
2367  *
2368  * \return Nothing
2369  */
2370 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2371 {
2372         struct ast_frame *fr;
2373         struct sync_payload *sync_payload;
2374         int num;
2375         struct ast_msg_data *msg;
2376
2377         ast_bridge_channel_lock(bridge_channel);
2378
2379         /* It's not good to have unbalanced frames and alert_pipe alerts. */
2380         ast_assert(!AST_LIST_EMPTY(&bridge_channel->wr_queue));
2381         if (AST_LIST_EMPTY(&bridge_channel->wr_queue)) {
2382                 /* No frame, flush the alert pipe of excess alerts. */
2383                 ast_log(LOG_WARNING, "Weird.  No frame from bridge for %s to process?\n",
2384                         ast_channel_name(bridge_channel->chan));
2385                 ast_alertpipe_read(bridge_channel->alert_pipe);
2386                 ast_bridge_channel_unlock(bridge_channel);
2387                 return;
2388         }
2389
2390         AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge_channel->wr_queue, fr, frame_list) {
2391                 if (bridge_channel->dtmf_hook_state.collected[0]) {
2392                         switch (fr->frametype) {
2393                         case AST_FRAME_BRIDGE_ACTION:
2394                         case AST_FRAME_BRIDGE_ACTION_SYNC:
2395                                 /* Defer processing these frames while DTMF is collected. */
2396                                 continue;
2397                         default:
2398                                 break;
2399                         }
2400                 }
2401                 ast_alertpipe_read(bridge_channel->alert_pipe);
2402                 AST_LIST_REMOVE_CURRENT(frame_list);
2403                 break;
2404         }
2405         AST_LIST_TRAVERSE_SAFE_END;
2406
2407         ast_bridge_channel_unlock(bridge_channel);
2408
2409         if (!fr) {
2410                 /*
2411                  * Wait some to reduce CPU usage from a tight loop
2412                  * without any wait because we only have deferred
2413                  * frames in the wr_queue.
2414                  */
2415                 usleep(1);
2416                 return;
2417         }
2418
2419         switch (fr->frametype) {
2420         case AST_FRAME_BRIDGE_ACTION:
2421                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, fr->data.ptr);
2422                 break;
2423         case AST_FRAME_BRIDGE_ACTION_SYNC:
2424                 sync_payload = fr->data.ptr;
2425                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, sync_payload->data);
2426                 break;
2427         case AST_FRAME_CONTROL:
2428                 bridge_channel_handle_control(bridge_channel, fr);
2429                 break;
2430         case AST_FRAME_NULL:
2431                 break;
2432         case AST_FRAME_TEXT:
2433                 ast_debug(1, "Sending TEXT frame to '%s': %*.s\n",
2434                         ast_channel_name(bridge_channel->chan), fr->datalen, (char *)fr->data.ptr);
2435                 ast_sendtext(bridge_channel->chan, fr->data.ptr);
2436                 break;
2437         case AST_FRAME_TEXT_DATA:
2438                 msg = (struct ast_msg_data *)fr->data.ptr;
2439                 ast_debug(1, "Sending TEXT_DATA frame from '%s' to '%s:%s': %s\n",
2440                         ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_FROM),
2441                         ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_TO),
2442                         ast_channel_name(bridge_channel->chan),
2443                         ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_BODY));
2444                 ast_sendtext_data(bridge_channel->chan, msg);
2445                 break;
2446         default:
2447                 /* Assume that there is no mapped stream for this */
2448                 num = -1;
2449
2450                 if (fr->stream_num > -1) {
2451                         ast_bridge_channel_lock(bridge_channel);
2452                         if (fr->stream_num < (int)AST_VECTOR_SIZE(&bridge_channel->stream_map.to_channel)) {
2453                                 num = AST_VECTOR_GET(&bridge_channel->stream_map.to_channel, fr->stream_num);
2454                         }
2455                         ast_bridge_channel_unlock(bridge_channel);
2456
2457                         /* If there is no mapped stream after checking the mapping then there is nowhere
2458                          * to write this frame to, so drop it.
2459                          */
2460                         if (num == -1) {
2461                                 break;
2462                         }
2463                 }
2464
2465                 /* Write the frame to the channel. */
2466                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
2467                 ast_write_stream(bridge_channel->chan, num, fr);
2468                 break;
2469         }
2470         bridge_frame_free(fr);
2471 }
2472
2473 /*! \brief Internal function to handle DTMF from a channel */
2474 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
2475 {
2476         struct ast_bridge_features *features = bridge_channel->features;
2477         struct ast_bridge_hook_dtmf *hook = NULL;
2478         char dtmf[2];
2479
2480         /*
2481          * See if we are already matching a DTMF feature hook sequence or
2482          * if this DTMF matches the beginning of any DTMF feature hooks.
2483          */
2484         dtmf[0] = frame->subclass.integer;
2485         dtmf[1] = '\0';
2486         if (bridge_channel->dtmf_hook_state.collected[0]
2487                 || (hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_SEARCH_PARTIAL_KEY))) {
2488                 enum ast_frame_type frametype = frame->frametype;
2489
2490                 bridge_frame_free(frame);
2491                 frame = NULL;
2492
2493                 ao2_cleanup(hook);
2494
2495                 switch (frametype) {
2496                 case AST_FRAME_DTMF_BEGIN:
2497                         /* Just eat the frame. */
2498                         break;
2499                 case AST_FRAME_DTMF_END:
2500                         ast_bridge_channel_feature_digit(bridge_channel, dtmf[0]);
2501                         break;
2502                 default:
2503                         /* Unexpected frame type. */
2504                         ast_assert(0);
2505                         break;
2506                 }
2507 #ifdef TEST_FRAMEWORK
2508         } else if (frame->frametype == AST_FRAME_DTMF_END) {
2509                 /* Only transmit this event on DTMF end or else every DTMF
2510                  * press will result in the event being broadcast twice
2511                  */
2512                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
2513 #endif
2514         }
2515
2516         return frame;
2517 }
2518
2519 static const char *controls[] = {
2520         [AST_CONTROL_RINGING] = "RINGING",
2521         [AST_CONTROL_PROCEEDING] = "PROCEEDING",
2522         [AST_CONTROL_PROGRESS] = "PROGRESS",
2523         [AST_CONTROL_BUSY] = "BUSY",
2524         [AST_CONTROL_CONGESTION] = "CONGESTION",
2525         [AST_CONTROL_ANSWER] = "ANSWER",
2526 };
2527
2528 /*!
2529  * \internal
2530  * \brief Feed notification that a frame is waiting on a channel into the bridging core
2531  *
2532  * \param bridge_channel Bridge channel the notification was received on
2533  */
2534 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
2535 {
2536         struct ast_frame *frame;
2537         int blocked;
2538
2539         if (!ast_strlen_zero(ast_channel_call_forward(bridge_channel->chan))) {
2540                 /* TODO If early bridging is ever used by anything other than ARI,
2541                  * it's important that we actually attempt to handle the call forward
2542                  * attempt, as well as expand features on a bridge channel to allow/disallow
2543                  * call forwarding. For now, all we do is raise an event, showing that
2544                  * a call forward is being attempted.
2545                  */
2546                 ast_channel_publish_dial_forward(NULL, bridge_channel->chan, NULL, NULL, "CANCEL",
2547                         ast_channel_call_forward(bridge_channel->chan));
2548         }
2549
2550         if (bridge_channel->features->mute) {
2551                 frame = ast_read_stream_noaudio(bridge_channel->chan);
2552         } else {
2553                 frame = ast_read_stream(bridge_channel->chan);
2554         }
2555
2556         if (!frame) {
2557                 ast_bridge_channel_kick(bridge_channel, 0);
2558                 return;
2559         }
2560
2561         if (!ast_channel_is_multistream(bridge_channel->chan)) {
2562                 /* This may not be initialized by non-multistream channel drivers */
2563                 frame->stream_num = -1;
2564         }
2565
2566         switch (frame->frametype) {
2567         case AST_FRAME_CONTROL:
2568                 switch (frame->subclass.integer) {
2569                 case AST_CONTROL_CONGESTION:
2570                 case AST_CONTROL_BUSY:
2571                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2572                         break;
2573                 case AST_CONTROL_HANGUP:
2574                         ast_bridge_channel_kick(bridge_channel, 0);
2575                         bridge_frame_free(frame);
2576                         return;
2577                 case AST_CONTROL_RINGING:
2578                 case AST_CONTROL_PROGRESS:
2579                 case AST_CONTROL_PROCEEDING:
2580                 case AST_CONTROL_ANSWER:
2581                         ast_channel_publish_dial(NULL, bridge_channel->chan, NULL, controls[frame->subclass.integer]);
2582                         break;
2583                 case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
2584                         ast_bridge_channel_lock_bridge(bridge_channel);
2585                         blocked = bridge_channel->bridge->technology->stream_topology_request_change
2586                                 && bridge_channel->bridge->technology->stream_topology_request_change(
2587                                         bridge_channel->bridge, bridge_channel);
2588                         ast_bridge_unlock(bridge_channel->bridge);
2589                         if (blocked) {
2590                                 /*
2591                                  * Topology change was intercepted by the bridge technology
2592                                  * so drop frame.
2593                                  */
2594                                 bridge_frame_free(frame);
2595                                 return;
2596                         }
2597                         break;
2598                 case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
2599                         /*
2600                          * If a stream topology has changed then the bridge_channel's
2601                          * media mapping needs to be updated.
2602                          */
2603                         ast_bridge_channel_lock_bridge(bridge_channel);
2604                         if (bridge_channel->bridge->technology->stream_topology_changed) {
2605                                 bridge_channel->bridge->technology->stream_topology_changed(
2606                                         bridge_channel->bridge, bridge_channel);
2607                         } else {
2608                                 ast_bridge_channel_stream_map(bridge_channel);
2609                         }
2610                         ast_bridge_unlock(bridge_channel->bridge);
2611                         break;
2612                 default:
2613                         break;
2614                 }
2615                 break;
2616         case AST_FRAME_DTMF_BEGIN:
2617         case AST_FRAME_DTMF_END:
2618                 frame = bridge_handle_dtmf(bridge_channel, frame);
2619                 if (!frame) {
2620                         return;
2621                 }
2622                 if (!bridge_channel->features->dtmf_passthrough) {
2623                         bridge_frame_free(frame);
2624                         return;
2625                 }
2626                 break;
2627         default:
2628                 break;
2629         }
2630
2631         /* Simply write the frame out to the bridge technology. */
2632         bridge_channel_write_frame(bridge_channel, frame);
2633         bridge_frame_free(frame);
2634 }
2635
2636 /*!
2637  * \internal
2638  * \brief Determine how long till the next timer interval.
2639  * \since 12.0.0
2640  *
2641  * \param bridge_channel Channel to determine how long can wait.
2642  *
2643  * \retval ms Number of milliseconds to wait.
2644  * \retval -1 to wait forever.
2645  */
2646 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
2647 {
2648         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
2649         struct ast_bridge_hook_timer *hook;
2650         int ms;
2651
2652         ast_heap_wrlock(interval_hooks);
2653         hook = ast_heap_peek(interval_hooks, 1);
2654         if (hook) {
2655                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
2656                 if (ms < 0) {
2657                         /* Expire immediately.  An interval hook is ready to run. */
2658                         ms = 0;
2659                 }
2660         } else {
2661                 /* No hook so wait forever. */
2662                 ms = -1;
2663         }
2664         ast_heap_unlock(interval_hooks);
2665
2666         return ms;
2667 }
2668
2669 /*!
2670  * \internal
2671  * \brief Determine how long till the DTMF interdigit timeout.
2672  * \since 12.8.0
2673  *
2674  * \param bridge_channel Channel to determine how long can wait.
2675  *
2676  * \retval ms Number of milliseconds to wait.
2677  * \retval -1 to wait forever.
2678  */
2679 static int bridge_channel_feature_timeout(struct ast_bridge_channel *bridge_channel)
2680 {
2681         int ms;
2682
2683         if (bridge_channel->dtmf_hook_state.collected[0]) {
2684                 ms = ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
2685                         ast_tvnow());
2686                 if (ms < 0) {
2687                         /* Expire immediately. */
2688                         ms = 0;
2689                 }
2690         } else {
2691                 /* Timer is not active so wait forever. */
2692                 ms = -1;
2693         }
2694
2695         return ms;
2696 }
2697
2698 /*!
2699  * \internal
2700  * \brief Determine how long till a timeout.
2701  * \since 12.8.0
2702  *
2703  * \param bridge_channel Channel to determine how long can wait.
2704  *
2705  * \retval ms Number of milliseconds to wait.
2706  * \retval -1 to wait forever.
2707  */
2708 static int bridge_channel_next_timeout(struct ast_bridge_channel *bridge_channel)
2709 {
2710         int ms_interval;
2711         int ms;
2712
2713         ms_interval = bridge_channel_next_interval(bridge_channel);
2714         ms = bridge_channel_feature_timeout(bridge_channel);
2715         if (ms < 0 || (0 <= ms_interval && ms_interval < ms)) {
2716                 /* Interval hook timeout is next. */
2717                 ms = ms_interval;
2718         }
2719
2720         return ms;
2721 }
2722
2723 /*!
2724  * \internal
2725  * \brief Wait for something to happen on the bridge channel and handle it.
2726  * \since 12.0.0
2727  *
2728  * \param bridge_channel Channel to wait.
2729  *
2730  * \note Each channel does writing/reading in their own thread.
2731  *
2732  * \return Nothing
2733  */
2734 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2735 {
2736         int ms;
2737         int outfd;
2738         struct ast_channel *chan;
2739
2740         /* Wait for data to either come from the channel or us to be signaled */
2741         ast_bridge_channel_lock(bridge_channel);
2742         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2743         } else if (bridge_channel->suspended) {
2744 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
2745                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2746                         bridge_channel->bridge->uniqueid, bridge_channel,
2747                         ast_channel_name(bridge_channel->chan));
2748                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2749         } else {
2750                 ast_bridge_channel_unlock(bridge_channel);
2751                 outfd = -1;
2752                 ms = bridge_channel_next_timeout(bridge_channel);
2753                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2754                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2755                 if (ast_channel_unbridged(bridge_channel->chan)) {
2756                         ast_channel_set_unbridged(bridge_channel->chan, 0);
2757                         ast_bridge_channel_lock_bridge(bridge_channel);
2758                         bridge_channel->bridge->reconfigured = 1;
2759                         bridge_reconfigured(bridge_channel->bridge, 0);
2760                         ast_bridge_unlock(bridge_channel->bridge);
2761                 }
2762                 ast_bridge_channel_lock(bridge_channel);
2763                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
2764                 ast_bridge_channel_unlock(bridge_channel);
2765                 if (!bridge_channel->suspended
2766                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2767                         if (chan) {
2768                                 bridge_handle_trip(bridge_channel);
2769                         } else if (ms == 0) {
2770                                 /* An interdigit timeout or interval expired. */
2771                                 bridge_channel_handle_feature_timeout(bridge_channel);
2772                                 bridge_channel_handle_interval(bridge_channel);
2773                         } else if (-1 < outfd) {
2774                                 /*
2775                                  * Must do this after checking timeouts or may have
2776                                  * an infinite loop due to deferring write queue
2777                                  * actions while trying to match DTMF feature hooks.
2778                                  */
2779                                 bridge_channel_handle_write(bridge_channel);
2780                         }
2781                 }
2782                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
2783                 return;
2784         }
2785         ast_bridge_channel_unlock(bridge_channel);
2786 }
2787
2788 /*!
2789  * \internal
2790  * \brief Handle bridge channel join/leave event.
2791  * \since 12.0.0
2792  *
2793  * \param bridge_channel Which channel is involved.
2794  * \param type Specified join/leave event.
2795  *
2796  * \return Nothing
2797  */
2798 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
2799 {
2800         struct ast_bridge_features *features = bridge_channel->features;
2801         struct ast_bridge_hook *hook;
2802         struct ao2_iterator iter;
2803
2804         /* Run the specified hooks. */
2805         iter = ao2_iterator_init(features->other_hooks, 0);
2806         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2807                 if (hook->type == type) {
2808                         break;
2809                 }
2810         }
2811         if (hook) {
2812                 /* Found the first specified hook to run. */
2813                 bridge_channel_suspend(bridge_channel);
2814                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2815                 do {
2816                         if (hook->type == type) {
2817                                 hook->callback(bridge_channel, hook->hook_pvt);
2818                                 ao2_unlink(features->other_hooks, hook);
2819                         }
2820                         ao2_ref(hook, -1);
2821                 } while ((hook = ao2_iterator_next(&iter)));
2822                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2823                 bridge_channel_unsuspend(bridge_channel);
2824         }
2825         ao2_iterator_destroy(&iter);
2826 }
2827
2828 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
2829 {
2830         int res = 0;
2831         uint8_t indicate_src_change = 0;
2832         struct ast_bridge_features *channel_features;
2833         struct ast_channel *swap;
2834
2835         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2836                 bridge_channel->bridge->uniqueid,
2837                 bridge_channel, ast_channel_name(bridge_channel->chan));
2838
2839         /*
2840          * Directly locking the bridge is safe here because nobody else
2841          * knows about this bridge_channel yet.
2842          */
2843         ast_bridge_lock(bridge_channel->bridge);
2844
2845         ast_channel_lock(bridge_channel->chan);
2846
2847         bridge_channel->read_format = ao2_bump(ast_channel_readformat(bridge_channel->chan));
2848         bridge_channel->write_format = ao2_bump(ast_channel_writeformat(bridge_channel->chan));
2849
2850         /* Make sure we're still good to be put into a bridge */
2851         if (ast_channel_internal_bridge(bridge_channel->chan)
2852                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
2853                 ast_channel_unlock(bridge_channel->chan);
2854                 ast_bridge_unlock(bridge_channel->bridge);
2855                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
2856                         bridge_channel->bridge->uniqueid,
2857                         bridge_channel,
2858                         ast_channel_name(bridge_channel->chan));
2859                 return -1;
2860         }
2861         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2862
2863         /* Attach features requested by the channel */
2864         channel_features = ast_channel_feature_hooks_get(bridge_channel->chan);
2865         if (channel_features) {
2866                 ast_bridge_features_merge(bridge_channel->features, channel_features);
2867         }
2868         ast_channel_unlock(bridge_channel->chan);
2869
2870         /* Add the jitterbuffer if the channel requires it */
2871         ast_jb_enable_for_channel(bridge_channel->chan);
2872
2873         if (!bridge_channel->bridge->callid) {
2874                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2875         }
2876
2877         /* Take the swap channel ref from the bridge_channel struct. */
2878         swap = bridge_channel->swap;
2879
2880         if (bridge_channel_internal_push(bridge_channel)) {
2881                 int cause = bridge_channel->bridge->cause;
2882
2883                 ast_bridge_unlock(bridge_channel->bridge);
2884                 ast_bridge_channel_kick(bridge_channel, cause);
2885                 ast_bridge_channel_lock_bridge(bridge_channel);
2886                 ast_bridge_features_remove(bridge_channel->features,
2887                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2888                 bridge_channel_dissolve_check(bridge_channel);
2889                 res = -1;
2890         }
2891         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2892
2893         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2894                 /*
2895                  * Indicate a source change since this channel is entering the
2896                  * bridge system only if the bridge technology is not MULTIMIX
2897                  * capable.  The MULTIMIX technology has already done it.
2898                  */
2899                 if (!(bridge_channel->bridge->technology->capabilities
2900                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2901                         indicate_src_change = 1;
2902                 }
2903
2904                 bridge_channel_impart_signal(bridge_channel->chan);
2905                 ast_bridge_unlock(bridge_channel->bridge);
2906
2907                 /* Must release any swap ref after unlocking the bridge. */
2908                 ao2_t_cleanup(swap, "Bridge push with swap successful");
2909                 swap = NULL;
2910
2911                 if (indicate_src_change) {
2912                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2913                 }
2914
2915                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2916
2917                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2918                         /* Wait for something to do. */
2919                         bridge_channel_wait(bridge_channel);
2920                 }
2921
2922                 /* Force a timeout on any accumulated DTMF hook digits. */
2923                 ast_bridge_channel_feature_digit(bridge_channel, 0);
2924
2925                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2926                 ast_bridge_channel_lock_bridge(bridge_channel);
2927         }
2928
2929         bridge_channel_internal_pull(bridge_channel);
2930         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2931         bridge_reconfigured(bridge_channel->bridge, 1);
2932
2933         /* Remove ourselves if we are the video source */
2934         ast_bridge_remove_video_src(bridge_channel->bridge, bridge_channel->chan);
2935
2936         ast_bridge_unlock(bridge_channel->bridge);
2937
2938         /* Must release any swap ref after unlocking the bridge. */
2939         ao2_t_cleanup(swap, "Bridge push with swap failed or exited immediately");
2940
2941         /* Complete any active hold before exiting the bridge. */
2942         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2943                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2944                         ast_channel_name(bridge_channel->chan));
2945                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2946         }
2947
2948         /* Complete any partial DTMF digit before exiting the bridge. */
2949         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2950                 ast_channel_end_dtmf(bridge_channel->chan,
2951                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2952                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2953         }
2954
2955         /* Complete any T.38 session before exiting the bridge. */
2956         if (ast_channel_is_t38_active(bridge_channel->chan)) {
2957                 struct ast_control_t38_parameters t38_parameters = {
2958                         .request_response = AST_T38_TERMINATED,
2959                 };
2960
2961                 ast_debug(1, "Channel %s simulating T.38 terminate for bridge end.\n",
2962                         ast_channel_name(bridge_channel->chan));
2963                 ast_indicate_data(bridge_channel->chan, AST_CONTROL_T38_PARAMETERS,
2964                         &t38_parameters, sizeof(t38_parameters));
2965         }
2966
2967         /* Indicate a source change since this channel is leaving the bridge system. */
2968         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2969
2970         /*
2971          * Wait for any dual redirect to complete.
2972          *
2973          * Must be done while "still in the bridge" for ast_async_goto()
2974          * to work right.
2975          */
2976         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2977                 sched_yield();
2978         }
2979         ast_channel_lock(bridge_channel->chan);
2980         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2981         ast_channel_unlock(bridge_channel->chan);
2982
2983         ast_bridge_channel_restore_formats(bridge_channel);
2984
2985         return res;
2986 }
2987
2988 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2989                 const char *exten, const char *context,
2990                 transfer_channel_cb new_channel_cb, void *user_data)
2991 {
2992         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2993         struct blind_transfer_data blind_data;
2994
2995         ast_channel_lock(transferee);
2996         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2997         ast_channel_unlock(transferee);
2998
2999         if (!transferee_bridge_channel) {
3000                 return -1;
3001         }
3002
3003         if (new_channel_cb) {
3004                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
3005         }
3006
3007         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
3008         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
3009
3010         return bridge_channel_queue_action_data(transferee_bridge_channel,
3011                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
3012 }
3013
3014 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
3015                 struct ast_channel *unbridged_chan)
3016 {
3017         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
3018         char unbridged_chan_name[AST_CHANNEL_NAME];
3019
3020         ast_channel_lock(transferee);
3021         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
3022         ast_channel_unlock(transferee);
3023
3024         if (!transferee_bridge_channel) {
3025                 return -1;
3026         }
3027
3028         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
3029                 sizeof(unbridged_chan_name));
3030
3031         return bridge_channel_queue_action_data(transferee_bridge_channel,
3032                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
3033                 sizeof(unbridged_chan_name));
3034 }
3035
3036 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
3037 {
3038         return bridge_channel->in_bridge
3039                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
3040 }
3041
3042 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
3043 static void bridge_channel_destroy(void *obj)
3044 {
3045         struct ast_bridge_channel *bridge_channel = obj;
3046         struct ast_frame *fr;
3047
3048         if (bridge_channel->callid) {
3049                 bridge_channel->callid = 0;
3050         }
3051
3052         if (bridge_channel->bridge) {
3053                 ao2_ref(bridge_channel->bridge, -1);
3054                 bridge_channel->bridge = NULL;
3055         }
3056
3057         /* Flush any unhandled wr_queue frames. */
3058         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
3059                 bridge_frame_free(fr);
3060         }
3061         ast_alertpipe_close(bridge_channel->alert_pipe);
3062
3063         /* Flush any unhandled deferred_queue frames. */
3064         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->deferred_queue, frame_list))) {
3065                 ast_frfree(fr);
3066         }
3067
3068         ast_cond_destroy(&bridge_channel->cond);
3069
3070         ao2_cleanup(bridge_channel->write_format);
3071         ao2_cleanup(bridge_channel->read_format);
3072
3073         AST_VECTOR_FREE(&bridge_channel->stream_map.to_bridge);
3074         AST_VECTOR_FREE(&bridge_channel->stream_map.to_channel);
3075 }
3076
3077 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
3078 {
3079         struct ast_bridge_channel *bridge_channel;
3080
3081         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
3082         if (!bridge_channel) {
3083                 return NULL;
3084         }
3085         ast_cond_init(&bridge_channel->cond, NULL);
3086         if (ast_alertpipe_init(bridge_channel->alert_pipe)) {
3087                 ao2_ref(bridge_channel, -1);
3088                 return NULL;
3089         }
3090         if (bridge) {
3091                 bridge_channel->bridge = bridge;
3092                 ao2_ref(bridge_channel->bridge, +1);
3093         }
3094
3095         /* The stream_map is initialized later - see ast_bridge_channel_stream_map */
3096
3097         return bridge_channel;
3098 }
3099
3100 void ast_bridge_channel_stream_map(struct ast_bridge_channel *bridge_channel)
3101 {
3102         ast_bridge_channel_lock(bridge_channel);
3103         ast_channel_lock(bridge_channel->chan);
3104         ast_stream_topology_map(ast_channel_get_stream_topology(bridge_channel->chan),
3105                 &bridge_channel->bridge->media_types, &bridge_channel->stream_map.to_bridge,
3106                 &bridge_channel->stream_map.to_channel);
3107         ast_channel_unlock(bridge_channel->chan);
3108         ast_bridge_channel_unlock(bridge_channel);
3109 }