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