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