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